
function myScope(func,obj,args) {
	if (typeof func != 'function') {
		return function() {
			//alert('error on myScope');
		}
	} 
	return function() {
		obj.args = args;
		return func.apply(obj,arguments);
	};
};

function sqldatetime2human(datetime) {
	re = /^(\d+)-0?(\d+)-0?(\d+) (\d+):(\d+):(\d+)$/;
	return datetime.replace(re, "$3. $2. $1 $4:$5");
}

function byteconvert(bytes) {
	var s = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];
	var e = Math.floor(Math.log(bytes)/Math.log(1024));
	if (bytes > 0) {
		return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
	}
	return bytes +" "+s[0];
}

function getXY(oElement,reference) {
	var iReturnValue = { 'x': 0, 'y': 0, 'sx': 0, 'sy': 0 };
	while ((oElement != null) && (oElement != reference)) {
		iReturnValue.y += oElement.offsetTop;
		iReturnValue.x += oElement.offsetLeft;
		if (oElement != document.body) {
			iReturnValue.sy += oElement.scrollTop;
			iReturnValue.sx += oElement.scrollLeft;
		}
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

function getY(oElement,reference) {
	var iReturnValue = 0;
	while ((oElement != null) && (oElement != reference)) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

function getX(oElement,reference) {
	var iReturnValue = 0;
	while ((oElement != null) && (oElement != reference)) {
		iReturnValue += oElement.offsetLeft;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}
var myURL = function(url) {
	
	this.url = ''+url;

	this.params = {};

	this.initQuery = function (all, name, value) {
		if (name) {
			this.params[name] = value;
		}
		return this;
	}

	this.setQuery = function (name, value) {
		if (name) {
			this.params[name] = value;
		}
		return this;
	}

	this.getQueryValue = function (name) {
		return this.params[name];
	}

	this.init = function() {
		//log.info(this.url);
		var reg1 = /(https?:\/\/)?([a-zA-Z0-9_\-\.]+)?(:[0-9]+)?\/?([^\?#]*)?(\?([^#]*)?)?(#(.*))?/;
		var result = this.url.match(reg1);
		this.scheme = result[1];
		this.host = result[2];
		this.port = result[3];
		this.path = result[4];
		this.query = result[6];
		this.hash = result[8];

		if (this.query) {
			var reg2 = /(?:^|&)([^&=]*)=?([^&]*)/g;
			var result = this.query.match(reg2);

			this.query.replace(reg2, myScope(this.initQuery,this));
		}
	}

	this.getScheme = function() {
		return ((this.scheme)?(this.scheme):(''));
	}

	this.getHost = function() {
		return ((this.host)?(this.host):(''));
	}

	this.getPort = function() {
		return ((this.port)?(':'+this.port):(''));
	}

	this.getPortValue = function() {
		return ((this.port)?(this.port):(''));
	}

	this.getPath = function() {
		return ((this.path)?('/'+this.path):(''));
	}

	this.getPathValue = function() {
		return ((this.path)?(this.path):(''));
	}

	this.addToString = function(k,v) {
		if (v !== false) { 
			this.queryString = ((this.queryString)?(this.queryString+'&'):('?')) + k + '=' +v;
		}
	}

	this.getQuery = function() {
		this.queryString = false;
		$.each(this.params,myScope(this.addToString,this));
		return this.queryString;
	}

	this.getHash = function() {
		return ((this.hash)?('#'+this.hash):(''));
	}

	this.getHashValue = function() {
		return ((this.hash)?(this.hash):(''));
	}

	this.getURL = function() {
		return this.getScheme() + this.getHost() + this.getPort() + this.getPath() + this.getQuery() + this.getHash();
	}

	this.init();
}


var eventArray = function(source,name) {

	this.source = source;
	this.name = name;
	this.size = 0;
	this.events = new Array();

	this.add = function(callback) {
		this.size++;
		this.events.push(callback);
		return true;
	}

	this.call = function() {
		var result = true;
		var index = 0;
		while ((result) && (this.size > index)) { 
			result = this.events[index](arguments);
			index++;
		}
		return result;
	}

	return this;
};

var log = false;
var logger = function() {

	this.last = '';
	this.span = false;
	this.count = 0;
	this.log = false; 
	this.make_log = false;
	//this.make_log = true;

	this.init = function() {
		if ($('#log').length == 0 && this.make_log) {
			$('head').append('<link rel="stylesheet" type="text/css" href="js/jquery.utils.css" media="screen" />');
			$('body').append('<ul id="log"></ul>');
			this.log = $('#log').hide();
			//this.log.hide();
			this.log.dblclick(myScope(this.hide,this));
			//$(document).keypress(myScope(this.show,this));
		}
	}

	this.show = function(e) {
		return true;
	}

	this.hide = function(e) {
		if (this.log) {
			this.log.hide();
		}
		return false;
	}

	this.error = function(message) {
		this.message(message,'error');
	}

	this.infoObjectItem = function(name,value) {
		log.info('+'+name + ':' + value);
	}

	this.infoObject = function(obj) {
		log.info('Object:');
		$.each(obj,myScope(this.infoObjectItem,this));
		return true;
	}

	this.info = function(message) {
		this.message(message,'info');
	}

	this.obj = function(obj,message) {
		this.message('[' + obj.name + ']: '+message,'info');
	}

	this.message = function(message,type) {
		if (this.make_log === false) { return false; }
		if (typeof console != 'undefined') {
			console.info(message);
			this.hide();
			return true;
		}
		if (this.log) {
			this.log.show();
			if ((message == this.last) && (this.span)) {
				this.count += 1;
				this.span.html(this.count+'x');
			} else {
				this.count = 1;
				this.log.prepend('<li class="'+type+'">'+message+'<span></span></li>');
				this.span = $('li:first span',this.log);
			}
			this.last = message;
		}
	}

	this.init();
};

var log = false;
$(document).ready(function() {
	log = new logger();
});

$.fn.settings = function() {

	this.idValues = {};
	this.objValues = {};

	this.add = function(idName,values) {
		if (typeof this.idValues[idName] == 'undefined') {
			this.idValues[idName] = {};
		}
		$.extend(this.idValues[idName],values);
	}

	this.addByObject = function(objName,values) {
		if (typeof this.objValues[objName] == 'undefined') {
			this.objValues[objName] = {};
		}
		
		$.extend(this.objValues[objName],values);
	}

	this.get = function(name) {
		if (this.values[name]) {
			return this.values[name];
		} 
		return {};
	}

	this.get = function(name) {
		if (typeof this.idValues[name] != 'undefined') {
			return this.idValues[name];
		} 
		return {};
	}

	this.getByObject = function(name) {
		if (typeof this.objValues[name] != 'undefined') {
			return this.objValues[name];
		} 
		return {};
	}
};

$(window).data({ 'settings' : new $.fn['settings']()});

function _s() {
	return  $(window).data('settings');
}

$.fn.openers = function() {

	this.windows = new Array();

	this.open = function(obj,url,w,h,s) {
		var newWindow = window.open(url, s+"_jswin", "toolbar=no,width="+w+",height="+h+",scrollbars=yes,resizable=yes");
		this.windows.push({ 'caller': obj, 'window': newWindow });
		return newWindow;
	}

	this.call = function(w,func,data) {
		for (var i = 0; i < this.windows.length; i++) {
			if (this.windows[i]['window'] == w) {
				return this.windows[i]['caller'][func](data);
			}
		}
		return false;
		
	}

	this.close = function(obj) {
		for (var i = 0; i < this.windows.length; i++) {
			if (this.windows[i]['caller'] == obj) {
				this.windows[i]['window'].close();
				this.windows.splice(i,1);
				return true;
			}
		}
		return false;
		
	}
}

var openers = new $.fn['openers']();

$.fn.collection = function(name) {

	this.name = name;
	this.layers = new Array();

	this.add = function(layer) {
		this.layers.push(layer);
	}

	this.getValue = function(func) {
		for (var i = 0; i < this.layers.length; i++) {
			if (this.layers[i][func]()) {
				return true;
			}
		}
		return false;
	}

	this.setOnlyMe = function(layer,name_on,name_off) {
		var result = false;
		for (var i = 0; i < this.layers.length; i++) {
			if (this.layers[i] == layer) {
				result = this.layers[i][name_on]();
			} else {
				this.layers[i][name_off]();
			}
		}
		return result;
	}

	this.set = function(name,args) {
		for (var i = 0; i < this.layers.length; i++) {
			this.layers[i][name](args);
		}
	}
}

var changeItems = new $.fn['collection']('changeItems');

$.getJSONError = function(url,success,error) {
	return jQuery.ajax({
		type: "GET",
		url: url,
		dataType: "json",
		success: success,
		error: error
	});
}

$.getScriptError = function(url,success,error) {
	//console.info('ScriptError: '+url);
	return jQuery.ajax({
		type: 'GET',
		url: url,
		dataType: 'script',
		success: success,
		async: false,
		error: error
	});
}

var loader = function(name,makers) {
	this.name = name;
	this.makers = makers;
	this.done = false;
	this.data = new Array();
	this.index = 0;


	this.init();

	return this;
}

var makers = function() {
	
	this.names = {};

	this.add = function(name,data) {
		if (typeof this.names[name] == 'undefined') {
			var load = new loader(name,this);
			this.names[name] = load;
		}
		this.names[name].add(data);
	}

	return this;
}

$.fn.make = function(name,local_settings,callback) {

	this.length = this.length;
	this.name = name;
	this.settings = local_settings;
	this.callback = callback;

	this.create = function(index,object) {
		var id = $(object).attr('id');

		var object_settings = {};
		jQuery.extend(object_settings, this.settings);
		jQuery.extend(object_settings, _s().get(id));
		jQuery.extend(object_settings, _s().getByObject(this.name));

		object_settings._first = (index == 0);
		object_settings._last = (index == this.length - 1);

		if ($.fn[this.name]) {
			var newObj = new $.fn[this.name](object,index,object_settings);
			//console.info(newObj.init);
			if (typeof this.callback == 'function') {
				this.callback(newObj);
			}
			return true;
		}
		return false;
	}

	this.loadDone = function() {
		$.each(this,myScope(this.create,this));
	};

	this.loadError = function() {
		//alert('Loading error v jquery utils');
	};

	this.init = function() {
		if (typeof this.settings == 'undefined') {
			this.settings = {};
		}
		if (this.length == 0) { return this; }
		if (typeof $.fn[name] == 'undefined') {
			$.getScriptError('/js/jquery.'+this.name+'.js', myScope(this.loadDone,this), myScope(this.loadError,this));
		} else {
			this.loadDone();
		}
		return this;
	}

	return this.init();
};

function make_calls(calls,local_settings,obj) {
	if (calls) {
		for (var i = 0; i < calls.length; i++) {
			//log.message(calls[i].selector + ': '+$(calls[i].selector,obj).length);
			//log.message(calls[i].name);
			$(calls[i].selector,obj).make(calls[i].name,local_settin[gs]);
		}
	}
}

jQuery.fn.swap = function() {

	var a = this[0];
	var b = this[1];

	if (a && b) {
		var parentNode = b.parentNode;

		if (a.nextSibling == b) {
			parentNode.replaceChild(a,b);
			parentNode.insertBefore(b,a);
		} else {
			parentNode.replaceChild(b,a);
			parentNode.insertBefore(a,b);
		}
	}
 
	return this;
};

function gs(str) {
	return str;
}

