$(function()
{
	var reportname = getCookie('current_report', "Subdomain Records");
	selectReport(reportname);
	
	$('.btn-report').click(function(event){
		event.preventDefault();
		var cpid = $(this).attr('id');
		var id = parseInt(cpid.replace("btn-report-", "")) - 1;
		if(id >= 0 && id < report_col_models.length) {
			selectReport(report_col_models[id]);
			//$('.btn-report').removeClass('btn-selected');
			//jQuery(this).addClass('btn-selected');
		}
	});
	
	$('#reportpreview-new').click(function(event){
		event.preventDefault();
		var reportname = getCookie('current_report', "Subdomain Records");
		var url = base_grid_ajax_url + "?c=report&name=" + encodeURIComponent(reportname);
		window.open(url,'_blank');
	});
	
	$('#reportpreview').click(function(event){
		event.preventDefault();
		var reportname = getCookie('current_report', "Subdomain Records");
		popup_report(reportname);
	});
	
	$('#emailreport').click(function(event){
		event.preventDefault();
		var reportname = getCookie('current_report', "Subdomain Records");
		email_report(reportname);
	});
	
	setupTableColumns('tablecolumns');
	$( "#reportlist" ).sortable({
		handle: ".handle",
        stop: function(event, ui) {
			reportsetup_sortorder();
		}
	}).find("li").addClass( "ui-corner-all" );
	make_list_selectable("reportlist", "report_selector_selected");
});

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

function popup_report(reportname)
{
	var datastr = get_ajax_datastr("get", "report", "preview");
	datastr += "&name=" + encodeURIComponent(reportname);
	ajax_call(datastr, ajax_popup_report, null);
}

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

function ajax_popup_report(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			$('#preview-body').css('overflow-x', 'auto');
			$('#preview-heading').hide();
			$('#preview-heading').html("");
			$('#preview-title').html("Report Preview");
			$('#preview-report').html(x.report);
			showPanel('panel-preview-popup', 'left');
		}
	}
}

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

function email_report(reportname)
{
	var datastr = get_ajax_datastr("admin", "email", "report");
	datastr += "&name=" + encodeURIComponent(reportname);
	ajax_call(datastr, ajax_email_report, null);
}

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

function ajax_email_report(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			showAlert("Email was sent");
		}
		else {
			showAlert("Email was not sent, please check the error logs and or email setup.");
		}
	}
}

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

function selectReport(reportname)
{
	var datastr = get_ajax_datastr("get", "report", "colmodel");
	datastr += "&group=" + encodeURIComponent(reportname);
	ajax_call(datastr, ajax_init_reports, null);
}

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

function init_panel_reportsetup()
{
	$('#reportsetup-error').html('');
	var reportname = getCookie('current_report', "Subdomain Records");
	$('#reportsetup-name').html(reportname);
	
	var datastr = get_ajax_datastr("admin", "report", "get");
	datastr += "&_repname=" + encodeURIComponent(reportname);
	
	var aqid = getCookieInt('current_autoquery', 0);
	var cid = getCookieInt('current_category', 0);
	if(cid > 0) 
		datastr += "&cid=" + cid;
	else if(aqid > 0) 
		datastr += "&aqid=" + aqid;
	else if(custom_query_in_use) 
		datastr += "&" + getCustomQueryData();
	
	ajax_call(datastr, ajax_init_reportsetup, null);
}

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

function ajax_init_reportsetup(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			$('#reportsetup-query').val(x.query);
			$('#reportsetup-params').val(x.params);
			$('#reportsetup-gquery').val(x.gquery);
			$('#reportsetup-gparams').val(x.gparams);
			if( (x.query == x.gquery || ('(' + x.query + ')' == x.gquery)) &&  x.params == x.gparams) {
				$('#reportsetup-local').hide();
				$('#reportsetup-copy').hide();
			}
			else {
				$('#reportsetup-local').show();
				$('#reportsetup-copy').show();
			}
		}
	}
}

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

function reportsetup_copy()
{
	$('#reportsetup-error').html('');
	var query = $('#reportsetup-query').val();
	var params = $('#reportsetup-params').val();
	var gquery = $('#reportsetup-gquery').val();
	var gparams = $('#reportsetup-gparams').val();
	if( (x.query == x.gquery || ('(' + x.query + ')' == x.gquery)) &&  x.params == x.gparams) {
		$('#reportsetup-error').html('Nothing to copy');
	}
	else {
		$('#reportsetup-query').val(x.gquery);
		$('#reportsetup-params').val(x.gparams);
		$('#reportsetup-error').html("Please click 'Update' to save changes,'Cancel' to discard");
	}
}

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

function reportsetup_submit()
{
	var reportname = getCookie('current_report', "Subdomain Records");
	$('#reportsetup-name').html(reportname);
	
	var query = $('#reportsetup-query').val();
	query = replaceAll(query, "<", " LT ");
	query = replaceAll(query, "<=", " LE ");
	query = replaceAll(query, ">", " GT ");
	query = replaceAll(query, ">=", " GE ");
	
	var datastr = get_ajax_datastr("admin", "report", "set");
	datastr += "&name=" + encodeURIComponent(reportname);
	datastr += "&query=" + encodeURIComponent(query);
	datastr += "&params=" + encodeURIComponent($('#reportsetup-params').val());
	ajax_call(datastr, ajax_save_reportsetup, null);
}

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

function ajax_save_reportsetup(x, jqXHR, textStatus, params)
{
	if(x != null) {
		var cbdata = '';
		var list = '';
		var iconlist = '';
		if(x.status == 'ok') {
			$("#reportstable").trigger("reloadGrid"); 
		}
	}
}

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

function report_selector_selected(liid)
{
	var report_selected_index = parseInt(liid.replace("reportselector-id-", ""));
	var count = report_col_models.length;
	if(report_selected_index >= 0 && report_selected_index < count) {
		reportname = report_col_models[report_selected_index];
		selectReport(reportname);
	}
}

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

function show_current_report_button()
{
	$('.btn-report').removeClass('btn-selected');
	var reportname = getCookie('current_report', "Subdomain Records");
	var rindex = report_col_models.indexOf(reportname);
	if(rindex >= 0 && rindex < report_col_models.length) {
		var btnid = "btn-report-" + (rindex+1);
		$('#'+btnid).addClass('btn-selected');
	}
}

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

function reportsetup_sortorder()
{
	var repnames = [];
	var count = report_col_models.length;
	$('#reportlist' + ' li').each(function() {
		var rindex = $(this).attr('id').replace("reportselector-id-", "");
		if(rindex >= 0 && rindex < count) {
			reportname = report_col_models[rindex];
			repnames.push(reportname);
		}
	});
	var datastr = get_ajax_datastr("admin", "report", "sort");
	datastr += "&names=" + encodeURIComponent(repnames.join(","));
	ajax_call(datastr, ajax_reportsetup_sorting, null);
}

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

function ajax_reportsetup_sorting(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			report_col_models = x.reports;
			init_panel_reportselector();
			show_current_report_button();
		}
	}
}

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

function reportselector_before_popup()
{
	var ht = $('.panel-card-body').css('max-height');
	ht = parseInt(ht.replace("px", ""));
	var clht = ht -  $('#rl-legend-reportlist').height();
	if(clht > 320)
		clht = 320;
	$('#reportlist').css('height', clht);
}

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

function init_panel_reportselector()
{
	var lidata = "";
	var creport = getCookie('current_report', "Subdomain Records");
	var count = report_col_models.length;
	for(var i = 0; i < count; i++) {
		var reportname = report_col_models[i];
		if(creport == reportname)
			lidata += "<li id=\"reportselector-id-" + i + "\" class=\"list-group-item ui-selectee ui-selected ui-state-highlight\">";
		else
			lidata += "<li id=\"reportselector-id-" + i + "\" class=\"list-group-item ui-selectee\">";
		lidata += "<div class=\"handle\"><span class=\"ui-icon grip-drag-action-" + "button" + "\"></span></div>\n" + reportname + "</li>";
	}
	$('#reportlist').html(lidata);
}

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

function ajax_init_reports(x, jqXHR, textStatus, params)
{
	if(x != null) {
		var cbdata = '';
		var list = '';
		var iconlist = '';
		if(x.status == 'ok') {
			saveCookie('current_report', x.name);
			current_report_colmodel = x.colmodel;
			show_current_report_button();
			LoadReportsGrid(true);
			initSizing();
			var fs = getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE);
			setTableFontSize(fs);
		}
	}
}

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

function init_panel_columnsetup()
{
	cateditor_selected_id = 0;
	var datastr = get_ajax_datastr("list", "report", "columns");
	ajax_call(datastr, ajax_init_columnsetup, null);
}

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

function ajax_init_columnsetup(x, jqXHR, textStatus, params)
{
	var list = "";
	if(x != null) {
		if(x.status == 'ok') {
			var exists = [];
			var datacolumns = current_report_colmodel; //getColModelFromGroupName(params);
			var colnum = datacolumns.length;
			for(i = 0; i < colnum; i++) {
				if(datacolumns[i].name != "rn" && datacolumns[i].name != "cb") { // && datacolumns[i].name != "domain") {
					var key = datacolumns[i].name;
					label = datacolumns[i].label;
					exists.push(key);
					var custom = 'button';
					if(x.columns.hasOwnProperty(key)) 
						custom = parseInt(x.columns[key]['custom']) ? 'custom' : 'button';
					if(key !== 'r_h_disp' && key !== 's.r_h_disp') {
						list += "<li><div class=\"handle\"><span class=\"ui-icon grip-drag-action-" + custom + "\"></span></div>\n"; //  + label + "</li>";
						list += "<label for=\"cb-" + key + "\"><input id=\"cb-" + key + "\" type=\"checkbox\" checked>" + label + "</label></li>\n";
					}
				}
			}
			
			// Custom Columns
			for (var key in x.columns) {
				//if (key === 'length' || !x.columns.hasOwnProperty(key) || key == "domain") continue;
				//if (!x.columns.hasOwnProperty(key)) continue;
				if (key === 'length' || !x.columns.hasOwnProperty(key)) continue;
				var custom = parseInt(x.columns[key]['custom']);
				if(!custom) continue;
				if(exists.indexOf(key) >= 0 || exists.indexOf(key.replace("d.", "")) >= 0)
					continue;
				var label = x.columns[key]['label'];
				var ftype = x.columns[key]['fieldtype'];
				var gridview = parseInt(x.columns[key]['gridview']);
				var editable = parseInt(x.columns[key]['editable']);
				if(gridview != 0 && key != "r_h_disp" && key != "s.r_h_disp") {
					list += "<li><div class=\"handle\"><span class=\"ui-icon grip-drag-action-button grip-drag-action-custom\"></span></div>\n"; //  + label + "</li>";
					list += "<label for=\"cb-" + key + "\"><input id=\"cb-" + key + "\" type=\"checkbox\">" + label + "</label></li>\n";
				}
			}
			
			// Non Custom Columns
			for (var key in x.columns) {
				//if (key === 'length' || !x.columns.hasOwnProperty(key) || key == "domain") continue;
				if (!x.columns.hasOwnProperty(key)) continue;
				var custom = parseInt(x.columns[key]['custom']);
				if(custom) continue;
				if(exists.indexOf(key) >= 0 || exists.indexOf(key.replace("d.", "")) >= 0)
					continue;
				var label = x.columns[key]['label'];
				var ftype = x.columns[key]['fieldtype'];
				var gridview = parseInt(x.columns[key]['gridview']);
				var editable = parseInt(x.columns[key]['editable']);
				if(gridview != 0 && key != "r_h_disp" && key != "s.r_h_disp") {
					list += "<li><div class=\"handle\"><span class=\"ui-icon grip-drag-action-button\"></span></div>\n"; //  + label + "</li>";
					list += "<label for=\"cb-" + key + "\"><input id=\"cb-" + key + "\" type=\"checkbox\">" + label + "</label></li>\n";
				}
			}
		}
	}
	$('#tablecolumns').html(list);
}

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

function setupTableColumns(listid, sdmode)
{
	$( "#"+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() 
			{
			});
		}
	})
    .find("li").addClass( "ui-corner-all" );
}

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

function columnsetup_submit()
{
	var checkedIds = $("#tablecolumns :checkbox:checked").map(function() {
        return this.id;
    }).get();
	
	var dgroup = getCookie('current_report', "Subdomain Records");
	var datastr = get_ajax_datastr("set", "report", "colmodel");
	datastr += "&group=" + encodeURIComponent(dgroup);

	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 += ";";
	}
	$('#columnsetup-error').html("");
	datastr += "&columns=" + encodeURIComponent(colsetup);
	ajax_call(datastr, ajax_columnsetup_done, dgroup); 
}

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

function ajax_columnsetup_done(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			window[params] = x.colmodel;
			hidePanelWithId("panel-columnsetup");
			current_report_colmodel = x.colmodel;
			LoadReportsGrid(true);
			initSizing();
			var fs = getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE);
			setTableFontSize(fs);
		}
		else
			$('#columnsetup-error').html(x.error);
	}
}

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

function columnsetup_reset()
{
	var dgroup = getCookie('current_report', "Subdomain Records");
	var datastr = get_ajax_datastr("set", "report", "colmodel");
	datastr += "&group=" + encodeURIComponent(dgroup);
	datastr += "&columns=";
	ajax_call(datastr, ajax_columnsetup_done, dgroup); 
}