
Function.prototype.setOrigin = function(obj) {
	var a = this;
	return function() {
		var c = arguments;
		var e = function() {
			return a.apply(obj, c);
		}
		return e();
	}
};

function dcurApplication(name, title, activate, get, post) {
	this.instance = dcurApplications.instance++;
	this.appName = name;
	this.name = name+this.instance;
	this.url = dcurApps.pluginBase+'apps/'+this.appName+'.app.php?instance='+this.name;
	this.url += this.serialize(get, '&');
	this.reloadData = null;
	this.reloadOnLoad = null;
	this.loadData = null;
	this.callStack = {};
	this.callTimeout = 5000;
	this.onLoad = null;

	dcurApplications[this.name] = this;
	this.create(title, activate, post);
}
dcurApplication.prototype = {
	serialize: function(data, sep) {
		if (data) {
			var _d = '';
			for(k in data)
				_d += (_d ? '&':'')+k+'='+data[k];
			return (_d && sep ? sep:'')+_d;
		} else
			return '';
	},

	create: function(title, activate, post) {
		jQuery('#dcur-apps').append('<div id="'+this.name+'-app" style="display: none;"></div>');
		jQuery('#dcur-menu').append('<li id="'+this.name+'">Loading...</li>');
		this.load(post, true);
		jQuery('#'+this.name).click(function() {
			dcurApps.switchApp(this.name);
		}.setOrigin(this)).dblclick(function() {
			this.reload(true);
		}.setOrigin(this));
		if (activate)
			dcurApps.switchApp(this.name);
	},

	load: function(data, initial, onload) {
		if (data && typeof data._get == 'function')
			this.reloadData = jQuery(data._get()).serialize();
		else if(data)
			this.reloadData = data;
		else
			this.reloadData = '';

		if (initial)
			this.loadData = this.reloadData;

		this.reloadOnLoad = onload;

		this.setTitle('Loading...');
		jQuery.post(this.url, this.reloadData, function(data) {
			jQuery('#'+this.name+'-app').html(data);
			if (typeof Performer != "undefined")
				if (Performer.Effects)
					Performer.ReInit();
				else
					Performer.Start();

			if (this.onLoad)
				this.onLoad()

			if (this.reloadOnLoad)
				this.reloadOnLoad();

			this.enableTabs("textarea");
		}.setOrigin(this));
	},

	reload: function(init) {
		if (init)
			this.reloadData = this.loadData;

		this.setTitle('Loading...');
		jQuery.post(this.url, this.reloadData, function(data) {
			jQuery('#'+this.name+'-app').html(data);
			if (typeof Performer != "undefined")
				if (Performer.Effects)
					Performer.ReInit();
				else
					Performer.Start();

			if (this.onLoad)
				this.onLoad()

			if (this.reloadOnLoad)
				this.reloadOnLoad();

			this.enableTabs("textarea");
		}.setOrigin(this));
	},

	call: function(proc, container, action, get, post, fn, bindto) {
		if (post && typeof post._get == 'function')
			data = jQuery(post._get()).serialize();
		else if(!post)
			data = 'action=';
		else
			data = post;

		var key = proc+container+action;

		if (this.callStack[key]) {
			this.callStack[key].next.push({
				proc: proc,
				container: container,
				action: action,
				get: get,
				post: data,
				fn: fn,
				bindto: bindto
			});
		} else {
			this.callStack[key] = {
				next: new Array(),
				progress: false
			};
		}

		this.processCallStack(key);
	},

	processCallStack: function(key) {
		if (this.callStack[key].progress)
			return;

		if (this.callStack[key].next.length == 0)
			return;

		this.callStack[key].progress = true;
		pars = this.callStack[key].next.shift();

		proc = pars.proc;
		container = pars.container;
		action = pars.action;
		get = pars.get;
		post = pars.data;
		fn = pars.fn;
		bindto = pars.bindto;

		var url = dcurApps.pluginBase+'apps/'+proc+'.proc.php?instance='+this.name+'call';
		url += this.serialize(get, '&');
		//alert(url);
		jQuery.post(url, data.replace(/action=[^&$]*/, 'action='+action), function(data) {
			if (container) {
				jQuery('#'+container).html(data);
				if (typeof Performer != "undefined")
					if (Performer.Effects)
						Performer.ReInit();
					else
						Performer.Start();

				this.enableTabs("textarea");
			}

			if (fn) {
				if (bindto)
					fn.apply(bindto, [data]);
				else
					fn(data);
			}

			this.callStack[key].progress = false;
			this.processCallStack(key);
		}.setOrigin(this));
	},

	setTitle: function(title) {
		jQuery('li#'+this.name).text(title);
	},

	show: function() {
		jQuery('#'+this.name+'-app').css('display', 'block');
		jQuery('#'+this.name).addClass('active');
	},

	hide: function() {
		jQuery('#'+this.name+'-app').css('display', 'none');
		jQuery('#'+this.name).removeClass('active');
	},

	close: function() {
		jQuery('#'+this.name+'-app').remove();
		jQuery('li#'+this.name).remove();
	},

	enableTabs: function(selectors) {
		jQuery(selectors).focus(function () {
			//alert(this.name);
			jQuery(this).keydown(function (e) {
				//alert(e.keyCode);
				var tab = "\t";
				var target = e.target;
				var selectionStart = target.selectionStart;
				var selectionEnd = target.selectionEnd;
				if (e.keyCode == 9) {
					e.preventDefault();
					// Multiline selection
					if (selectionStart != selectionEnd && target.value.slice(selectionStart,selectionEnd).indexOf("\n") != -1) {
						var pre = target.value.slice(0,selectionStart);
						var sel = target.value.slice(selectionStart,selectionEnd);
						var post = target.value.slice(selectionEnd,target.value.length);
						if(sel.match(/\n(\t){1}/g))
							var lines = sel.match(/\n(\t){1}/g).length + 1;
						else
							var lines = sel.split(/\n/).length;
						if(!e.shiftKey) {
							sel = sel.replace(/\n/g,"\n"+tab);
							target.value = pre.concat(tab).concat(sel).concat(post);
							target.selectionStart = selectionStart;
							target.selectionEnd = selectionEnd + lines * tab.length;
						} else {
							if(sel.match(/^(\t){1}/m) || sel.match(/\n(\t){1}/g)) {
								sel = sel.replace(/^(\t){1}/m,"");
								sel = sel.replace(/\n(\t){1}/g,"\n");
								target.value = pre.concat(sel).concat(post);
								target.selectionStart = selectionStart;
								target.selectionEnd = selectionEnd - lines * tab.length;
							}
						}
					}
					// No selection or sigle line selection
					else {
						if(!e.shiftKey) {
							target.value = target.value.slice(0,selectionStart).concat(tab).concat(target.value.slice(selectionStart,target.value.length));
							if (selectionStart == selectionEnd) {
								target.selectionStart = target.selectionEnd = selectionStart + tab.length;
							}
							else {
								target.selectionStart = selectionStart;
								target.selectionEnd = selectionEnd + tab.length;
							}
						} else {
							if (selectionStart != selectionEnd) {
								var pre = target.value.slice(0,selectionStart);
								var post = target.value.slice(selectionEnd,target.value.length);
								var sel = target.value.slice(selectionStart,selectionEnd);
								if(sel.match(/^(\t){1}/)) {
									sel = sel.replace(/^(\t){1}/,"");
									target.value = pre.concat(sel).concat(post);
									target.selectionStart = selectionStart;
									target.selectionEnd = selectionEnd - tab.length;
								}
							}
						}
					}
				}
			});
		});
	}
}

function dcurApplications() {
	this.name = 'DCUR-APP-OBJECT';
	this.instance = 0;
	this.activeApp = null;

	jQuery(document).ready(function() {
		if (typeof(userSettings) != "undefined")
			this.init();
	}.setOrigin(this));
}
dcurApplications.instance = 0;

dcurApplications.prototype = {
	init: function() {
		this.pluginBase = userSettings.url+'wp-content/plugins/dcuregistration/';
		if (typeof(dcurAutoload) != "undefined")
			this.loadApp(dcurAutoload, 'Application', true, dcurAutoloadGetParams, dcurAutoloadPostParams);
	},
	loadApp: function(name, title, activate, get, post) {
		var a = new dcurApplication(name, title, activate, get, post);
	},

	unloadApp: function(instance) {
		dcurApplications[instance] = null;
	},

	switchApp: function(instance) {
		if (this.activeApp)
			this.activeApp.hide();
		this.activeApp = dcurApplications[instance];
		this.activeApp.show();
	},

	closeApp: function(instance) {
		var app;

		if (instance)
			app = dcurApplications[instance];
		else if (this.activeApp) {
			app = this.activeApp;
		} else
			return false;

		app.close();
		if (this.activeApp == app)
			this.activeApp = null;
		this.unloadApp(app.name);
	}
}

function dcurForm(name, options) {
	this.name = name;
	this.options = options;

	dcurForms[name] = this;

}
dcurForm.prototype = {
	set: function(item, value) {
		this._get().elements[item].value = value;

		return this;
	},

	get: function(item, def) {
		var v = this._get().elements[item].value;
		return v ? v:def;
	},

	submit: function() {
		//alert(jQuery(this._get()).serialize());
	},

	_get: function() {
		return document[this.name];
	},

	disable: function(item) {
		var el = this._get().elements[item];
		if (!el)
			return;

		if (!el.nodeName) {
			for(i = 0; i<el.length; i++) {
				if (el.item == undefined)
					el[i].disabled = true;
				else
					el.item(i).disabled = true;
			}
		} else
			el.disabled = true;
	},

	enable: function(item) {
		var el = this._get().elements[item];
		if (!el)
			return;

		if (!el.nodeName) {
			for(i = 0; i<el.length; i++) {
				if (el.item == undefined)
					el[i].disabled = false;
				else
					el.item(i).disabled = false;
			}
		} else
			el.disabled = false;
	},

	getVPos: function(item) {
		var el = this._get().elements[item];

		if (el)
			return el.scrollTop;
		else
			return null;
	},

	setVPos: function(item, vpos) {
		var el = this._get().elements[item];

		if (el)
			el.scrollTop = vpos;
	},

	setFocus: function(item) {
		var el = this._get().elements[item];

		if (el)
			el.focus();
	},

	getEventKey: function(e) {
		var keycode;
		if (window.event) keycode = window.event.keyCode;
		else if (e) keycode = e.which;
		else keycode = null;

		return keycode;
	}
}

var dcurForms = new Object();

function dcurDebug(options) {
	this.options = options;
	this.container = 'jsDebug';
}
dcurDebug.prototype = {
	addVar: function(name, obj) {
		var _cnt = jQuery('#'+this.container).html();
		_cnt += '<pre>'+this.print_r(obj, name)+'</pre>';
		jQuery('#'+this.container).html(_cnt);
	},

	print_r: function(obj, name, pad, level) {
		if (!pad)
			pad = '';
		if (!level)
			level = 0;

		str = pad;
		if (name)
			str += name+': ';

		if (level > 2)
			return str+" recursion limit reached\n";

		switch(typeof(obj)) {
			case 'string':
				str += "'"+obj.toString().replace(/</g, '&lt;')+"'\n";
				break;
			case 'number':
				str += obj.toString()+"\n";
				break;
			case 'object':
				if (obj instanceof Date) {
					str += obj.toString();
				} else if (obj instanceof Array) {
					str += obj.toString()+" [\n";
					for(i in obj) {
						str += this.print_r(obj[i], i, pad+'    ', level+1);
					}
					str += pad+"]\n";
				} else if (obj instanceof Object) {
					str += obj.toString()+" {\n";
					for(p in obj) {
						if (!(obj[p] instanceof Function)) {
							if (obj[p])
								str += this.print_r(obj[p], p, pad+'    ', level+1);
						} else
							str += pad+'    '+p+" : method\n";
					}
					str += pad+"}\n";
				}
				break;
		}
		return str;
	}
}

var dcurDebug = new dcurDebug();
var dcurApps = new dcurApplications();


