/**
 * @author sjorek
 */

var application = (function($,appId,appOpts){
	app = function(id,opts){
		this.id=id;
		if (typeof(opts)=='object') {
			this.options = $.extend(1,this.options,opts);
		}
		var obj = this;
		var activityResetFn = function(){
			obj._resetActivityTracking();
			$(this).trigger('user.active');
			application.debug('user active');
		}
		$(window).mousemove(activityResetFn);
		$(window).keypress(activityResetFn);
		if (typeof($.fn.wheel)=='function') {
			$(window).wheel(activityResetFn);
		}
		$(window).focus(function(){
			obj._startActivityTracking(true);
			$(this).trigger('user.active');
			application.debug('user active');
		});
		$(window).blur(function(){
			obj._stopActivityTracking(true);
			$(this).trigger('user.inactive');
			application.debug('user inactive');
		});
	};
	app.prototype.id=null;
	app.prototype.options={
		debug:false,
		trackingInterval:5000,
		proccessSelector:'body'
	};
	app.prototype.init = function(overrideOpts){
		if (typeof(overrideOpts)=='object') {
			this.options = $.extend(1,this.options,overrideOpts);
		}
		$(this.options.proccessSelector).removeClass('static').addClass('dynamic');
		var obj = this;
		$(document).ready(function(){obj.ready();});
	};
	app.prototype._ready = false;
	app.prototype.ready = function(){
		if (!this._ready) {
			$(document).trigger('ready.dom');
			this._ready=true;
		}
		return this._ready;
	};
	app.prototype.lib={};
	app.prototype.factory={};
	app.prototype._instances={};
	app.prototype.control = function(id,obj){
		if (id) {
			if (obj) {
				this._instances[id]=obj;
				return id;
			}
			return this._instances[id];
		}
		return this._instances;
	};
	app.prototype._interval=false;
	app.prototype._blocked=false;
	app.prototype._stopActivityTracking=function(force){
		if ((!this._blocked || force) && this._interval != false) {
			window.clearInterval(this._interval);
			this._interval=false;
		}
		if (force) {
			this._blocked=true;
		}
	};
	app.prototype._startActivityTracking=function(force){
		if ((!this._blocked || force) && this._interval == false) {
			var obj = this;
			this._interval = window.setInterval(function(){
				obj._updateActivityTracking();
			}, this.options.trackingInterval);
		}
		if (force) {
			this._blocked=false;
		}
	};
	app.prototype._resetActivityTracking=function(){
		if (!this._blocked) {
			this._stopActivityTracking(false);
			this._startActivityTracking(false);
		}
	};
	app.prototype._updateActivityTracking=function(){
		this._resetActivityTracking();
		$(this).trigger('user.inactive');
		application.debug('user inactive');
	};
	app.prototype.debug=function(msg,data){
		if (this.options.debug) {
			if (typeof(console)=='object' && typeof(console.log)=='function') {
				console.log(msg);
				if (typeof(data)=='object' && typeof(console.dir)=='function') {
					console.dir(data);
				}
			} else {
				alert(msg);
			}
		}
	}

	return new app(appId,appOpts);
})(jQuery,'prix',null);


