ax_forms = {};
lang.form = {
	'es':{'load':"Cargando datos...",
		   'submit':"Mandando datos..."
		  },
	'en':{'load':"Loading data...",
		  'submit':"Submitting data..."
		  }
};

AxForm = Class.create();
AxForm.prototype = {
	
	/**
	 * Object Constructor
	 */
	initialize: function(id, options) {
		
		this.id = id;	
		this.self = $(this.id);
	
		this.validators = {};
		this.media_inputs = {};
		this.options = options || {};
		this.reset_form = (this.options.reset_form != undefined) ? this.options.reset_form : true;
		this.curStep = 0;
		
		if (this.options.updater) {
			this.updater = updaters[this.options.updater];	
		}
		
		var me = this;
		page_init.scripts['axform_'+this.id] = function() {
			if (screen_overlay.register) screen_overlay.register(me);
		};
		
		if (btns) {
			this.btn = {};
			this.btn.save = btns[this.id + "_save"];
			this.btn.reset = btns[this.id + "_reset"];
			this.btn.cancel = btns[this.id + "_cancel"];
		}

		this._injectBehaviours();
		
	},
	
	/** PUBLIC METHODS **/
	
	loadData: function(cmd, id) {
		var callParams = [];
		callParams.push('cmd=' + ((cmd) ? cmd : this.cmd));	
		callParams.push('item=' + id);
		this.updater.run(callParams, cmd, lang.form[cur_lang].load);
		this.clearForm();
	},
	
	attemptSubmit: function() {
		if (console) console.log('attempting submit: ' + this.self.id + ' step complete: ' + this._isStepComplete());
		
		if (this._isStepComplete()) {
			
			var orig = this._encryptForm();
			if (this.updater) {
				var args = [];
				ApexUtil.extractForm(this.self, args);
				this.revertForm(orig);
				this.updater.run(args, this.options.cmd, lang.form[cur_lang].submit);
				//this.self.elements[0].0focus();
				
				if (this.reset_form) this.clearForm();
			} else {
				this.self.submit();
			}
		}
		
		if (!no_return) {
			return false;
		}
	},
	
	show: function(use_visibility) {
		if (use_visibility) {
			this.self.style.visibility = '';
		} else {
			this.self.style.display = '';
		}
	},
	
	hide: function(use_visibility) {
		if (use_visibility) {
			this.self.style.visibility = 'hidden';
		} else {
			this.self.style.display = 'none';	
		}
	},
	
	clearForm: function() {
		if (console) console.log('Clear Form called!!!');
		this.self.reset();
		for(var name in this.media_inputs) {
			var ob  = this.media_inputs[name];
			if (ob) {
				if (ob.label) ob.label.innerHTML = ob.starting_label;	
				if (ob.input) ob.input.value = '';
			}
		}

		var inputs = this.self.getElementsByTagName('input');
		if (inputs.length) {
			for(var i=0; i<inputs.length; ++i) {				
				if (inputs[i].type == 'hidden' && !inputs[i].getAttribute('constant')) {					
					inputs[i].value = '';	
				}
			}
		}
		
		if (typeof(txtEditor) != 'undefined') {
			tinyMCE.setContent('');	
		}
		
		if (this.self.elements[0] && this.self.elements[0].type != 'hidden') this.self.elements[0].focus();
		
	},
	
	cancelForm: function() {
		this.clearForm();
		this.hide();
	},
	
	revertForm: function(orig) {
		for(var i=0; i<orig.length; ++i) {
			var ob = orig[i];
			ob.self.value = ob.val;
		}
	},
	
	disableGroup: function(step) {
		var group = this.validators['step' + step];
		for(var i=0; i<group.length; ++i) {
			group[i].setActive(false);	
		}	
	},
	
	enableGroup: function(step) {
		var group = this.validators['step' + step];
		for(var i=0; i<group.length; ++i) {
			group[i].setActive(true);	
		}
	},
	
	getMediaFile: function(target, type, folder) {
		this.cur_media_target = target;
		mediaBrowser.open(this, null, type, folder);	
	},
	
	mediaInsert: function(res) {
		if (this.cur_media_target) {
			var parts = res.split('|');
			var target = this.media_inputs[this.cur_media_target];

			target.label.innerHTML = parts[1];
			target.input.value = parts[0];
		}
		this.cur_media_target = null;
	},
	
	/** PRIVATE METHODS **/
	
	_injectBehaviours: function() {
		if (console) console.log(this.options.use_return);
		if (this.options.use_return && this.self) {
			this.self.onkeyup = this._keyupHandler.bindAsEventListener(this);
		}
		
		if (this.btn.save) {
			this.btn.save.setAction(this.attemptSubmit.bind(this));	
		}
		
		if (this.btn.reset) {
			this.btn.reset.setAction(this.clearForm.bind(this));	
		}
		
		if (this.btn.cancel) {
			this.btn.cancel.setAction(this.cancelForm.bind(this));	
		}
		
		this._parseFormElements();
	},	
	
	_parseFormElements: function() {
		if (console) console.log('IN FORM: '+this.id + ' self: ' + this.self);
		this.validators = {};
		var elmts = this.self.elements;
		for(var i=0; i<elmts.length; i++) {
			var e = elmts[i];
			if (e.getAttribute('validator')) {
				var validator = (elmts[i].getAttribute('validator')).split(':');
				var group = 'step' + validator.shift();
				var id = e.id;
				var type = validator.shift();
				if (console) console.log('Validator Found : ' + group + ' : ' + id + ': ' + type + " : ARGS : " + validator);
				
				if (!this.validators[group]) {
					this.validators[group] = [];	
				}
				if (console) console.log('Validator for group: '+group);
				this.validators[group].push(new Validator(this, id, {app:this.app, type:type, args:validator}));
			}
			if (console) console.log(this.validators);
		}
		
		var divs = this.self.getElementsByTagName('div');
		for(var i=0; i<divs.length; i++) {
			var e = divs[i];
			if (e.getAttribute('media')) {
				var id = e.id;
				var temp = {};
				temp.label = $(id + '_label');
				temp.input = $(id + '_input');
				temp.starting_label = temp.label.innerHTML;
				this.media_inputs[id] = temp;
			}
			
		}
	},
	
	_keyupHandler: function(e) {
		if (e.keyCode == 13) {
			this.attemptSubmit(true);
		}
	},
	
	_encryptForm: function() {
		if (console) console.log('USING KEY: '+this.options.key);
		var elmts = this.self.elements;
		var original = [];
		for(var i=0; i<elmts.length; i++) {
			var e = elmts[i];
			if (e.getAttribute('encrypt') && e.value) {
				var ob = {self:e, val:e.value};
				original.push(ob);
				var res = encodeStr(this.options.key, e.value);
				e.value = res.join('|');
			}
		}
		return original;
	},
	
	_isStepComplete: function(step) {
		if (!step) step = this.curStep;
		
		if (this.options.validate_all) {
			var group = [];
			for(var i in this.validators) {
				for(var j in this.validators[i]) {
					group.push(this.validators[i][j]);
				}
			}
		} else {
			var group = this.validators['step' + step];
		}
		
		var res = true;
		if (group && group.length) {
			for(var i=0; i<group.length; ++i) {
				var v = group[i];
				if (console) console.log(v.self.id + ' = ' + v.args);
				if (v.args.indexOf('optional') != -1) {
					continue;	
				}
				if (v.type != 'cmd') {
					v.blurHandler();	
				} 
				
				if (!v.status || !v.self.value) {
					if (console) console.log(v.self.id + ' = ' + v.self.value);
					res = false;
				}
			}
		}
		
		if (console)console.log('Result: ' + res);
		
		return res;
	}

	
};


