var VALID_TAG   = 'valid';
var SESSION_TAG = 'MPIHA_SSID';
var USER_TAG    = 'user';
var TYPE_TAG    = 'type';
var MSG_TAG     = 'msg';

var COOKIE_TIMEOUT = 3600; // One hour

function MPIHA_USER ()
{
  this.SSID = $.cookie(SESSION_TAG);
  this.username = $.cookie(USER_TAG);
  this.usertype = $.cookie(TYPE_TAG);
  this.timeout_handle;

  if(this.usertype == null) this.usertype = -1;

	this.login = function (user, pass, callback)
	{
        var obj = this;

		$.ajax({
			type: "POST",
			url: "/request/AdminLogin.php",
			data: "&username="+user+"&password="+pass,
			dataType: 'json',
			success: function (data)
			{
  			if(data[VALID_TAG] == false)
  			{
  			  if(typeof(callback) == 'function')
  			    callback(data[VALID_TAG],data[MSG_TAG]);
			  }
      	else
      	{
        	obj.update_cookies(data[SESSION_TAG], data[USER_TAG], data[TYPE_TAG]);
  			  if(typeof(callback) == 'function')
  			    callback(data[VALID_TAG],data[MSG_TAG]);
      	}
	    },
			error: function(Obj, Err, Exception){
				console.error(Err);
			}
		});
	}

	this.logout = function (callback)
	{
        var obj = this;
		$.ajax({
			type: "POST",
			url: "/request/AdminLogout.php",
			data: "&SSID="+this.SSID,
			dataType: 'json',
			success: function (data)
			{
  			obj.unset_cookies();
			  if(typeof(callback) == 'function')
  			  callback(data[VALID_TAG],data[MSG_TAG]);
			},
			error: function(Obj, Err, Exception){
				console.error(Err);
			}
		});
	}

  this.update_cookies = function (SSID,user,thetype)
  {
  	this.SSID = SSID;
  	this.username = user;
  	this.usertype = thetype;

  	this.timeout(COOKIE_TIMEOUT * 1000);

    $.cookie(SESSION_TAG, SSID, { expires: COOKIE_TIMEOUT, path: '/' } );
    $.cookie(USER_TAG, user, { expires: COOKIE_TIMEOUT, path: '/' });
    $.cookie(TYPE_TAG, thetype, { expires: COOKIE_TIMEOUT, path: '/' });
  }

  this.unset_cookies = function ()
  {
  	this.SSID = '';
  	this.username = '';
  	this.usertype = -1;

    $.cookie(SESSION_TAG, null, { path: '/' });
    $.cookie(USER_TAG, null, { path: '/' });
    $.cookie(TYPE_TAG, null, { path: '/' });
  }

  this.timeout = function (msec)
  {
    var _self = this;

    if(typeof(this.timeout_handle) != 'undefined')
      clearTimeout(this.timeout_handle);

    this.timeout_handle = setTimeout(function()
    {
      _self.unset_cookies();
    }, msec);
  }

  // Check to see if this login is still valid
  if(this.username != null)
  {
    var obj = this;
    $.ajax({
    	type: "POST",
    	url: "/request/AdminCheck.php",
    	success: function (data)
    	{
    		if(data == -1)
              obj.unset_cookies();
            else
              obj.update_cookies(obj.SSID,obj.user,obj.thetype);
        }
    });
  }
}

