var Kaf;
var AllDom;
var KafDom;
var KafClasses;
var KafNameSpace = "kaf-";
var LightBox;
var popupCloseDelay = 2500;

window.addEvent('domready', function (event) {
	Kaf = new KafRequire();
	Kaf.loadAll();
});

function kafFilter(item, index) {
	try {
		if (item.className && item.className.indexOf(KafNameSpace) != -1) {
			KafDom.push(item);
			if (item.className.indexOf(' ') == -1) {
				KafClasses.push(item.className.split(KafNameSpace).join(""));
			}
			else {
				var classes = item.className.split(" ");
				classes.each(function (item, index) {
					if (item && item.indexOf(KafNameSpace) != -1) {
						KafClasses.push(item.split(KafNameSpace).join(""));
					}
				});
			}
		}
	}
	catch(e) {
		
	}
}

var KafRequire = new Class({
	initialize: function () {
		this.library;
		this.styles;
		this.clean;
		this.loader;
	},
	loadAll: function () {
		KafDom = new Array();
		KafClasses = new Array();

		AllDom = document.getElement("body").getElements("*");
		AllDom.each(kafFilter);

		KafClasses = KafClasses;

		this.library = new Array();
		this.styles = new Array();
		this.clean = new Array();

		KafClasses.each(this.add.bind(this))
		this.loader = new Loader({
			'scripts': this.library,
			'styles': this.styles
		});
	},
	add: function (item, index) {
		this.clean.push(item);
		this.library.push(KafConfig.basePath + item + '/js/' + item + '.js');
		this.styles.push(KafConfig.basePath + item + '/css/' + item + '.css');
	}
});

var KafResponseManager = new Class({
	initialize: function (response, form) {
		this.response = response;
		this.form = form;
		this.type;
		this.decoded;
		this.hash;

		this.handleResponse();
	},

	isJSON: function (value) {
		this.decoded = null;
		try {
			this.decoded = JSON.decode(value);
			if (typeof this.decoded != 'object') {
				this.decoded = false;
			}
		}
		catch (e) {
			this.decoded = false;
		}
		return this.decoded;
	},

	handleResponse: function () {
		this.typeDetector();
	},

	typeDetector: function () {
		if (typeof this.response == "undefined") {
			this.type = "empty";
			if (typeof (SystemNotification) != 'undefined')
				SystemNotification.show(KafConfig.locale.error);
			return;
		}
		this.type = "html";
		if (this.isJSON(this.response)) {
			this.type = "json";
			if (this.form) {
				this.jsonAction();
				return;
			}
		}

		if (this.type == "html") {
			this.htmlAction();
		}
	},

	jsonAction: function () {

		this.hash = new Hash(this.decoded);

		if (this.hash.message) {
			var info = this.form.getElement('.summary');
			if (!this.hash.isBoxed) {
				var scroller = new SmoothScroll(window);
				scroller.toElement(info);
			}

			var classToAdd = "success";
			if (this.hash.failed) {
				classToAdd = "error";
			}

			if (this.hash.callback) {
				this.hash.callback.apply(null, this.hash.params);
			}

			if (typeof (info) != "undefined" && info) {
				info.addClass(classToAdd);
				info.setStyle('display', 'block');
				info.set('html', '<div>' + this.hash.message + '</div>');
			}
		}

		if (this.hash.errors) {
			this.hash.errors.each(function (item, index) {
				var element = this.form.getElement('#' + item.controlid);
				if (element) {
					var p = new Element('p', { 'class': 'validation' });
					p.set('html', item.text);
					p.inject(element.getParent(), 'bottom');
					element.getParent("li").addClass("error");

					element.addEvent('focus', function(){
						var p = element.getParent().getElement('.error');
						var parentLi = element.getParent('li');
						
						if (p) {
							p.dissolve();
							setTimeout(function(){ p.dispose();}, 1000);
							parentLi.removeClass('error');
						}
					});
				}
			}.bind(this));
		}

		if (this.hash.redirect && !this.hash.message) {
			window.location = this.hash.redirect;
		}
		
		if (this.hash.close && $defined(SqueezeBox)) {
			(function(){SqueezeBox.close()}).delay(popupCloseDelay);
		}
	},

	htmlAction: function () {
		var element = new Element('div');
		element.set('html', this.response);
		var first = element.getFirst();
		if (first) {
			var id = first.id;
			var target = document.id(id);
			if (target) {
				target.set('html', first.get('html'));
				var scroller = new SmoothScroll({ duration: 700 });
				scroller.toElement(target);
			}
		}
	}
});

var KafRequest = new Class({
	initialize: function (path, method, form) {
		this.path = path;
		this.method = method || 'get';
		this.form = form;
		this.request = new Request({
			method: this.method,
			url: this.path,
			onSuccess: this.success,
			evalScripts: true,
			noCache:true
		}).send();
	},
	success: function (response, responseXML) {
		new KafResponseManager(response, this.form);
	}
});
