
	function $(id) {return document.getElementById(id);}
	
	function n(type, id, count) {
		if (count > 0) {
			var res = [];
			for (var i = 0; i < count; i ++) {
				res.push(n(type, id?id+i:null));
			}
			return res;
		} else {
			var o = document.createElement(type);
			if (!id) 
				id = 'object' + (new Date()).getTime();
			o.setAttribute('id', id);
			
			return o;
		}
	}
	
	function createMethodReference(object, method) {
		if (!(method instanceof Function)) {
			method = object[method];
		}
		
		return function () {
			method.apply(object, arguments);
		};
	}
	
	function attachEvent(o, sEventName, oCallback) {
		try {
			if (typeof o.addEventListener != 'undefined') {
			  o.addEventListener(
				sEventName,
				oCallback,
				false
			  );
			} else if (typeof o.attachEvent != 'undefined') {
			  o.attachEvent(
				'on' + sEventName,
				oCallback
			  );
			}
			
			return true;
		} catch (E) {
			return false;
		}
	}
	
	function clone(obj) {
		var n = {};
		for (p in obj) {
			n[p] = obj[p];
		}
		return n;
	};
	
	function write_list_for(id, fid, title, s_options) {
		var list = $(id);
		
		var nlist = n('div');
		nlist.className = 'select-imitation';
		
		var noptions = n('div');
		noptions.style.position = 'absolute';
		noptions.style.display = 'none';
		noptions.className = 'select-imitation-options';
		
		$(fid).appendChild(nlist);
		$(fid).appendChild(noptions);
		$(fid).className = 'select-imitation-container';
		$(fid).style.display = '';
		
		var ndata = {
			num: 0, 
			title: title || "Wybrano", 
			nlist: nlist, 
			noptions: noptions, 
			no: [], 
			focus: false, 
			opened: false, 
			selected: 0, 
			"default": "", 
			list:list, 
			"multiple": true,
			"checkboxes": true,
			'min': 0, 'max': 0,
			'icon_caption': false,
			'icon-height': 0
		};
		
		if (s_options) {
			for (var k in s_options) {
				var val = s_options[k];
				switch (k) {
					case 'options-width':
						noptions.style.width = val + 'px';
						break;
						
					case 'select-width':
						nlist.style.width = val + 'px';
						break;
						
					default:
						ndata[k] = val;
						break;
				}
			}
		}
		
		var first = -1;
		var o = list.childNodes;
		for (var i = 0; i < o.length; i ++) {
			if ((new String(o[i].nodeName)).toLowerCase() == 'option') {
				var first = i;
				break;
			}
		}
		
		if (first >= 0) {
			nlist.innerHTML = o[first].innerHTML;
			ndata["default"] = o[first].innerHTML;
		}
		
		list_parse_options(o, first+1, ndata);
		
		if ((ndata.num) * 26 < 250) {
			noptions.style.overflow = '';
			noptions.style.height = 'auto';
		}
		
		attachEvent(nlist, 'click', createMethodReference(ndata, function () {
			if (this.opened) {
				this.noptions.style.display = 'none';
			} else {
				this.noptions.style.display = '';
			}
			
			this.focus = true;
			this.opened = !this.opened;
		}));
		
		attachEvent(document.body, 'click', createMethodReference(ndata, function () {
			if (!this.focus) {
				this.noptions.style.display = 'none';
				this.opened = false;
			}
		}));
		
		var set_focus = createMethodReference(ndata, function () {
			this.focus = true;
		});
		var unset_focus = createMethodReference(ndata, function () {
			this.focus = false;
		});
		
		attachEvent(nlist, 'mouseover', set_focus);
		attachEvent(nlist, 'mousemove', set_focus);
		attachEvent(nlist, 'mouseout', unset_focus);
		attachEvent(noptions, 'mouseover', set_focus);
		attachEvent(noptions, 'mousemove', set_focus);
		attachEvent(noptions, 'mouseout', unset_focus);
		
		list.style.display = 'none';
		list.name = '';
	}
	
	function list_parse_options(o, first, ndata) {
		for (var i = first; i < o.length; i ++) {
			var no = n('div');
			var span = n('span');
			var check = n('input');
			
			no.className = 'select-imitation-option';
			
			if (o[i].nodeName.toLowerCase() == 'optgroup') {
				no.className = 'select-imitation-group';
				no.innerHTML = o[i].getAttribute('label');
				ndata.noptions.appendChild(no);
				ndata.num ++;
				list_parse_options(o[i].getElementsByTagName('option'), 0, ndata);
				continue;
			}
			
			if (o[i].nodeName.toLowerCase() != 'option') {
				continue;
			}
			ndata.noptions.appendChild(no);
			
			var table = new CTable(no);
			table.style.width = '90%';
			var no_side = table.createRow(2);
			
			no_side[0].className = 'select-imitation-option-left';
			//~ if (ndata.noptions.style.width) {
				//~ no_side[1].style.width = new String((parseInt(ndata.noptions.style.width) - parseInt(no_side[0].style.width) - 10) + 'px');
				//~ no_side[1].style.width = new String((parseInt(ndata.noptions.offsetWidth) - parseInt(no_side[0].offsetWidth) - 10) + 'px');
			//~ }
			no_side[1].className = 'select-imitation-option-right';
			
			check.type = ndata.multiple ? 'checkbox' : 'radio';
			check.name = ndata.list.name;
			check.value = o[i].value;
			no_side[0].appendChild(check);
			check.readonly = true;
			check.className = 'no-replace';
			check.style.padding = '0';
			check.style.margin = '0';
			check.style.border = '0';
			check.style.background = 'transparent';
			
			if (!ndata.checkboxes)
				check.style.display = 'none';
			
			var settings = {};
			
			if ((new String(o[i].getAttribute('title'))).charAt(0) == '{') {
				try {
					eval('var settings = ' + o[i].getAttribute('title') + ';');
				} catch (E) {
					var settings = {};
				}
			}
			
			if (o[i].getAttribute('icon')) {
				settings.icon = o[i].getAttribute('icon');
			}
			
			var icon = null;
			if (settings.icon) {
				icon = n('img');
				icon.src = settings.icon;
				check.style.display = 'none';
				no_side[0].appendChild(icon);
			}
			
			var nod = {selected: false, element: no, side: no_side, value: o[i].value, name: o[i].innerHTML, last:0, check:check, icon:icon};
			if (o[i].getAttribute('selected') == "1") {
				check.checked = true;
				no.className = 'select-imitation-option select-imitation-option-active';
				
				nod.selected = true;
				ndata.selected ++;
				
				if (ndata.selected == 0) {
					ndata.nlist.innerHTML = ' ' + ndata['default'];
					ndata.nlist.style.fontWeight = 'normal';
				} else if (ndata.selected == 1) {
					if (ndata.icon_caption && icon) {
						ndata.nlist.innerHTML = '<img src="' + icon.src + '" ' + (ndata['icon-height'] > 0 ? 'style="height: ' + ndata['icon-height'] + 'px;"' : '')+' />';
					} else {
						ndata.nlist.innerHTML = ' ' + o[i].innerHTML;
					}
					ndata.nlist.style.fontWeight = 'bold';
				} else {
					ndata.nlist.innerHTML = ' '+ndata.title+': ' + ndata.selected;
					ndata.nlist.style.fontWeight = 'bold';
				}
			}
			
			span.innerHTML = ' ' + o[i].innerHTML;
			no_side[1].appendChild(span);
			
			ndata.no.push(nod);
			ndata.num ++;
			
			var clicked = createMethodReference({ndata:ndata, no:no, check:check, span:span, nod:nod}, function () {
				var t = (new Date).getTime();
				if ((t - this.nod.last) < 200) {
					return;
				}
				this.nod.last = t;
				
				if (this.ndata['min'] > 0 && this.nod.selected && this.ndata['min'] <= this.ndata.selected) {
					return;
				}
				
				if (this.ndata['max'] > 0 && !this.nod.selected && this.ndata['max'] >= this.ndata.selected) {
					return;
				}
				
				this.nod.selected = !this.nod.selected;
				this.check.checked = this.nod.selected;
				
				if (this.check.checked) {
					if (!this.ndata.multiple) {
						for (var i = 0; i < this.ndata.no.length; i ++) {
							if (this.ndata.no[i].selected && this.ndata.no[i].check.id != this.check.id) {
								this.ndata.no[i].selected = false;
								this.ndata.no[i].check.checked = false;
								this.ndata.selected --;
								this.ndata.no[i].element.className = 'select-imitation-option';
							}
						}
					}
					
					this.ndata.selected ++;
					this.no.className = 'select-imitation-option select-imitation-option-active';
				} else {
					this.ndata.selected --;
					this.no.className = 'select-imitation-option';
				}
				
				if (this.ndata.selected == 0) {
					this.ndata.nlist.innerHTML = this.ndata['default'];
					this.ndata.nlist.style.fontWeight = 'normal';
				} else if (this.ndata.selected == 1) {
					for (var i = 0; i < this.ndata.no.length; i ++) {
						if (this.ndata.no[i].selected) {
							if (this.ndata.icon_caption && this.ndata.no[i].icon) {
								this.ndata.nlist.innerHTML = '<img src="' + this.ndata.no[i].icon.src + '" ' + (this.ndata['icon-height'] > 0 ? 'style="height: ' + this.ndata['icon-height'] + 'px;"' : '')+'  />';
							} else {
								this.ndata.nlist.innerHTML = ' ' + this.ndata.no[i].name;
							}
							break;
						}
					}
					this.ndata.nlist.style.fontWeight = 'bold';
				} else {
					this.ndata.nlist.innerHTML = ' '+this.ndata.title+': ' + this.ndata.selected;
					this.ndata.nlist.style.fontWeight = 'bold';
				}
				
				if (this.nod.selected && ndata.list.onchange) 
					createMethodReference({value: this.nod.value}, ndata.list.onchange)();
			});
			
			attachEvent(no, 'click', clicked);
			attachEvent(check, 'click', clicked);
		}
	}
	
	var _connections_id = {};
	var TConnection = function (sUrl, fOnData, conn_id) {
		this.onData = null;
		this.oConn = getAC();
		this.sMethod = 'GET';
		this.sUrl = '';
		this.sConnId = conn_id;
		
		if (conn_id) {
			_connections_id[conn_id] = (new Date).getTime() + "_" + Math.round(Math.random()*1000);
			this.sConnLast = _connections_id[conn_id];
		}
		
		this.oConn.onreadystatechange = createMethodReference(this, function () {
			if (this.oConn.readyState == 4) {
				if (this.onData) {
					if (this.sConnId) {
						if (_connections_id[this.sConnId] != this.sConnLast) {
							return;
						}
					}
					
					this.onData(this.oConn);
				}
			}
		});
		
		//fast call
		if (sUrl) {
			this.sUrl = sUrl;
			this.onData = fOnData;
			this.open();
		}
	};
	TConnection.prototype.onData = null;
	TConnection.prototype.sMethod = 'GET';
	TConnection.prototype.sUrl = '';
	TConnection.prototype.bCacheProtection = true;
	
	TConnection.prototype.open = function () {
		this.oConn.open(this.sMethod, this.sUrl + (this.bCacheProtection ? '&_t='+(new Date()).getTime() : ''));
		this.oConn.send('');
	};
	
	function getAC() {
		var res;
		if (window.XMLHttpRequest) {
			try {
				res = new XMLHttpRequest();
		   } catch(e) {
				res = false;
		   }
		} else if (window.ActiveXObject) {
		   try {
			res = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				try {
					res =  new ActiveXObject("Msxml2.XMLHTTP");
				} catch(e) {
					res = false;
				}
			}
		}
		//res.timeout = 1000;

		return res;
	}
	
	var _delay_action = {};
	function delay_action(name, delay, action) {
		clearInterval(_delay_action[name]);
		_delay_action[name] = setTimeout(action, delay);
	}
	
	function unregister_delay(name) {
		if (delay_registered(name)) {
			clearInterval(_delay_action[name]);
			_delay_action[name] = null;
			
			//console.log('unregister_delay ' + name);
		}
	}
	
	function register_delay(name, handle) {
		if (delay_registered(name)) {
			unregister_delay(name);
		}
		
		_delay_action[name] = handle;
		
		//console.log('register_delay ' + name);
	}
	
	function delay_registered(name) {
		return _delay_action[name];
	}
	
	var clone = function(obj) {
		var n = {};
		for (p in obj) {
			n[p] = obj[p];
		}
		return n;
	};
	
	function get_type(obj) {
		return (new String(typeof(obj))).toLowerCase();
	}
	
	function ucfirst(str) {
		var str = new String(str);
		return str.charAt(0).toUpperCase() + str.substr(1, str.length-1);
	}
	
	var _mouse = {x:0, y:0};
	function getMouseXY() {
		return _mouse;
	}
	
	function getBodyElement() {
		if (document.documentElement) {
			return document.documentElement;
		} else {
			return document.body;
		}
	}
	
	if (document) {
		attachEvent(document, 'mousemove', function (e) {
			if (isIe()) {
				_mouse = {
					x: e.clientX + getBodyElement().scrollLeft,
					y: e.clientY + getBodyElement().scrollTop
				};
			} else if (e && e.pageX) { 
				_mouse = {
					x: e.pageX,
					y: e.pageY
				};
			} else {
				_mouse = {x:0, y:0};
			}
		});
	}
	
	function get_html_translation_table(table) {
		var entities = {}, histogram = {}, decimal = 0, symbol = '';
		
		entities['38'] = '&amp;';
		entities['60'] = '&lt;';
		entities['62'] = '&gt;';
		
		for (decimal in entities) {
			symbol = String.fromCharCode(decimal)
			histogram[symbol] = entities[decimal];
		}
		
		return histogram;
	}
	
	function htmlspecialchars (string, quote_style) {
		var histogram = {}, symbol = '', tmp_str = '', i = 0;
		tmp_str = string.toString();
		
		if (false === (histogram = get_html_translation_table('HTML_SPECIALCHARS', quote_style))) {
			return false;
		}
		
		for (symbol in histogram) {
			entity = histogram[symbol];
			tmp_str = tmp_str.split(symbol).join(entity);
		}
		
		return tmp_str;
	}
	
	function strip_tags(str, allowed_tags) {
		var key = '', tag = '', allowed = false;
		var matches = allowed_array = [];
	 
		var replacer = function(search, replace, str) {
			return str.split(search).join(replace);
		};
	 	
		// Build allowes tags associative array
		if (allowed_tags) {
			allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
		}
	  
		str += '';
	 
		// Match tags
		matches = str.match(/(<\/?[^>]+>)/gi);
	 
		// Go through all HTML tags
		for (key in matches) {
			if (isNaN(key)) {
				// IE7 Hack
				continue;
			}
	 
			// Save HTML tag
			html = matches[key].toString();
	 
			// Is tag not in allowed list? Remove from str!
			allowed = false;
	 
			// Go through all allowed tags
			for (k in allowed_array) {
				// Init
				allowed_tag = allowed_array[k];
				i = -1;
	 			
				if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
				if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
				if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
	 
				// Determine
				if (i == 0) {
					allowed = true;
					break;
				}
			}
	 
			if (!allowed) {
				str = replacer(html, "", str); // Custom replace. No regexing
			}
		}
	 
		return str;
	}
	
	function on_window_load(func) {
		if (isIe()) {
			attachEvent(document, 'readystatechange', createMethodReference({func:func}, function () {
				if (document.readyState == 'complete') {
					this.func();
				}
			}));
		} else {
			attachEvent(window, 'load', createMethodReference({func:func}, function () {
				this.func();
			}));
		}
	}
	
	if (/msie/i.test (navigator.userAgent)) //only override IE
	{
		document.nativeGetElementById = document.getElementById;
		document.getElementById = function(id)
		{
			var elem = document.nativeGetElementById(id);
			if(elem)
			{
				//make sure that it is a valid match on id
				if(elem.id == id)
				{
					return elem;
				}
				else
				{
					//otherwise find the correct element
					for(var i=1;i<document.all[id].length;i++)
					{
						if(document.all[id][i].id == id)
						{
							return document.all[id][i];
						}
					}
				}
			}
			return null;
		};
	}
	
	var in_array = function (search, arr) {
		for (k = 0; k < arr.length; k ++) {
			if (arr[k] == search) {
				return true;
			}
		}
		
		return false;
	};
	
	function get_price(iCent, bCurrency) {
		iCent = new String(iCent);
		iCent.replace(/^(-)?0+/, '', iCent);
		
		if (parseInt(iCent) >= 100) {
			sPrice = iCent.substr(0, iCent.length - 2) + ',' + iCent.substr(-2);
		} else if (parseInt(iCent) >= 10) {
			sPrice = '0,' + iCent;
		} else {
			sPrice = '0,0' + iCent;
		}
		
		return sPrice + (bCurrency !== false ? ' zł' : '');
	}
	
	var _rows_ck = {};
	function check_row(element) {
		if (_rows_ck[element.getAttribute('name')]) {
			var row = _rows_ck[element.getAttribute('name')];
		} else {
			return;
		}
		
		row.element = element;
		
		delay_action('check_' + row.name, 500, createMethodReference(row, function () {
			if (this.prefs.required && is_input_null(this.element)) {
				var res = {
					status: "error",
					msg: this.prefs.msg
				};
			} else if (this.callback) {
				var res = createMethodReference(this, this.callback)(this.element.value);
			} else {
				res = {
					status: "ok",
					msg: ""
				};
			}
			
			if (res) {
				set_row_status(this.name, res);
			}
		}));
	}
	
	function set_row_status(name, res) {
		if (_rows_ck[name]) {
			var row = _rows_ck[name];
		} else {
			return;
		}
		
		var div = row.element.parentNode.parentNode.getElementsByTagName('div'), status = null;
		
		for (var k = 0; k < div.length; k ++) {
			if (div[k].className == 'form-status') {
				status = div[k];
				break;
			}
		}
		
		if (status) {
			status.innerHTML = '';
			if (res.status != 'ok') {
				status.innerHTML = '<img src="' + JS_HOST + 'view/img/icon_' + res.status + '.png" class="mid" /> ' + res.msg;
			}
			
			if (res.status == 'error') {
				status.parentNode.className = 'form-row form-notgood';
			} else {
				status.parentNode.className = 'form-row';
			}
		}
	}
	
	function register_row(name, callback, prefs) {
		if (!prefs) {
			prefs = {
				required: false,
				msg: "Pole jest wymagane."
			};
		}
		
		if (!prefs.msg) {
			prefs.msg = "Pole jest wymagane.";
		}
		
		_rows_ck[name] = {
			callback: callback,
			prefs: prefs,
			name: name,
			element: $('_check_'+name)
		};
		
		var e = $('_check_'+name);
		attachEvent(e, 'keyup', createMethodReference(e, function () {
			//check_row(this);
		}));
		attachEvent(e, 'blur', createMethodReference(e, function () {
			check_row(this);
		}));
		
		if ((new String(e.nodeName)).toLowerCase() == 'input' && e.type == 'checkbox') {
			attachEvent(e, 'change', createMethodReference(e, function () {
				check_row(this);
			}));
		}
	}
	
	function check_all_rows() {
		var block = true;
		
		for (var k in _rows_ck) {
			var row = _rows_ck[k];
			row.element = $('_check_' + row.name);
			
			if (row.prefs.required) {
				if (is_input_null(row.element)) {
					block = false;
					set_row_status(row.name, {
						status: "error",
						msg: row.prefs.msg
					});
					
					if (block)
						row.element.focus();
				}
			} else if (row.prefs.quick) {
				
			}
		}
		
		if (!block) {
			if ($('_button_check')) {
				if ($('__check_form_rows')) {
					var div = $('__check_form_rows');
				} else {
					var div = n('div');
					$('_button_check').parentNode.insertBefore(div, $('_button_check'));
				}
				
				div.id = '__check_form_rows';
				div.className = 'notgood';
				div.innerHTML = 'Wypełnij poprawnie formularz.';
			}
		}
		
		return block;
	}
	
	function is_input_null(input) {
		return (
			(
				((new String(input.nodeName)).toLowerCase() == 'input') 
				&& (
					(input.type == 'checkbox' && !input.checked) 
					|| ((input.type == 'password' || input.type == 'text') && input.value == '')
				)
			)
			|| (
				(in_array((new String(input.nodeName)).toLowerCase(), ['textarea', 'select']))
				&& (
					input.value == ''
				)
			)
		);
	}
	
	function writeCoordinates(lat1, lng1, lat2, lng2){

		//pierwsze to wspolrzedne srodka
		//drugie wpolrzedne punktu myszy
		
		var lat1Field = document.getElementById("lat1");
		lat1Field.value = lat1;
		
		var lng1Field = document.getElementById("lng1");
		lng1Field.value = lng1;
		
		var lat2Field = document.getElementById("lat2");
		lat2Field.value = lat2;
		
		var lng2Field = document.getElementById("lng2");
		lng2Field.value = lng2;
		
	}
	
	function writePointCoordinates(lat1, lng1){

		var lat1Field = document.getElementById("lat1");
		lat1Field.value = lat1;
		
		var lng1Field = document.getElementById("lng1");
		lng1Field.value = lng1;
		
		
	}
	
	function add_hint_for(el, hint) {
		return new (function (el, hint) {
			this.el = el;
			this.hint = hint;
			this.over = true;
			
			this.onout = function () {
				this.over = false;
				setTimeout(createMethodReference(this, this.close), 800);
			};
			
			this.onmove = function () {
				this.over = true;
				this.hint.style.display = '';
			};
			
			this.close = function () {
				if (!this.over) {
					this.hint.style.display = 'none';
				}
			};
			
			this.hint.style.position = 'absolute';
			this.hint.style.top = get_element_absolute(this.el).top + 'px';
			this.hint.style.left = get_element_absolute(this.el).left + 'px';
			
			attachEvent(this.hint, 'mousemove', createMethodReference(this, this.onmove));
			attachEvent(this.el, 'mousemove', createMethodReference(this, this.onmove));
			attachEvent(this.hint, 'mouseout', createMethodReference(this, this.onout));
			attachEvent(this.el, 'mouseout', createMethodReference(this, this.onout));
			attachEvent(this.hint, 'mouseup', createMethodReference(this, this.onmove));
			attachEvent(document.body, 'mousedown', createMethodReference(this, this.onout));
		})(el, hint);
	}
	
	function get_element_absolute(element) {
		var res = {
			top: element.offsetTop,
			left: element.offsetLeft
		}
		
		if (element.offsetParent) {
			var parent = get_element_absolute(element.offsetParent);
			res.top += parent.top;
			res.left += parent.left;
		}
		
		return res;
	}
	
	function getElementsByClass(searchClass,node,tag) {
		if (document.getElementsByClassName) {
			return document.getElementsByClassName(searchClass);
		}
		
		var classElements = new Array();
		if ( node == null )
			node = document;
		if ( tag == null )
			tag = '*';
		var els = node.getElementsByTagName(tag);
		var elsLen = els.length;
		//var pattern = new RegExp("(^|[ 	]*)"+searchClass+"([ 	]*|$)");
		for (i = 0, j = 0; i < elsLen; i++) {
			//if ( pattern.test(els[i].className) ) {
			if (is_subclass_of(els[i], searchClass)) {
				classElements[j] = els[i];
				j++;
			}
		}
		return classElements;
	}

	function is_subclass_of(element, className) {
		if (!element.className) return;
		
		return (element.className == className || element.className.indexOf(" "+className) !== -1 || element.className.indexOf(className+" ") !== -1);
		className = new String(className);
		className = className.replace(/-/, '\\-');
		
		var pattern = new RegExp("(^|[ 	]+)"+className+"([ 	]+|$)");
		return pattern.test(element.className);
		
		return (new String(element.className)).match("/(^|[ 	]*)" + className + "([ 	]*|$)/");
	}

