window.EL = function() {
	var i; //global iterator :-)
	var objects = {};
	return {
		override : function(c, o)
		{
			for (i in o) {
				c.prototype[i] = o[i];
			}
		},
        extend : function()
        {
	        // inline overrides
	        var io = function(o){
	            for(var m in o){
	                this[m] = o[m];
	            }
	        };
	        var oc = Object.prototype.constructor;
	
	        return function(sb, sp, overrides){
	            if(typeof sp == 'object'){
	                overrides = sp;
	                sp = sb;
	                sb = overrides.constructor != oc ? overrides.constructor : function(){sp.apply(this, arguments);};
	            }
	            var F = function(){}, sbp, spp = sp.prototype;
	            F.prototype = spp;
	            sbp = sb.prototype = new F();
	            sbp.constructor=sb;
	            sb.superclass=spp;
	            if(spp.constructor == oc){
	                spp.constructor=sp;
	            }
	            sb.override = function(o){
	                EL.override(sb, o);
	            };
	            sbp.override = io;
	            EL.override(sb, overrides);
	            sb.extend = function(o){EL.extend(sb, o);};
	            return sb;
	        };
	    }(),
	    save : function(id, obj)
	    {
	    	if (objects[id]) {
	    		throw "Object with id="+id+" already registered";
	    	}
	    	objects[id] = obj;
	    },
	    getObject: function(id)
	    {
	    	return objects[id];
	    },

		loadContent : function(url, target, popup)
		{
			try {
				//TODO popup in external window
				if (popup) {
					if (jQuery.blockUI) {
						$('#'+target).html("Загрузка...");
						$.blockUI({message: $('#'+target), css:{padding:"10px"} });
					}
				}
	    		$('#'+target).load(url, null, function(text, status, req){
	    			if (req.status != 200) {
	    				$('#'+target).html('<span style="color:red; font-weight:bold">Произошла ошибка при загрузке данных с сервера. Попробуйте позже или обратитесь к администратору.<span>');
	    			}
					if (popup && jQuery.blockUI) {
						$.blockUI({message:$('#'+target)});
						if (req.status != 200 || text.indexOf("form-not-found-error") >= 0) {
							setTimeout("$.unblockUI()", 4000);
						}
						$('#'+target).prepend("<div style='text-align:right'><a href='#' onclick='$.unblockUI(); return false' style='background-color:red; color:white; -moz-border-radius-bottomleft:10px; display:block; text-align:center; margin:0 0 auto auto; width:20px; height:20px; text-decoration:none; font-weight:bold'>x</a></div>");

						var bel = $('#'+target).parent();
						var h = bel.height();
						var vh=$(window).height();
						var css = { top: (h>vh?10:Math.round((vh-h)/2)) + 'px' };
						if (h > vh) {
							css.height = vh-20;
							css.overflow = 'auto';
						}
						$.blockUI({
							message: $('#'+target),
							centerY: false,
							css: css
						});

					}
					EL.initAjaxLinks($('#'+target));
	    		});
	    	} catch (e) {
				if (popup && jQuery.blockUI) {
					$.unblockUI();
				}
	    		alert(e.message);
	    	}
		},
	    
	    //parseUri 1.2.1 http://blog.stevenlevithan.com/archives/parseuri
	    parseUri : function(str) {
	    	var	o   = EL.parseUri.options,
				m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
				uri = {},
				i   = 14;
	
			while (i--) uri[o.key[i]] = m[i] || "";
	
			uri[o.q.name] = {};
			uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
				if ($1) uri[o.q.name][$1] = $2;
			});
	
			return uri;
		},
	    props : function(e, rec)
	    {
	    	var ret='';
	    	for (var i in e) {
	    		try {
	    			if (e[i] instanceof Object && rec) {
	    				ret+=i+" = {"+props(e[i], rec)+"}\n";
	    			} else {
	    				ret+=i+" = "+e[i]+"\n";
	    			}
	    		} catch (e) {
	    			ret+=i+" = [CAN'T GET VALUE]\n";
	    		}
	    	}
	    	return ret;
	    },
	    loadScript : function(url, callback)
	    {
	    	if (EL.scripts[url]) {
	    		callback();
	    	} else {
	    		jQuery.getScript(url, callback);
	    	}
	    }
	};
}();

EL.init = function()
{
	EL.forms = {};
	EL.initAjaxLinks($(document));
	if ($.blockUI) {
		$.blockUI.defaults.applyPlatformOpacityRules = false;
	}
	$("body").append("<div id='el-modal-message' style='display:none'></div>");
}

EL.initAjaxLinks = function(el)
{
	el.find('.form-link').each(function(index, link){
		if ( link.target[0] != '_' && $('#'+link.target)[0] ) {
			EL.forms[link.href] = $(link)	.click(function() {
				var uri = EL.parseUri(this.href);
				var newlink = uri.protocol+"://"+uri.host+"/form/"+uri.relative.substr(1);
				var popup = this.target.indexOf("-popup") > 0;
				EL.loadContent(newlink, this.target, popup);
				return false;
			});
		}
	});
	el.find('.ajax-link').each(function(index, link){
		if ( link.target[0] != '_' && $('#'+link.target)[0] ) {
			EL.forms[link.href] = $(link)	.click(function() {
				var uri = EL.parseUri(this.href);
				var newlink = uri.protocol+"://"+uri.host+"/ajax/load.php?__page="+uri.relative.substr(1);
				var popup = this.target.indexOf("-popup") > 0;
				EL.loadContent(newlink, this.target, popup);
				return false;
			});
		}
	});
}

EL.page = {}; //variable for page vars and functions
EL.scripts = {}; //loaded scripts

//parseUri options 1.2.1 http://blog.stevenlevithan.com/archives/parseuri
EL.parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

jQuery(document).ready(EL.init);

