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

var app_current_url = '';

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

$(function()
{
	initButtons();
	app_current_url = window.location.href.replace(app_root_url, "");
	if(typeof user_details != "undefined") {
		if(user_details['rights'] != 65535)
			$('.opt-admin').hide();
		if(!allow_category_edit())
			$('.opt-catedit').hide();
		if(!allow_autoquery_edit())
			$('.opt-queryedit').hide();
		if(!allow_download()) 
			$('.opt-download').hide();
	}
});

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

function is_an_admin_user() {
	if(typeof user_details != "undefined") {
		if(user_details['rights'] == 65535) 
			return true;
	}
	return false;
}

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

function allow_download() {
	if(typeof user_details != "undefined") {
		var rights = user_details['rights'];
		if(rights == 65535 || (bit_test(rights, ALLOW_DOWNLOAD_BITPOS)))
			return true;
	}
	return false;
}

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

function allow_category_edit() {
	if(typeof user_details != "undefined") {
		var rights = user_details['rights'];
		if(rights == 65535 || (bit_test(rights, ALLOW_CATEDIT_BITPOS) && bit_test(rights, ALLOW_ALLDOMAINS_BITPOS)))
			return true;
	}
	return false;
}

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

function allow_category_add() {
	if(typeof user_details != "undefined") {
		var rights = user_details['rights'];
		if(rights == 65535 || (bit_test(rights, ALLOW_CATEDIT_BITPOS) && bit_test(rights, ALLOW_ALLDOMAINS_BITPOS) && bit_test(rights, ALLOW_ADD_BITPOS)))
			return true;
	}
	return false;
}

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

function allow_category_delete() {
	if(typeof user_details != "undefined") {
		var rights = user_details['rights'];
		if(rights == 65535 || (bit_test(rights, ALLOW_CATEDIT_BITPOS) && bit_test(rights, ALLOW_ALLDOMAINS_BITPOS) && bit_test(rights, ALLOW_DELETE_BITPOS)))
			return true;
	}
	return false;
}

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

function allow_autoquery_edit() {
	if(typeof user_details != "undefined") {
		var rights = user_details['rights'];
		if(rights == 65535 || (bit_test(rights, ALLOW_AQUERY_BITPOS) && bit_test(rights, ALLOW_ALLDOMAINS_BITPOS)))
			return true;
	}
	return false;
}

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

function allow_autoquery_add() {
	if(typeof user_details != "undefined") {
		var rights = user_details['rights'];
		if(rights == 65535 || (bit_test(rights, ALLOW_AQUERY_BITPOS) && bit_test(rights, ALLOW_ALLDOMAINS_BITPOS) && bit_test(rights, ALLOW_ADD_BITPOS)))
			return true;
	}
	return false;
}

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

function allow_autoquery_delete() {
	if(typeof user_details != "undefined") {
		var rights = user_details['rights'];
		if(rights == 65535 || (bit_test(rights, ALLOW_AQUERY_BITPOS) && bit_test(rights, ALLOW_ALLDOMAINS_BITPOS) && bit_test(rights, ALLOW_DELETE_BITPOS)))
			return true;
	}
	return false;
}

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

function getKeyByValue(object, value) {
  //return Object.keys(object).find(key => object[key] === value);
	for(var key in object) {
		if(object[key] === value) {
			return key;
		}
	}
	return false;
}

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

if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
        return this.substring(this_len - search.length, this_len) === search;
    };
}

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

function bit_test(num, bit){
    return ((num>>bit) % 2 != 0)
}

// This is a function that scrolls to $(selector)
function goToByScroll(parent, selector)
{
	var position = $(parent).offset();
	$(parent).scrollTop($(parent + ' li:nth-child(1)').position().top);
	if ($(selector).length )
		$(parent).animate({scrollTop: $(selector).offset().top-position.top-20}, 'fast');
}

// This is a function that scrolls to $(selector)
function showSelector(parent, selector)
{
	var position = $(parent).offset();
	$(parent).scrollTop($(parent + ' li:nth-child(1)').position().top);
	if ($(selector).length )
		$(parent).scrollTop($(selector).offset().top-position.top-20);
}

function reloadApp()
{
	var old_url = window.location.href;
	var new_url = old_url.substring(0, old_url.indexOf('?'));
	window.location.href = new_url;
}

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

function make_list_selectable(listid, callback)
{
	$('#'+listid).selectable({
		stop: function() {
			$('#' + listid + ' li').each(function() {
				$(this).removeClass('ui-state-highlight');
			});
			$( ".ui-selected", this ).each(function() {
				$(this).addClass('ui-state-highlight');
				if(callback != null) {
					var fnName = callback;
					try {
						if(typeof window[fnName] == "function")
							window[fnName]($(this).attr('id'));
					}
					catch(err) {
						console.log('Error: '+ fnName + ': ' + err);
					}
				}
			});
		},
		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');
        }
    });
}

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

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 centerGridTitle(gridid)
{
	var captionDiv = jQuery("#" + gridid)[0].grid.cDiv;
	var titleSpan = jQuery(".ui-jqgrid-title",captionDiv);
	titleSpan.css ("float", "none");
	titleSpan.parent().css ("text-align", "center");
}

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

function gridSessionTimedoutError(jqXHR)
{
	if(jqXHR.status == 408 || jqXHR.status == 400) {
		if(jqXHR.status == 408)
			sessionRestart("auth_error_session_timeout");
		else if(jqXHR.status == 400)
			sessionRestart("notloggedin");
		return true;
	}
	return false;
}

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

function setTableFontSize(fs)
{
	var hfs = fs-1;
	// Change the font size in the jqgrid (titlebar, grid and pager)
	$('.ui-jqgrid-btable').css('font-size', fs+'px');
	$('.ui-pg-table').css('font-size', fs+'px');
	$('.ui-jqgrid-htable').css('font-size', hfs+'px');
	$('.ui-search-input > input').css('font-size', fs+'px');
	// Change the Tab View font size.
	var tbfs = fs-1;
	$('#categorytab').css('font-size', tbfs+'px');
	$('#detailstab').css('font-size', tbfs+'px');
	$('.panel').css('font-size', fs+'px');
	
	$('.ui-jqdialog').css('font-size', fs+'px');
	$('.ui-autocomplete').css('font-size', fs+'px');
	$('.form-control').css('font-size', fs+'px');
	
	$('.ui-pg-table').css('font-size', (fs-2)+'px');
	$('.ui-jqgrid-title').css('font-size', (fs+1)+'px');
	$('.ui-dialog-titlebar').css('font-size', (fs+1)+'px');
	
	var bgposint = fs-13;
	if(bgposint > 3)
		bgposint = 3;
	var bgpos = '3px ' + bgposint.toString() + 'px';
	$('ul.list-group-flush li.list-group-item').css('background-position', bgpos);
	
	var dbfs = fs+2;
	$('.detailsbox').css('font-size', dbfs+'px');
}

function escapeRegExp(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

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

function isJson(str)
{
	if (typeof str !== 'string')
		return false;
	try {
		JSON.parse(str);
	}
	catch (e) {
		return false;
	}
	return true;
}

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

function initEnterKeyHandler(inpdiv, trigid)
{
	$("#"+inpdiv).off('keydown');
	$("#"+inpdiv).keydown(function(event)  {
		if(!HandleEnterKey(event, trigid))
			return false;
	});
}

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

function HandleEnterKey(e, submitid)
{
	var keycode = (e.keyCode ? e.keyCode : (e.which ? e.which : e.charCode));
	if (keycode == 13) {
		if(submitid != "")
			$("#" + submitid).click();
		return false;
	}
	return true;
}

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

function clearAllCookies()
{
	var cookies = $.cookie();
	for(var cookie in cookies) {
	   $.removeCookie(cookie);
	}
}

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

function scrollToRow (targetGrid, id) 
{
    var rowHeight = getGridRowHeight(targetGrid) || 23; // Default height
    var index = jQuery(targetGrid).getInd(id);
	if(index > 5)
		jQuery(targetGrid).closest(".ui-jqgrid-bdiv").scrollTop(rowHeight * index - rowHeight*3);
}

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

function getGridRowHeight (targetGrid) 
{
    var height = 23; // Default
    try {
		count = $(targetGrid).getGridParam("reccount");
		if(count)
			height = $(targetGrid).height() / count;
    }
    catch(e){
    }
    return height;
}

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

function centerDialog(dlgid)
{
	var dlgDiv = $("#"+dlgid);
	var parentDiv = dlgDiv.parent(); 
	var dlgWidth = dlgDiv.width();
	var parentWidth = parentDiv.width();
	var dlgHeight = dlgDiv.height();
	var parentHeight = parentDiv.height();
	// TODO: change parentWidth and parentHeight in case of the grid
	//       is larger as the browser window
	dlgDiv[0].style.top = Math.round((parentHeight-dlgHeight)/2) + "px";
	dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";
}

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

function showServerTime(swipein)
{
	// Don't swipe-in (sw=false) because this is called repeatedly and
	// we don't want this messing with session timeout
	var datastr = get_ajax_datastr("get", "time", "") + "&sw=false";
	ajax_call(datastr, ajax_servertime_info, null);
}

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

function ajax_servertime_info(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok')
			$("#server_time").html(x.server_time);
	}
}

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