var default_category_selection = 1;
var categoryNames = [];

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

var last_category_edit_row = -1;
var last_domain_edit_row = -1;

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

function LoadDomainCategoryGrid()
{
	var datastr = get_ajax_datastr("grid", "category", "");
	jQuery("#domaincategorytable").jqGrid({
		hidegrid: false,
		height: 400,
		width: 150,
		altRows:true,
		autoencode: false,
		altclass: "category_grid_alt_row",
		url: base_grid_ajax_url + "?" + datastr + "&columns=cid,caticon,name,dcount,sortindex", 
		editurl: base_grid_ajax_url + "?" + datastr, 
		datatype: "json",
		colNames:['Category Name','','#','SortIndex'],
		colModel:[
			{name:'name', width:118,sortable:false,editable:true,editoptions:{size:35}, classes:"dccell category-name-cell"},
			{name:'caticon', width:32,sortable:false,editable:false,search: false,formatter:'categoryFormatter',fixed:true, align:'left', classes:"dccell category-icon-cell"},
			{name:'dcount', width:60,search:false,sortable:false,editable:false, fixed: true, align:'left',classes:"dccell category-count-cell"},
			{name:'sortindex', hidden: true}
		],
		rowNum:1000,
		rowList:[],
		rownumWidth: 50,
		rownumbers: true,
		viewrecords: false,
		caption:"",
		multiselect: false,
		pager: "#domaincategorytablepager",
		scrollOffset:18,
		sortname: 'sortindex',
		sortorder: 'asc',
		scroll:1,
		shrinkToFit: true,
		loadError: function (jqXHR, textStatus, errorThrown) 
		{
			gridSessionTimedoutError(jqXHR);
		},
		onSelectRow: function(ids) 
		{
			if(ids == null) 
				ids = 0;
			var cid = getCookieInt('current_category', 0);
			if(cid != ids && ids > 0)
				selectCategory(ids);
			if(ids && last_category_edit_row != ids) {
				jQuery('#domaincategorytable').restoreRow(last_category_edit_row);
				last_category_edit_row = -1;
			}
		},
		beforeSelectRow: function(rowid, e) 
		{
			if ($(this).getGridParam('selrow') == rowid) 
				return false;
			else
				return true;
        },
		loadComplete : function () 
		{
			if ($('#domaintable').length)
				show_selected_domain_info();
			categoryNames = [];
			var cats = jQuery('#domaincategorytable').getDataIDs();
			for(i = 0;i < cats.length; i++) {
				var rowData = jQuery('#domaincategorytable').getRowData(cats[i]); 
				categoryNames[cats[i]] = rowData['name'];
			}
			initQueries();
        },
		gridComplete : function()
		{
			var cc = getCookieInt('current_category', 0);
			$("#domaincategorytable").setGridParam({scrollrows:false}); 
			$("#domaincategorytable").setSelection(cc, true);
			scrollToRow($("#domaincategorytable"), cc);
			if ($('#domaintable').length)
				setDomainTableCaption();
		},
		ondblClickRow: function () {
            var row_id = $("#domaincategorytable").getGridParam('selrow');
			if(row_id && last_category_edit_row != row_id) {
				jQuery('#domaincategorytable').restoreRow(last_category_edit_row);
				last_category_edit_row = row_id;
			}
			if(bit_test(user_access_rights, ALLOW_CATEDIT_BITPOS) && grid_enable_inline_edit)
				jQuery('#domaincategorytable').editRow(row_id, true);
        }
	});
	
	jQuery("#domaincategorytable").jqGrid(
		'filterToolbar',{
			stringResult: true,
			searchOnEnter : false
		}
	);
	
	var allowedit = (allow_category_edit() && !is_an_admin_user()) ? true : false;
	jQuery("#domaincategorytable").navGrid('#domaincategorytablepager', {add:allow_category_add(),edit:allowedit,del:allow_category_delete(),search:false},
	{	// Edit
		width: 'auto',
		viewPagerButtons: false,
		closeOnEscape:true,
		afterShowForm: function(form) 
		{
			centerDialog('editmoddomaincategorytable');
		},
		resize: false,
		beforeShowForm: function(form)
		{
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
		}
	},
	{	// Add
		width: 'auto',
		closeOnEscape:true,
		closeAfterAdd: true,
		resize: false,
		afterShowForm: function(form) 
		{
			centerDialog('editmoddomaincategorytable');
		},
		beforeShowForm: function(form)
		{
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
		}
	},
	{	// Delete
		width: 'auto',
		closeOnEscape:true,
		resize: false,
		afterShowForm: function(form) 
		{
			centerDialog('delmoddomaincategorytable');
		},
		beforeShowForm: function(form)
		{
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
		}
	}
	);
	
	if(allow_category_edit() && is_an_admin_user()) {
		jQuery("#domaincategorytable").navButtonAdd('#domaincategorytablepager',
		{
			caption:"", 
			buttonicon:"ui-icon-pencil", 
			onClickButton: function()
			{ 
				var cid = getCookieInt('current_category', 0);
				if(cid == 1)
					cid = 0;
				init_cateditor_for(cid);
				showPanel("panel-cateditor", 'right');
			}, 
			position: "first"
		});
		
		addCategoryOrderButtons();
	}
	
	jQuery("#domaincategorytable").jqGrid('setLabel', 'caticon', '<img src="lib/layouts/images/icons/16/header.png" width="10" height="14">');
}

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

function LoadDomainQueryGrid()
{
	var datastr = get_ajax_datastr("grid", "query", "");
	jQuery("#domainquerytable").jqGrid({
		hidegrid: false,
		height: 400,
		width: 451,
		altRows:true,
		autoencode: false,
		altclass: "category_grid_alt_row",
		url: base_grid_ajax_url + "?" + datastr + "&columns=id,name,qicon,query,params,sortindex", 
		editurl: base_grid_ajax_url + "?" + datastr,
		datatype: "json",
		colNames:['Auto Queries', '', 'Query', 'Parameters','Sort Index'],
		colModel:[
			{name:'name', width: 118,sortable:true,editable:true, editoptions:{size:50}, formoptions:{label: 'Name'}, classes:"aqcell auto-name-cell"},
			{name:'qicon', width:32,sortable:false,editable:false,search: false,formatter:'categoryFormatter',fixed:true, align:'left', classes:"aqcell auto-icon-cell"},
			{name:'query', width: 118,sortable:true,editable:true, editoptions:{rows:'4',cols:'50'}, formoptions:{label: 'Query'}, editrules:{edithidden:true}, hidden: true, edittype: 'textarea', classes:"aqcell auto-query-cell"},
			{name:'params', width: 118,sortable:true,editable:true, editoptions:{rows:'4',cols:'50'}, formoptions:{label: 'Parameters'}, editrules:{edithidden:true}, hidden: true, edittype: 'textarea', classes:"aqcell auto-params-cell"},
			{name:'sortindex', hidden: true}
		],
		rowNum:1000,
		rowList:[],
		rownumWidth: 50,
		rownumbers: true,
		viewrecords: false,
		caption:"",
		multiselect: false,
		pager: "#domainquerytablepager",
		scrollOffset:18,
		sortname: 'sortindex',
		sortorder: 'asc',
		shrinkToFit: true,
		scroll:1,
		loadError: function (jqXHR, textStatus, errorThrown) 
		{
			gridSessionTimedoutError(jqXHR);
		},
		onSelectRow: function(ids) 
		{
			if(ids == null) 
				ids = 0;
			selectAutoQuery(ids);
		},
		beforeSelectRow: function(rowid, e) 
		{
			if ($(this).getGridParam('selrow') == rowid) 
				return false;
			else
				return true;
        },
		loadComplete : function () 
		{
        },
		gridComplete : function()
		{
			var cc = getCookieInt('current_autoquery', 0);
			$("#domainquerytable").setGridParam({scrollrows:false});
			$("#domainquerytable").setSelection(cc, true);
			scrollToRow($("#domainquerytable"), cc);
		}
	});
	
	jQuery("#domainquerytable").jqGrid(
		'filterToolbar',{
			stringResult: true,
			searchOnEnter : false
		}
	);
	
	jQuery("#domainquerytable").navGrid('#domainquerytablepager', {add:allow_autoquery_add(),edit:allow_autoquery_edit(),del:allow_autoquery_delete(),search:false},
	{	// Edit
		width: 'auto',
		resize: false,
		viewPagerButtons: false,
		closeOnEscape:true,
		afterShowForm: function(form) 
		{
			centerDialog('editmoddomainquerytable');
		},
		afterComplete : function (response, postdata, formid)
		{
			var aqid = getCookieInt('current_autoquery', 0);
			if(aqid > 0)
			{
				scrollToRow($("#domainquerytable"), aqid);
			}
		},
		beforeShowForm: function () 
		{
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
		}
	},
	{	// Add
		width: 'auto',
		closeAfterAdd: true,
		closeOnEscape:true,
		resize: false,
		afterShowForm: function(form) 
		{
			centerDialog('editmoddomainquerytable');
		},
		beforeShowForm: function () 
		{
			$('<span class="pull-left"<a href="#"><span class="ui-icon ui-icon-newwin"></span>Help</a></span>')
			.click(function() 
			{
				window.open (app_root_url + "?link=guide");
			}).addClass("fm-button ui-state-default ui-corner-all fm-button-icon-left")
			  .prependTo("#Act_Buttons>td.EditButton");  
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
		}
	},
	{	// Delete
		width: 'auto',
		closeOnEscape:true,
		resize: false,
		afterShowForm: function(form) 
		{
			centerDialog('delmoddomainquerytable');
		},
		beforeShowForm: function () 
		{
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
		}
	}
	);
	
	if(allow_autoquery_edit()) {
		addReOrderButtons('domainquerytable');
	}
}

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

function addCategoryOrderButtons()
{
	addReOrderButtons('domaincategorytable');
	/*
	$("#domaincategorytable").navSeparatorAdd("#domaincategorytablepager",{})
	.navButtonAdd('#domaincategorytablepager', {
		caption:"", 
		buttonicon:"ui-icon-arrowthick-1-n", 
		onClickButton: function() { 
			moveCategoryUpDown(-1);
		},
		position:"last",
		title:'Move Category Up'
	});
	
	$("#domaincategorytable")
	.navButtonAdd('#domaincategorytablepager', {
		caption:"", 
		buttonicon:"ui-icon-arrowthick-1-s", 
		onClickButton: function() { 
			moveCategoryUpDown(1);
		},
		position:"last",
		title:'Move Category Down'
	});
	*/
}

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

function addReOrderButtons(table)
{
	var target = "category";
	if(table == "domainquerytable")
		target = "query";
	$("#"+table).navSeparatorAdd("#" + table + "pager",{})
	.navButtonAdd('#'+table+'pager', {
		caption:"", 
		buttonicon:"ui-icon-arrowthick-1-n", 
		onClickButton: function() { 
			moveCategoryUpDown(target,-1);
		},
		position:"last",
		title:'Move Item Up'
	});
	
	$("#"+table)
	.navButtonAdd('#'+table+'pager', {
		caption:"", 
		buttonicon:"ui-icon-arrowthick-1-s", 
		onClickButton: function() { 
			moveCategoryUpDown(target,1);
		},
		position:"last",
		title:'Move Item Down'
	});
}

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

function ajax_category_sort(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			if(x.target == "category") {
				$("#domaincategorytable").trigger("reloadGrid"); 
				setTimeout(function(){
				  $("#domaincategorytable").setSelection(x.id, false);
				},500);
			}
			else {
				$("#domainquerytable").trigger("reloadGrid"); 
				setTimeout(function(){
				  $("#domainquerytable").setSelection(x.id, false);
				},500);
			}
		}
		else {
			
		}
	}
	else {
	}
}

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

function moveCategoryUpDown(target,incr)
{
	var cid = getCookieInt('current_category', 0);
	if(target == "query")
		cid = getCookieInt("current_autoquery", 0);
	if(cid != 0 && cid != 1) {
		//var datastr = "c=set&t=" + target + "&oper=sort";
		var datastr = get_ajax_datastr("set", target, "sort");
		datastr += "&id=" + cid + "&pos=" + incr;
		ajax_call(datastr, ajax_category_sort, null);
	}
}

