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

var reports_table_jqgrid         = null;
var current_report_colmodel      = [];

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

var user_access_rights = parseInt(user_details['rights']);
var base_grid_ajax_url = app_root_url + api_url_path;

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

function LoadReportsGrid(preservepage)
{
	selected_page_for_reload = 0;
	gridunloaded = false;
	if(reports_table_jqgrid != null) {
		if(preservepage)
			selected_page_for_reload = $('#reportstable').jqGrid('getGridParam', 'page');
		reports_table_jqgrid.GridUnload();
		gridunloaded = true;
	}
	var durl = getReportsDataURL(current_report_colmodel);
	
	var ww = $(window).width();
	var rowsperpage = getCookieInt('report_rows_per_page', 100);
	var rowlist = [10,50,100,250,500,1000,2000];
	if(jQuery.inArray(rowsperpage, rowlist) < 0)
		rowsperpage = 100;
	var viewrecords = true;
	var pginput = true;
	
	if(ww <= 767) {
		viewrecords = false;
		rowlist = [];
		pginput = false;
	}
	
	
	var datastr = get_ajax_datastr("grid", "domain", "");
	var sortname = getCookie('current_rsort_column', "d.sid");
	var sortorder = getCookie('current_rsort_order', "desc");
	reports_table_jqgrid = jQuery("#reportstable").jqGrid(
	{
		height: $("#domainpane").height()-120,
		width: $("#domainpane").width()-24,
		altRows:true,
		hidegrid: false,
		altclass: "domain_grid_alt_row",
		url: durl,
		editurl: base_grid_ajax_url + "?" + datastr,
		shrinkToFit: false,
		pager: "#reportstablepager",
		jsonReader : {repeatitems: false},
		rownumWidth: 50,
		rowList: rowlist,
		datatype: "json",
		sortname: sortname,
		sortorder: sortorder,
		colModel: current_report_colmodel,
		rowNum: rowsperpage,
		rownumbers: true,
		viewrecords: viewrecords,
		mtype: 'POST',
		multiselect: true,
		multiboxonly: true,
		gridView: true,
		pginput: pginput,
		caption: getCookie('current_report', "Subdomain Records"),
		recordtext: "{0} - {1} of {2}",
		sortable: {
			options: {
				stop: function(event, ui) {
					save_current_column_model();
				},
				items: ">th:not(:has(#jqgh_reportstable_cb,#jqgh_reportstable_rn,#jqgh_reportstable_r_h_disp),:hidden)"
		   }
		},
		onSortCol: function (index, columnIndex, sortOrder) {
			save_current_column_model();
		},
		loadComplete : function () 
		{
			if(selected_page_for_reload > 1)
			{
				var cpage = selected_page_for_reload;
				selected_page_for_reload = 0;
				if (this.p.datatype === 'json') 
				{
					setTimeout(function() {$("#reportstable").trigger("reloadGrid",[{page:cpage}]);}, 50);
					return;
				}
			}
			//reportsGridLoadComplete();
        },
		gridComplete : function()
		{
			// Cookie the sort column and order
			var sort_column = $("#reportstable").jqGrid('getGridParam','sortname');
			var sort_order  = $("#reportstable").jqGrid('getGridParam','sortorder');
			saveCookie('current_rsort_column', sort_column);
			saveCookie('current_rsort_order', sort_order);
			var rowsperpage = $("#reportstable").jqGrid('getGridParam','rowNum');
			saveCookie('report_rows_per_page', rowsperpage);
		},
		onPaging: function (pgButton) {
		},
		onSelectAll: function(ids, status)
		{
		},
		onSelectRow: function(ids) 
		{
		},
		loadError: function (jqXHR, textStatus, errorThrown) 
		{
			gridSessionTimedoutError(jqXHR);
		},
		beforeRequest: function() 
		{
		},
		ondblClickRow: function () {
        },
		resizeStop: function(newwidth, index) {
			var cm = $("#reportstable").jqGrid('getGridParam','colModel');
			$("#reportstable").jqGrid('setColProp',cm[index].name,{width:newwidth});
			if(bit_test(user_access_rights, ALLOW_UICHANGE_BITPOS)) {
				var datastr = get_ajax_datastr("admin", "domain", "set");
				datastr += "&width=" + newwidth + "&name=" + cm[index].name;
				ajax_call(datastr, ajax_dummy_return, null);
			}
		}
	});
	
	jQuery("#reportstable").navGrid('#reportstablepager', {add:false,edit:false,del:false,search:false,view:false,refreshstate:'current'});
	
	jQuery("#reportstable").jqGrid(
		'filterToolbar',{
			stringResult: true,
			searchOnEnter : grid_search_on_enter,
			autosearchDelay: grid_auto_search_delay
		}
	);
	
	if(gridunloaded) {
		var fs = getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE);
		setTableFontSize(fs);
	}
	
	centerGridTitle("reportstable");
	
	jQuery("#reportstable").jqGrid('setLabel', 'availability', '<img src="lib/layouts/images/icons/fields/avail-head.png" width="12" height="14">');
	jQuery("#reportstable").jqGrid('setLabel', 'page_token_found', '<img src="lib/layouts/images/icons/fields/htmltoken-head.png" width="12" height="14">');
}

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

function getReportsDataURL(datacolumns)
{
	var sortname = getCookie('current_rsort_column', "d.sid");
	var found_sort_col = false;
	var colnum = datacolumns.length;
	var datastr = get_ajax_datastr("grid", "domain", "");
	var durl = base_grid_ajax_url + "?" + datastr + "&columns=sid,";
	for(i = 0; i < colnum; i++) {
		if(datacolumns[i].name != "rn" && datacolumns[i].name != "cb") {
			durl += encodeURIComponent(datacolumns[i].name);
			durl += ",";
			if(sortname != "" && sortname == datacolumns[i].name)
				found_sort_col = true;
		}
	}
	// Make sure that the sort column is in the column list.
	// Otherwise set the sort column to blank
	if(!found_sort_col)
		saveCookie('current_rsort_column', "");
	
	var report_name = getCookie('current_report', "Subdomain Records");
	var hd = getCookieInt('domain_highlight_days', 30);
	durl += "&highlight=" + hd;
	durl += "&_repname=" + encodeURIComponent(report_name);
	
	var aqid = getCookieInt('current_autoquery', 0);
	var cid = getCookieInt('current_category', 0);
	var hd = getCookieInt('domain_highlight_days', 30);
	if(cid > 0) {
		durl += "&cid=" + cid;
		$("#domainquerytable").resetSelection();
	}
	else if(aqid > 0) {
		$("#domaincategorytable").resetSelection();
		durl += "&aqid=" + aqid;
	}
	else if(custom_query_in_use) {
		durl += "&" + getCustomQueryData();
		$("#domainquerytable").resetSelection();
		$("#domaincategorytable").resetSelection();
	}
	durl += "&highlight=" + hd;
	
	return durl;
}

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

function getColModelFromGroupName(dgroup)
{
	return window[dgroup];
}

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

function save_current_column_model()
{
	if(bit_test(user_access_rights, ALLOW_UICHANGE_BITPOS)) {
		var dgroup = getCookie('current_report', "Subdomain Records");
		var colmodel = $("#reportstable").jqGrid('getGridParam','colModel');
		var colsetup = "";
		for(var i = 0; i < colmodel.length; i++) {
			if(colmodel[i].name != "r_h_disp" && colmodel[i].name != "rn" && colmodel[i].name != "cb") {
				if(colsetup != "")
					colsetup += ";" + colmodel[i].name;
				else
					colsetup += colmodel[i].name;
			}
		}
		var sortColumnName = $("#reportstable").jqGrid('getGridParam','sortname');
		var sortOrder = $("#reportstable").jqGrid('getGridParam','sortorder');
		
		var datastr = get_ajax_datastr("set", "report", "colmodel");
		datastr += "&group=" + encodeURIComponent(dgroup);
		datastr += "&columns=" + encodeURIComponent(colsetup);
		//datastr += "&sidx=" + encodeURIComponent(sortColumnName);
		//datastr += "&sord=" + encodeURIComponent(sortOrder);
		ajax_call(datastr, ajax_dummy_return, dgroup); 
	}
}

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

function clearSearchFilter()
{
    var grid = $("#reportstable");
    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 selectCustomQuery(flag)
{
	$.cookie('current_category', "0");
	$.cookie('current_autoquery', "0");
	custom_query_in_use = flag;
	var durl = getReportsDataURL(current_report_colmodel);
	jQuery("#reportstable").setGridParam({url:durl});
	$("#reportstable").trigger("reloadGrid");  
	//setDomainTableCaption();
}

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

function selectCategory(ids)
{
	$.cookie('current_category', String(ids));
	$.cookie('current_autoquery', "0");
	custom_query_in_use = false;
	var durl = getReportsDataURL(current_report_colmodel);
	jQuery("#reportstable").setGridParam({url:durl});
	$("#reportstable").trigger("reloadGrid");  
	//setDomainTableCaption();
}

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

function selectAutoQuery(ids)
{
	if(ids == null) 
		ids = 0;
	$.cookie('current_category', "0");
	$.cookie('current_autoquery', String(ids));
	custom_query_in_use = false;
	clearSearchFilter();
	var durl = getReportsDataURL(current_report_colmodel);
	jQuery("#reportstable").setGridParam({url:durl});
	$("#reportstable").trigger("reloadGrid");  
	$("#domaincategorytable").resetSelection();
	//setDomainTableCaption();
}
