function AttachScript(src) {
	var script = document.createElement("SCRIPT");
	script.type = "text/javascript";
	script.src = src;
	document.getElementsByTagName("head")[0].appendChild(script);
	Twitter.loaded_url = src;
}
/* Additional methods */
Element.addMethods(
	{
		upToClassName : function (element, className) {
			do {
				if (element == document) {
					return false;
				}
				if (element.hasClassName && element.hasClassName(className)) {
					return element;
				}
			} while (element = $(element.parentNode));
			return false;
		},
		upToId : function (element, id) {
			do {
				if (element == document) {
					return false;
				}
				if (element.id == id) {
					return element;
				}
			} while (element = $(element.parentNode));
			return false;
		},
		upToTagName : function (element, tagName) {
			do {
				if (element == document) {
					return false;
				}
				if (element.tagName.toLowerCase() == tagName) {
					return element;
				}
			} while (element = $(element.parentNode));
			return false;
		},
		descedantOfClassName : function (element, className) {
			for (var i = 0; i < element.childNodes.length; i++) {
				if (element.childNodes[i].nodeType == 1 && $(element.childNodes[i]).hasClassName(className))
					return element.childNodes[i];
			}
			return false;
		},
		descedantsOfClassName : function (element, className) {
			var descedants = [];
			for (var i = 0; i < element.childNodes.length; i++) {
				if (element.childNodes[i].nodeType == 1 && $(element.childNodes[i]).hasClassName(className))
					descedants[descedants.length] = element.childNodes[i];
			}
			return descedants;
		},
		getPosition : function (element) {
			var left = 0;
			var top  = 0;
			do {
				left += element.offsetLeft;
				top  += element.offsetTop;
			} while (element = element.offsetParent);
			return {'left' : left, 'top' : top};
		}
	}
);

/* Window show/hide/options */
var WindowOptions = {
	/* params */
	classes : {
		toggle  : 'toggle',
		option  : 'options',
		optionOpen : 'options-open',
		window  : 'area',
		content : 'container',
		collapsable : 'titled',
		title   : 'title',
		open    : 'area-open',
		hide    : 'area-close',
		wait    : 'area-hold'
	},
	/* set all window size togglers */
	fullSetup : function (start) {
		start = $(start);
		if (!start)
			return false;
		var elements = start.getElementsByClassName(WindowOptions.classes.window);
		for (var i = 0; i < elements.length; i++)
			WindowOptions.windowSetup(elements[i]);
		Tabber.setAll(start);
		return false;
	},
	/* set size toggler on window */
	windowSetup : function (wnd) {
		wnd = $(wnd);
		if (
			wnd
			&&
			(
				wnd.hasClassName(WindowOptions.classes.open)
				||
				wnd.hasClassName(WindowOptions.classes.hide)
				||
				wnd.hasClassName(WindowOptions.classes.wait)
			)
		) {
			var title = wnd.descedantOfClassName(WindowOptions.classes.title);
			if (title) {
				title.onclick = WindowOptions.toggleSize;
			}
		}
	},
	/* set options toggler on window */
	optionsSetup : function (wnd, options, windowOptions) {
		if (typeof windowOptions == 'undefined' || !windowOptions) {
			var windowOptions = {};
		}
		$H(WindowOptions.classes).each(
			function (item) {
				if (typeof windowOptions[item.key] == 'undefined') {
					windowOptions[item.key] = item.value;
				}
			}
		);
		var holder = document.createElement('ul');
		for (var i = 0; i < options.length; i++) {
			holder.appendChild(document.createElement('li'));
			holder.lastChild.appendChild(document.createElement('a'));
			holder.lastChild.lastChild.appendChild(document.createTextNode(options[i].text));
			holder.lastChild.lastChild.href = options[i].link;
			holder.lastChild.lastChild.rel = 'nofollow';
			holder.lastChild.lastChild.onclick = WindowOptions.loadOption;
			holder.lastChild.lastChild.__loadType = options[i].load;
		}
		holder.onclick = WindowOptions.toggleOptions;
		var label = document.createElement('a');
		label.href = '#';
		label.appendChild(document.createTextNode(HWW.strings.Options));
		label.className = 'label';
		label.onclick = WindowOptions.toggleOptions;
		var container = document.createElement('div');
		container.className = WindowOptions.classes.option;
		container.__windowOptions = windowOptions;
		container.appendChild(label);
		container.appendChild(holder);
		$(wnd).appendChild(container);
		$(container.parentNode).addClassName('with-options');
	},
	/* options toggler */
	toggleOptions : function (element) {
		element = $(!element || element.type ? this : element).up();
		if (element.className == element.__windowOptions.option) {
			element.className = element.__windowOptions.optionOpen;
		}
		else {
			element.className = element.__windowOptions.option
		}
		return false;
	},
	/* options loader */
	loadOption : function (element) {
		element = $(!element || element.type ? this : element);
		if (!element) {
			return false;
		}
		var options = element.upToClassName(WindowOptions.classes.option)
			||
			element.upToClassName(WindowOptions.classes.optionOpen);
		if (!options || !options.__windowOptions) {
			options = WindowOptions.classes;
		}
		else {
			options = options.__windowOptions;
		}
		var content = element.upToClassName(options.window);
		var id = content.id;
		var onComplete = function () {}
		if (!element.__loadType || element.__loadType == 'content') {
			if (content.hasClassName('block')) {
				content = content.descedantOfClassName('content');
			}
			else {
				content = $$("#" + id + " .container > .content")[0];
			}
			if (!content.id) {
				content.id = 'WindowContent' + Math.round(Math.random() * 1000);
			}
			HWW.killEditor(content);
			id = content.id;
			new Loader(content, {text:HWW.strings.Loading});
		}
		else if (element.__loadType == 'window') {
			var holder = document.createElement('div');
			holder.id = 'AjaxHolder' + Math.round(Math.random() * 1000);
			holder.className = 'ajax-holder';
			content.parentNode.insertBefore(holder, content);
			HWW.killEditor(content);
			content.parentNode.removeChild(content);
			id = holder.id;
			new Loader(holder, {text:HWW.strings.Loading});
			onComplete = function () {
				var holder = document.getElementById(id);
				while (holder.firstChild) {
					holder.parentNode.insertBefore(holder.removeChild(holder.firstChild), holder);
				}
				holder.parentNode.removeChild(holder);
			}
		}
		new Ajax.Updater(
			id,
			HWW.randomUrl(HWW.ieUrl(element)),
			{
				evalScripts : true,
				onComplete : onComplete,
				requestHeaders : [
					'X-Referer', HWW.ieUrl(window.location.href),
					'X-Update', id
				]
			}
		);
		return false;
	},
	/* Maximize window */
	maximize : function (element) {
		element = WindowOptions.__getWindow(element, this);
		if (!element)
			return false;
		if (element.hasClassName(WindowOptions.classes.open))
			return false;
		else
			return WindowOptions.toggleSize(element);
	},
	/* Minimize window */
	minimize : function (element) {
		element = WindowOptions.__getWindow(element, this);
		if (!element)
			return false;
		if (element.hasClassName(WindowOptions.classes.hide))
			return false;
		else
			return WindowOptions.toggleSize(element);
	},
	/* Toggle min/max size of window */
	toggleSize : function (element) {
		element = WindowOptions.__getWindow(element, this);
		if (!element || element.hasClassName(WindowOptions.classes.wait)){
			return false;
		}

		var content = element.descedantOfClassName(WindowOptions.classes.content);
		var isHidden = element.hasClassName(WindowOptions.classes.hide);
		element.addClassName(WindowOptions.classes.wait);
		if (!content.__originalHeight && !isHidden) {
			content.__originalHeight = content.offsetHeight;
		}
		if (isHidden) {
			content.style.display = 'none';
			element.removeClassName(WindowOptions.classes.hide);
		}
		new Effect.toggle(
			content,
			'blind',
			{
				afterFinish : WindowOptions.__afterToggle,
				duration : WindowOptions.__getDuration(content.__originalHeight)
			}
		);
		return false;
	},
	__getWindow : function (element, caller) {
		element = $(!element || element.type ? caller : element);
		if (!element)
			return false;
		else
			return element.upToClassName(WindowOptions.classes.window);
	},
	/* Get duration for maximize/minimize effect */
	__getDuration : function (height) {
		if (!height)
			return .5;
		if (height < 50)
			return .2;
		if (height < 110)
			return .3;
		if (height < 170)
			return .4;
		if (height < 230)
			return .5;
		if (height < 290)
			return .6;
		if (height < 350)
			return .7;
		if (height < 410)
			return .8;
		if (height < 460)
			return .9;
		return 1;
	},
	/* Fixes after maximize/minimize effect */
	__afterToggle : function (effect) {
		var element = effect.element.upToClassName(WindowOptions.classes.window);
		if (effect.element.getStyle('display') == 'none') {
			element.removeClassName(WindowOptions.classes.open);
			element.addClassName(WindowOptions.classes.hide);
		}
		else {
			element.removeClassName(WindowOptions.classes.hide);
			element.addClassName(WindowOptions.classes.open);
		}
		element.removeClassName(WindowOptions.classes.wait);
		WindowOptions.afterToggle(element);
	},
	/* User callback after maximize/minimize effect */
	afterToggle : function (wnd) {}
}

var Loader = Class.create();
Loader.prototype = {
	defaultText : 'Loading',
	__needInit : [],
	initialize : function (target, options) {
		if (options && options.element == 'popup') {
			target = document.getElementsByTagName('body')[0];
			options.append = true;
		}
		this.target = $(target);
		if (!this.target) {
			return;
		}
		if (!options) {
			this.clear();
			this.text = HWW.strings[this.defaultText] || this.defaultText;
			this.target.appendChild(this.paragraph());
		}
		else {
			this.text = typeof(options.text) != 'undefined' ? options.text : HWW.strings[this.defaultText] || this.defaultText;
			this.title = typeof(options.title) != 'undefined' ? options.title : false;
			this.id = typeof(options.id) != 'undefined' ? options.id : false;
			this.tagName = typeof(options.tagName) != 'undefined' ? options.tagName : 'p';

			if (!this[options.element]) {
				if (this.tagName) {
					options.element = 'tag';
				}
				else {
					options.element = 'paragraph';
				}
			}

			if (typeof(options.insertAfter) != 'undefined') {
				target = $(options.insertAfter);
				target.parentNode.insertBefore(this[options.element](), target.nextSibling);
			}
			else if (typeof(options.insertBefore) != 'undefined') {
				target = $(options.insertBefore);
				target.parentNode.insertBefore(this[options.element](), target);
			}
			else if (typeof(options.insertFirst) != 'undefined') {
				this.target.insertBefore(this[options.element](), this.target.firstChild);
			}
			else if (!options.append) {
				this.clear();
				this.target.appendChild(this[options.element]());
			}
			else {
				var loaderElement = this[options.element]();
				this.target.appendChild(loaderElement);
			}
			for (var i = 0; i < this.__needInit.length; i++) {
				Turn.set(this.__needInit[i]);
			}
		}
	},
	clear : function (target) {
		if (!target)
			target = this.target;
		while (target.firstChild)
			target.removeChild(target.firstChild);
	},
	tag : function () {
		var element = document.createElement(this.tagName);
		element.className = 'loader';
		element.appendChild(document.createTextNode(this.text));
		if (this.id) {
			element.id = this.id;
		}
		return element;
	},
	paragraph : function () {
		var element = document.createElement('p');
		element.className = 'loader';
		element.appendChild(document.createTextNode(this.text));
		if (this.id)
			element.id = this.id;
		return element;
	},
	window : function () {
		if (this.target.id == 'aside') {
			return this.aside();
		}
		var element = document.createElement('div');
		if (this.id) {
			element.id = this.id + 'Outer';
		}
		element.appendChild(document.createElement('div'));
		element.lastChild.className = 'lt';
		element.appendChild(document.createElement('div'));
		element.lastChild.className = 'rt';
		if (this.title) {
			element.className = 'window titled';
			element.appendChild(document.createElement('h2'));
			element.lastChild.className = 'title';
			element.lastChild.appendChild(document.createTextNode(this.title));
			this.__needInit[this.__needInit.length] = element.id;
		}
		else {
			element.className = 'window';
		}
		element.appendChild(document.createElement('div'));
		element.lastChild.className = 'container';
		element.lastChild.appendChild(document.createElement('div'));
		element.lastChild.lastChild.className = 'content';
		if (this.id) {
			element.lastChild.lastChild.id = this.id + 'Inner';
		}
		this.id = false;
		this.title = false;
		element.lastChild.lastChild.appendChild(this.paragraph());
		return element;
	},
	aside : function () {
		var element = document.createElement('div');
		element.className = 'section';
		if (this.id) {
			element.id = this.id;
		}
		element.appendChild(document.createElement('h2'));
		element.lastChild.appendChild(document.createTextNode(this.title));
		element.appendChild(document.createElement('div'));
		if (this.id) {
			element.lastChild.id = this.id + 'Inner';
		}
		this.id = false;
		this.title = false;
		element.lastChild.appendChild(this.paragraph());
		return element;
	},
	popup : function () {
		var element = $('overlay');
		if (!element) {
			element = document.createElement('div');
			element.id = 'overlay';

			// IE6 guess
			if (Prototype.Version < '1.6') {
				var tmp = document.createElement('iframe');
				tmp.className = 'ieIframeFix';
				element.appendChild(tmp);
				$(element).show();
			}

			var tmp = document.createElement('div');
			tmp.className = 'opacity';
			element.appendChild(tmp);

			var container = tmp.appendChild(document.createElement('div'));
			container.className = 'container';

			tmp = container.appendChild(document.createElement('div'));
			tmp.className = 'content';
		}
		else {
			var container = $(element).descedantOfClassName('opacity').firstChild;
			if (HWW.winLevel == 1) {
				// first popup
				var tmp = container.firstChild;
				this.clear(tmp);
			}
			else {
				// popup is called from another popup
				var new_window = document.createElement('div');
				new_window.id = 'temp';
				new_window.className = 'content cascade';
				container.insertBefore(new_window, container.firstChild);
				var tmp = $(new_window);
				var margin = HWW.cascadeOffset * (HWW.winLevel - 1) +
					3 * (HWW.winLevel - 2) + 'px';
				tmp.setStyle({
					marginTop : margin,
					marginLeft : margin,
					zIndex : HWW.winLevel - 1
				});
			}
		}
		element.style.height = this.target.offsetHeight +
			parseInt(this.target.getStyle('marginTop')) +
			parseInt(this.target.getStyle('marginBottom')) +
			parseInt(this.target.getStyle('paddingTop')) +
			parseInt(this.target.getStyle('paddingBottom')) +
			'px';
		container.style.marginTop =
			(document.documentElement.scrollTop || document.body.scrollTop) +
			document.documentElement.clientHeight/10 +
			'px';
		$(element).show();
		if (this.id) {
			tmp.id = this.id;
			this.id = false;
		}
		tmp.appendChild(this.paragraph());
		Tip.hideFieldTip();
		return element;
	}
};

var Tip = {
	tipClass : 'tip',
	fields : {},
	set : function (args) {
		if (!args || typeof args != 'object')
			return;
		for (var id in args) {
			if (typeof args[id] == 'string') {
				var field = $(id);
				if (!field)
					return;
				Tip.fields[id] = args[id];
				field.tipDefaultValue = args[id];
				field.observe('focus', Tip.processFocus.bind(field));
				field.observe('blur', Tip.processBlur.bind(field));
			if (!field.value) {
					field.value = Tip.fields[id];
					field.addClassName(Tip.tipClass);
				}
			}
		}
	},
	process : function () {
		var field = $(this);
		if (field.hasClassName(Tip.tipClass)) {
			field.value = '';
			field.removeClassName(Tip.tipClass);
		}
		else if (!field.value) {
			field.value = Tip.fields[field.id];
			field.addClassName(Tip.tipClass);
		}
	},
	processFocus : function () {
		var field = $(this);
		if (field.value == Tip.fields[field.id]) {
			field.value = '';
		}
		field.removeClassName(Tip.tipClass);
	},
	processBlur : function () {
		var field = $(this);
		if (!field.usingTagCloud && !field.value) {
			field.value = Tip.fields[field.id];
			field.addClassName(Tip.tipClass);
		}
	},
	/* Field tip */
	fieldTip : false,
	fieldTipClose : false,
	fieldTipText : {},
	setFieldTipEvents : function (ids) {
		for (var i = 0; i < ids.length; i++)
			document.getElementById(ids[i]).onclick = Tip.toggleFieldTip;
	},
	setFieldTipTexts : function (values) {
		for (var i = 0; i < values.length; i++)
			Tip.fieldTipText[values[i].id] = values[i].text;
	},
	setFieldTip : function (tip, text) {
		if (!Tip.fieldTip) {
			Tip.fieldTip = document.createElement('div');
			Tip.fieldTip.className = 'tip';
			Tip.fieldTip.style.display = 'none';
			document.getElementsByTagName('body')[0].appendChild($(Tip.fieldTip));
			Tip.fieldTipClose = document.createElement('div');
			Tip.fieldTipClose.className = 'close';
			Tip.fieldTipClose.onclick = Tip.hideFieldTip;
		}
		Tip.fieldTip.innerHTML = text;
		Tip.fieldTip.insertBefore(Tip.fieldTipClose, Tip.fieldTip.firstChild);

		var pos = tip.getPosition();
		Tip.fieldTip.style.left = pos.left + 'px';
		Tip.fieldTip.style.top  = pos.top + 'px';
	},
	showFieldTip : function (tip) {
		tip = $(!tip || tip.type ? this : tip);
		Tip.setFieldTip(tip, Tip.fieldTipText[tip.id] || tip.title);
		Tip.fieldTip.style.display = 'block';
	},
	hideFieldTip : function (tip) {
		if (Tip.fieldTip)
			Tip.fieldTip.style.display = 'none';
	},
	toggleFieldTip : function (tip) {
		tip = $(!tip || tip.type ? this : tip);
		Tip.setFieldTip(tip, Tip.fieldTipText[tip.id] || tip.title);
		Tip.fieldTip.toggle();
	}
}

var Disease = {
	loading : {},
	reload : {},
	setAll : function (id) {
		var items = document.getElementById(id);
		for (var i = 0; i < items.childNodes.length; i++) {
			if (items.childNodes[i].tagName && items.childNodes[i].tagName.toLowerCase() == 'ul') {
				links = items.childNodes[i].getElementsByTagName('a');
				for (var j = 0; j < links.length; j++)
					links[j].onclick = Disease.loadList;
			}
		}
	},
	loadList : function (item) {
		item = $(!item || item.type ? this : item);
		var container = item.upToClassName('diseases').parentNode;
		if (!container.id)
			container.id = 'DiseaseWidget' + Math.round(Math.random() * 1000);
		new Loader(container.id, {text:'Loading diseases list...'});
		new Ajax.Updater(
			container.id,
			HWW.randomUrl(HWW.ieUrl(item)),
			{
				onComplete : HWW.popupCorrectHeight,
				evalScripts : true,
				requestHeaders : [
					'X-Referer', HWW.ieUrl(window.location.href),
					'X-Update', container.id
				]
			}
		);
		return false;
	},
	setBasic : function (id, url, name, options) {
		var input = $(id);
		if (!input) {
			return false;
		}
		id = input.id;
		var link = $(id + 'CheckLink');
		if (!link) {
			link = document.createElement('span');
			link.id = id + 'CheckLink';
			link.className = 'float-left ajax-link';
			link.style.marginRight = '.5em';
			link.appendChild(document.createTextNode(HWW.strings.BaseDiseaseWidgetCheck));
			input.parentNode.insertBefore(link, input.nextSibling);
		}
		link.__sourceInput = id;
		if (typeof options == 'undefined') {
			var options = {};
		}
		if (!options.result) {
			options.result = id + "CheckResult";
		}
		input.__targetContainer = link.__targetContainer = options.result;
		link.onclick = function () {
			var container = $(this.__targetContainer);
			if (!container) {
				container = document.createElement('div');
				container.id = this.__targetContainer;
				container.className = "clear-both";
				$(this.__sourceInput).parentNode.appendChild(container);
				container = $(container);
			}
			new Loader(container.id, {text:'Loading diseases list...'});
			var headers = {
				'X-Referer' : HWW.ieUrl(window.location.href),
				'X-Update'  : container.id
			}
			if (options.headers) {
				$H(options.headers).each(
					function (item) {
						if (item.value) {
							headers[item.key] = item.value;
						}
					}
				);
			}
			new Ajax.Updater(
				container.id,
				HWW.randomUrl(HWW.ieUrl(url)),
				{
					onComplete : HWW.popupCorrectHeight,
					parameters : {
						'string' : input.value,
						'input' : name
					},
					evalScripts : true,
					requestHeaders : headers
				}
			);
			return false;
		}
		Disease.setBasicResult(input);
		return true;
	},
	setBasicResult : function (id) {
		var input = $(id);
		if (!input) {
			return false;
		}
		id = input.id;
		var onclick = function () {
			var item = $(this).upToTagName('li');
			if (item.up().hasClassName("filters")) {
				$(id + "Checked").appendChild(
					item.parentNode.removeChild(item)
				);
				$(id).addClassName("margin-left");
			}
			else {
				var checkResult = $(input.__targetContainer);
				if (checkResult) {
					checkResult.descedantOfClassName("filters").appendChild(
						item.parentNode.removeChild(item)
					);
					if (!$(id + "Checked").childNodes.length) {
						$(id).removeClassName("margin-left");
					}
				}
			}
			return true;
		}
		var container = $(input.__targetContainer);
		if (container) {
			$A(container.getElementsByTagName("input")).each(
				function (item) {item.onclick = onclick}
			);
		}
		HWW.popupCorrectHeight();
		return true;
	},
	setAdvanced : function (widgetId, loadUrl, targetName, options) {
		if (typeof options == 'undefined') {
			var options = {};
		}
		var widget = $(widgetId);
		widget.__loadUrl = loadUrl;
		widget.__targetName = targetName;
		if (!options.result) {
			widget.__resultsContainer = widget.id + "Result";
			widget.descedantOfClassName("disease-widget-advanced-result").id =
				widget.__resultsContainer;
		}
		else {
			widget.__resultsContainer = options.result;
		}
		$$("#" + widget.id + " .disease-widget-advanced-dimension input").each(
			function (item) {
				if (item.type == 'checkbox') {
					item.onclick = function () {
						this.parentNode.parentNode.parentNode.removeChild(
							this.parentNode.parentNode
						);
						Disease.loadAdvancedList(widgetId);
					}
				}
			}
		);
		widget.__popupHeader = {};
		if (options.headers) {
			$H(options.headers).each(
				function (item) {
					if (item.value) {
						widget.__popupHeader[item.key] = item.value;
					}
				}
			);
		}
		$$("#" + widget.id + " .disease-widget-advanced-dimension a.icon").each(
			function (item) {
				item = $(item);
				var targetId = item.upToTagName("dl").id;
				var form = item.upToTagName('form');
				if (form) {
					if (!form.id) {
						form.id = 'Form' + Math.round(Math.random() * 1000);
					}
					item.__popupForm = form.id;
				}
				item.__popupMethod = 'post';
				item.__onComplete = "Disease.setAdvancedChooser('" + targetId + "')"
				item.onclick = HWW.popupLink;
			}
		);
		Disease.reload[widget.id] = false;
		Disease.loading[widget.id] = false;
	},
	setAdvancedChooser : function (targetId) {
		HWW.popupCorrectHeight();
		$$("#overlay .disease-widget-advanced-dimension input").each(
			function (item) {
				// this is for IE6 that uncheck elements when show chooser loader
				// reason unknown, happens in Loader, on final appendChild call
				item.checked = true;
			}
		);
		$$("#overlay .disease-widget-advanced-chooser input").each(
			function (item) {
				if (item.type == 'checkbox') {
					item.onclick = function () {
						var targetList = $(targetId);
						var widgetId = targetList.upToClassName("disease-widget-advanced").id;
						targetList.insertBefore(
								document.createElement("dd"),
								$$("#" + targetList.id + " dt + dd")[0]
							).
							appendChild(
								this.parentNode.parentNode.removeChild(
									this.parentNode
								)
							);
						this.checked = true;
						Disease.loadAdvancedList(widgetId);
						this.onclick = function () {
							this.parentNode.parentNode.parentNode.removeChild(
								this.parentNode.parentNode
							);
							Disease.loadAdvancedList(widgetId);
						}
						HWW.popupClose();
					}
				}
			}
		);
	},
	loadAdvancedList : function (widgetId) {
		var widget = $(widgetId);
		widgetId = widget.id;
		if (Disease.loading[widgetId]) {
			Disease.reload[widgetId] = true;
			return;
		}

		var result = $(widget.__resultsContainer);
		new Loader(result);
		var params = {input : widget.__targetName};
		$$("#" + widget.id + " .disease-widget-advanced-dimension input").each(
			function (item) {
				if (item.type == 'checkbox' && item.checked) {
					params[item.name] = item.value;
				}
			}
		);
		var headers = {
			'X-Referer' : HWW.ieUrl(window.location.href),
			'X-Update'  : result.id
		}
		if (widget.__popupHeader) {
			$H(widget.__popupHeader).each(
				function (item) {
					if (item.value) {
						headers[item.key] = item.value;
					}
				}
			);
		}
		Disease.reload[widgetId] = false;
		Disease.loading[widgetId] = true;
		new Ajax.Updater(
			result.id,
			HWW.randomUrl(widget.__loadUrl),
			{
				parameters : params,
				evalScripts : true,
				onComplete : function () {
					Disease.loading[widgetId] = false;
					if (Disease.reload[widgetId]) {
						Disease.loadAdvancedList(widgetId);
					}
					HWW.popupCorrectHeight()
				},
				requestHeaders : headers
			}
		);
		HWW.popupCorrectHeight();
	},
	widget : {
		init : function (target_id, max) {
			var target = $(target_id + 'Result');
			$A(target.getElementsByTagName("input")).each(
				function (item) {
					$(item).observe(
						'click',
						Disease.widget.unselect.bind(item)
					);
				}
			);
			$A(target.getElementsByClassName("empty")).each(
				function (item) {
					item.id = target_id + 'Empty';
				}
			);
			var clearLink = document.createElement('li');
			clearLink.innerHTML = HWW.strings.DiseaseWidgetClear;
			clearLink.id = target_id + "Clear";
			clearLink.className = 'empty ajax-link';
			target.appendChild(clearLink);
			$(clearLink).observe('click', Disease.widget.clear.bind(clearLink));
			var clearAllLink = document.createElement('li');
			clearAllLink.innerHTML = HWW.strings.DiseaseWidgetClearAll;
			clearAllLink.id = target_id + "ClearAll";
			clearAllLink.className = 'empty ajax-link';
			target.appendChild(clearAllLink);
			$(clearAllLink).observe('click', Disease.widget.clear.bind(clearAllLink));
			if (max) {
				var maxError = target.getElementsByClassName("error-message");
				if (maxError.length) {
					maxError = maxError[0];
				}
				else {
					maxError = document.createElement('li');
					maxError.innerHTML = MHE.l10n.getMsg(
						"DiseaseWidgetTooMuchError",
						{count : max}
					);
					maxError.className = "error-message";
					target.insertBefore(maxError, target.firstChild);
				}
				maxError.id = target_id + "MaxError";
				maxError.__max = max;
			}
			Disease.widget.processNote(target);
			Search.touchButton(target);
		},
		processPopup : function (source_id, target_id) {
			var target = $(target_id + 'Result');
			var source = $(source_id + 'Result');
			if (target && source) {
				$A(source.upToClassName('form2').getElementsByClassName('submit')).
					each (
						function (item) {
							Disease.widget.addEnter = function (event) {
								if (typeof event == 'undefined') {
									event = window.event;
								}
								if (event.keyCode == Event.KEY_RETURN) {
									Disease.widget.add(source.id, target.id);
								}
								return true;
							}
							Event.observe(
								item,
								'click',
								Disease.widget.add.bind(item, source.id, target.id)
							);
							Event.observe(
								document.documentElement,
								'keyup',
								Disease.widget.addEnter
							);
						}
					);
				Disease.widget.processNote(target.id);
			}
			HWW.addPopupCloseCallback(
				function () {
					Event.stopObserving(
						document.documentElement,
						'keyup',
						Disease.widget.addEnter
					);
				}
			);
		},
		blockAdd : function (source) {
			var form = $(source).upToClassName('form2');
			form.__disable = true;
			$A(form.getElementsByClassName('submit')).each(
				function (item) {
					$(item).addClassName('disabled');
				}
			);
		},
		revokeAdd : function (source) {
			var form = $(source).upToClassName('form2');
			form.__disable = false;
			$A(form.getElementsByClassName('submit')).each(
				function (item) {
					$(item).removeClassName('disabled');
				}
			);
		},
		add : function (source, target) {
			target = $(target);
			source = $(source);
			if (source.upToClassName('form2').__disable) {
				return false;
			}
			var rootId = target.upToClassName("disease").id;
			$A(source.getElementsByTagName("input")).each(
				function (item) {
					if (item.checked) {
						var selector = "#" + target.id + " input[value=" + item.value + "]";
						if (!$$(selector).length) {
							item = $(item);
							item.id = rootId + item.value;
							item.next().htmlFor = item.id;
							target.insertBefore(
								item.parentNode.parentNode.removeChild(
									item.parentNode
								),
								target.lastChild.previousSibling
							);
							item.checked = true;
							item.observe(
								'click',
								Disease.widget.unselect.bind(item)
							);
						}
					}
				}
			);
			Disease.widget.processNote(target);
			Search.touchButton(target);
			HWW.popupClose();
			return true;
		},
		clear : function () {
			var target = $(this).upToClassName("disease");
			var clearAll = this.id == target.id + "ClearAll";
			$A(target.getElementsByTagName("input")).each(
				function (item) {
					if (clearAll || !item.checked) {
						item.parentNode.parentNode.removeChild(item.parentNode);
					}
				}
			);
			Disease.widget.processNote(target);
		},
		unselect : function () {
			var target = $(this).upToClassName("disease");
			Disease.widget.processNote(target);
		},
		processNote : function (target) {
			target = $(target);
			var selected = 0;
			var noteAction = "show";
			var clearAction = "hide";
			var clearAllAction = "hide";
			var inputs = target.getElementsByTagName("input");
			if (inputs.length) {
				noteAction = "hide";
				clearAllAction = "show";
				for (var i = 0; i < inputs.length; i++) {
					if (!inputs[i].checked) {
						clearAction = "show";
					}
					else {
						selected++;
					}
				}
			}
			$(target.upToClassName("disease").id + "Empty")[noteAction]();
			$(target.upToClassName("disease").id + "Clear")[clearAction]();
			$(target.upToClassName("disease").id + "ClearAll")[clearAllAction]();
			var maxError = $(target.upToClassName("disease").id + "MaxError");
			if (maxError) {
				maxError[selected > maxError.__max ? "show" : "hide"]();
			}
			HWW.popupCorrectHeight();
			Search.touchButton(target);
		},
		processResult : function (source) {
			source = $(source);
			if (!source) {
				return false;
			}
			var enable = false;
			$A(source.getElementsByTagName("input")).each(
				function (item) {
					if (item.checked) {
						enable = true;
					}
					if (!item.__observed) {
						item.__observed = true;
						$(item).observe(
							"click",
							Disease.widget.processResult.bind(item, source.id)
						);
					}
				}
			);
			if (enable) {
				Disease.widget.revokeAdd(source);
			}
			else {
				Disease.widget.blockAdd(source);
			}
		},
		lettersSwitcher : function (result, target, source) {
			result = $(result);
			if (!result) {
				return false;
			}
			var dl = result.upToTagName("dl");
			if (!dl) {
				dl = result;
				result = dl.getElementsByTagName("dd")[0];
			}
			var switcher = function (event) {
				if (typeof event == 'undefined') {
					var event = window.event;
				}
				Event.stop(event)
				new Loader(result.id);
				var thisDt = $(this).up();
				$A(thisDt.up().getElementsByTagName("dt")).each(
					function (dt) {
						$(dt).removeClassName("active");
					}
				);
				thisDt.addClassName("active");
				new Ajax.Updater(
					result.id,
					HWW.randomUrl(HWW.ieUrl(this)),
					{
						method : 'get',
						onComplete : HWW.popupCorrectHeight,
						evalScripts : true,
						requestHeaders : {
							'X-Referer' : HWW.ieUrl(window.location.href),
							'X-Update'  : result.id,
							'X-Source'  : source,
							'X-Target'  : target
						}
					}
				);
				return false;
			}
			$A(dl.getElementsByTagName("dt")).each(
				function (dt) {
					var link = $(dt).down();
					link.observe(
						"click",
						switcher.bind(link)
					);
				}
			);
			return true;
		}
	}
}

var Tabber = {
	defaults : {
		text : 'Loading',
		texts : {},
		tabs : 'tabs',
		active : 'active',
		root : 'content'
	},
	set : function (element) {
		if ($(element).hasClassName('no-ajax')) {
			return;
		}
		var tabs = element.getElementsByTagName('li');
		for (var i = 0; i < tabs.length; i++) {
			tabs[i].__hww_text = Tabber.currents.texts[tabs[i].id] ? Tabber.currents.texts[tabs[i].id] : Tabber.currents.text;
			tabs[i].__hww_class = Tabber.currents.active;
			tabs[i].getElementsByTagName('a')[0].onclick = Tabber.load;
		}
	},
	setAll : function (root, options) {
		Tabber.defaults.text = HWW.strings[Tabber.defaults.text] || Tabber.defaults.text;
		if (typeof options == 'undefined') {
			Tabber.currents = Tabber.defaults;
		}
		else {
			for (var item in Tabber.defaults) {
				Tabber.currents[item] = typeof options[item] == 'undefined' ? Tabber.defaults[item] : options[item];
			}
			if (typeof options.texts != 'undefined') {
				Tabber.currents.texts = options.texts;
			}
		}
		$A($(typeof root == 'undefined' ? Tabber.currents.root : root).getElementsByClassName(Tabber.currents.tabs)).each(Tabber.set);
	},
	load : function (tab) {
		tab = $(typeof tab == 'undefined' ? this : HWW.elementFromEvent(tab));
		var isAside = tab.upToId('aside');
		if (tab.tagName.toLowerCase() == 'span')
			tab = $(tab.parentNode);
		else if (tab.tagName.toLowerCase() == 'li')
			tab = tab.down();
		var target = tab.upToClassName(isAside ? 'window' : WindowOptions.classes.window).descedantOfClassName('container').descedantOfClassName('content');
		Tabber.activate(tab.parentNode);
		HWW.killEditor(target);
		new Loader(target, {text : tab.__hww_text});
		var url = HWW.ieUrl(tab);
		new Ajax.Updater(
			target.id,
			HWW.randomUrl(url),
			{
				method : 'get',
				evalScripts : true,
				requestHeaders : [
					'X-Referer', HWW.ieUrl(window.location.href),
					'X-Update', target.id
				],
				onSuccess : function (transport) {
					var fav = $('FavoritePage');
					if (fav) {
						if (parseInt(transport.getResponseHeader('X-Favoritable'))) {
							fav.href = transport.getResponseHeader('X-Favorite');
							if (parseInt(transport.getResponseHeader('X-Favorited'))) {
								fav.className = 'icon i-cross';
								fav.firstChild.nodeValue = HWW.strings.FavRem;
							}
							else {
								fav.className = 'icon i-star';
								fav.firstChild.nodeValue = HWW.strings.FavAdd;
							}
							fav.parentNode.style.display = 'block';
						}
						else {
							fav.parentNode.style.display = 'none';
						}
					}
				}
			}
		);
		return false;
	},
	activate : function (tab) {
		tab = $(typeof tab == 'undefined' ? this : tab);
		var items = tab.upToTagName('ul');
		items = items.getElementsByTagName('li');
		for (var i = 0; i < items.length; i++) {
			$(items[i]).removeClassName(items[i].__hww_class);
			$(items[i]).removeClassName('hover');
		}
		tab.addClassName(tab.__hww_class);
		return false;
	}
};

var Submitter = Class.create();
Submitter.prototype = {
	texts : {
		load : 'Sending form...',
		success : 'Form successfully sent.',
		fail : 'Some error occured, please try again.'
	},
	initialize : function (target, options) {
		this.target = $(target);
		if (!this.target) {
			return;
		}

		this.target.__hww_texts = this.texts;
		if (!this.target.parentNode.id) {
			this.target.parentNode.id = 'Updater' + Math.round(Math.random() * 1000);
		}

		var headers = {'X-Referer' : HWW.ieUrl(window.location.href)};
		if (typeof options != 'undefined') {
			if (options === false) {
				return;
			}

			if (typeof options.update == 'undefined') {
				options.update = this.target.parentNode.id;
			}

			this.setBefore(options);
			var callbacks = this.getAfter(options);
			var method = options.method || this.target.method;
			headers['X-Update'] = typeof options.update == 'string'
				?
				options.update
				:
				this.target.id;
		}
		else {
			options.update = this.target.parentNode.id;
			this.setBefore();
			var callbacks = this.getAfter();
			var method = this.target.method;
			headers['X-Update'] = options.update;
		}
		if (typeof options.header != 'undefined') {
			$H(options.header).each(
				function (item) {
					if (item.value) {
						headers[item.key] = item.value;
					}
				}
			);
		}

		if (options.update) {
			this.target.onsubmit = function () {
				HWW.killEditor($(this).upToTagName('form'));
				Tip.hideFieldTip();
				this.__hww_before();
				new Ajax.Updater(
					options.update,
					HWW.randomUrl(HWW.ieUrl(this)),
					{
						method : method,
						parameters : $(this).serialize(),
						evalScripts : true,
						onSuccess : callbacks.onSuccess,
						onFailure : callbacks.onFailure,
						onComplete : callbacks.onComplete,
						onCreate : callbacks.onCreate,
						requestHeaders : headers
					}
				);
				return false;
			}
		}
		else {
			this.target.onsubmit = function () {
				HWW.killEditor($(this).upToTagName('form'));
				Tip.hideFieldTip();
				this.__hww_before();
				new Ajax.Request(
					HWW.randomUrl(HWW.ieUrl(this)),
					{
						method : method,
						parameters : $(this).serialize(),
						evalScripts : true,
						onSuccess : callbacks.onSuccess,
						onFailure : callbacks.onFailure,
						onComplete : callbacks.onComplete,
						onCreate : callbacks.onCreate
					}
				);
				return false;
			}
		}
	},
	setBefore : function (options) {
		if (typeof options.scroll == 'undefined') {
			options.scroll = true;
		}
		if (typeof options.before == 'function') {
			this.target.__hww_before = options.before;
		}
		else if (typeof options.before == 'string') {
			this.target.__hww_before = function() {
				eval(options.before)
			};
		}
		else if (typeof options.loader == 'object') {
			if (!options.loader.id) {
				options.loader.id = 'Popup' + Math.round(Math.random() * 1000);
			}
			if (options.loader.target)	{
				this.target.__hww_before = function () {
					var loader = new Loader(
						options.loader.target,
						options.loader
					);
					if (options.scroll) {
						$(options.loader.id).scrollTo();
					}
				}
			}
			else {
				this.target.__hww_before = function () {
					var target = $(this);
					if (options.scroll) {
						this.scrollTo();
					}
					this.hide();
					new Loader(
						this.parentNode.id,
						options.loader
					);
				}
			}
		}
		else if (typeof options.loader == 'string') {
			this.target.__hww_before = function () {
				var target = $(this);
				if (options.scroll) {
					this.scrollTo();
				}
				this.hide();
				new Loader(
					this.parentNode,
					{
						text : options.loader,
						append : true
					}
				);
			}
		}
		else {
			this.target.__hww_before = function () {
				var target = $(this);
				if (options.scroll) {
					this.scrollTo();
				}
				this.hide();
				new Loader(
					this.parentNode,
					{
						text : this.__hww_texts.load,
						append : true
					}
				);
			}
		}
	},
	getAfter : function (options) {
		var ret = {
			onSuccess : function () {return;},
			onFailure : function () {return;},
			onComplete : function () {return;}
		};

		if (typeof options.timeout != 'undefined') {
			var time = 30
			var text = 'AjaxTimeout';
			if (typeof options.timeout == 'object') {
				time = options.timeout.time || time;
				text = options.timeout.text || text;
			}
			else if (typeof options.timeout == 'string') {
				text = options.timeout;
			}
			else if (typeof options.timeout == 'number') {
				time = options.timeout;
			}
			ret.onCreate = function (request) {
				request['timeoutId'] = window.setTimeout(
					function () {
						switch (request.transport.readyState) {
							case 1 :
							case 2 :
							case 3 :
								request.transport.abort();
								var message = HWW.strings[text] || text;
								$(request.request.container.failure).update(
									'<p class="error">' + message + '</p>'
								);
								window.location.search += 'flash=' + escape(text);
								return;
						}
					},
					time * 1000
				);
			}
			ret.onComplete = function (request) {
				window.clearTimeout(request['timeoutId']);
			}
		}

		if (typeof options.after == 'object') {
			if (typeof options.after.success == 'function')
				ret.onSuccess = options.after.success;
			else if (typeof options.after.success == 'string')
				ret.onSuccess = function () {eval(options.after.success);};

			if (typeof options.after.fail == 'function')
				ret.onFailure = options.after.fail;
			else if (typeof options.after.fail == 'string')
				ret.onFailure = function () {eval(options.after.fail);};
		}
		else if (typeof options.after == 'function') {
			if (ret.onComplete) {
				var complete = ret.onComplete;
				ret.onComplete = function (request) {
					complete();
					options.after();
				}
			}
			else {
				ret.onComplete = options.after;
			}
		}
		else if (options.after) {
			if (ret.onComplete) {
				var complete = ret.onComplete;
				ret.onComplete = function (request) {
					complete();
					eval(options.after);
				}
			}
			else {
				ret.onComplete = function () {eval(options.after);};
			}
		}

		return ret;
	}
}

var TagCloud = Class.create();
TagCloud.prototype = {
	defaults : {
		className : 'checked',
		tagName : 'a',
		eventName : false
	},
	initialize : function (cloud, input, options) {
		cloud = $(cloud);
		input = $(input);
		if (!cloud || !input) {
			return false;
		}
		input.usingTagCloud = true;
		if (typeof options != 'undefined') {
			var className = options.className || this.defaults.className;
			var tagName = options.tagName || this.defaults.tagName;
			var eventName = options.eventName || this.defaults.eventName;
		}
		else {
			var className = this.defaults.className;
			var tagName = this.defaults.tagName;
			var eventName = this.defaults.eventName;
		}
		cloud.__tagName = tagName;
		function tagsFromInput(value) {
			var tags = [];
			var tagsOriginal = [];
			$A(value.match(/[^,]+/g)).each(
				function (tag) {
					if (tag = tag.strip()) {
						tags.push(tag.toLowerCase());
						tagsOriginal.push(tag);
					}
				}
			);
			tags.uniq();
			tagsOriginal.uniq();
			return {lowered : tags, original : tagsOriginal}
		}
		var tags = tagsFromInput(input.value);
		$A(cloud.getElementsByTagName(tagName)).each(
			function (tag) {
				tag.__cloudInput = input.id;
				if (tags.lowered.indexOf(tag.firstChild.nodeValue.strip().toLowerCase()) != -1) {
					$(tag).addClassName(className);
				}
				tag.onclick = function () {
					var input = $(this.__cloudInput);
					if (!input) {
						return false;
					}
					if (
						typeof input.tipDefaultValue != 'undefined'
						&&
						input.value == input.tipDefaultValue
					) {
						input.value = '';
					}
					var tags = tagsFromInput(input.value);
					var index = tags.lowered.indexOf(
						this.firstChild.nodeValue.strip().toLowerCase()
					);
					if (index != -1) {
						tags.original = tags.original.without(tags.original[index]);
					}
					else {
						tags.original.push(this.firstChild.nodeValue);
					}
					input.value = tags.original.join(', ');
					input.onchange();
					input.focus();
					HWW.moveCaretToEnd(input);
					return false;
				}
			}
		);
		if (typeof input.__cloudElement == 'undefined') {
			input.__cloudElement = [cloud.id];
			input.onchange = function () {
				var tags = tagsFromInput(input.value);
				for (var i = 0; i < input.__cloudElement.length; i++) {
					var cloud = $(input.__cloudElement[i]);
					var thisTags = $A(cloud.getElementsByTagName(cloud.__tagName));
					for (var j = 0; j < thisTags.length; j++) {
						var index = tags.lowered.indexOf(
							thisTags[j].firstChild.nodeValue.strip().toLowerCase()
						);
						if (index != -1) {
							$(thisTags[j]).addClassName(className);
						}
						else {
							$(thisTags[j]).removeClassName(className);
						}
					}
				}
			}
		}
		else if (!$A(input.__cloudElement).member(cloud.id)) {
			input.__cloudElement.push(cloud.id);
		}
		if (eventName) {
			input.observe(
				eventName.on,
				(function (event) {
					this["__" + eventName.on] = true;
					$(cloud.id).show();
				}).bind(input)
			);

			input.observe(
				eventName.off,
				(function (event) {
					this["__" + eventName.on] = false;
					var id = this.id;
					setTimeout(
						function () {
							if (!$(id)["__" + eventName.on]) {
								if (!$(id).value) {
									if (typeof $(id).tipDefaultValue != 'undefined') {
										$(id).value = $(id).tipDefaultValue;
									}
								}
								if ($(id).value == Tip.fields[$(id).id]) {
									$(id).addClassName(Tip.tipClass);
								}
								$(cloud.id).hide();
							}
						},
						500
					);
				}).bind(input)
			);
			cloud.hide();
		}
		return true;
	}
}

var Search = {
	initDoctorCategory : function (model, baseUrl, text) {
		var type = $(model + 'Type');
		var area = $(model + 'Area');
		var spec = $(model + 'Specialty');
		var rel  = $(model + 'Related');

		var Init = function (element) {
			element.disable();
			element.up().addClassName('hold');
			while (element.firstChild) {
				element.removeChild(element.firstChild);
			}
		}

		var MakeLoader = function (element) {
			var loader = $(model + 'Loader');
			if (loader) {
				loader.remove();
			}
			new Loader(
				element.parentNode.parentNode,
				{
					id : model + 'Loader',
					text : text,
					insertAfter : element.parentNode
				}
			);
		}

		var TypeChange = function () {
			var area = $(model + 'Area');
			var spec = $(model + 'Specialty');
			if (!area) {
				return;
			}
			Init(area);
			Init(spec);
			SpecChange.call(spec);
			if (this.selectedIndex) {
				MakeLoader(area);
				new Ajax.Request(
					baseUrl + '/area/' + this.value,
					{
						onComplete : function () {
							AreaChange.call(area);
						},
						requestHeaders : [
							'X-Referer', HWW.ieUrl(window.location.href),
							'X-Update', area.id
						]
					}
				);
			}
		}

		var AreaChange = function () {
			var spec = $(model + 'Specialty');
			if (!spec) {
				return;
			}
			Init(spec);
			SpecChange.call(spec);
			if (this.selectedIndex) {
				MakeLoader(spec);
				new Ajax.Request(
					baseUrl + '/specialty/' + this.value,
					{
						requestHeaders : [
							'X-Referer', HWW.ieUrl(window.location.href),
							'X-Update', spec.id
						]
					}
				);
			}
		}

		var SpecChange = function () {
			var rel  = $(model + 'Related');
			if (rel) {
				if (!this.disabled && this.selectedIndex) {
					rel.up().removeClassName('hold');
					rel.enable();
				}
				else {
					rel.up().addClassName('hold');
					rel.disable();
				}
			}
		}

		try {
			type.observe('change', TypeChange.bind(type));
			area.observe('change', AreaChange.bind(area));
			spec.observe('change', SpecChange.bind(spec));
			if (!area.selectedIndex) {
				Init(area);
				Init(spec);
			}
			SpecChange.call(spec);
		}
		catch (e) {}
	},
	populate : function (target, values) {
		target = $(target);
		if (!target) {
			return;
		}
		$A(target.up().up().getElementsByClassName('loader')).each(
			function (item) {
				$(item).remove();
			}
		);
		while (target.firstChild) {
			target.removeChild(target.firstChild);
		}
		target.appendChild(document.createElement('option'));
		target.lastChild.value = '';
		target.lastChild.appendChild(document.createTextNode(' '));
		for (var i = 0; i < values.length; i++) {
			target.appendChild(document.createElement('option'));
			target.lastChild.value = values[i][0];
			target.lastChild.appendChild(document.createTextNode(values[i][1]));
		}
		target.enable();
		target.up().removeClassName('hold');
	},
	touchButton : function (target, options) {
		target = $(target);
		if (!target) {
			return false;
		}

		var formTag = 'form';
		var formClass = false;
		var buttonTag = false;
		var buttonClass = 'buttons';
		if (typeof options != 'undefined') {
			formTag = options.formTag || formTag;
			formClass = options.formClass || formClass;
			buttonTag = options.buttonTag || buttonTag;
			buttonClass = options.buttonClass || buttonClass;
		}
		if (!buttonTag && !buttonClass) {
			return false;
		}

		if (formTag) {
			target = target.upToTagName(formTag);
		}
		else if (formClass) {
			target = target.upToClassName(formClass);
		}

		if (buttonTag) {
			var buttons = target.getElementsByTagName(buttonTag);
		}
		else {
			var buttons = target.getElementsByClassName(buttonClass);
		}
		$A(buttons).each(
			function (item) {
				item = $(item);
				item.hide();
				item.show();
			}
		);

		return true;
	},
	replace : function (id, content) {
		var target = $(id);
		if (!target) {
			return false;
		}
		var container = document.createElement('div');
		var scripts = content.extractScripts();
		container.innerHTML = content;
		var elements = container.getElementsByTagName(target.tagName);
		for (var i = 0; i < elements.length; i++) {
			if (elements[i].id == target.id) {
				target.parentNode.insertBefore(elements[i], target);
				target.parentNode.removeChild(target);
				scripts.map(function(script) {try {eval(script)} catch (e) {}});
				return true;
			}
		}
		return false;
	},
	recommendInput : function (item) {
		item = $(item);
		if (!item) {
			return;
		}

		var enableDisable = function () {
			if ($(this).firstDescendant().checked) {
				$(this).descedantsOfClassName('input').each(
					function (item) {
						$(item).removeClassName('disabled');
					}
				);
			}
			else {
				$(this).descedantsOfClassName('input').each(
					function (item) {
						$(item).addClassName('disabled');
					}
				);
			}
		}
		var selectDeselect = function () {
			if (this.checked) {
				var parent = $(this).
					upToClassName('input').
						up().
							upToClassName('input');
				$A(parent.getElementsByTagName('input')).each(
					function (item) {
						if (item.type == 'hidden') {
							item.disabled = true;
						}
					}
				);
				$A(this.parentNode.getElementsByTagName('input')).each(
					function (item) {
						if (item.type == 'hidden') {
							item.disabled = false;
						}
					}
				);
				parent.firstDescendant().checked = true;
				enableDisable.call($(this).upToClassName('input'));
			}
			else {
				$A(this.getElementsByTagName('input')).each(
					function (item) {
						if (item.type == 'hidden') {
							item.disabled = true;
						}
					}
				);
			}
		}
		var showClick = function () {
			try {
				var input = $(this).upToClassName('input').firstDescendant();
				input.checked = true;
				selectDeselect.call(input);
			}
			catch (e) {}
		}
		var changeClick = function () {
			try {
				var input = $(this).
					upToClassName('input').
						up().
							firstDescendant();
				input.checked = true;
				selectDeselect.call(input);
			}
			catch (e) {}
		}
		var selectExclusive = function () {
			var inputs = $(this).
				upToClassName('input').
					up().
						descedantsOfClassName('input');
			var thisId = this.id;
			if (this.checked) {
				$A(inputs).each(
					function (item) {
						item = $(item);
						if (item.firstDescendant().id != thisId) {
							item.addClassName('disabled');
							item.firstDescendant().disabled = true;
						}
					}
				);
			}
			else {
				$A(inputs).each(
					function (item) {
						item = $(item);
						if (item.firstDescendant().id != thisId) {
							item.removeClassName('disabled');
							item.firstDescendant().disabled = false;
						}
					}
				);
			}
		}
		// set "enabling/disabling" underlaying elements on parent check/uncheck
		item.descedantsOfClassName('input').each(
			function (item) {
				item = $(item);
				enableDisable.call(item);
				item.observe('click', enableDisable.bind(item));
				// set check to parent when child is selected
				item.descedantsOfClassName('input').each(
					function (item) {
						item = $(item);
						item.observe(
							'click',
							selectDeselect.bind(item.firstDescendant())
						);
						item.descedantsOfClassName('ajax-link').each(
							function (item) {
								item.__beforeLoad = showClick.bind(item);
							}
						);
					}
				);
				// set check when option is changed by chooser link
				$A(item.getElementsByClassName('ajax-link')).each(
					function (item) {
						$(item).observe('click', changeClick.bind(item));
					}
				);
			}
		);
		// Process exclusive options in radio-button like manner
		$A(item.getElementsByClassName('exclusive')).each(
			function (item) {
				$(item).observe('click', selectExclusive.bind(item));
			}
		);
	}
}

var Poll = {
	classes : {
		initial : 'radio',
		replace : 'stars',
		voted : 'voted',
		intensityBlock : 'intensity',
		intensityBar : 'bar'
	},
	numbers : ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'],
	replace : function (target) {
		target = typeof target == 'undefined' ? 'content' : target;
		var elements = $$('#' + target + ' .input.' + this.classes.initial);
		if (!elements) {
			return false;
		}
		var method = typeof elements[0].select != 'undefined' ? 'select' : 'getElementsBySelector';
		for (var i = 0; i < elements.length; i++) {
			var inputs = elements[i][method]('input[type="radio"]');
			var voted = false;
			var stars = document.createElement('ol');
			stars.className = this.classes.replace;
			stars.onmouseover = function () {
				this.className = Poll.classes.replace;
			}
			stars.onmouseout = function () {
				this.className = Poll.classes.replace + ' ' + Poll.classes.voted;
			}
			$(elements[i]).addClassName(this.classes.replace);
			for (var j = 0; j < inputs.length; j++) {
				var label = elements[i][method]('label[for="' + inputs[j].id + '"]')[0];
				inputs[j].style.display = 'none';
				label.style.display = 'none';
				var star = document.createElement('li');
				star.className = 'star' + (j + 1);
				stars.appendChild(star);
				star = star.appendChild(document.createElement('a'));
				star.href = 'javascript:void(0)';
				star.title = inputs[j].value;
				star.htmlFor = inputs[j].id;
				if (inputs[j].checked) {
					voted = true;
					star.className = Poll.classes.voted;
				}
				star.onclick = function () {
					var ol = $(this).upToTagName('ol');
					ol.addClassName(Poll.classes.voted);
					ol[method]('a.' + Poll.classes.voted).each(
						function (element) {
							$(element).removeClassName(Poll.classes.voted)
						}
					);
					$(this).addClassName(Poll.classes.voted);
					ol.up()[method]('input[type="radio"]').each(
						function (element) {$(element).checked = false}
					);
					$(this.htmlFor).checked = true;
				};
				star = star.appendChild(document.createElement('span'));
				star.appendChild(document.createTextNode(label.firstChild.nodeValue));
			}
			if (voted) {
				stars.className += ' ' + Poll.classes.voted;
			}
			inputs[0].parentNode.appendChild(stars);
		}
		return true;
	},
	/*vote : function (voter, input) {
		document.getElementById(input).value = voter.title;
		var ol = $(voter.parentNode.parentNode);
		var li = ol.down();
		do {
			a = li.down();
			a.className = (a == voter) ? "voted" : "";
		} while (li = li.next());
		ol.addClassName("voted");
		Poll.init(ol);
	},
	reset : function (btn) {
		var dl = btn.parentNode.parentNode;
		for (var i = 0; i < dl.childNodes.length; i++)
			if (dl.childNodes[i].nodeName == "DD")
				for (var j = 0; j < dl.childNodes[i].childNodes.length; j++)
					if (dl.childNodes[i].childNodes[j].nodeName == "OL") {
						var ol = $(dl.childNodes[i].childNodes[j]);
						ol.className = "stars";
						var li = ol.down();
						do li.down().className = ""; while (li = li.next());
					}
					else if (dl.childNodes[i].childNodes[j].value)
						dl.childNodes[i].childNodes[j].value = "";
	},*/
	init : function (ol) {
		/*if (ol.className.indexOf("level") != -1) {
			if (ol.className.indexOf("invert") != -1) {
				ol.onmouseover = function () {this.className = "level invert";}
				ol.onmouseout = function () {this.className = "level invert voted";}
			}
			else {
				ol.onmouseover = function () {this.className = "level";}
				ol.onmouseout = function () {this.className = "level voted";}
			}
		}
		else {
			ol.onmouseover = function () {this.className = "stars";}
			ol.onmouseout = function () {this.className = "stars voted";}
		}*/
	},
	intensity : function (target, options) {
		target = $(target);
		if (!target) {
			return false;
		}
		if (!options) {
			options = {}
		}
		var blockClass = options.blockClass || Poll.classes.intensityBlock;
		var barClass = options.barClass || Poll.classes.intensityBar;
		var targetField = options.fieldId;
		if (targetField) {
			targetField = $(targetField);
		}
		if (!target.id) {
			target.id = 'Intensity' + Math.round(Math.random() * 1000);
		}
		$A(target.getElementsByClassName(barClass)).each(
			function (bar) {
				bar.style.cursor = 'pointer';
				bar.__thisValue = $w(bar.className).find(
					function (number) {
						return Poll.numbers.indexOf(number) != -1;
					}
				);
				bar.__thisNumber = Poll.numbers.indexOf(bar.__thisValue) + 1;
				bar.onmouseover = function () {
					var block = $(this.parentNode);
					if (typeof block.__initialValue == 'undefined') {
						block.__initialNumber = block.lastChild.nodeValue.strip();
						block.__initialValue = Poll.numbers[block.__initialNumber - 1];
					}
					block.className = blockClass + ' ' + this.__thisValue;
					block.lastChild.nodeValue = ' ' + this.__thisNumber;
				}
				bar.onmouseout = function () {
					var block = $(this.parentNode);
					if (typeof block.__initialValue != 'undefined') {
						block.className = blockClass + ' ' + block.__initialValue;
						block.lastChild.nodeValue = ' ' + block.__initialNumber;
					}
				}
				if (targetField) {
					bar.onclick = function () {
						var block = $(this.parentNode);
						block.__initialNumber = this.__thisNumber;
						block.__initialValue = this.__thisValue;
						$(targetField).value = this.__thisNumber;
					}
				}
				bar.__popupHeader = {'X-Target' : target.id}
			}
		);
		return true;
	},
	setIntensity : function (target, value, options) {
		target = $(target);
		if (!target) {
			return false;
		}
		if (!target.id) {
			target.id = 'Intensity' + Math.round(Math.random() * 1000);
		}
		if (!options) {
			options = {}
		}
		var blockClass = options.blockClass || Poll.classes.intensityBlock;
		target.__initialNumber = value;
		target.__initialValue = Poll.numbers[target.__initialNumber - 1];
		target.className = blockClass + ' ' + target.__initialValue;
		target.lastChild.nodeValue = ' ' + target.__initialNumber;
		return true;
	}
};

var Artifact = {
	artifacts : ['user', 'community', 'doctor'],
	initialize : function (target) {
		var artifacts = this.artifacts;
		target = $(typeof target == 'undefined' ? 'content' : target);
		for (var i = 0; i < artifacts.length; i++) {
			if (target.hasClassName(artifacts[i])) {
				if (target.getAttribute('__artifactType')) {
					return true;
				}
				target.setAttribute('__artifactType', artifacts[i]);
				return this.init(target);
			}
		}
		//var cnt = 0;
		for (var i = 0; i < artifacts.length; i++) {
			$$("#" + target.id + " a." + artifacts[i]).each(
				function (element) {
					element = $(element);
					if (element.getAttribute('__artifactType')) {
						return true;
					}
					for (var i = 0; i < artifacts.length; i++) {
						if (element.hasClassName(artifacts[i])) {
							element.setAttribute('__artifactType', artifacts[i]);
							break;
						}
					}
					Artifact.init(element);
					return true;
				}
			);
		}
		return true;
	},
	init : function (element) {
		element = $(element);
		element.onmouseover = function (event) {
			if (typeof artifactInfoPopup == 'undefined') {
				var body = document.getElementsByTagName('body')[0];
				artifactInfoPopup = $(body.appendChild(document.createElement('div')));
			}
			if (!artifactInfoPopup.id) {
				artifactInfoPopup.id = "ArtifactPopup" + Math.round(Math.random() * 1000);
			}
			var id = artifactInfoPopup.id;
			if (artifactInfoPopup.__currentArtifact) {
				return false;
			}
			if (!this.id) {
				this.id = "ArtifactLink" + Math.round(Math.random() * 1000);
			}
			artifactInfoPopup.__currentArtifact = this.id;
			if (this.__artifactInfo) {
				while (this.__artifactInfo.firstChild) {
					artifactInfoPopup.appendChild(
						this.__artifactInfo.removeChild(
							this.__artifactInfo.firstChild
						)
					);
				}
			}
			else {
				new Loader(id);
				new Ajax.Updater(
					id,
					HWW.randomUrl(HWW.ieUrl(element)).replace(/homepage/, 'info').replace(/home/, 'info'),
					{
						evalScripts : true,
						requestHeaders : [
							'X-Referer', HWW.ieUrl(window.location.href),
							'X-Update', id
						]
					}
				);
			}
			if (!event) {
				event = window.event;
			}
			var position = this.positionedOffset();
			artifactInfoPopup.style.position = 'absolute';
			artifactInfoPopup.style.backgroundColor = 'red';
			artifactInfoPopup.style.left = (position.left + this.getDimensions().width) + 'px';
			artifactInfoPopup.style.top = /*(position.top - artifactInfoPopup.getDimensions().height)*/(event.pageY || event.clientY + document.documentElement.scrollTop) + 'px';
			artifactInfoPopup.show();
			var linkId = this.id;
			var outFunc = function (event) {
				if (!event) {
					event = window.event;
				}
				var target = event.relatedTarget || event.toElement;
				if (!target || !target.id || (target.id != id && target.id != linkId)) {
					artifactInfoPopup.__currentArtifact = false;
					artifactInfoPopup.hide();
					this.__artifactInfo = document.createElement('div');
					while (artifactInfoPopup.firstChild) {
						this.__artifactInfo.appendChild(
							artifactInfoPopup.removeChild(
								artifactInfoPopup.firstChild
							)
						);
					}
				}
			};
			this.onmouseout = outFunc;
			artifactInfoPopup.onmouseout = outFunc;
			return true;
		}
		return true;
	}
}

/* misc functions */
var HWW = {
	winLevel : 0,
	winStack : {},
	cascadeOffset : 15, /*px*/
	tinymceManager : false,
	tinymceTabIndex : false,
	__updaters : {},
	__popupCallbacks : [],

	reloadCaptcha : function () {
		document.getElementById(this.id.substr(0, this.id.length - 7)).src = HWW.randomUrl(this.href);
		return false;
	},
	elementFromEvent : function (item) {
		if (item.nodeName)
			return item;
		if (!item)
			item = window.event;
		item = item.target || item.srcElement;
		if (item.nodeType == 3)
			item = item.parentNode;
		return item;
	},
	popupLink : function () {
		var options = {
			id         : this.__popupId || this.id ? this.id + 'Popup' : 'Popup' + Math.round(Math.random() * 1000),
			form       : this.__popupForm,
			method     : this.__popupMethod,
			confirm    : this.__popupConfirm,
			text       : this.__popupText,
			title      : this.__popupTitle,
			beforeLoad : this.__beforeLoad,
			onComplete : this.__onComplete,
			params     : this.__popupParams,
			headers    : this.__popupHeader
		};
		return HWW.popup(this.__popupLink || HWW.ieUrl(this), options);
	},
	popup : function (url, options) {
		if (!options) {
			options = {}
		}
		var popupId = options.id || 'Popup' + Math.round(Math.random() * 1000);

		if (options.confirm) {
			if (!confirm(options.confirm)) {
				return false;
			}
		}

		HWW.winLevel++;

		if (options.beforeLoad) {
			if (typeof options.beforeLoad == 'function') {
				options.beforeLoad(this);
			}
			else {
				eval(options.beforeLoad);
			}
		}

		HWW.hideFlash();
		if (HWW.winLevel == 1) {
			HWW.killEditor('content');
		}
		else {
			HWW.killEditor('overlay');
		}

		var params = {};
		if (options.form) {
			params = $(options.form).serialize();
		}
		else if (options.params) {
			params = options.params;
		}

		new Loader(
			false,
			{
				element : 'popup',
				id : popupId,
				text : options.text,
				title : options.title
			}
		);

		if (options.onComplete) {
			$(popupId).__onPopupComplete = options.onComplete;
		}
		else {
			$(popupId).__onPopupComplete = HWW.popupCorrectHeight;
		}

		var headers = {
			'X-Referer' : HWW.ieUrl(window.location.href),
			'X-Update'  : popupId
		};
		if (options.headers) {
			$H(options.headers).each(
				function (item) {
					if (item.value) {
						headers[item.key] = item.value;
					}
				}
			);
		}
		new Ajax.Updater(
			popupId,
			HWW.randomUrl(url),
			{
				method : options.method || 'get',
				evalScripts : true,
				parameters : params,
				onComplete : typeof $(popupId).__onPopupComplete == 'function'
					?
					$(popupId).__onPopupComplete
					:
					function () {eval($(popupId).__onPopupComplete);},
				requestHeaders : headers
			}
		);

		HWW.addPopupClose();
		return false;
	},
	popupClose : function () {
		if (HWW.__popupCallbacks[HWW.winLevel]) {
			for (var i = 0; i < HWW.__popupCallbacks[HWW.winLevel].length; i++) {
				HWW.__popupCallbacks[HWW.winLevel][i]();
			}
			delete HWW.__popupCallbacks[HWW.winLevel];
		}

		HWW.winLevel--;
		if (HWW.winLevel < 0) {
			HWW.winLevel = 0;
		}

		var popup_id = $$('#overlay .container .content')[0].id;
		HWW.killEditor(popup_id);

		if (HWW.winLevel > 0) {
			$$('#overlay .popup-close')[0].remove();
			$$('#overlay .container .content')[0].remove();
			HWW.addEditor('overlay');
			$$('#overlay .popup-close')[0].removeClassName('inactive');
			// Registering Esc action again as TinyMCE editor reveal hurted it
			Event.observe(document.documentElement, 'keyup', HWW.popupEscClose);
		}
		else {
			HWW.addEditor('content');
			HWW.showFlash();
			$('overlay').hide();
			// Unregister Esc action
			Event.stopObserving(document.documentElement, 'keyup', HWW.popupEscClose);
		}

		return false;
	},
	addPopupCloseCallback : function (callback) {
		if (!HWW.__popupCallbacks[HWW.winLevel]) {
			HWW.__popupCallbacks[HWW.winLevel] = [];
		}
		HWW.__popupCallbacks[HWW.winLevel].push(callback);
	},
	addPopupClose : function () {
		var container = $$('#overlay .container')[0];
		var overlay = $('overlay');
		var close = document.createElement('div');
		close.className = 'popup-close';

		if (HWW.winLevel > 1) {
			$$('#overlay .popup-close')[0].addClassName('inactive');
			container.insertBefore(close, $$('#overlay .content')[1]);
			close = $(close);

			var offset = (HWW.winLevel - 1) *
				(HWW.cascadeOffset + parseInt(container.getStyle('borderTopWidth')));
			close.setStyle({
				position : 'absolute',
				top : parseInt(close.getStyle('top')) + offset + 'px',
				right : parseInt(close.getStyle('right')) - offset + 'px',
				zIndex : HWW.winLevel - 1
			});
		}
		else {
			if (!$$('#overlay .popup-close').length) {
				container.appendChild(close);
			}
			// Registering Esc action
			Event.observe(document.documentElement, 'keyup', HWW.popupEscClose);
		}
		close.onclick = HWW.popupClose;

		// Altering overlay height...
		HWW.popupCorrectHeight();
	},
	popupAutoClose : function (timeout) {
		if (timeout) {
			window.setTimeout(HWW.popupClose, timeout * 1000);
		}
		else {
			HWW.popupClose();
		}
	},
	popupCorrectHeight : function () {
		var overlay = $('overlay');
		if (!overlay || !overlay.visible()) {
			return;
		}
		var height = 0;
		var offset = $$('#overlay .container')[0].offsetTop;
		$$('#overlay .container > .content').each(
			function (item) {
				// 80 = margin + padding + border + bottom space
				var currentHeight = item.offsetHeight + offset + 80;
				if (currentHeight > height) {
					height = currentHeight;
				}
			}
		);
		if (overlay.offsetHeight < height) {
			overlay.style.height = height + 'px';
		}
	},
	popupEscClose : function (event) {
		if (typeof event == 'undefined') {
			event = window.event;
		}
		if (event.keyCode == Event.KEY_ESC) {
			HWW.popupClose();
			return false;
		}
		return true;
	},
	chatLink : function () {
		wnd = window.open(
			HWW.ieUrl(this),
			this.id,
			'width=730,height=450,scrollbars=yes,menubar=no,toolbar=no'
		);
		wnd.focus();
		if (this.reloadParent) {
			window.location.reload();
		}
		if (this.reloadNotifier) {
			if (typeof Notifier != 'undefined') {
				Notifier.deleteMessage();
			}
		}
		return false;
	},
	hideFlash : function () {
		$$('object').invoke('setStyle', {visibility:"hidden"});
	},
	showFlash : function () {
		$$('object').invoke('setStyle', {visibility:"visible"});
	},
	fieldAdd : function (button) {
		button = HWW.elementFromEvent(button);
		var toReplace = ['id', 'htmlFor', 'name'];
		var block = $(button.parentNode).previous().cloneNode(true);
		$(block).descendants().each(
			function (item) {
				if (item.nodeName == 'LABEL' && !item.previous()) {
					item.parentNode.removeChild(item);
					return;
				}
				for (var j = 0; j < toReplace.length; j++) {
					if (item[toReplace[j]]) {
						item[toReplace[j]] = item[toReplace[j]].replace(
							/([a-zA-Z_\-\[\]]+)(\d+)([a-zA-Z_\-\[\]]*)/,
							function (str, start, num, end) {
								return start + (parseInt(num) + 1) + end;
							}
						);
					}
				}
				if (item.type == 'checkbox' || item.type == 'radio')
					item.checked = false;
				else if (item.type == 'select')
					item.selectedIndex = 0;
				else if (item.value)
					item.value = '';
			}
		);
		button.parentNode.parentNode.insertBefore(block, button.parentNode);
		// IE6 guess
		if (Prototype.Version < '1.6') {
			block.firstChild.currentStyle.marginLeft;
		}
		return false;
	},
	killEditor : function (target, className) {
		target = $(target || 'content');
		if (!target) {
			return;
		}
		var editors = target.getElementsByClassName(className || 'tinymce');
		for (var i = 0; i < editors.length; i++) {
			var editor = $(editors[i]);
			if (!editor.hasClassName("disabled")) {
				tinyMCE.execCommand('mceRemoveControl', false, editor.id);
				editor.addClassName("disabled");
			}
		}
	},
	addEditor : function (target, className) {
		target = $(target || 'content');
		if (!target) {
			return;
		}
		var editors = target.getElementsByClassName(className || 'tinymce');
		for (var i = 0; i < editors.length; i++) {
			var editor = $(editors[i]);
			if (editor.hasClassName("disabled")) {
				tinyMCE.execCommand('mceAddControl', false, editor.id);
				editor.removeClassName("disabled");
			}
		}
	},
	updater : function (options) {
		var id = 'id' + Math.round(Math.random() * 10000);
		var Updater = Class.create();
		Updater.prototype = {
			effects : false,
			time : 30,
			initialize : function (options) {
				Object.extend(this, options);
				if (this.immediate) {
					this.update(this);
				}
				else {
					this.start(this);
				}
			},
			start : function (obj) {
				if (!obj.__needFinish) {
					obj.__timer = window.setTimeout(
						function(){obj.update(obj)},
						obj.time * 1000
					);
				}
				else {
					obj.__timer = false;
				}
			},
			stop : function () {
				this.__needFinish = true;
			},
			resume : function () {
				this.__needFinish = false;
				if (!this.__timer) {
					this.start(obj);
				}
			},
			update : function (obj) {
				if (obj.beforeRequest) {
					obj.beforeRequest(obj);
				}
				if (obj.effects && obj.effects.beforeRequest) {
					obj.runEffect(
						obj.effects.beforeRequest,
						function () {
							obj.__update(obj);
						}
					);
				}
				else {
					obj.__update(obj);
				}
			},
			__update : function (obj) {
				new Ajax.Request(
					obj.randomize
						?
						HWW.randomUrl(HWW.ieUrl(obj.url), obj.randomize)
						:
						HWW.ieUrl(obj.url),
					{
						method : 'get',
						onFailure : function (transport) {
							if (obj.onFirstFailure) {
								obj.onFirstFailure(obj, transport);
								delete(obj.onFirstFailure);
							}
							if (obj.onFailure) {
								obj.onFailure(obj, transport);
							}
							obj.start(obj)
						},
						onSuccess : function (transport) {
							obj.__loaded = transport.responseText;
							obj.__needFinish = transport.getResponseHeader('X-Stop-Update');
							obj.__noUpdate = transport.getResponseHeader('X-No-Update');
							obj.__noEffect = transport.getResponseHeader('X-No-Effect');
							if (obj.onFirstSuccess) {
								obj.onFirstSuccess(obj, transport);
								delete(obj.onFirstSuccess);
							}
							if (obj.onSuccess) {
								obj.onSuccess(obj, transport);
							}
							if (obj.__noUpdate) {
								obj.start(obj);
							}
							else if (!obj.effects || obj.__noEffect) {
								obj.getElement(obj.element).innerHTML = obj.__loaded;
								obj.start(obj);
							}
							else if (obj.effects.beforeLoad) {
								obj.runEffect(
									obj.effects.beforeLoad,
									function(){
										obj.getElement(obj.element).innerHTML = obj.__loaded;
										if (obj.effects.afterLoad) {
											obj.runEffect(
												obj.effects.afterLoad,
												function() {
													obj.start(obj);
												}
											);
										}
										else {
											obj.start(obj);
										}
									}
								);
							}
							else {
								obj.getElement(obj.element).innerHTML = obj.__loaded;
								if (obj.effects.afterLoad) {
									obj.runEffect(
										obj.effects.afterLoad,
										function() {
											obj.start(obj);
										}
									);
								}
								else {
									obj.start(obj);
								}
							}
						}
					}
				);
				if (obj.effects && obj.effects.afterRequest) {
					obj.runEffect(obj.effects.afterRequest);
				}
			},
			getElement : function (param) {
				return param.indexOf('#') != -1 || param.indexOf('.') != -1
					?
					$$(param)
					:
					$(param);
			},
			runEffect : function (effect, afterEffect) {
				if (effect) {
					if (typeof effect == 'object') {
						var name = effect.name;
						var element = effect.element || this.element;
						var options = effect.options;
					}
					else {
						var name = effect[0];
						var element = effect[1];
						var options = effect[2];
					}
					if (afterEffect) {
						options.afterFinish = afterEffect;
					}
					new Effect[name](
						this.getElement(element),
						options
					);
				}
			}
		}
		HWW.__updaters[id] = new Updater(options);
		return id;
	},
	getUpdater : function (id) {
		return HWW.__updaters[id];
	},
	delUpdater : function (id) {
		HWW.__updaters[id].stop(HWW.__updaters[id]);
	},
	randomUrl : function (url, replacement) {
		var seed = Math.round(Math.random() * 10000);
		return typeof replacement != 'undefined'
			?
			url.replace(new RegExp(replacement), seed)
			:
			url.indexOf('?') == -1 ? url + '?' + seed : url + '&' + seed;
	},
	ieUrl : function (url) {
		// IE6 guess
		if (Prototype.Version < '1.6') {
			if (typeof url != typeof 'string') {
				if (url.getAttribute) {
					if (url.href) {
						url = url.getAttribute('href', 2);
					}
					else if (url.action) {
						url = url.getAttribute('action', 2);
					}
					else {
						return false;
					}
				}
				else {
					url = url.href || url.action;
				}
			}
			return escape(url).replace(/%25([0-9A-F]{2})/g, '%$1').replace(/%3A/g, ':');
		}
		return typeof url != typeof 'string'
			?
			url.href || url.action
			:
			url;
	},
	setTabIndexValue : function(value){
		this.tinymceTabIndex = value;
	},
	setTabIndex : function() {
		if (this.tinymceTabIndex) {
			$$('.mceIframeContainer > iframe')[0].setAttribute('tabIndex', this.tinymceTabIndex);
		}
	},
	showSearchResults : function(form) {
		$('header').scrollTo();
	},
	selectRadio : function (inp) {
		inp = $(inp);
		var id = inp.id;
		var name = inp.name;
		$(inp.form).getInputs("radio", name).each(
			function (element) {
				if (element.id == id) {
					element.checked = true;
				}
				else {
					element.checked = false;
				}
			}
		);
	},
	selectCheck : function (container, state) {
		container = $(container);
		if (!container) {
			return false;
		}
		state = typeof state == 'undefined' || state ? true : false;
		$A(container.getElementsByTagName('input')).each(
			function (item) {
				if (item.type == 'checkbox') {
					item.checked = state;
				}
			}
		);
		return true;
	},
	singleCheck : function (container) {
		container = $(container);
		if (!container) {
			return false;
		}
		var onclick = function() {
			var thisId = this.id;
			$A(this.form[this.name]).each(
				function (item) {
					if (item.id != thisId) {
						item.checked = false;
					}
				}
			)
		};
		$A(container.getElementsByTagName('input')).each(
			function (item) {
				if (item.type == 'checkbox') {
					item.onclick = onclick;
				}
			}
		);
		return true;
	},
	replaceButtons : function (target, baseUrl) {
		target = $(target);
		if (target) {
			if (target.nodeName.toLowerCase() == 'input' && target.type == 'submit') {
				var buttons = [target.parentNode];
			}
			else {
				var buttons = target.getElementsByClassName('submit');
			}
			$A(buttons).each(
				function (element) {
					var ext = 'png';
					// IE6 guess
					if (Prototype.Version < '1.6') {
						ext = 'gif';
					}
					var button = element.getElementsByTagName('input');
					if (button.length) {
						button = $(button[0]);
					}
					else {
						button = element.getElementsByTagName('a');
						if (button.length) {
							button = $(button[0]);
						}
						else {
							return false;
						}
					}
					var replacement = document.createElement('div');
					var value = button.nodeName.toLowerCase() == 'a'
						?
						button.firstChild.nodeValue
						:
						button.value;
					replacement.className = 'btn-replace';
					replacement.style.backgroundImage = 'url(' +
						baseUrl + '/' +
						value.strip().toLowerCase().replace(' ', '_') +
						'.' + ext +
						')';
					element.appendChild(replacement);
					replacement = $(replacement);
					replacement.onclick = button.nodeName.toLowerCase() == 'a'
						?
						function (event) {
							var link = $(this).up().down();
							if (link.onclick) {
								return link.onclick.call(link);
							}
							else if (link.click) {
								link.click();
							}
							else {
								window.location = link.href;
							}
							return false;
						}
						:
						function (event) {
							var form = Event.findElement(event || window.event, 'form');
							if (form.onsubmit) {
								form.onsubmit();
							}
							else {
								form.submit();
							}
							return false;
						};
					replacement.style.width  = element.style.width;
					replacement.style.height = element.style.height;
					return true;
				}
			);
		}
	},
	moreTags : function (id, url, name) {
		var input = $(id);
		if (!input) {
			return false;
		}
		var link = $(id + "AllTagsLink");
		if (!link) {
			link = document.createElement("span");
			link.id = id + "AllTagsLink";
			link.className = "ajax-link";
			link.appendChild(document.createTextNode(HWW.strings.MoreTagsShow));
			var note = input.up().getElementsByClassName("note");
			if (note.length) {
				note = note[0];
				link.style.marginLeft = ".5em";
			}
			else {
				note = input.parentNode.appendChild(document.createElement("div"));
				note.className = "note";
			}
			note.appendChild(link);
		}
		if (!link.onclick) {
			link.onclick = function () {
				var input = $(id);
				var container = $(id + "AllTags");
				if (container && container.visible()) {
					container.hide();
					this.innerHTML = HWW.strings.MoreTagsShow;
					return true;
				}
				this.innerHTML = HWW.strings.MoreTagsHide;
				if (!container) {
					container = input.parentNode.appendChild(
						document.createElement("div")
					);
					container.id = id + "AllTags";
					container.className = "tag-list-container";
					container = $(container);
				}
				container.show();
				new Loader(container.id);
				new Ajax.Updater(
					container.id,
					HWW.randomUrl(url),
					{
						evalScripts : true,
						parameters : {input : name},
						requestHeaders : {
							'X-Referer' : HWW.ieUrl(window.location.href),
							'X-Update'  : container.id,
							'X-Target'  : id
						}
					}
				);
				return true;
			}
		}
		return true;
	},
	makeVideoPaging : function (options) {
		if (options.pages > 1) {
			var list = document.createElement('ul');
			list.className = 'inline';
			if (typeof options.label == 'undefined' || options.label) {
				var item = document.createElement('li');
				item.className = 'label';
				item.appendChild(document.createTextNode(typeof options.label == typeof 'string' ? options.label : 'Check more video:'));
				list.appendChild(item);
			}
			for (var i = 1; i <= options.pages; i++) {
				var item = document.createElement('li');
				if (i == 1) {
					item.className = 'current';
				}
				item.appendChild(document.createTextNode(i));
				item.onclick = function () {
					var pageNum = this.firstChild.nodeValue;
					delete(so);
					var playerContent = $('PlayerContent');
					while (playerContent.firstChild) {
						playerContent.removeChild(playerContent.firstChild);
					}
					so = new SWFObject(
						HWW.randomUrl(options.player),
						"PlayerFlash",
						"260",
						"407",
						"7",
						"#d9d9d9"
					);
					so.addVariable(
						"file",
						HWW.randomUrl(options.url + '/' + pageNum + '.xml')
					);
					so.addVariable("displayheight", "276");
					so.addVariable("playlist", "bottom");
					so.addVariable("playlistsize", "180");
					so.addVariable("allowscriptaccess", "always");
					so.write("PlayerContent");
					for (var i = 0; i < this.parentNode.childNodes.length; i++) {
						$(this.parentNode.childNodes[i]).removeClassName('current');
					}
					$(this).addClassName('current');
					var lnk = $$('#VideoPlayerInner .popup-link');
					if (lnk.length) {
						lnk[0].href = options.url + '/' + pageNum;
					}
				}
				list.appendChild(item);
				list.appendChild(document.createTextNode(' '));
			}
			var playerContent = document.getElementById('PlayerContent');
			playerContent.parentNode.insertBefore(list, playerContent.nextSibling);
		}
		else {
			var list = $('PlayerContent').next();
		}
		if (typeof options.copyright != 'undefined') {
			var copyright = document.createElement('p');
			copyright.className = "video-source";
			copyright.appendChild(document.createElement('a'));
			copyright.firstChild.href = options.copyright.link;
			copyright.firstChild.target = '_blank';
			copyright.firstChild.className = 'icon-link';
			copyright.firstChild.appendChild(document.createTextNode(options.copyright.text));
			if (typeof options.links != 'undefined') {
				copyright.appendChild(document.createTextNode(' ('));
				copyright.appendChild(document.createElement('a'));
				copyright.lastChild.href = HWW.randomUrl(options.url + '/1');
				copyright.lastChild.className = 'popup-link';
				copyright.lastChild.onclick = HWW.popupLink;
				copyright.lastChild.appendChild(document.createTextNode(options.links.text || "videos information"));
				copyright.appendChild(document.createTextNode(')'));
			}
			document.getElementById('PlayerContent').parentNode.insertBefore(copyright, list.nextSibling);
		}
	},
	packActions : function (target, options) {
		target = $(target);
		if (!target) {
			return false;
		}
		if (typeof options == 'undefined') {
			options = {}
		}
		var baseClass = options.base || 'actions-inline';
		var openClass = options.open || 'actions-inline-open';
		$A(target.getElementsByClassName(baseClass)).each(
			function (element) {
				$(element.parentNode).addClassName(baseClass);
				element.parentNode.onmouseover = function () {
					$(this).addClassName(openClass);
				}
				element.parentNode.onmouseout = function (event) {
					if (!event) {
						event = window.event;
					}
					var target = $(event.relatedTarget || event.toElement);
					if (!target || !target.descendantOf(this)) {
						$(this).removeClassName(openClass);
					}
				}
			}
		);
		return true;
	},
	Profile : {
		open : function (element) {
			if (
				typeof element == 'undefined'
				||
				typeof element.nodeType == 'undefined'
			) {
				element = this;
			}
			var container = $(element.parentNode.parentNode);
			if (!container.id) {
				container.id = "ProfileEditContainer" + Math.round(Math.random() * 1000);
			}
			container.addClassName('edit');
			new Loader(
				container.id,
				{element:'tag', tagName:'div', id:container.id + 'Editor', append:true}
			);
			new Ajax.Updater(
				container.id + 'Editor',
				HWW.randomUrl(HWW.ieUrl(element)),
				{
					method : 'get',
					evalScripts : true,
					onComplete : function () {
						$(container.id + 'Editor').removeClassName('loader');
						HWW.popupCorrectHeight();
					},
					requestHeaders : {
						'X-Referer' : HWW.ieUrl(window.location.href),
						'X-Update' : container.id + 'Editor'
					}
				}
			);
			return false;
		},
		close : function (element) {
			if (
				typeof element == 'undefined'
				||
				typeof element.nodeType == 'undefined'
			) {
				element = this;
			}
			var container = $(element).upToClassName('edit');
			if (container) {
				$(container.id + 'Editor').remove();
				container.removeClassName('edit');
				return false;
			}
			return true;
		},
		reload : function (element) {
			element = $(element);
			if (!element) {
				return false;
			}
			var container = element.upToClassName('row');
			if (!container) {
				return false;
			}
			while (container.firstChild) {
				if (container.firstChild.id == element.id) {
					break;
				}
				container.removeChild(container.firstChild);
			}
			while (container.lastChild) {
				if (container.lastChild.id == element.id) {
					break;
				}
				container.removeChild(container.lastChild);
			}
			while (element.firstChild) {
				container.appendChild(element.removeChild(element.firstChild));
			}
			container.removeChild(container.firstChild);
			container.removeClassName('edit');
			return true;
		},
		none : function (element) {
			if (
				typeof element == 'undefined'
				||
				typeof element.nodeType == 'undefined'
			) {
				element = this;
			}
			var container = $(element).upToClassName('column');
			if (container) {
				$A(container.getElementsByTagName('input')).each(
					function (item) {
						if (item.checked) {
							item.checked = false;
						}
						if (item.selected) {
							item.selected = false;
						}
					}
				);
				return false;
			}
			return true;
		},
		all : function (element) {
			if (
				typeof element == 'undefined'
				||
				typeof element.nodeType == 'undefined'
			) {
				element = this;
			}
			var container = $(element).upToClassName('column');
			if (container) {
				$A(container.getElementsByTagName('input')).each(
					function (item) {
						if (item.type == 'checkbox') {
							item.checked = true;
						}
					}
				);
				return false;
			}
			return true;
		},
		replace : function (target, valuesLeft, valuesRight) {
			target = $(target);
			if (!target) {
				return false;
			}
			var replace = function (target, values) {
				if (values) {
					target.removeClassName("empty");
					if (target.tagName.toLowerCase() != "dl") {
						var newTarget = document.createElement("dl");
						newTarget.className = target.className;
						if (target.id) {
							newTarget.id = target.id;
						}
						newTarget.appendChild(document.createElement("dt"));
						newTarget.firstChild.innerHTML = target.innerHTML;
						target.parentNode.insertBefore(newTarget, target);
						target.parentNode.removeChild(target);
						target = newTarget;
						$(target).removeClassName("empty");
					}
					else {
						var elements = target.getElementsByTagName("dd");
						while (elements.length) {
							target.removeChild(elements[0]);
						}
					}
					$A(values).each(
						function (item) {
							var element = document.createElement("dd");
							element.appendChild(document.createTextNode(item));
							target.appendChild(element);
						}
					);
				}
				else {
					if (target.tagName.toLowerCase() == "dl") {
						var newTarget = document.createElement("dl");
						newTarget.className = target.className;
						newTarget.id = target.id;
						newTarget.innerHTML = target.getElementsByTagName("dt")[0].innerHTML;
						target.parentNode.insertBefore(newTarget, target);
						target.parentNode.removeChild(target);
						target = newTarget;
						$(target).addClassName("empty");
					}
				}
			}
			replace(target.descedantOfClassName('left'), valuesLeft);
			replace(target.descedantOfClassName('right'), valuesRight);
			return true;
		}
	},
	cancel : function () {
		var cancel = $(this);
		if (cancel) {
			if (cancel.upToClassName('edit')) {
				return HWW.Profile.close(cancel);
			}
			else if (cancel.upToId('overlay')) {
				return HWW.popupClose();
			}
		}
		return true;
	},
	locationMatch : function (targetId) {
		$(targetId + 'Distance').onchange = function () {
			if (this.value) {
				$(targetId + 'MatchDistance').checked = true;
			}
		};
	},
	locationWidget : function (targetId, baseUrl, zipCountries, usId) {
		var target = $(targetId);

		target.baseUrl = baseUrl;

		// Setup refs
		target.countryId = $(targetId + 'CountryId');
		target.stateId = $(targetId + 'StateId');
		target.city = $(targetId + 'City');
		target.zip = $(targetId + 'Zip');
		target.match = $(targetId + 'MatchWrap');

		// Setup backrefs
		target.countryId.owner = target;
		target.stateId.owner = target;
		target.city.owner = target;
		target.zip.owner = target;

		// Setup loaders
		var needLoader = [target.stateId, target.city, target.zip];
		for (var i = 0; i < needLoader.length; ++i) {
			var loader = document.createElement('div');
			loader.className = 'loader';

			needLoader[i].previousSibling.appendChild(loader);
			needLoader[i].loader = loader;
			$(loader).hide();
		}

		// Setup notes
		var noteWrap = $(document.createElement('div'));
		noteWrap.className = 'note';
		target.appendChild(noteWrap);

		var usNote = $(document.createElement('span'));
		usNote.innerHTML = MHE.l10n.getMsg('LocationUsNote') + ' ';
		usNote.hide();
		noteWrap.appendChild(usNote);

		var nonUsNote = $(document.createElement('span'));
		nonUsNote.innerHTML = MHE.l10n.getMsg('LocationNonUsNote') + ' ';
		nonUsNote.hide();
		noteWrap.appendChild(nonUsNote);

		var resetLink = $(document.createElement('span'));
		resetLink.className = 'ajax-link';
		resetLink.innerHTML = MHE.l10n.getMsg('LocationReset');
		noteWrap.appendChild(resetLink);

		target.usNote = usNote;
		target.nonUsNote = nonUsNote;
		target.resetLink = resetLink;
		resetLink.owner = target;

		// Setup city autocomplete
		var cityACList = document.createElement('div');
		cityACList.className = 'autocomplete';
		cityACList.activeItem = null;
		cityACList.isEmpty = true;
		cityACList.appendChild(document.createElement('ul'));
		target.city.parentNode.appendChild(cityACList);
		target.city.ACList = cityACList;
		target.city.ACList.owner = target.city;
		$(cityACList).hide();

		// Calculate city autocomplete position
		var offset;
		try {
			offset = target.city.positionedOffset();
		}
		catch (e) {
			// If Prototype.Version < 1.6 (browser is IE 6)
			offset = Position.positionedOffset(target.city);
		}
		cityACList.style.left = offset[0] + 'px';
		cityACList.style.top = offset[1] + target.city.offsetHeight + 'px';

		// Setup countryId additional properties
		target.countryId.zipCountries = zipCountries;

		// Setup city additional properties
		target.city.stateId = target.stateId.value;
		target.city.oldValue = '';

		// Setup destructor
		Event.observe(
			window,
			'unload',
			function () {
				target.stateId.loader = null;
				target.city.loader = null;
				target.zip.loader = null;

				target.city.ACList.activeItem = null;
				target.city.ACList.owner = null;
				target.city.ACList = null;

				target.countryId.owner = null;
				target.stateId.owner = null;
				target.city.owner = null;
				target.zip.owner = null;
				target.resetLink.owner = null;

				target.usNote = null;
				target.nonUsNote = null;
				target.resetLink = null;
			}
		);

		// Add methods for target
		target.updateMatch = function () {
			if (this.match) {
				var emptyCity = ! Boolean(this.city.value).valueOf();
				var emptyZip  = ! Boolean(this.zip.value).valueOf();
				var metropolitan = $(this.id + 'MatchMetropolitan');
				metropolitan.disabled = emptyZip && emptyCity;

				if (metropolitan.disabled) {
					$(metropolitan.parentNode).addClassName('limited');
				}
				else {
					$(metropolitan.parentNode).removeClassName('limited');
				}

				var distance = $(this.id + 'MatchDistance');
				distance.disabled = $(this.id + 'Distance').disabled = emptyZip;

				if (distance.disabled) {
					$(distance.parentNode).addClassName('limited');
				}
				else {
					$(distance.parentNode).removeClassName('limited');
				}
			}
		};
		target.updateNotes = function () {
			if (this.countryId.value == usId) {
				this.usNote.show();
				this.nonUsNote.hide();
			}
			else {
				this.usNote.hide();
				this.nonUsNote.show();
			}
		};

		// Add methods for countryId
		target.countryId.isUseZip = function () {
			return this.zipCountries[this.value];
		};
		target.countryId.updateVisibility = function () {
			this.owner.zip.updateVisibility();
			var wrap = $(this.parentNode.nextSibling);
			if (this.value == 0) {
				wrap.hide();
			}
			else {
				wrap.show();
			}
			this.owner.updateMatch();
			this.owner.updateNotes();
		};
		target.countryId.onchange = function () {
			this.owner.stateId.updateData();
			this.owner.city.resetData();
			this.updateVisibility();
		};


		// Add methods for stateId
		target.stateId.onFinishRequest = function () {
			this.activeRequest = null;
			this.loader.hide();

			if (! this.isActual) {
				this.updateData();
				return false;
			}
			return true;
		};
		target.stateId.updateData = function () {
			this.options.length = 1;
			if (this.activeRequest) {
				this.isActual = false;
			}
			else {
				this.isActual = true;

				if (this.owner.countryId.value != 0) {
					var self = this;

					this.loader.show();
					this.activeRequest = new Ajax.Request(
						HWW.randomUrl(this.owner.baseUrl + 'locations/states'),
						{
							parameters: {
								country_id : this.owner.countryId.value
							},
							onFailure: function () {
								self.onFinishRequest();
							},
							onSuccess: function (transport) {
								if (self.onFinishRequest()) {
									// IE 6 fixes
									var response = transport.responseJSON;
									if (! response) {
										response = eval(transport.responseText);
									}
									$A(response).each(function (item) {
										var option = document.createElement('option');
										option.value = item.State.id;
										option.appendChild(
											document.createTextNode(item.State.name)
										);
										self.appendChild(option);
									});
								}
							}
						}
					);
				}
			}
		};
		target.stateId.onchange = function () {
			if (this.value != 0 &&
				this.value != this.owner.city.stateId) {
				this.owner.city.resetData();
			}
		};

		// Add methods for city autocomplete list
		target.city.ACList.resetActiveItem = function(newActiveItem) {
			if (this.activeItem) {
				this.activeItem.removeClassName('active');
				this.activeItem = null;
			}
			if (newActiveItem && !this.isEmpty) {
				this.activeItem = $(newActiveItem);
				this.activeItem.addClassName('active');
			}
		};
		target.city.ACList.nextActiveItem = function () {
			if (this.isEmpty) {
				return;
			}
			var list = this.firstChild;
			var newActiveItem = list.firstChild;
			if (this.activeItem && this.activeItem.nextSibling) {
				newActiveItem = this.activeItem.nextSibling;
			}
			this.resetActiveItem(newActiveItem);
		};
		target.city.ACList.prevActiveItem = function () {
			if (this.isEmpty) {
				return;
			}
			var list = this.firstChild;
			var newActiveItem = list.lastChild;
			if (this.activeItem && this.activeItem.previousSibling) {
				newActiveItem = this.activeItem.previousSibling;
			}
			this.resetActiveItem(newActiveItem);
		};
		target.city.ACList.clearList = function() {
			this.resetActiveItem();
			var list = this.firstChild;
			while (list.firstChild) {
				list.removeChild(list.firstChild);
			}
			this.isEmpty = true;
			this.hide();
		};
		target.city.ACList.populateList = function(items) {
			this.clearList();

			var count = 0;
			var list = this.firstChild;
			var self = this;
			var onHover = function () {
				if (self.activeItem != this) {
					self.resetActiveItem(this);
				}
			};
			var onClick = function () {
				if (self.activeItem != this) {
					self.resetActiveItem(this);
				}
				self.selectActiveItem();
			};
			$A(items).each(function (item) {
				var li = document.createElement('li');
				li.innerHTML = item.City.name.replace(
					new RegExp('(' + self.owner.value + ')', 'i'),
					'<strong>$1</strong>'
				);
				if (self.owner.owner.stateId.value == 0) {
					li.innerHTML += ' (' + item.State.name + ')';
				}
				li.onmouseover = onHover;
				li.onclick = onClick;

				li.city = item.City.name;
				li.stateId = item.State.id;
				li.zip = item.City.default_zip;

				list.appendChild(li);
				count++;
			});
			this.isEmpty = (count == 0);
			if (this.isEmpty) {
				var li = document.createElement('li');
				li.className = 'error';
				li.innerHTML = 'City not found';
				list.appendChild(li);
			}
			if (this.owner.hasFocus) {
				this.show();
			}
		};
		target.city.ACList.selectActiveItem = function () {
			if (this.activeItem) {
				this.owner.stateId = this.owner.owner.stateId.value =
					this.activeItem.stateId;
				//Auto setting up default zip for selected city is not needed now
				//this.owner.owner.zip.value = this.activeItem.zip;
				this.owner.value = this.activeItem.city;
				this.owner.oldValue = this.owner.value;
				this.clearList();
			}
		};

		// Add methods for city
		target.city.resetData = function() {
			this.value = '';
			this.oldValue = '';
			this.stateId = this.owner.stateId.value;
			this.owner.zip.value = '';
			this.ACList.clearList();
			this.owner.updateMatch();
		};
		target.city.onFinishRequest = function () {
			this.activeRequest = null;
			this.loader.hide();

			if (! this.isActual) {
				this.updateData();
				return false;
			}
			return true;
		};
		target.city.updateData = function() {
			if (this.oldValue != this.value || !this.isActual) {
				if (this.delayedRequest) {
					clearTimeout(this.delayedRequest);
					this.delayedRequest = null;
				}

				if (this.activeRequest) {
					this.isActual = false;
				}
				else {
					if (this.value.length > 2 && this.owner.countryId.value != 0) {
						var self = this;

						this.delayedRequest = setTimeout(
							function () {
								self.delayedRequest = null;

								self.isActual = true;
								self.loader.show();
								self.activeRequest = new Ajax.Request(
									HWW.randomUrl(self.owner.baseUrl + 'locations/cities'),
									{
										parameters: {
											country_id : self.owner.countryId.value,
											state_id : self.owner.stateId.value,
											city : self.value
										},
										onFailure: function () {
											self.onFinishRequest();
										},
										onSuccess: function (transport) {
											// IE 6 fixes
											var response = transport.responseJSON;
											if (! response) {
												response = eval(transport.responseText);
											}
											self.ACList.populateList(response);
											self.onFinishRequest();
										}
									}
								);
							},
							100
						);
					}
				}
			}
			this.oldValue = this.value;
			this.owner.updateMatch();
		};
		target.city.onchange = function () {
			this.updateData();
		};
		target.city.onkeyup = function (event) {
			if (this.ACList.visible()) {
				// Fixes for IE
				if (! event) {
					event = window.event;
				}

				switch (event.keyCode) {
					case Event.KEY_RETURN:
						if (this.ACList.activeItem) {
							this.ACList.activeItem.onclick();
						}
						return false;

					case Event.KEY_UP:
						this.ACList.prevActiveItem();
						return false;

					case Event.KEY_DOWN:
						this.ACList.nextActiveItem();
						return false;
				}
			}
			this.updateData();
		};
		target.city.onfocus = function () {
			this.hasFocus = true;
			this.updateData();
			if (this.delayedBlur) {
				clearTimeout(this.delayedBlur);
				this.delayedBlur = null;
			}
		};
		target.city.onblur = function () {
			var self = this;
			this.delayedBlur = setTimeout(
				function () {
					self.oldValue = '';
					self.ACList.clearList();
					self.hasFocus = false;
					self.delayedBlur = null;
				},
				300
			);
		};
		// Fixes for IE 7 and Opera
		target.city.onkeypress = function (event) {
			if (! event) {
				event = window.event;
			}
			if (event &&
				event.keyCode == Event.KEY_RETURN &&
				this.ACList.visible() &&
				this.ACList.activeItem) {

				this.ACList.activeItem.onclick();
				return false;
			}
		};

		// Add methods for zip
		target.zip.updateVisibility = function () {
			if (this.owner.countryId.isUseZip()) {
				$(this.parentNode.parentNode.parentNode).addClassName('show-zip');
			}
			else {
				$(this.parentNode.parentNode.parentNode).removeClassName('show-zip');
			}
		};
		target.zip.onFinishRequest = function () {
			this.activeRequest = null;
			this.loader.hide();

			if (! this.isActual) {
				this.updateData();
				return false;
			}
			return true;
		};
		target.zip.updateData = function () {
			if (this.activeRequest) {
				this.isActual = false;
			}
			else {
				var self = this;
				this.isActual = true;
				this.loader.show();
				this.activeRequest = new Ajax.Request(
					HWW.randomUrl(this.owner.baseUrl + 'locations/zip'),
					{
						parameters: {
							country_id : this.owner.countryId.value,
							zip : this.value
						},
						onFailure: function () {
							self.onFinishRequest();
						},
						onSuccess: function (transport) {
							// IE 6 fixes
							var response = transport.responseJSON;
							if (! response) {
								response = eval(transport.responseText);
							}
							if (self.onFinishRequest()) {
								self.owner.stateId.value = response.State.id;
								self.owner.city.value = response.City.name;
							}
						}
					}
				);
			}
		};
		target.zip.onchange = function () {
			this.updateData();
			this.owner.updateMatch();
		};
		target.zip.onkeyup = function () {
			if (this.value != this.oldValue && this.value.length == 5) {
				this.updateData();
			}
			this.oldValue = this.value;
			this.owner.updateMatch();
		};

		// Add methods for resetLink
		target.resetLink.onclick = function () {
			if (this.owner.countryId.value != usId) {
				this.owner.countryId.value = 0;
				this.owner.countryId.onchange();
			}
			else {
				this.owner.stateId.value = 0;
				this.owner.city.resetData();
			}
		};

		// Init widget
		target.countryId.updateVisibility();
	},
	moveCaretToEnd : function (inputObject){
		nav = navigator.appName.toLowerCase();
		isIE = !('opera'==nav||'netscape'==nav);
		isFF = 'netscape'==nav;
		if (isIE) {
			if (inputObject.createTextRange){
				var r = inputObject.createTextRange();
				r.collapse(false);
				r.select();
			}
		}
		if (isFF) {
			var code  = ' '.charCodeAt(0);
			var event = document.createEvent("KeyboardEvent");
			event.initKeyEvent('keypress', true, true, window, false, false, false, false, code, code);
			inputObject.dispatchEvent(event);
		}
	},
	addChangesChecker : function (formId) {
		var formObj = $(formId);
		if (!formObj) {
			return false;
		}
		formObj.observe(
			'submit',
			(function () {
				return !$(this).down('input[type=submit]').disabled;
			}).bind(formObj)
		);
		var button = formObj.down('input[type=submit]');
		button.disabled = true;
		button.up().addClassName('disabled');
		var checkState = function () {
			var form = $(this.form);
			var enabled = false;
			var elements = form.getElements();
			for (var j = 0; j < elements.length; j++) {
				enabled |= (elements[j].value != elements[j].initValue);
			}
			var button = form.down('input[type=submit]');
			if (enabled) {
				button.disabled = false;
				button.up().removeClassName('disabled');
			}
			else {
				button.disabled = true;
				button.up().addClassName('disabled');
			}
		};
		var elements = formObj.getElements();
		for (var i = 0; i < elements.length; i++) {
			elements[i].initValue = elements[i].value;
			if (
				elements[i].tagName.toLowerCase() == 'textarea'
				||
				(
					elements[i].tagName.toLowerCase() == 'input'
					&&
					(
						elements[i].type == 'text'
						||
						elements[i].type == 'password'
					)
				)
			) {
				elements[i].observe('keyup', checkState.bind(elements[i]));
			}
			elements[i].observe('change', checkState.bind(elements[i]));
		}
		return true;
	}
}

var Twitter = {
	since_id : 1,
	type : 'latest',
	url : '',
	wrap_id : 'twitter_wrap',
	limit : 5,
	refresh_freq : 15,
	loaded_url : '',
	connection_confirm: 0,
	waiting_timeout : 10000,
	first_load : 1,
	no_messages : 0,
	setup : function (obj) {
		if (typeof obj.url == 'string') {
			this.url = obj.url;
		}
		else {
			return false;
		}
		if (typeof obj.since_id == 'number') {
			this.since_id = obj.since_id;
		}
		if (
			typeof obj.type == 'string'
			&&
			(obj.type == 'latest' || obj.type == 'related')
		) {
			this.type = obj.type;
		}
		if (typeof obj.refresh_freq == 'number') {
			this.refresh_freq = obj.refresh_freq;
		}
		if (typeof obj.wrap_id == 'string') {
			this.wrap_id = obj.wrap_id;
		}
		if (typeof obj.limit == 'number') {
			this.limit = obj.limit;
		}
		if (typeof obj.first_load == 'number') {
			this.first_load = obj.first_load;
		}
		this.start();
		return true;
	},

	start : function () {
		if (typeof Twitter.timeout_job != 'undefined') {
			clearTimeout(Twitter.timeout_job);
		}
		if (typeof Twitter.timeout_twitter_detect_job != 'undefined') {
			clearTimeout(Twitter.timeout_twitter_detect_job);
		}
		Twitter.connection_confirm = 0;
		Twitter.timeout_twitter_detect_job = setTimeout(
			function () {
				if (!Twitter.connection_confirm) {
					$(Twitter.wrap_id).update(
						'<div class="twitter_error">'
						+
						HWW.strings.TwitterError
						+
						'</div>'
					);
				}
			},
			Twitter.waiting_timeout
		);
		AttachScript(
			HWW.randomUrl(
				Twitter.url.replace(/::since_id::/, Twitter.since_id),
				"::rand::"
			)
		);
	},

	populate : function (data) {
		var div = document.createElement('div');
		div.id = 'twitt_id_' + data.id;
		div.className = 'twitter_item_wrap';
		div.innerHTML = '<img alt="' + data.user + '" class="user_photo" src="' + data.avatar + '" />' +
			'<div class="twitter_text">' +
			'<strong><a href="http://www.twitter.com/' + data.user + '">' +
			data.user +
			"</a></strong>" +
			'<br />' +
			data.text +
			'</div>';
		return div;
	},

	truncate : function (container, limit) {
		container = $(container);
		if (container) {
			while (container.childNodes.length > limit) {
				container.removeChild(container.lastChild);
			}
		}
		return true;
	},

	twitter_callback : function (json_obj) {
		var target = $(Twitter.wrap_id);
		if (!target) {
			return false;
		}
		Twitter.connection_confirm = 1;
		var head = document.getElementsByTagName("head")[0];
		for (var i = 0; i < head.childNodes.length; i++) {
			if (
				head.childNodes[i].tagName
				&&
				head.childNodes[i].tagName == 'SCRIPT'
				&&
				head.childNodes[i].src == Twitter.loaded_url
			) {
				head.removeChild(head.childNodes[i]);
			}
		}
		if (typeof json_obj == 'undefined') {
			Twitter.since_id = 1;
			target.update('<div class="twitter_error">' + HWW.strings.TwitterError + '</div>');
		}
		else if (typeof json_obj.error == 'undefined') {
			if (
				target.firstChild.nodeName.toLowerCase() != 'div'
				||
				target.firstChild.className != 'twitter_item_wrap'
			) {
				target.update();
			}
			if (Twitter.type == 'related') {
				if (json_obj.results.length != 0) {
					Twitter.since_id = json_obj.results[0].id;
					for (var i = json_obj.results.length - 1; i >= 0; i--) {
						target.insertBefore(
							Twitter.populate(
								{
									id : json_obj.results[i].id,
									user : json_obj.results[i].from_user,
									avatar : json_obj.results[i].profile_image_url,
									text : json_obj.results[i].text
								}
							),
							target.firstChild
						);
					}
				}
				else {
					if (Twitter.first_load) {
						Twitter.no_messages = 1;
						target.update('<div class="twitter_error">'+HWW.strings.TwitterNoTwitts+'</div>');
					}
				}
			}
			else {
				if (json_obj.length != 0) {
					Twitter.since_id = json_obj[0].id;
					for (var i = json_obj.length - 1; i >= 0; i--) {
						target.insertBefore(
							Twitter.populate(
							{
								id : json_obj[i].id,
								user : json_obj[i].user.screen_name,
								avatar : json_obj[i].user.profile_image_url,
								text : json_obj[i].text
							}
							),
							target.firstChild
						);
					}
				}
				else {
					if (Twitter.first_load) {
						Twitter.no_messages = 1;
						target.update('<div class="twitter_error">'+HWW.strings.TwitterNoTwitts+'</div>');
					}
				}
			}
			Twitter.truncate(target, Twitter.limit);
		}
		Twitter.first_load = 0;
		if (!Twitter.no_messages) {
			Twitter.timeout_job = setTimeout(
				function () {
					AttachScript(
						HWW.randomUrl(
							Twitter.url.replace(/::since_id::/, Twitter.since_id),
							"::rand::"
						)
					);
				},
				Twitter.refresh_freq
			);
		}
		return true;
	}
}

var MHE = {
	l10n : {
		dict : null,
		locale : null,
		getMsg : function (id, params) {
			var result = id;
			if (! this.locale) {
				return id;
			}
			params = params || {};
			var form = params.count ? this.locale.getPluralForm(params.count) : 0;

			if (this.dict
				&& this.dict[id]
				&& this.dict[id][form]) {
				result = this.dict[id][form];
			}

			for (name in params) {
				result = result.replace('%(' + name + ')s', params[name]);
			}

			return result;
		}
	}
};

var HWWToolTip = {
	showDelay : 500,
	timeoutJob: false,
	loaderText: 'Please, wait ...',
	toolTipClass: 'hww-tooltip',
	toolTipTipClass: 'hww-tooltip-tip',
	toolTipWrapClass: 'hww-tooltip-wrapper',
	baseUrl: '',
	cache : new Hash(),
	fullSetup : function (start, classes) {
		var elements = [];
		var start = $(start);
		if (
			!start || 
			typeof classes == 'undefined' || 
			typeof start.id == 'undefined'
		) {
			return false;
		}
		if (typeof classes == 'string') {
			elements = $$('#' + start.id + ' a.' + classes);
			$A(elements).each(
				function(item) {
					HWWToolTip.setup(item, classes);
				}
			);
		}
		if (typeof classes == 'object') {
			$A(classes).each(
				function(item) {
					var type = item;
					elements =  $$('#' + start.id + ' a.' + item);
					$A(elements).each(
						function(item) {
							HWWToolTip.setup(item, type);
						}
					);
				}
			);
		}
		return false;
	},
	setup : function (obj, type) {
		obj = $(obj);
		if (!obj) {
			return false;
		}
		if (!obj.id) {
			obj.id = type + "Artifact" + Math.round(Math.random() * 10000);
		}
		obj.artifactType = type;
		Event.observe(
			obj,
			'mouseover',
			function () {
				obj.showToolTip = true;
				HWWToolTip.timeoutJob = setTimeout(
					function () {
						if (!$(obj.toolTipId) && obj.showToolTip) {
							HWWToolTip.show(obj);
						}
					},
					HWWToolTip.showDelay
				);
			}
		);
		Event.observe(
			obj,
			'mouseout',
			function () {
				obj.showToolTip = false;
			}
		);
	},
	mouseMoveHandler : function (evt) {
		if (typeof this.toolTipId == 'undefined') {
			return;
		}
		var target = $(evt.target || evt.srcElement);
		if (!target) {
			HWWToolTip.hide(this);
			return;
		}
		this.canEraseToolTip = false;
		if (
			(target.id != this.id && !target.upToId(this.id))
			&&
			(target.id != this.toolTipId && !target.upToId(this.toolTipId))
		) {
			this.canEraseToolTip = true;
			HWWToolTip.timeoutJob = setTimeout(
				(function () {
					HWWToolTip.hide(this);
				}).bind(this),
				HWWToolTip.showDelay
			);
		}
	},
	show : function (obj) {
		var alias = obj.getAttribute('alias');
		if (!alias) {
			return false;
		}
		var cacheKey = obj.artifactType + alias;
		var toolTipId = obj.id + "ToolTip";
		var container = document.createElement('div');
		container = $(container);
		container.id = toolTipId;
		container.addClassName(HWWToolTip.toolTipClass);
		document.body.appendChild(container);
		
		var tip = document.createElement('div');
		tip = $(tip);
		tip.id = toolTipId + 'Tip';
		tip.addClassName(HWWToolTip.toolTipTipClass);
		container.appendChild(tip);
		
		var wrap = document.createElement('div');
		wrap = $(wrap);
		wrap.id = toolTipId + 'Wrap';
		wrap.addClassName(HWWToolTip.toolTipWrapClass);
		container.appendChild(wrap);
		
		obj.toolTipId = toolTipId;
		Event.observe(document, 'mousemove', HWWToolTip.mouseMoveHandler.bind(obj));
		if (HWWToolTip.cache[cacheKey]) {
			wrap.update(HWWToolTip.cache[cacheKey]);
			HWWToolTip.setPosition(obj, $(toolTipId));
		}
		else {
			new Loader(
				wrap.id,
				{
					id : toolTipId + 'Loader',
					tagName : 'div',
					text : HWWToolTip.loaderText
				}
			);
			HWWToolTip.setPosition(obj, $(toolTipId));
			var ajaxUrl = HWWToolTip.buildAjaxLink(obj);
			new Ajax.Request(
				ajaxUrl,
				{
					requestHeaders : {
						'X-Referer' : HWW.ieUrl(window.location.href)
					},
					onSuccess : function (transport) {
						if ($(wrap)) {
							if (transport.responseText) {
								wrap.update(transport.responseText);
								HWWToolTip.cache[cacheKey] = transport.responseText;
							}
							else {
								wrap.update('No data for tooltip');
							}
							HWWToolTip.setPosition(obj, $(toolTipId));
						}
					},
					onFailure : function (transport) {
						wrap.update('Error');
					}
				}
			);
		}
	},
	hide : function (obj) {
		var toolTip = $(obj.toolTipId);
		if (!toolTip) {
			return false;
		}
		if (obj.canEraseToolTip) {
			toolTip.remove();
			Event.stopObserving(document, 'mousemove', HWWToolTip.mouseMoveHandler.bind(obj));
		}
	},
	setPosition : function (obj, toolTip) {
		obj = $(obj);
		obj = obj.down('span.artifact-avatar') ? obj.down('span.artifact-avatar') : obj;
		toolTip = $(toolTip);
		if (!obj || !toolTip) {
			return false;
		}
		var cpos = Position.cumulativeOffset(obj);
		var rpos = Position.realOffset(obj);
		var pw = HWWToolTip.getClientWidth();
		var ph = HWWToolTip.getClientHeight();
		var ow = obj.offsetWidth;
		var oh = obj.offsetHeight;
		var tw = toolTip.offsetWidth;
		var th = toolTip.offsetHeight;
		var left = cpos[0] + ow - 10 + "px";
		var right = pw - cpos[0] - 10 + "px";
		var top = cpos[1] + oh - 5 + "px";
		var bottom = ph - cpos[1] - 8 + "px";
		if (Prototype.Version < '1.6') {
			bottom = ph - cpos[1] + rpos[1] + "px";
		}
		var xSide = 'right';
		var ySide = 'top';
		var positionObj = {};
		
		if (pw - (cpos[0] - rpos[0]) - ow >= tw) {
			xSide = 'right'
		}
		else if (cpos[0] - rpos[0] >= tw) {
			xSide = 'left'
		}
		else {
			if (pw - (cpos[0] - rpos[0]) - ow > cpos[0] - rpos[0]) {
				xSide = 'right'
			}
			else {
				xSide = 'left'
			}
		}
		
		if (cpos[1] - rpos[1] >= th) {
			ySide = 'top';
		}
		else if (ph - (cpos[1] - rpos[1]) - oh >= th) {
			ySide = 'bottom';
		}
		else {
			if (cpos[1] - rpos[1] >= ph - (cpos[1] - rpos[1]) - oh) {
				ySide = 'top';
			}
			else {
				ySide = 'bottom';
			}
		}
		toolTip.addClassName(xSide + '-' + ySide);
		xSide = (xSide == 'left') ? 'right' : 'left';
		ySide = (ySide == 'top') ? 'bottom' : 'top';
		positionObj[xSide] = eval(xSide);
		positionObj[ySide] = eval(ySide);
		toolTip.setStyle(positionObj);
	},
	getClientWidth : function () {
		return document.compatMode=='CSS1Compat' 
			&& !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
	},
	getClientHeight : function () {
		return document.compatMode=='CSS1Compat' 
			&& !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
	},
	buildAjaxLink : function (obj) {
		var alias = obj.getAttribute('alias');
		if (!alias) {
			return false;
		}
		var controller = HWWToolTip.pluralize(obj.artifactType);
		if (!obj.artifactType) {
			return false;
		}
		return HWWToolTip.baseUrl + controller + '/info/' + alias;
	},
	pluralize : function (str) {
		switch (str) {
			case 'user': return 'users';
			case 'community': return 'communities';
			case 'doctor': return 'doctors';
			case 'disease': return 'diseases';
		}
		return false;
	}
}