function echo () {
	// http://kevin.vanzonneveld.net
	// +   original by: Philip Peterson
	// +   improved by: echo is bad
	// +   improved by: Nate
	// +    revised by: Der Simon (http://innerdom.sourceforge.net/)
	// +   improved by: Brett Zamir (http://brett-zamir.me)
	// +   bugfixed by: Eugene Bulkin (http://doubleaw.com/)
	// +   input by: JB
	// +   improved by: Brett Zamir (http://brett-zamir.me)
	// +   bugfixed by: Brett Zamir (http://brett-zamir.me)
	// +   bugfixed by: Brett Zamir (http://brett-zamir.me)
	// %        note 1: If browsers start to support DOM Level 3 Load and Save (parsing/serializing),
	// %        note 1: we wouldn't need any such long code (even most of the code below). See
	// %        note 1: link below for a cross-browser implementation in JavaScript. HTML5 might
	// %        note 1: possibly support DOMParser, but that is not presently a standard.
	// %        note 2: Although innerHTML is widely used and may become standard as of HTML5, it is also not ideal for
	// %        note 2: use with a temporary holder before appending to the DOM (as is our last resort below),
	// %        note 2: since it may not work in an XML context
	// %        note 3: Using innerHTML to directly add to the BODY is very dangerous because it will
	// %        note 3: break all pre-existing references to HTMLElements.
	// *     example 1: echo('<div><p>abc</p><p>abc</p></div>');
	// *     returns 1: undefined

	var arg = '', argc = arguments.length, argv = arguments, i = 0;
	var win = this.window;
	var d = win.document;
	var ns_xhtml = 'http://www.w3.org/1999/xhtml';
	var ns_xul = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; // If we're in a XUL context

	var holder;

	var stringToDOM = function (str, parent, ns, container) {
		var extraNSs = '';
		if (ns === ns_xul) {
			extraNSs = ' xmlns:html="'+ns_xhtml+'"';
		}
		var stringContainer = '<'+container+' xmlns="'+ns+'"'+extraNSs+'>'+str+'</'+container+'>';
		if (win.DOMImplementationLS &&
			win.DOMImplementationLS.createLSInput &&
			win.DOMImplementationLS.createLSParser) { // Follows the DOM 3 Load and Save standard, but not
			// implemented in browsers at present; HTML5 is to standardize on innerHTML, but not for XML (though
			// possibly will also standardize with DOMParser); in the meantime, to ensure fullest browser support, could
			// attach http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.js (see http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.xhtml for a simple test file)
			var lsInput = DOMImplementationLS.createLSInput();
			// If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
			lsInput.stringData = stringContainer;
			var lsParser = DOMImplementationLS.createLSParser(1, null); // synchronous, no schema type
			return lsParser.parse(lsInput).firstChild;
		}
		else if (win.DOMParser) {
			// If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
			try {
				var fc = new DOMParser().parseFromString(stringContainer, 'text/xml');
				if (!fc || !fc.documentElement ||
					fc.documentElement.localName !== 'parsererror' ||
					fc.documentElement.namespaceURI !== 'http://www.mozilla.org/newlayout/xml/parsererror.xml') {
					return fc.documentElement.firstChild;
				}
			// If there's a parsing error, we just continue on
			}
			catch(e) {
			// If there's a parsing error, we just continue on
			}
		}
		else if (win.ActiveXObject) { // We don't bother with a holder in Explorer as it doesn't support namespaces
			var axo = new ActiveXObject('MSXML2.DOMDocument');
			axo.loadXML(str);
			return axo.documentElement;
		}
		/*else if (win.XMLHttpRequest) { // Supposed to work in older Safari
            var req = new win.XMLHttpRequest;
            req.open('GET', 'data:application/xml;charset=utf-8,'+encodeURIComponent(str), false);
            if (req.overrideMimeType) {
                req.overrideMimeType('application/xml');
            }
            req.send(null);
            return req.responseXML;
        }*/
		// Document fragment did not work with innerHTML, so we create a temporary element holder
		// If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
		//if (d.createElementNS && (d.contentType && d.contentType !== 'text/html')) { // Don't create namespaced elements if we're being served as HTML (currently only Mozilla supports this detection in true XHTML-supporting browsers, but Safari and Opera should work with the above DOMParser anyways, and IE doesn't support createElementNS anyways)
		if (d.createElementNS &&  // Browser supports the method
			(d.documentElement.namespaceURI || // We can use if the document is using a namespace
				d.documentElement.nodeName.toLowerCase() !== 'html' || // We know it's not HTML4 or less, if the tag is not HTML (even if the root namespace is null)
				(d.contentType && d.contentType !== 'text/html') // We know it's not regular HTML4 or less if this is Mozilla (only browser supporting the attribute) and the content type is something other than text/html; other HTML5 roots (like svg) still have a namespace
				)) { // Don't create namespaced elements if we're being served as HTML (currently only Mozilla supports this detection in true XHTML-supporting browsers, but Safari and Opera should work with the above DOMParser anyways, and IE doesn't support createElementNS anyways); last test is for the sake of being in a pure XML document
			holder = d.createElementNS(ns, container);
		}
		else {
			holder = d.createElement(container); // Document fragment did not work with innerHTML
		}
		holder.innerHTML = str;
		while (holder.firstChild) {
			parent.appendChild(holder.firstChild);
		}
		return false;
	// throw 'Your browser does not support DOM parsing as required by echo()';
	};


	var ieFix = function (node) {
		if (node.nodeType === 1) {
			var newNode = d.createElement(node.nodeName);
			var i, len;
			if (node.attributes && node.attributes.length > 0) {
				for (i = 0, len = node.attributes.length; i < len; i++) {
					newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i].nodeName));
				}
			}
			if (node.childNodes && node.childNodes.length > 0) {
				for (i = 0, len = node.childNodes.length; i < len; i++) {
					newNode.appendChild(ieFix(node.childNodes[i]));
				}
			}
			return newNode;
		}
		else {
			return d.createTextNode(node.nodeValue);
		}
	};

	for (i = 0; i < argc; i++ ) {
		arg = argv[i];
		if (this.php_js && this.php_js.ini && this.php_js.ini['phpjs.echo_embedded_vars']) {
			arg = arg.replace(/(.?)\{\$(.*?)\}/g, function (s, m1, m2) {
				// We assume for now that embedded variables do not have dollar sign; to add a dollar sign, you currently must use {$$var} (We might change this, however.)
				// Doesn't cover all cases yet: see http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
				if (m1 !== '\\') {
					return m1+eval(m2);
				}
				else {
					return s;
				}
			});
		}
		if (d.appendChild) {
			if (d.body) {
				if (win.navigator.appName == 'Microsoft Internet Explorer') { // We unfortunately cannot use feature detection, since this is an IE bug with cloneNode nodes being appended
					d.body.appendChild(stringToDOM(ieFix(arg)));
				}
				else {
					var unappendedLeft = stringToDOM(arg, d.body, ns_xhtml, 'div').cloneNode(true); // We will not actually append the div tag (just using for providing XHTML namespace by default)
					if (unappendedLeft) {
						d.body.appendChild(unappendedLeft);
					}
				}
			}else {
				d.documentElement.appendChild(stringToDOM(arg, d.documentElement, ns_xul, 'description')); // We will not actually append the description tag (just using for providing XUL namespace by default)
			}
		} else if (d.write) {
			d.write(arg);
		}/* else { // This could recurse if we ever add print!
            print(arg);
        }*/
	}
}



function var_dump () {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brett-zamir.me)
	// +   improved by: Zahlii
	// +   improved by: Brett Zamir (http://brett-zamir.me)
	// -    depends on: echo
	// %        note 1: For returning a string, use var_export() with the second argument set to true
	// *     example 1: var_dump(1);
	// *     returns 1: 'int(1)'

	var output = '', pad_char = ' ', pad_val = 4, lgth = 0, i = 0, d = this.window.document;
	var _getFuncName = function (fn) {
		var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
		if (!name) {
			return '(Anonymous)';
		}
		return name[1];
	};

	var _repeat_char = function (len, pad_char) {
		var str = '';
		for (var i = 0; i < len; i++) {
			str += pad_char;
		}
		return str;
	};
	var _getInnerVal = function (val, thick_pad) {
		var ret = '';
		if (val === null) {
			ret = 'NULL';
		}
		else if (typeof val === 'boolean') {
			ret = 'bool(' + val + ')';
		}
		else if (typeof val === 'string') {
			ret = 'string(' + val.length+') "' + val + '"';
		}
		else if (typeof val === 'number') {
			if (parseFloat(val) == parseInt(val, 10)) {
				ret = 'int(' + val + ')';
			}
			else {
				ret = 'float('+val+')';
			}
		}
		// The remaining are not PHP behavior because these values only exist in this exact form in JavaScript
		else if (typeof val === 'undefined') {
			ret = 'undefined';
		}
		else if (typeof val === 'function') {
			var funcLines = val.toString().split('\n');
			ret = '';
			for (var i = 0, fll = funcLines.length; i < fll; i++) {
				ret += (i !== 0 ? '\n'+thick_pad : '') + funcLines[i];
			}
		}
		else if (val instanceof Date) {
			ret = 'Date('+val+')';
		}
		else if (val instanceof RegExp) {
			ret = 'RegExp('+val+')';
		}
		else if (val.nodeName) { // Different than PHP's DOMElement
			switch(val.nodeType) {
				case 1:
					if (typeof val.namespaceURI === 'undefined' || val.namespaceURI === 'http://www.w3.org/1999/xhtml') { // Undefined namespace could be plain XML, but namespaceURI not widely supported
						ret = 'HTMLElement("' + val.nodeName + '")';
					}
					else {
						ret = 'XML Element("' + val.nodeName + '")';
					}
					break;
				case 2:
					ret = 'ATTRIBUTE_NODE(' + val.nodeName + ')';
					break;
				case 3:
					ret = 'TEXT_NODE(' + val.nodeValue + ')';
					break;
				case 4:
					ret = 'CDATA_SECTION_NODE(' + val.nodeValue + ')';
					break;
				case 5:
					ret = 'ENTITY_REFERENCE_NODE';
					break;
				case 6:
					ret = 'ENTITY_NODE';
					break;
				case 7:
					ret = 'PROCESSING_INSTRUCTION_NODE(' + val.nodeName + ':' + val.nodeValue+')';
					break;
				case 8:
					ret = 'COMMENT_NODE(' + val.nodeValue + ')';
					break;
				case 9:
					ret = 'DOCUMENT_NODE';
					break;
				case 10:
					ret = 'DOCUMENT_TYPE_NODE';
					break;
				case 11:
					ret = 'DOCUMENT_FRAGMENT_NODE';
					break;
				case 12:
					ret = 'NOTATION_NODE';
					break;
			}
		}
		return ret;
	};

	var _formatArray = function (obj, cur_depth, pad_val, pad_char) {
		var someProp = '';
		if (cur_depth > 0) {
			cur_depth++;
		}

		var base_pad = _repeat_char(pad_val * (cur_depth - 1), pad_char);
		var thick_pad = _repeat_char(pad_val * (cur_depth + 1), pad_char);
		var str = '';
		var val = '';

		if (typeof obj === 'object' && obj !== null) {
			if (obj.constructor && _getFuncName(obj.constructor) === 'PHPJS_Resource') {
				return obj.var_dump();
			}
			lgth = 0;
			for (someProp in obj) {
				lgth++;
			}
			str += 'array('+lgth+') {\n';
			for (var key in obj) {
				var objVal = obj[key];
				if (typeof objVal === 'object' && objVal !== null &&
					!(objVal instanceof Date) && !(objVal instanceof RegExp) && !objVal.nodeName) {
					str += thick_pad + '[' + key + '] =>\n' + thick_pad + _formatArray(objVal, cur_depth + 1, pad_val, pad_char);
				} else {
					val = _getInnerVal(objVal, thick_pad);
					str += thick_pad + '[' + key + '] =>\n' + thick_pad + val + '\n';
				}
			}
			str += base_pad + '}\n';
		} else {
			str = _getInnerVal(obj, thick_pad);
		}
		return str;
	};

	output = _formatArray(arguments[0], 0, pad_val, pad_char);
	for (i=1; i < arguments.length; i++) {
		output += '\n' + _formatArray(arguments[i], 0, pad_val, pad_char);
	}

	if (d.body) {
		this.echo(output);
	}
	else {
		try {
			d = XULDocument; // We're in XUL, so appending as plain text won't work
			this.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">'+output+'</pre>');
		}
		catch (e) {
			this.echo(output); // Outputting as plain text may work in some plain XML
		}
	}
}

/*
 * Function changing status activity
**/

function changeActivity(id, link, activeName, deactiveName) {
	$.post(link, null, function(data) {
		if (parseInt(data) == 1) {
			var img = $('#' + id).children();
			var val = img.attr('alt');

			if (val == activeName) {
				img.attr({
					src: '/themes/default/icons/24x24/activate.png',
					alt: deactiveName,
					title: deactiveName
				});
			}
			if (val == deactiveName) {
				img.attr({
					src: '/themes/default/icons/24x24/deactivate.png',
					alt: activeName,
					title: activeName
				});
			}
		}
	});

	return false;
}

function loadOverlay() {
	$('body:last-child').append('<div id="codila_overlay" style="position: absolute; width: 100%; height: 100%; opacity: .5; background: #5E5E5E; top: 0; left: 0; z-index: 1500;-moz-opacity:0.45;filter:alpha(opacity=45);"></div>');
}

function removeOverlay() {
	$('#codila_overlay').remove();
}

function loadSearchTemplate(template,module,classes,action,type) {
	loadOverlay();
	$.post('/panel/panel/searchp/prepareTemplate/',{
		'template':template,
		'module':module,
		'class':classes,
		'action':action,
		'type':type
	},function(data) {
		$('body:last-child').append(data);
		$('.draggable-box').draggable();
		$('#codila_overlay').click(function() {
			$(this).remove();
			$('.codila_searchBox').remove();
		});
	});
}

function closeCodilaSearchBox() {
	$('#codila_boxSearch').remove();
	removeOverlay();
}

function ajax_loader(data) {
	$('#codilaSearchResults').html(data);
}

function codilaSearchList(formToSerialize, page) {
	ajax_loader('<img alt="" src="/themes/ajax-loader.gif">');
	$('#codila_pagin_page_number').val(page);
	$.post('/panel/panel/searchp/searchList/',$('#' + formToSerialize).serialize(),function(data) {
		$('#codilaSearchResults').html(data);
	});
}

/*
 * Function translates js files
**/

function translateJs(string) {
	var ret = '';
	$.ajax({
		url: '/translateJs/translateJs/init/' + string,
		success: function(data) {
			ret = data;
		},
		async: false
	});
	
	return ret;
}

/*
 * Function selects all checkboxes
**/

function checkAll(class_name) {
	$('.' + class_name).attr('checked',$('#' + class_name + 'All').attr('checked'));
}

function markOne(table) {
	$(table + ' tbody :checkbox').click(function() {
		if ($(this).is(':checked')) {
			$(this).parents('tr:first').addClass('codila__checked');
		} else {
			$(this).parents('tr:first').removeClass('codila__checked');
		}
	});
}

function markAll(el, table) {
	$(el).click(function() {
		$(table + ' tbody tr').addClass('codila__checked').find(':checkbox:not(:checked)').attr('checked', true);
	});
}
function unmarkAll(el, table) {
	$(el).click(function() {
		$(table + ' tbody tr').removeClass('codila__checked').find(':checkbox').removeAttr('checked');
	});
}

/*
 * Function opens main menu on click
**/

function nav(name) {
	$(name).removeClass('codila__noJS').find('> ul > li > a').click(function() {
		$(this).parent().find('> ul').fadeIn('fast');

		$(this).parent().hover(function() {
			}, function(){
				$(this).stop().find('> ul').fadeOut('normal');
			});

		return ($(this).parent().has('ul').length) ? false : true;
	});
}

/*
 * Function opens photo in original size in shadowbox
 *
**/

function shadowboxGallery() {
	Shadowbox.setup('.codila__thumbnail', {
		counterType: 'skip'
	});
}

/*
 * Function opens menu languages after click
 *
**/

function langChoice(name) {
	$(name).removeClass('codila__noJS').find('span').click(function() {
		$(this).parent().find('> ul').slideDown('normal');

		$(this).parent().hover(function() {
			}, function(){
				$(this).find('> ul').slideUp('normal');
			});

		return false;
	});
}


/*
 * Function opens links in new tab (eq. target="_blank")
 *
**/

function linkInNewTab() {
	$('a[rel="external"]').click(function() {
		this.target = '_blank';
	});
}


/*
 * Function converts rgb to hex
 *
**/

function rgb2hex(rgb) {
	if (rgb.search('rgb') == -1) {
		return rgb;
	} else {
		rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
		function hex(x) {
			return ('0' + parseInt(x).toString(16)).slice(-2);
		}
		return '#' + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); 
	}
}


/*
 * Function creating tabs when JS on
 *
**/

function createTabs() {
	$('#codila__tabs').tabs();
	$('#codila__tabs > ul').css('display', 'block');
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}



/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
 
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
		for(var item in arr) {
			var value = arr[item];

			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}


/**
 * Confirm delete checked items
 *
 * @param cs - class.name to find input type checkbox
 * @param sel- message to alert when no find checked input
 * @param del- message to confirm
 *
 * @return bool (true - if confirm, false - if not find or no confirm)
 *
 */
 
function delConfirm(cs, sel, del) {
	var b = $('input.'+cs+'[type=checkbox]');
	if (b.filter(':checked').length == 0){
		alert(sel);
		return false;
	} else {
		return confirm(del);
	}
}


/*
 * Function selects province after hover
 *
**/

function map(el) {
	$('body').delegate(el, 'mouseover mouseout', function(event) {
		if (event.type == 'mouseover') {
			$('#codila__poland').after($('<div id="codila__province"></div>'));
			$('#codila__province').addClass($(this).attr('class')).animate({opacity: 1}, 500);
		} else {
			$('#codila__province').remove();
		}
	});
}


/**
 * Block backspace
 * 
 */
 
//$(document).keydown(function(e) {
//	var element = e.target.nodeName.toLowerCase();
//	if (element != 'input' && element != 'textarea') {
//		if (e.keyCode === 8) {
//			return false;
//		}
//	}
//});

$(function() {
	$('.codila__tooltip').easyTooltip();
	linkInNewTab();
});

function print_r(theObj, silent){
	textOut='';
	if(!silent) silent=false;
	if (typeof(theObj)!='undefined') {
		if(theObj.constructor == Array ||
			theObj.constructor == Object){
			textOut="<ul>";
			for(var p in theObj){
				if(theObj[p].constructor == Array||
					theObj[p].constructor == Object){
					textOut+="<li>["+p+"] => "+typeof(theObj)+"</li>";
					textOut+="<ul>";
					textOut+=print_r(theObj[p],true);
					textOut+="</ul>";
				} else {
					textOut+="<li>["+p+"] => "+theObj[p]+"</li>";
				}
			}
			textOut+="</ul>";
		}
		if (silent) {
			return textOut;
		} else {
			alert(textOut);
		}
	}
}

