var current_profile = '';
var current_registration_data = null;
var domain_costs = {};
var avail_checked_domains = {};
var apiProfiledata = null;
var current_domain = '';
var available_profile_count = 0;

$(function() 
{
	$('.wrapper').off();
	$('.header').on('change', '#apiprofiles', function(e) {
		var profile = $('#apiprofiles').val();
		current_profile = profile;
		getBalance(profile);
		
		DataTableView.getTable('domaindatatable').setFilter('api_profile', "="+profile, true, false);
		var ds = "c=admin&t=regapi&oper=action&action=getcreatedata&name=" + current_profile;
		ajax_call(ds, showDomainInfo, null);
	});
	
	$('.control').on('click', '#sedhome', function(e) {
		window.location.href = '../';
	});
	
	$('.control').on('click', '#sedsettings', function(e) {
		window.location.href = '../admin.php';
	});
	
	
	$('.control').on('click', '.btn-logout', function(e) {
		window.location.href = '../?logout&return=toolbox';
	});
	
	$('.control').on('click', '#hidedomaintable', function(e) {
		if($('#dtablewrapper').is(":visible")) {
			$('#dtablewrapper').hide();
			$('#currentdomain').css('margin-top', 0);
			$('#hidedomaintable').attr('src', 'images/' + current_theme_name + '/view-normal@128px.png');
		}
		else {
			$('#dtablewrapper').show();
			$('#currentdomain').css('margin-top', 12);
			$('#hidedomaintable').attr('src', 'images/' + current_theme_name + '/view-compact@128px.png');
		}
	});
	
	$('.wrapper').on('click', '#renew-domain', function(e) {
		var domain = $('#domain_to_renew').val();
		if(domain == "")
			domain = current_domain;
		if(domain != "") {
			var years = $('#renew-years').val();
			PopupPanel.confirmAction({
				title: 'About to Renew ' + domain + " for " + years + (parseInt(years) == 1 ? " year" : " years"),
				information: "Please check the costs involved before proceeding. Your registrar account will be automatically charged and you may not be able to cancel it and get a refund. Premium domains may cost more than the normal renewal costs. This will work only if you have sufficient funds.",
				message: 'Are You Sure?',
				data: {domain:domain, duration:years, api: current_profile},
				onyes: renewTheDomain
			});
		}
	});
	
	$('.wrapper').on('click', '#calculate-regcosts', function(e) {
		var domain = $('#register_new').val();
		if(domain != "" && current_profile != "") {
			findDomainCost(current_profile, domain, "register");
		}
	});
	
	$('.wrapper').on('click', '#calculate-renewcosts', function(e) {
		var domain = $('#domain_to_renew').val();
		if(domain != "" && current_profile != "") {
			findDomainCost(current_profile, domain, "renew");
		}
	});
	
	$('.wrapper').on('click', '.domaincheck', function(e) {
		var id = $(this).attr('id');
		var domain = id.replace("dc-", "");
		$('#register_new').val(domain);
	});
	
	
	
	$('.wrapper').on('click', '#load-createdata', function(e) {
		var domain = current_domain;
		var ds = "c=admin&t=regapi&oper=action&action=getcreatedata&name=" + encodeURIComponent(current_profile);
		ds += "&domain=" + encodeURIComponent(domain);
		ajax_call(ds, showDomainInfo, null);
	});
	
	$('.wrapper').on('click', '#setns', function(e) {
		var domain = current_domain;
		var nservers = $('#nsdata').val();
		nservers = nservers.split('\n');
		var ns = [];
		for(var i = 0; i < nservers.length; i++) {
			var n = nservers[i].trim();
			if(n != "")
				ns.push(n);
		}
		nservers = ns.join(",");
		if(nservers != "") {
			PopupPanel.confirmAction({
				title: 'Name servers for ' + domain,
				information: "The name servers will be changed to " +  ns.join(", "),
				message: 'Are You Sure?',
				data: {domain:domain, ns: nservers, api: current_profile},
				onyes: setNameservers
			});
		}
	});
	
	$('.wrapper').on('click', '#check-domain', function(e) {
		var domains = $('#domains-to-check').val();
		domains = domains.split("\n");
		domains = domains.join(",");
		var ds = "c=admin&t=regapi&oper=action&action=availcheck&name=" + encodeURIComponent(current_profile);
		ds += "&domains=" + encodeURIComponent(domains);
		ajax_call(ds, showDomainCheckData, null);
	});
	
	$('.wrapper').on('click', '#register-domain', function(e) {
		var domain = $('#register_new').val();
		if(domain != "") {
			var years = $('#register-years').val();
			var cid = $('#new_domain_category').val();
			PopupPanel.confirmAction({
				title: 'About to Register ' + domain + " for " + years + (parseInt(years) == 1 ? " year" : " years"),
				information: "Please check the costs involved before proceeding. Your registrar account will be automatically charged and you may not be able to cancel it and get a refund. Premium domains may cost more than the normal registration costs. This will work only if you have sufficient funds.",
				message: 'Are You Sure?',
				data: {domain:domain, duration:years, api: current_profile, cid: cid},
				onyes: registerTheDomain
			});
		}
	});
	
	$('.wrapper').on('click', '#calculate-regcosts', function(e) {
	});
	
	
	$('#prevpage').click(function(e) {
		var table = DataTableView.getTable('domaindatatable');
		table.navigate("previous");
	});
	
	$('#nextpage').click(function(e) {
		var table = DataTableView.getTable('domaindatatable');
		table.navigate("next");
	});
		
	$('#scrolltop').click(function(e) {
		$("html, body").animate({ scrollTop: 0 }, "slow");
		return false;
	});
	
	$('#scrollbottom').click(function(e) {
		$('html,body').animate({scrollTop: document.body.scrollHeight},"slow");
	});
	
	$('#largetable').click(function(e) {
		$('#dtablewrapper > .dtcard').css('height', '100%');
		$('.cards').hide();
	});
	
	$('#smalltable').click(function(e) {
		$('#dtablewrapper > .dtcard').css('height', 300);
		$('.cards').show();
	});
	
	var wto;
	$('.header').on('keyup', '#globalsearch', function(event) {
		var word = $(this).val();
		clearTimeout(wto);
		wto = setTimeout(function() {
			refreshCards(word);
		}, 600);
	});
	
	disableThumbwheelParentScroll();
	getAPIProfiles();
	
	var datastr = get_ajax_datastr("list", "category", "user");
	ajax_call(datastr, ajax_get_category_list, null);
});

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

function setNameservers(optionData) {
	var domain = optionData.domain;
	var ns = optionData.ns;
	var api = optionData.current_profile;
	var ajax_url = "../api.php";
	datastr = "c=admin&t=regapi&oper=action&action=setns&name=" + encodeURIComponent(optionData.api) + "&domain=" + encodeURIComponent(optionData.domain) + "&ns=" + encodeURIComponent(ns);
	var request = $.ajax({type: "POST",	url: ajax_url, data: datastr});
	request.done(function(msg) {  
		var x = ajax_parse(msg);
		domainNSChanged(x, optionData);
	});
	request.fail(function(jqXHR, textStatus) {
		domainNSChanged(null, optionData);
	});
}

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

function domainNSChanged(x, optionData) {
	if(x.status == 'ok' && x.data.updated == "true") {
		PopupPanel.showInformation({
				title: 'Nameservers Changed',
				information: "The name servers for the domain " + optionData.domain + " were changed to " + optionData.ns,
				message: ''
			});
	}
	else if(typeof x.error != "undefined" && x.error.length) {
		var edata = x.error.split('##');
		var emsg = edata[edata.length-1].trim();
		var years = optionData.duration;
		PopupPanel.showInformation({
				title: 'Set Nameservers Failed',
				information: "Unable to change the name servers for the domain " + optionData.domain,
				message: emsg
			});
	}
}

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

function registerTheDomain(optionData) {
	loadRegistrationData();
	var ajax_url = "../api.php";
	datastr = "c=admin&t=regapi&oper=action&action=register&name=" + encodeURIComponent(optionData.api) + "&domain=" + encodeURIComponent(optionData.domain) + "&years=" + encodeURIComponent(optionData.duration) + "&cid=" + optionData.cid;
	datastr += "&data=" + encodeURIComponent(JSON.stringify(current_registration_data));
	var request = $.ajax({type: "POST",	url: ajax_url, data: datastr});
	request.done(function(msg) {  
		var x = ajax_parse(msg);
		domainRegistered(x, optionData);
	});
	request.fail(function(jqXHR, textStatus) {
		domainRegistered(null, optionData);
	});
}

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

function renewTheDomain(optionData) {
	var ajax_url = "../api.php";
	datastr = "c=admin&t=regapi&oper=action&action=renew&name=" + encodeURIComponent(optionData.api) + "&domain=" + encodeURIComponent(optionData.domain) + "&years=" + encodeURIComponent(optionData.duration);
	var request = $.ajax({type: "POST",	url: ajax_url, data: datastr});
	request.done(function(msg) {  
		var x = ajax_parse(msg);
		domainRenewed(x, optionData);
	});
	request.fail(function(jqXHR, textStatus) {
		domainRenewed(null, optionData);
	});
}

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

function domainRenewed(x, optionData) {
	if(x.status == 'ok' && x.data.renew_status == "true") {
		var charged = x.data.charged_amount;
		var orderid = x.data.order_id;
		var api = x.api;
		var registrar = x.registrar;
		var title = x.data.domain + " (" + optionData.domain + ") renewed";
		var msg = "The new expiry date is " + x.data.new_expiry_date + ". You were charged " + charged;
		PopupPanel.showInformation({
				title: title,
				information: msg,
				message: "Order ID: " + orderid
			});
		getBalance(x.api);
	}
	else if(typeof x.error != "undefined" && x.error.length) {
		var edata = x.error.split('##');
		var emsg = edata[edata.length-1].trim();
		var years = optionData.duration;
		PopupPanel.showInformation({
				title: 'Renewal Failed for ' + optionData.domain + " (" + years + (parseInt(years) == 1 ? " year)" : " years)"),
				information: "This can happen for a number of reasons including not having sufficient funds, domain not available or not belonging to you, etc.",
				message: emsg
			});
	}
}

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

function domainRegistered(x, optionData) {
	if(x.status == 'ok' && x.data.registered == "true") {
		var charged = x.data.charged_amount;
		var orderid = x.data.order_id;
		var api = x.api;
		var registrar = x.registrar;
		var title = x.data.domain + " (" + optionData.domain + ") registered";
		var msg = "You were charged " + charged;
		PopupPanel.showInformation({
				title: title,
				information: msg,
				message: "Order ID: " + orderid
			});
		getBalance(x.api);
	}
	else if(typeof x.error != "undefined" && x.error.length) {
		var edata = x.error.split('##');
		var emsg = edata[edata.length-1].trim();
		var years = optionData.duration;
		PopupPanel.showInformation({
				title: 'Registration Failed for ' + optionData.domain + " (" + years + (parseInt(years) == 1 ? " year)" : " years)"),
				information: "This can happen for a number of reasons including not having sufficient funds, domain not available or not belonging to you, etc.",
				message: emsg
			});
	}
}

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

function get_ajax_datastr(command, target, oper)
{
	var datastr = "";
	if(command != "") {
		datastr += "c=" + encodeURIComponent(command);
		if(target != "")
			datastr += "&t=" + encodeURIComponent(target);
		if(oper != "")
			datastr += "&oper=" + encodeURIComponent(oper);
	}
	return datastr;
}

function ajax_get_category_list(x, jqXHR, textStatus, params)
{
	var options = "<option value=\"" + 0 + "\">" + "Optional Category To Add New Domain To" + "</option>";
	if(x != null) {
		if(x.status == "ok") {
			var count = x.ids.length;
			for(var i = 0; i < count; i++) {
				var name = x.ids[i].name;
				var cid = parseInt(x.ids[i].id);
				var icon = x.ids[i].caticon;
				if(cid > 1)
					options += "<option value=\"" + cid + "\">" + name + "</option>";
			}
		}
	}
	$('#new_domain_category').html(options);
}

function getAPIProfiles() {
	var ajax_url = "../api.php";
	datastr = "c=admin&t=regapi&oper=list";
	var request = $.ajax({type: "POST",	url: ajax_url, data: datastr});
	request.done(function(msg) {  
		var x = ajax_parse(msg);
		fillAPIProfiles(x);
	});
	request.fail(function(jqXHR, textStatus) {
	});
}

function fillAPIProfiles(x) {
	available_profile_count = 0;
	if(x != null) {
		if(x.status == 'ok') {
			var selected = "";
			var select = "";
			apiProfiledata = x.data;
			for (var profilename in x.data) {
				if(profilename === 'length' || !x.data.hasOwnProperty(profilename)) continue;
				var supported = x.data[profilename]['supported'];
				if(supported.includes('renew') || supported.includes('register')) {
					select += "<option value=\"" + profilename + "\">" + profilename + "</option>";
					if(selected == "")
						selected = profilename;
					available_profile_count++;
				}
			}
			if(available_profile_count) {
				current_profile = selected;
				$('#apiprofiles').html(select);
				getBalance(selected);

				if($('#dtablewrapper').length != 0) {
					initDomainDataTable();
					DataTableView.getTable('domaindatatable').setFilter('api_profile', "="+selected, true, false);
				}
				var ds = "c=admin&t=regapi&oper=action&action=getcreatedata&name=" + encodeURIComponent(current_profile);
				ajax_call(ds, showDomainInfo, null);
				findCosts(current_profile, "com", "register");
				findCosts(current_profile, "net", "register");
				findCosts(current_profile, "com", "renew");
				findCosts(current_profile, "net", "renew");
			}
		}
		else {
			// x.error
		}
	}
	else {
	}
	if(!available_profile_count) {
		$('#dtablewrapper').html('<h3 style="text-align: center;">No supported registrar profiles found. Currently tool box supports only Namecheap</h3>');
		$('#cardview').html('');
	}
}

function findDomainCost(apiprofile, domain, type) {
	var ds = "c=admin&t=regapi&oper=action&action=pricing&name=" + apiprofile + "&for=" + type + "&domain=" + encodeURIComponent(domain);
	ajax_call(ds, gotDomainPrice, null);
}

function findCosts(apiprofile, tld, type) {
	for(var profile in domain_costs) {
		if(domain_costs.hasOwnProperty(profile)) {
			var dc = domain_costs[profile];
			if(dc.hasOwnProperty(tld)) {
				var dci = dc[tld];
				if(dci.hasOwnProperty(type))
					return;
			}
		}
	}
	var ds = "c=admin&t=regapi&oper=action&action=pricing&name=" + apiprofile + "&for=" + type + "&tld=" + encodeURIComponent(tld);
	ajax_call(ds, gotDomainPrice, null);
}

function gotDomainPrice(x, jqXHR, textStatus, params) {
    if(x != null) {
		if(x.status == 'ok' && x.tld != "" && x.data.length) {
			var api = x.api;
			var type = x.for;
			var tld = x.tld;
			var dci = [];
			var pd = x.data;
			for(var i = 0; i < pd.length; i++) {
				dci.push( (i+1) + 'yr: ' + pd[i].actual_total_cost.toFixed(2));
			}
			if(!domain_costs.hasOwnProperty(api))
				domain_costs[api] = {};
			if(!domain_costs[api].hasOwnProperty(tld)) {
				domain_costs[api][tld] = {};
			}
			if(!domain_costs[api][tld].hasOwnProperty(type)) {
				domain_costs[api][tld][type] = [];
			}
			domain_costs[api][tld][type] = dci;
			domain_costs[api][tld]['currency'] = pd[0]['currency'];
			showDomainCosts();
			if(typeof x.domain != "undefined" && $('#register_new').val() == x.domain) {
				$('#register-costdata').html(pd[0]['currency'] + " " + dci.join(", "));
				$('#domain-register-costdata').html(x.domain);
			}
			if(typeof x.domain != "undefined" && $('#domain_to_renew').val() == x.domain) {
				$('#renew-costdata').html(pd[0]['currency'] + " " + dci.join(", "));
				$('#domain-renew-costdata').html(x.domain);
			}
		}
		else {
			// x.error
		}
	}
	else {
	}
}

function showDomainCosts() {
	var row = "";
	for(var profile in domain_costs) {
		if(domain_costs.hasOwnProperty(profile)) {
			for(var tld in domain_costs[profile]) {
				if(domain_costs[profile].hasOwnProperty(tld)) {
					for(var type in domain_costs[profile][tld]) {
						if(type !== "currency" && domain_costs[profile][tld].hasOwnProperty(type) && domain_costs[profile][tld][type].length)
							row += "<p>" + profile + ":" + tld + ":" + type + ":" + domain_costs[profile][tld][type].join(", ") + "</p>";
					}
				}
			}
		}
	}
	$('#pricing').html(row);
}

function getBalance(profilename) {
	var ajax_url = "../api.php";
	datastr = "c=admin&t=regapi&oper=action&action=balance&name=";
	datastr += encodeURIComponent(profilename);
	var request = $.ajax({type: "POST",	url: ajax_url, data: datastr});
	request.done(function(msg) {  
		var x = ajax_parse(msg);
		showBalance(x, null, null, null);
	});
	request.fail(function(jqXHR, textStatus) {
		showBalance(null, jqXHR, textStatus, null);
	});
}

function showBalance(x, jqXHR, textStatus, params) {
    if(x != null) {
		if(x.status == 'ok') {
			$('#balance').html(x.data.currency + ' <b>' + x.data.available_balance + '</b>');
		}
		else {
			// x.error
		}
	}
	else {
	}
}


// Prevent outer parent from scrolling when the thumbwheel 
// has reached the end of the child scroll limit.
function disableThumbwheelParentScroll() {
	$(document).on('DOMMouseScroll mousewheel', '.Scrollable', function(ev) {
		var $this = $(this),
			scrollTop = this.scrollTop,
			scrollHeight = this.scrollHeight,
			height = $this.innerHeight(),
			delta = (ev.type == 'DOMMouseScroll' ?
				ev.originalEvent.detail * -40 :
				ev.originalEvent.wheelDelta),
			up = delta > 0;

		var prevent = function() {
			ev.stopPropagation();
			ev.preventDefault();
			ev.returnValue = false;
			return false;
		}

		if (!up && -delta > scrollHeight - height - scrollTop) {
			// Scrolling down, but this will take us past the bottom.
			$this.scrollTop(scrollHeight);
			return prevent();
		} else if (up && delta > scrollTop) {
			// Scrolling up, but this will take us past the top.
			$this.scrollTop(0);
			return prevent();
		}
	});
}

function iconPath(nicon) {
	return 'images/' + current_theme_name + '/' + nicon + '@128px.png';
}

function fixDivSizes() {
}

function domainDataRowSelected(rowid) {
	var data = DataTableView.getTable('domaindatatable').options.data;
	if(data) {
		for(var i = 0; i < data.length; i++) {
			if(data[i].id == rowid) {
				var domaindata = data[i];
				$('#currentdomain').html(domaindata.domain);
				$('#domain_to_renew').val(domaindata.domain);
				current_domain = domaindata.domain;
				$('#nsdata').val('');
				var ds = "c=admin&t=regapi&oper=action&action=getns&name=" + current_profile + "&domain=" + domaindata.domain;
				ajax_call(ds, showDomainNSInfo, domaindata.domain);
				showRegistrationData();
				showDomainCosts();
			}
		}
	}
}

function loadRegistrationData() {
	if(current_registration_data) {
		for(var key in current_registration_data) {
			if(current_registration_data.hasOwnProperty(key) && key != "DomainName") {
				var value = $('#' + key).val();
				current_registration_data[key] = value;
			}
		}
	}
}

function showRegistrationData() {
	var ddata = "";
	if(current_registration_data) {
		for(var key in current_registration_data) {
			if(current_registration_data.hasOwnProperty(key) && key != "DomainName") {
				ddata += "<div class=\"break\">";
				ddata += "<label for=\"" + key + "\">" + key + "</label>";
				if(key == "Nameservers") {
					var ns = current_registration_data[key];
					ns = ns.split(",").join("\n");
					ddata += '<textarea id="' + key + '" name="' + key + '" placeholder="' + key + '">' + ns + '</textarea>';
				}
				else {
					ddata += '<input type="text" id="' + key + '" name="' + key + '" placeholder="' + key + '"' + ' value="' + current_registration_data[key] + '">';
				}
				ddata += "</div>";
			}
		}
		$('#regdata').html(ddata);
	}
}

function showDomainCheckData(x, jqXHR, textStatus, params) {
	if(x != null) {
		if(x.status == 'ok') {
			domaincheckresults = x.data;
			for(var i = 0; i < x.data.length; i++) {
				var domain = x.data[i].domain;
				avail_checked_domains[domain] = x.data[i];
			}
			var html = "";
			for(var d in avail_checked_domains) {
				if(avail_checked_domains.hasOwnProperty(d)) {
					var classname = 'available';
					if(avail_checked_domains[d].available == "false") {
						classname = 'not-available';
					}
					if(avail_checked_domains[d].is_premium_name == "true") {
						classname += '-premium';
					}
					classname += " domaincheck";
					html += '<li id="dc-' + d + '" class="' + classname + '">' + d + '</li>';
				}
			}
			$('#domainstatus').html(html);
		}
		else {
			// x.error
		}
	}
	else {
	}
}

function showDomainInfo(x, jqXHR, textStatus, params) {
	if(x != null) {
		if(x.status == 'ok') {
			current_registration_data = x.data;
			showRegistrationData();
		}
		else {
			// x.error
		}
	}
	else {
	}
}

function showDomainNSInfo(x, jqXHR, textStatus, params) {
	if(x != null) {
		if(x.status == 'ok') {
			var nsdata = "";
			for(var i = 0; i < x.data.length; i++) {
				nsdata += x.data[i] + "\n";
			}
			$('#nsdata').val(nsdata);
		}
		else {
			// x.error
		}
	}
	else {
	}
}

function initDomainDataTable() {
	let columndata = [
		{name:'serial', label:'#',width:{default:48},resize:true},
		{name:'cb', label:'', width:{default:24}, resize:false, type: 'cb'},
		{name:'domain', label:'Domain', width:{default:'auto', min: 150}, resize: true, sortable: true, search:{type: 'text'}},
		{name:'tld', label:'TLD', width:{default: 80}, resize: true, sortable: true, search:{type: 'text'}},
		//{name:'registry_expiry', label:'Registry Expiry', width:{default: 150}, resize: true, sortable: true, search:{type: 'text'}},
		{name:'registrar_expiry', label:'Registrar Expiry', width:{default: 150}, resize: true, sortable: true, search:{type: 'text'}},
		{name:'api_profile', label:'Profile', width:{default: 110}, resize: true, sortable: true, search:{type: 'text'}}
	];
	var source = {type: 'ajax', params: {url:'../api.php', data: 'c=grid&t=domain&columns=sid,domain,tld,registry_expiry,registrar_expiry,api_profile'}};
	var footer = [{role:'separator'},{role:'copy'},{role:'download'},{role:'separator'},{role:'refresh'}];
	var handlers = {resize: fixDivSizes, select: domainDataRowSelected, iconPath: iconPath, ajaxData: tableDataReceived};
	new DataTableView('domaindatatable', {columns:columndata, source:source, parent: 'dtablewrapper', footer: footer, handlers:handlers, sort: 'domain', sortorder: 'desc', count: 100});
}

function tableDataReceived(tdata) {
	if(tdata) {
	}
}

function ajax_call(datastr, callbackFn, param) {
	var ajax_url = "../api.php";
	var request = $.ajax({type: "POST",	url: ajax_url, data: datastr});
	request.done(function(msg) {  
		var x = ajax_parse(msg);
		if(typeof x.validate != "undefined") {
			if(x.validate == 1)
				sessionRestart("auth_error_session_timeout");
			else if(x.validate == -1 || x.validate == -2)
				sessionRestart("notloggedin");
		}
		callbackFn(x, null, null, param);
	});
	request.fail(function(jqXHR, textStatus) {
		callbackFn(null, jqXHR, textStatus, param);
	});
}

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

function sessionRestart(reason)
{
	var location = "../?logout&return=toolbox";
	window.location = location;
}


function ajax_parse(msg) {
	try {
		x = jQuery.parseJSON(msg);
		return x;
	}
	catch(err) {
		console.log('Error: JSON Parser');
	}
	return [];
}
