/**
 * Generic JavaScript file
 * ALL RIGHTS RESERVED!
 *
 * + third party libraries, additional copyrights below
 **/

/** COMMENT POSTING **/
function comments() {}
comments.prototype = {
	autoUpdate: true,
	autoUrl: null,
	replying: false,
	htmlId: null,

	setAutoUrl: function(url) {
		this.autoUrl = url;
	},

	postComment: function(formElement, url) {
		if(!Prototype) {
			return true;
		}

		if($(this.htmlId + '_comment').value == "") {
			alert(lang.get("writeamessagefirst"));
			return false;
		}

		this.autoUpdate = false;

		new Ajax.Request(url, { 
				method: 'post',
				parameters: Form.serialize(formElement),
				onComplete: this.postCommentFetch.bind(this)
			}); 

		Form.disable(this.htmlId + '_cForm');

		return false;
	},

	setReplyComment: function (alias, commentid) {
		if(this.replying) {
			this.unsetReplyComment();
		}

		$(this.htmlId + '_replyCommentid').value = commentid;
		$(this.htmlId + '_replyCommentAlias').innerHTML = alias;
		$(this.htmlId + '_replyCommentAliasInput').value = alias;
		$(this.htmlId + '_replyComment').show();
		$(this.htmlId + '_replyCommentButton_' + commentid).disable();

		// scroll
		$(this.htmlId + '_replyComment').scrollTo();

		this.replying = true;
	},

	unsetReplyComment: function() {
		try {
			$(this.htmlId + '_replyCommentButton_' + $(this.htmlId + '_replyCommentid').value).enable();
			$(this.htmlId + '_replyCommentid').value = '';
			$(this.htmlId + '_replyCommentAlias').innerHTML = '';
			$(this.htmlId + '_replyCommentAliasInput').value = '';
			$(this.htmlId + '_replyComment').hide();
		} catch (e) {
		}

		this.replying = false;
	},

	updateCommentField: function(html) {
		Element.update(this.htmlId + '_xmlCommentContent', html);
		handleComments(this.htmlId + '_com', 'td');
	},

	postCommentFetch: function(r) {
		// is this required anymore?
		if(this.replying) {
			this.unsetReplyComment();
		}

		Form.enable(this.htmlId + '_cForm');
		$(this.htmlId + '_comment').value = '';

		this.updateCommentField(r.responseText);

		this.updateComments();
	},

	registerCommentSubmit: function() {
		// submit the form
		$(this.htmlId + '_cForm').submit();

		// disable hoverbox
		hoverBox.disable();
	},

	updateComments: function(r, opts) {
		if(typeof(r) != "undefined" && r != null) 
		{
			this.updateCommentField(r.responseText);
		} else {
			new Ajax.Request(this.autoUrl, { 
				method: 'get', 
				onComplete: this.updateComments.bind(this),
				parameters: opts.parameters != null ? opts.parameters : null
				});
		}
	},

	toggleDelete: function() {
		var TDitems = $$('input.' + this.htmlId + '_singleDeleteButton');
		for(var i=0;i<TDitems.length;i++) {
			Element.toggle(TDitems[i]);
		}
	},

	toggleVisible: function(commentIds) {
		// show comment rows
		for(var i=0;i<commentIds.length;i++) {
			try {
				$(this.htmlId + '_comment_' + commentIds[i]).show();
			} catch(e) {}
		}

		// hide view all link
		$(this.htmlId + '_viewAllLink').hide();
	},

	deleteComment: function(commentid, url) {
		var htmlId = this.htmlId;

		if(!areyousurereturn()) {
			return false;
		}

		new Ajax.Request(url, {
			method: 'post',
			onComplete: function(r) {
				// TODO: check if responseText contains "DELETED" and fade only then
				Effect.Fade(htmlId + '_comment_' + commentid);
			}
		});
	}
}

/** Common functions **/
function nl2br (s) {
	return s.replace(/\r/g, '<br>');
}
function htmlspecialchars (s) {
	s = s.replace(/</g, '&lt;');
	s = s.replace(/>/g, '&gt;');
	return s;
}
function icon(icon, text) {
	return '<img class=icon src="/vimages/html/images/icons/' + icon + '.png" alt="">' + text;
}
function getTime() {
	var dt = new Date();
	return ((dt.getTime() - dt.getMilliseconds()) / 1000);
}
function shorten(str, length) {
	if(length && str.length > length) {
		str = str.substr(0, length);
		str += "...";
	}
	return str;
}
function areyousure(url) {
	// ie gludge for utf8 chars
	if(navigator.userAgent.indexOf("MSIE") != -1) {
		// first, split by ?
		var newurl = url.split("\?");

		// escape first part, last part leave as it is
		url = escape(newurl[0]) + (newurl[1] != null ? "?" + newurl[1] : "");
	}

	if(confirm(lang.get("areyousure"))) {
		window.location = url;
	}
}
function areyousurereturn () {
	if(confirm(lang.get("areyousure"))) {
		return true;
	} else {
		return false;
	}
}
function areyousurecustom(msg, url) {
	if(confirm(lang.get(msg))) {
		window.location = url;
	}
}
function gotoSelectedUrl (url, selectElement, prefix) {
	if(prefix == "") {
		prefix = 0;
	}

	var selected = selectElement.selectedIndex;
	var newIndex = selected + prefix;

	if(newIndex < 0) {
		return;
	}

	if(selectElement[newIndex] == null) {
		return;
	}

	document.location.href = url + selectElement[newIndex].value;
}
function validate(elem, vReg)
{
	var re = new RegExp(vReg);
	var ret = re.exec(elem.value);

	if(ret)
	{
		elem.className = null;
		return true;
	}
	else
	{
		elem.className = "error";
	}
}
function addslashes(str){ 
	return str.replace(/\'/g, '\\\''); 
}
function addLinks(s) 
{   
	var linkRegExp = / http:\/\/([^ \,\;\:\!\)\(\"\'\<\>\f\n\r\t\v])+/g;
	return s.replace(linkRegExp, function ($str) { return $str.link($str); });
}

function boxToggle(name) {
	/* search by id's and toggle */
	try {
		Element.toggle(name + '_editor');
	} catch (e) {}
	try {
		Element.toggle(name + '_content');
	} catch (e) {}

	/* toggle classes as well */
	var items = $$('.' + name + '_editor');
	for(var i=0;i<items.length;i++) {
		Element.toggle(items[i]);
	}

	var items = $$('.' + name + '_content');
	for(var i=0;i<items.length;i++) {
		Element.toggle(items[i]);
	}
}

/** User list **/
function uListMenu (uid)
{
	document.getElementById('uid[' + uid + ']').innerHTML = document.getElementById('userListDropDown').innerHTML;
}

function prevNextLink (pageNum, curPage)
{
	if(document.getElementById('userList-' + pageNum) == null)
	{
		return true;
	}
	else
	{
		document.getElementById('userList-' + pageNum).style.display = '';

		if(curPage != pageNum)
		{
			document.getElementById('userList-' + curPage).style.display = 'none';
		}
		document.location.hash = '#' + pageNum;
		
		return false;
	}
}

function uListInitialize (curPage)
{
	var hash = document.location.hash;
	if(hash.length > 1)
	{
		hash = hash.substr(1, 10);

		if(document.getElementById('userList-' + hash) != null)
		{
			curPage = hash;
		}
	}
		
	document.getElementById('userList-' + curPage).style.display = '';
}

/**
 * globalClass yleinen luokka
 **/
globalClass = {
	pos_x: 0,
	pos_y: 0,

	popup_height: 0,
	popup_width: 0,

	popup_mouseDistance: 20,

	initialize: function() {
		if(typeof(Prototype) != "undefined") {
			Event.observe(document, 'mousemove', this.mousemove.bindAsEventListener(this));
		}
	},

	mousemove: function (e) {
		this.pos_x = Event.pointerX(e);
		this.pos_y = Event.pointerY(e);

		this.movePopup();
	},

	movePopup: function () {
		var posY = 0;
		var posX = 0;

		// x koordinaatti
		try {
			if(globalClass.pos_x + globalClass.popup_width + 50 > document.body.offsetWidth) {
				posX = globalClass.pos_x - globalClass.popup_width - this.popup_mouseDistance;
			} else {
				posX = globalClass.pos_x + this.popup_mouseDistance;
			}

			// y koordinaatti
			if(globalClass.pos_y - globalClass.popup_height - 50 - document.body.scrollTop > 0) {
				posY = globalClass.pos_y - globalClass.popup_height - this.popup_mouseDistance;
			} else {
				posY = globalClass.pos_y + this.popup_mouseDistance;
			}

			// siirretään boksia
			if( $('smallImg') && $('smallImg').style )
			{
				$('smallImg').style.left = posX + 'px';
				$('smallImg').style.top = posY + 'px';
			}
		} catch(e) {}
	},
	
	updatePopup: function (txt) {
		// asetetaan sisältö
		$('smallImg').innerHTML = txt;

		// asetetaan leveys yms
		var dim = Element.getDimensions('smallImg');
		this.popup_height = dim["height"];
		this.popup_width = dim["width"];

		this.movePopup();

		Element.show('smallImg');
	},

	hidePopup: function() {
		Element.hide('smallImg');
	}
}
globalClass.initialize();

/**
 * Popup process
 **/
popup = {
	timer: null,
	enabled: true,
	matcher: /^(http:\/\/.*\.hoitonetti\.fi){0,1}\/user.php\?nick\=([^ \&]{1,})$/,
	waitTime: 575,
	state_loading: false,
	popupCache: Object(),
	fetch_type: null,
	fetch_val: null,
	allowImagePopup: false,

	process: function(elem) {
		if(!this.enabled) {
			return false;
		}

		if(elem == null) {
			elem = document;
		}

		var links = elem.getElementsByTagName("a");

		for(var i=0;i<links.length;i++) {
			var ret = this.matcher.exec(links[i].getAttribute("href"));

			if(ret != null) {
				var nick = ret[2];

				Event.observe(links[i], 'mouseover', this.mouseover.bindAsEventListener(this), false);
				Event.observe(links[i], 'mouseout', this.mouseout.bindAsEventListener(this), false);
			}
		}
	},

	mouseover: function(e) {
		// jos on jo timer päällä
		if(this.timer != null) {
			return;
		}
		
		var elem = Event.element(e);

		// jos on joku muu kuin A tagi
		if(elem.tagName != "A") {
			// kuville ei popuppeja
			if(this.allowImagePopup == false && elem.tagName == "IMG") {
				return false;
			}

			// haetaan parent
			elem = elem.parentNode;
		}

		// löytyykö linkkiä
		var ret = this.matcher.exec(elem.getAttribute("href"));
		if(ret == null) {
			return false;
		}
		var nick = ret[2];

		// escapet
		if(nick.search(/%/)) {
			nick = unescape(nick);
		}

		this.fetch_type = 'user';
		this.fetch_val = nick;

		// aloitetaan ajastin
		this.timer = setTimeout(this.fetch.bind(this), this.waitTime);
	},

	fetch: function() {
		if(this.timer != null) {
			clearTimeout(this.timer);
			this.timer = null;
		}

		debug("fetching: " + this.state_loading);

		if(this.state_loading != false) {
			return false;
		}

		this.state_loading = this.fetch_type + "_" + this.fetch_val;

		// tarkistetaan josko löytyy jo cachesta
		if(typeof(this.popupCache[this.state_loading]) != "undefined") {
			debug("cache found!");
			var reply = this.popupCache[this.state_loading];

			this.showPopup(reply);
			return true;
		}

		debug("making request");

		new Ajax.Request('/misc/popup.php', {
			method: 'get',
			parameters: 'type=' + this.fetch_type + '&val=' + this.fetch_val,
			onComplete: this.showPopup.bind(this)
			});
	},

	showPopup: function(reply) {
		debug("got reply!");
		// jos objekti
		if(typeof(reply) == "object") {
			reply = reply.responseText;
		}

		// jos state päällä
		if(this.state_loading == false) {
			return false;
		}

		// cachetus
		this.popupCache[this.state_loading] = reply;
		this.state_loading = false;

		// näytetään
		globalClass.updatePopup(reply);

		debug("set state loading to: " + this.state_loading);
	},

	mouseout: function(e) {
		if(this.timer != null) {
			clearTimeout(this.timer);
			this.timer = null;
		}
		this.state_loading = false;

		globalClass.hidePopup();
	}
}

function debug(txt) {
	// jos objekti on olemassa
	if(typeof($('debug')) != "object") {
		return false;
	}
	
	//$('debug').innerHTML += txt + "<br>";
}

/**
 * Show Ajax loading graph
 * 
 * @param string elemName Element name which will contain the loading image
 * @return void
 */
function AJAX_showLoading(elemName, doReturn)
{
	var elem = $(elemName);
	if(elem == null) {
		return false;
	}

	var dimensions = elem.getDimensions();

	var doHtml = 
		'<div class=loadingDiv style="height: ' + dimensions.height + 'px; min-height: 50px;">' +
			'<img src="/vimages/html/images/lightbox/loading.gif" height="16"><br>' + lang.get("loading") + 
		'</div>';
	if(!doReturn) {
		$(elemName).innerHTML = doHtml;
	} else {
		return doHtml;
	}
}

/**
 *	Check if file is a image file
 **/
function checkFileType( path, errorCanvas )
{
	var filepath = path.toLowerCase();
	if( filepath.indexOf( ".jpg" ) == -1 && filepath.indexOf( ".gif" ) == -1 && filepath.indexOf( ".png" ) == -1 && filepath.indexOf( ".bmp" ) == -1 )
	{
		$( errorCanvas ).show();
		return;
	}
	$( errorCanvas ).hide();
	return;
}

hoverBox = {
	onCloseScrollTo: null,
	footerTimer: null,

	setContent: function(msg) {
	},

	_ie6_style: function() {
		// scrollto after cloe (ie6)
		hoverBox.onCloseScrollTo = document.viewport.getScrollOffsets();

		// set styles
		$('dimmer').setStyle( { 'position': 'absolute', 'height': document.body.offsetHeight + 'px', 'width': '100%' } );
		$('dimmer').show();
		
		// get dimensions
		dimensions = $('dimmer').getDimensions();
		var left = (dimensions.width) / 2 - 250;

		// hoverbox setup
		$('hoverBox').setStyle( { 'position': 'absolute', 'left': left + "px", 'top': "150px", 'width': '550px' } );
		$('hoverBox').show();
		$('hoverBox').scrollTo();
	},

	enable: function(options) {
		if(options == null) {
			options = {};
		}

		// for ie7 & ie6, other browsers ignore this
		$('dimmer').style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=70)';

		var ie6_style = false;

		// Check for IE6
		try {
			if ( new String( navigator.userAgent ).indexOf( "MSIE 6" ) != -1 ) {
				this._ie6_style();
				ie6_style = true;
			}
		} catch ( error ) { }

		if ( ie6_style == false ) {
			// show dimmer
			$('dimmer').show();

			// get dimensions for dimmer
			var dimensions = $('dimmer').getDimensions();
			var left = (dimensions.width) / 2 - 250;

			// hoverbox setup
			$('hoverBox').setStyle( { 'left': left + "px", 'top': ( dimensions.height * 0.1) + "px", 'maxWidth': '670px' } );
			$('hoverBox').show();
		}

		// create parameters
		if(options.parameters == null) {
			options.parameters = {};
		}
		// Check if ajax param is not set and set it true
		if ( typeof( options.parameters.ajax ) == "undefined" ) {
			options.parameters.ajax = true;
		}

		// content
		if(options.htmlContent != null) 
		{
			// store contents directly
			hoverBox.setContent(options.htmlContent);

		} 
		else if (options.url != null) 
		{
			// get ajax url
			new Ajax.Updater ('hoverBox_inner', options.url, 
				{ 
					parameters: options.parameters,
					evalScripts: true
				 });

			hoverBox.setContent(AJAX_showLoading('hoverBox_inner', true));
		} 
		else if (options.iframe != null) 
		{
			hoverBox.setContent("<iframe width=670 height=400 src='" + options.iframe + "' frameborder=0 marginwidth=0 marginheight=0></iframe><br><br>");
		} 
		else 
		{
			hoverBox.setContent("No data.");
		}

		// Add onkeydown event
		document.onkeydown = function(event) {
			if(window.event) {
				var kCode = window.event.keyCode;
			} else {
				var kCode = event.keyCode;
			}

			if(kCode == 13) {
				// enter?
			} else if(kCode == 27) {
				hoverBox.disable();
			}
		};
	},

	setContent: function(content) {
		$('hoverBox_footer_extra').innerHTML = '';
		$('hoverBox_inner').innerHTML = content;

		hoverBox.footerTimer = setTimeout("$('hoverBox_footer').style.width = $('hoverBox_inner_wrapper').getWidth();", 500);
	},

	disable: function() {
		$('dimmer').hide();
		$('hoverBox_inner').innerHTML = "";
		$('hoverBox_footer_extra').innerHTML = '';
		$('hoverBox').hide();

		if(hoverBox.onCloseScrollTo) {
			window.scrollTo(0, hoverBox.onCloseScrollTo.top);
			hoverBox.onCloseScrollTo = null;
		}

		clearTimeout(hoverBox.footerTimer);
	},

	dummy: function() {
	}
}

function listingElementClickable (name, clickable) {
	var elements = document.getElementsByName(name);

	for(var i=0; i<elements.length; i++) {
		elements[i].disabled = clickable ? false : true;
	}
}

medget_links_hide_timeout = [];
/**
 *	Medget onmouseover event
 *
 */
function medgetHover( mid ) {
	if ( medget_links_hide_timeout != null ) {
		clearTimeout( medget_links_hide_timeout[mid] );
	}
	if($('medget_' + mid + '_link_1') != null) {
		$('medget_' + mid + '_link_1').show();
	}
	if($('medget_' + mid + '_link_2') != null) {
		$('medget_' + mid + '_link_2').show();
	}
}

/**
 *	Medget onmouseout event
 *
 */
function medgetHoverOff( mid, timeout_triggered ) {
	if ( typeof( timeout_triggered ) == "undefined" || !timeout_triggered ) {
		medget_links_hide_timeout[mid] = setTimeout( function() { medgetHoverOff( mid, true ); }, 250 );
		return;
	}
	if($('medget_' + mid + '_link_1') != null) {
		$('medget_' + mid + '_link_1').hide();
	}
	if($('medget_' + mid + '_link_2') != null) {
		$('medget_' + mid + '_link_2').hide();
	}
	//$('medget_' + mid + '_link_3').hide();
}

function postMediListing_newForm (id, req1url, req2url)
{
	// fetch params first
	var params = $('form_' + id).serialize();

	// then, disable box + show ajax wait
	hoverBox.disable(); 
	AJAX_showLoading(id + '_ownListing'); 

	// post form
	new Ajax.Request(req1url, 
		{
			method: 'post',
			parameters: params,
			onComplete: function(t) {
				// on complete reload list
				new Ajax.Updater(id + '_ownListing', req2url);
			}
		});
}

helpBox = {
	counter: 0,

	summon: function (positionId, content)
	{
		var id = "helpBox_temp_" + helpBox.counter;

		var nDIV = document.createElement('div');
		nDIV.className = "helpDiv";

		nDIV.setAttribute("id", id);
		nDIV.style.display = "none";

		nDIV.innerHTML = 
			"<div class=helpDivHeader></div>" +

			"<div class=helpDivMiddle>" +
				"<div style='width:10px;float:right;'><a href='javascript:void(0);' onclick=\"Element.hide('" + id + "');\">" + icon("ni0072-16", "") + "</a></div>" + 
				"<h3>" + lang.get("quickhelp") + "</h3>" + content +
				"<div class=spacer></div>" + 
			"</div>" + 

			"<div class=helpDivFooter></div>";

		$('helpBoxContainer').appendChild(nDIV);

		setTimeout("helpBox.activate('" + positionId + "', '" + id + "');", 500);

		helpBox.counter++;
	},

	activate: function(positionId, id) {
		var hoverHeight = $(id).getHeight();

		var viewPort = $(positionId).viewportOffset();
		var viewPortWidth = $(positionId).getWidth();

		$(id).show();
		$(id).style.top = (viewPort[1] - hoverHeight) + "px";
		$(id).style.left = (viewPort[0] - 55 + (viewPortWidth/2)) + "px";
	}
}

function joinItems(itemList) {
	var str = "";
	for(var i=0;i<itemList.length;i++) {
		str += itemList[i];
	}

	document.write('<a href="mailto:' + str + '">' + str + '</a>');
}

userTabs = {
	tabListing: new Array,

	/**
	 * this adds new tab fold to the array
	 **/
	addTabFold: function(condPre) {
		userTabs.tabListing.push(condPre);
	},

	/**
	 * opens tab and closes all others
	 **/
	tabSetActive: function (condPre, activeTab, url)
	{
		var allTabs = new Array("main", "info", "comments");

		// go thru all the tabs and close them
		for(var a=0;a<userTabs.tabListing.length;a++) {
			for(var i=0;i<allTabs.length;i++) {
				// keep main open for others than the one being opened
				if(allTabs[i] == "main" && userTabs.tabListing[a] != condPre) {
					continue;
				}

				try {
					// close em
					$(userTabs.tabListing[a] + '_' + allTabs[i]).hide();
					$(userTabs.tabListing[a] + '_' + allTabs[i] + "_button").className = "";
				} catch (e) {
				}
			}
		}

		// if active tab not set
		if(activeTab == null) {
			return;
		}

		// tab highligh
		$(condPre + '_' + activeTab + "_button").className = "hig";

		// scroll to new tab
		Effect.ScrollTo(condPre + '_scrollTo', {
			duration: 0.5, 
			afterFinish: function() {
				try {
					Effect.Appear(condPre + '_' + activeTab, { duration: 0.3 });
				} catch (error) {
				}
			}
		});

		// if we're fetching new data by ajax
		if(url != null) {
			AJAX_showLoading(condPre + "_" + activeTab);
			new Ajax.Updater(condPre + "_" + activeTab, url, 
				{
					method:'post', 
					evalScripts: true
				});
		}
	}
}

function showOpener(id) {
	
	if(typeof(curOpenerId) != "undefined") {
		$(curOpenerId).hide();
	}
	
	$(id).show();
	
	curOpenerId = id; 
	
}

opener = {
	curOpen: null,

	show: function(id) {
	
		if(opener.curOpen) {
			try {
				$(opener.curOpen).style.display = "none";
				$(opener.curOpen + "_selector").removeClassName("selected");
			} catch(e) {}
		}

		opener.curOpen = id;
		
		try {
			$(opener.curOpen + "_selector").addClassName("selected");
		} catch(e) {}

		$(id).style.display = "block";
	}
}

/** MEDGETS **/
function ShowInPlaceEdit(medget_id) {
	var input_obj = $(medget_id + '_val_edit');
	$(medget_id + '_val_edit_div').show();
	input_obj.disabled = false;
	input_obj.focus();
	var txt_obj = $(medget_id + '_val_txt');
	txt_obj.hide();

	if(txt_obj.innerHTML != "?") {
		input_obj.value = txt_obj.innerHTML;
	} else {
		input_obj.value = '';
	}
}

function MedgetInPlaceEditKeyDown(event, medget_id) {
	if(typeof(event) == "undefined" || event == null ) {
		return;
	}
	switch(event.keyCode) {
		case 13: // Enter
			// Save value
			MedgetEndInPlaceEdit(medget_id, true);
			break;
		case 27: // Esc
			// Cancel changes
			MedgetEndInPlaceEdit(medget_id, false);
			break;
	}
}

function MedgetEndInPlaceEdit(medget_id, save_changes, doUid) {
	var txt_obj = $( medget_id + '_val_txt' );
	txt_obj.show();
	var edit_obj = $( medget_id + '_val_edit' );
	var edit_obj_div = $( medget_id + '_val_edit_div' );
	edit_obj_div.hide();
	if(edit_obj.disabled) {
		// Input field already processed
		return;
	}
	edit_obj.disabled = true;
	if(edit_obj.blur) {
		edit_obj.blur();
	}
	if(typeof(save_changes) != "undefined" && !save_changes) {
		// Discard changes
		edit_obj.value = txt_obj.innerHTML;
	} else {
		if ( txt_obj.innerHTML == edit_obj.value ) {
			// Not changed
			return;
		}
		var medget_name = $( medget_id + '_whoAmI' ).value;
		if(edit_obj.value == '') {
			new Ajax.Request( '/misc/ajax.php', { 'method': 'post', 'parameters': { 
				'do': 'doDisable', 
				'ajax': 'medget_' + medget_name, 
				'do-uid': doUid
				}, onComplete: function (e) { 
					if(e.responseText == "OK") {
						var medget_obj = $(medget_id);
						txt_obj.innerHTML = '?';
						if(medget_obj && medget_obj.parentNode && medget_obj.parentNode.id == "medgets_set") {
							$('medgets_unset').appendChild(medget_obj);
						}
					}
				} } );
			return;
		}
		// Save changes
		var req = new Ajax.Request( '/misc/ajax.php', { 
			parameters: { 'ajax': 'medget_' + medget_name, 'do': 'saveValue', 'do-value': edit_obj.value },
			evalScripts: true,
			onComplete: function (e) {
				if( new String( e.responseText ).indexOf( 'headError' ) != -1 ) {
					hoverBox.enable( { 'htmlContent': e.responseText } );
				} else {
					txt_obj.innerHTML = '';
					txt_obj.appendChild( document.createTextNode( edit_obj.value ) );
					var medget_obj = $(medget_id);
					if(medget_obj && medget_obj.parentNode && medget_obj.parentNode.id == "medgets_unset") {
						$('medgets_set' ).appendChild( medget_obj );
					}
				}
			} } );
	}
}
