/*
PiAnoS (Picture Annotation System), A fingerprint examiner training tool
Copyright (C) 2011-2021 University of Lausanne, Switzerland
https://ips-labs.unil.ch/pianos

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see http://www.gnu.org/licenses/.
*/

p4install = {
	
	rpc: function(method, data, _ok, _error, _complete)
	{
		_error = _error || function(){};
		_complete = _complete || function(){};
		$.ajax({
			url: '?rpc=1&method='+encodeURIComponent(method),
			type: 'POST',
			data: data,
			dataType: 'json',
			beforeSend: function(xhr, settings) {
				xhr.p4inst = {success:false,ret:null};
			},
			success: function(data, textStatus, xhr) {
				//console.log('ajax call HTTP succeeded');
				//console.log(data);
				if (typeof(data) == 'object' && 'ret' in data && 'success' in data)
				{
					if (data.success)
					{
						xhr.p4inst.success = true;
						xhr.p4inst.ret = data.ret;
						_ok(data.ret);
					}
					else
						_error('RPC failed: '+data.message);
				}
				else
				{
					_error('RPC failed: invalid return value');
				}
			},
			error: function(xhr, textStatus, errorThrown) {
				if (xhr.status != 200)
					_error('HTTP error ('+xhr.status+' '+errorThrown+')');
				else
					_error('Error in response data: '+errorThrown);
			},
			complete: function(xhr) {
				//console.log('ajax call completed');
				_complete(xhr.p4inst.success, xhr.p4inst.ret);
			}
		});
	},
	
	// Function to set the user selection to the provided (pure HTML) DOM element
	// Credit to Tim Down 
	// Source: http://stackoverflow.com/questions/4183401/can-you-set-and-or-change-the-users-text-selection-in-javascript
	selectElementContents: function(el) 
	{
		if (window.getSelection && document.createRange) 
		{
			var sel = window.getSelection();
			var range = document.createRange();
			range.selectNodeContents(el);
			sel.removeAllRanges();
			sel.addRange(range);
		} 
		else if (document.selection && document.body.createTextRange) 
		{
			var textRange = document.body.createTextRange();
			textRange.moveToElementText(el);
			textRange.select();
		}
	}	
}

