var MainWnd = parent;
var CurrentPageIframeTopOffset = 0;
var IframeObj;
var tempIFrame;
var currentPage;
var replaceAddressFrom = '';
var replaceAddressTo = '';

if (typeof guiRoot == 'undefined')
{
	if (top.guiRoot)
		guiRoot = top.guiRoot;
}

var Browser = Class.create();
Browser.prototype =
{
	version: null,
	safari: null,
	opera: null,
	msie: null,
	mozilla: null,
	chrome: null,
	
	initialize: function()
	{
		var userAgent = navigator.userAgent.toLowerCase();
		this.version = 0
		this.safari = /applewebkit/.test( userAgent );
		this.opera = /opera/.test( userAgent );
		this.msie = /msie/.test( userAgent ) && !/opera/.test( userAgent );
		this.mozilla = /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent );
		this.chrome = /chrome/.test(userAgent);
		
		/**
		* msie = Internet Explorer
		* chrome = Google Chrome
		* firefox = Mozilla Firefox
		* version = Opera, Safari
		*/
		this.version = (userAgent.match( /.+(?:msie|chrome|version|firefox)[\/: ](\d+\.\d+)/i ) || [])[1];
		
		if (!isNaN(this.version))
		{
			this.version = parseFloat(this.version);
		}
	}
};
browser = new Browser();

Event = Object.extend({
	KEY_A: 65,
	KEY_B: 66,
	KEY_C: 67,
	KEY_D: 68,
	KEY_E: 69,
	KEY_F: 70,
	KEY_G: 71,
	KEY_H: 72,
	KEY_I: 73,
	KEY_J: 74,
	KEY_K: 75,
	KEY_L: 76,
	KEY_M: 77,
	KEY_N: 78,
	KEY_O: 79,
	KEY_P: 80,
	KEY_Q: 81,
	KEY_R: 82,
	KEY_S: 83,
	KEY_T: 84,
	KEY_U: 85,
	KEY_V: 86,
	KEY_W: 87,
	KEY_X: 88,
	KEY_Y: 89,
	KEY_Z: 90,
	KEY_E: 69
}, Event);

function toggleEditor()
{
	/**
	* Check if layoutmenuContainer is displaying and act accordingly
	*/
	if ($('layoutmenuContainer').getStyle('display') == 'block')
	{
		// We are now moving to content editor
		$('youAreInEditor').update(Lang.EditorYouAreInContentEditor);
		$('toggleEditor').value = Lang.EditorToggleEditorToLayout;
		$('linksContent').show();
		$('linksLayout').hide();
		getEditorWindow().em.start();
	}
	else
	{
		// We are now moving to layout editor
		layout.initLayoutEditor();
		$('youAreInEditor').update(Lang.EditorYouAreInLayoutEditor);
		$('toggleEditor').value = Lang.EditorToggleEditorToContent;
		$('linksContent').hide();
		$('linksLayout').show();
		getEditorWindow().em.stop();
	}
	
	$('layoutmenuContainer').toggle();
	ResizeCurrentPageIframe();
}

/**
*    Resize current_page iFrame to match clients browser window inner height
*/
function ResizeCurrentPageIframe()
{
	var cssEditorWidth = $('layoutmenuContainer').getStyle('display') == 'block' ? $('layoutmenuContainer').getWidth() : 0;
	$('currentPageIframeHolder').setStyle({
		width: document.viewport.getWidth() - cssEditorWidth + 'px',
		height: document.viewport.getHeight() - $('aava_bars').getHeight() + 'px'
	});
	
	$('loading_bar').setStyle({
		width: document.viewport.getWidth() - cssEditorWidth + 'px',
		height: document.viewport.getHeight() - $('aava_bars').getHeight() + 'px'
	});
	
	$('layoutmenuContainer').setStyle({
		height: document.viewport.getHeight() - $('aava_bars').getHeight() - 5 + 'px',
		bottom: 0 + 'px'
	});
	
	if ($('layoutEditorDisabler'))
	{
		$('layoutEditorDisabler').setStyle({
			height: document.viewport.getHeight() - $('aava_bars').getHeight() + 'px'
			,top: $('layoutmenuContainer').cumulativeOffset().top + 'px'
		})
	}
}

// Change page in dropdown menu to match current page
function updatePageSelection()
{
	try
	{
		for (var i = 0; i < $('pageSelect').options.length; i++)
		{
			$('pageSelect').options[i].selected = false;
			
			if ($('pageSelect').options[i].getAttribute('pageid') == window.PageId)
			{
				$('pageSelect').options[i].selected = true;
			}
		}
	}
	catch (Exception)
	{
		/*alert(Exception);*/
	}
}

function AddNewElement()
{
	var win = getEditorWindow();
	win.em.showAddNewElement();
}

/**
*    Scroll current_page iFrame same place before refresh
*/
function CheckCurrentPageIframeTopOffset()
{
	if (CurrentPageIframeTopOffset > 0)
	{
		this.CurrentPage = window.CurrentPage;
		this.CurrentPage.scrollTo(0, CurrentPageIframeTopOffset);
		CurrentPageIframeTopOffset = 0;
	}
}

/**
Get preview url
*/
function getPreviewUrl()
{
	var str = $('address_container').lastChild.href;
	var reStr = new RegExp("https://");
	return str.replace(reStr, 'http://');
}

function refreshContents()
{
	var win = getEditorWindow();
	win.location.reload();
}

/**
Returns the window on which the site contents is currently viewing.
With this function you do not need to worry if user is editing css or
contents.
*/
function getEditorWindow()
{
	var elem;

	if (document.frames)
	{
		if (document.frames['current_page_iframe'].document.frames['viewWindow'])
			elem = document.frames['current_page_iframe'].document.frames['viewWindow'].window;
		else
			elem = document.frames['current_page_iframe'].window;
	}
	else
	{
		if ($('current_page_iframe').contentDocument.getElementById('viewWindow'))
			elem = $('current_page_iframe').contentDocument.getElementById('viewWindow').contentWindow;
		else
			elem = $('current_page_iframe').contentWindow;
	}

	return elem;
}

function getEditorDocument()
{
	var elem;
	var wnd = getEditorWindow();

	if (document.frames)
	{
		if (document.frames['current_page_iframe'].document.frames['viewWindow'])
			elem = document.frames['current_page_iframe'].document.frames['viewWindow'].document;
		else
			elem = document.frames['current_page_iframe'].document;
	}
	else
	{
		if ($('current_page_iframe').contentDocument.getElementById('viewWindow'))
			elem = $('current_page_iframe').contentDocument.getElementById('viewWindow').contentDocument;
		else
			elem = $('current_page_iframe').contentDocument;
	}

	return elem;
}

function showHelp(anchor)
{
	helpWindow = OpenWindow('helpWindow', '/aava/help/help.php#' + anchor, 600, 600);
	helpWindow.focus();
}

/**
* Update help text on Quick Help Bar
*
* @param string HelpText New help text to show
*/
function ShowQuickHelp(HelpText)
{
	return;
	/*if ($('helptext'))
	{
		$('helptext').innerHTML = HelpText;
		return;
	}
	else if (MainWnd.$('helptext'))
	{
		elem = MainWnd.$('helptext').innerHTML = HelpText;
	}*/
}

/**
Sets $([elemId]).style.display to 'block' or 'none'
*/
function ShowHideElem(elemId)
{
	elem = $(elemId);
	style = $(elemId).style;

	if (style.display == 'none' || elem.offsetHeight == 0)
		$(elemId).style.display = 'block';
	else
		$(elemId).style.display = 'none';
}

function openModulesEditor()
{
	modulesWindow = OpenWindow('modulesWindow', '/aava/modulewindow/', 980, 680);
}

function UpdateElementHtml(ElementId)
{
	var element = $(getEditorWindow().document.getElementById('ElementHolder' + ElementId));
	
	if (element != null)
	{
		window.loader.show();

		sajax_remote_uri = guiRoot + 'ajax/main.php';
		CallPhpFunction(
			'GetElementHtml',
			ElementId,
			function()
			{
				element.replace(arguments[0]);
				getEditorWindow().em.initAavaDrag();
				window.loader.hide();
			}
			);
	}
	else
	{
		RefreshCurrentPage();
	}
}

function urlencode(String)
{
	String = escape(String);
	String = String.replace(/\+/g, '%2B');
	String = String.replace(/%20/g, '+');
	String = String.replace(/\*/g, '%2A');
	String = String.replace(/\//g, '%2F');
	String = String.replace(/@/g, '%40');
	return String;
}

function urldecode(String)
{
	String = String.replace(/\+/g, ' ');
	String = unescape(String);
	return String;
}

/**
*
*  UTF-8 data encode / decode
*  http://www.webtoolkit.info/
*
**/

var Utf8 =
{

	// public method for url encoding
	encode: function(string)
	{
		string = string.replace(/\r\n/g, "\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++)
		{

			var c = string.charCodeAt(n);

			if (c < 128)
			{
				utftext += String.fromCharCode(c);
			}
			else if ((c > 127) && (c < 2048))
			{
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else
			{
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}

		return utftext;
	},

	// public method for url decoding
	decode: function(utftext)
	{
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while (i < utftext.length)
		{

			c = utftext.charCodeAt(i);

			if (c < 128)
			{
				string += String.fromCharCode(c);
				i++;
			}
			else if ((c > 191) && (c < 224))
			{
				c2 = utftext.charCodeAt(i + 1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else
			{
				c2 = utftext.charCodeAt(i + 1);
				c3 = utftext.charCodeAt(i + 2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}

		return string;
	}
}

function DeleteElement(Id, PageId, Place, Type, ElementId)
{
	window.aavaWindow.topic = 'Varmistus';
	window.aavaWindow.setText("Haluatko varmasti poistaa tämän elementin?");
	window.aavaWindow.buttons = new Array(
		new Array('Kyllä', "window.loader.show(); DoDeleteModule("+Id+","+PageId+",'"+Place+"','"+Type+"',"+ElementId+");"),
		new Array('Ei', '')
	);
	window.aavaWindow.create();
}

function DoDeleteModule(Id, PageId, Place, Type, ElementId)
{
	// *** Array to send to php function
	var Properties = new Object();
	// *** Populate array
	Properties['PageId'] = escape(PageId);
	Properties['Id'] = escape(Id);
	Properties['Place'] = escape(Place);
	Properties['Type'] = escape(Type);
	// *** Execute php function
	sajax_remote_uri = guiRoot + 'main.php';
	CallPhpFunction('DeleteModule', escape(JSON.stringify(Properties)),
		function()
		{
			window.loader.hide();
			$(getEditorDocument().getElementById('ElementHolder' + ElementId)).remove();
		}
	);
}

function EditElementSettings(elementId)
{
	window.loader.show();
	sajax_remote_uri = guiRoot + 'ajax/modulesettings.php';
	CallPhpFunction('GetElementSettings', elementId,
		function(contentHtml)
		{
			if (contentHtml == false)
			{
				window.aavaWindow.topic = Lang.TopicError;
				window.aavaWindow.setContent('Loading element content failed!');
				window.aavaWindow.buttons = new Array(
					new Element('input', {'type':'button', 'value':Lang.ButtonsOk}).observe('click', function()
					{
						window.aavaWindow.close();
					}.bind(this))
				);
				window.aavaWindow.create();
				window.loader.hide();
				return false;
			}
			
			window.aavaWindow.topic = Lang.ElementManagerElementEditorTopic;
			window.aavaWindow.setContent(contentHtml);
			window.aavaWindow.buttons = new Array(
				new Element('input', {'type':'button', 'value':Lang.ButtonsCancel}).observe('click', function()
				{
					window.aavaWindow.close();
				}),
				new Element('input', {'type':'button', 'value':Lang.ButtonsSave}).observe('click',
					function()
					{
						window.loader.show();
						
						var TimingStart = "";
						var TimingEnd = "";

						if ($('elementUseTimingTrue').checked)
						{
							TimingStart = $('elementDateStart').value + ' '
								+ $('elementTimeStartHour').value + ':'
								+ $('elementTimeStartMinute').value;
							TimingEnd = $('elementDateEnd').value + ' '
								+ $('elementTimeEndHour').value + ':' + $('elementTimeEndMinute').value;
						}

						sajax_remote_uri = guiRoot + 'ajax/modulesettings.php';
						CallPhpFunction('SaveElementSettings', $('elementId').value,
							$('elementPublishTrue').checked ? '1' : '0',
							$('elementShowTopicTrue').checked ? '1' : '0',
							$('elementTopic').value /* Result of replace */,
							$('elementUseTimingTrue').checked ? '1' : '0', TimingStart, TimingEnd,
							$('elementShowModuleDivTrue').checked ? '1' : '0', 
							function(res)
							{
								window.loader.hide();
								
								if (res == '')
								{
									UpdateElementHtml(elementId);
								}
								else
								{									
									window.aavaWindow.topic = Lang.TopicError;
									window.aavaWindow.setContent(Lang.CommonSaveFail + ': ' + res);
									window.aavaWindow.buttons = new Array(
										new Element('input', {'type':'button', 'value':Lang.ButtonsOk}).observe('click', function()
										{
											window.aavaWindow.close();
										}.bind(this))
									);
									window.aavaWindow.create();
								}
							}
						);
							
						window.aavaWindow.close();
					}
				)
			);
			window.aavaWindow.create();
			window.loader.hide();
		}
	);
}

/*
*   float div
*
*/

function startFloatLayer(forceNewHeigth)
{
	if (!$('rightHolder'))
		return false;

	//alert($('leftHolder').getStyle('height') +'|'+ $('rightHolder').getStyle('height'));
	if (parseInt($('leftHolder').getStyle('height')) > parseInt($('rightHolder').getStyle('height'))
		|| forceNewHeigth == true)
	{
		$('rightHolder').setStyle(
		{
			height: $('leftHolder').getStyle('height')
		});

		$('propertiesBox').setStyle(
		{
			position: 'absolute',
			top: '0px',
			left: '0px'
		});

		if (forceNewHeigth == false)
		{
			DivHeight = parseInt($('propertiesBox').getStyle('height'));
			DivTop = FindElementYPosition($('propertiesBox'));
			setInterval("actFloatLayer(600, " + DivTop + ", " + DivHeight + ")", 10);
		}
	}
}

function actFloatLayer(slideTime, LayerTop, LayerHeight)
{
	find = document.viewport.getHeight();
	current = parseInt($('propertiesBox').getStyle('top'));
    /*
    if (browser.isOpera == true)
        current += 30;
    */
	position = document.viewport.getScrollOffsets();
	LayerHeight = parseInt($('propertiesBox').getStyle('height'));

	if ((current + parseInt($('propertiesBox').getStyle('height')))
		< parseInt($('rightHolder').getStyle('height')))
	{
		scrollAt = position.top + 30;
	}
	else
	{
		scrollAt = position.top + parseInt($('propertiesBox').getStyle('height')) + 30;
	}

	if (isNaN(Math.log(scrollAt -= LayerTop)))
	{
		scrollAt = 0;
	}
	newTarget = scrollAt;

	if (find < LayerHeight)
	{
		do_this = false;

		if (scrollAt - (LayerHeight - find) > current)
		{
			newTarget -= (LayerHeight - find);
			do_this = true;
		}
		else if (scrollAt < current)
		{
			do_this = true;
		}
	}
	else
	{
		do_this = true;
	}

	if (current != newTarget && do_this == true)
	{
		if (newTarget != this.target)
		{
			target = newTarget;
			now = new Date();
			Mul = target - current; //
			Wave = Math.PI / (2 * slideTime);
			Pass = now.getTime();

			if (Math.abs(Mul) > find)
			{
				Dis = (Mul > 0) ? target - find : target + find;
				Mul = (Mul > 0) ? find : -find;
			}
			else
			{
				Dis = current
			}
		}
		now = new Date();
		newPosition = Mul * Math.sin(Wave * (now.getTime() - Pass)) + Dis;
		newPosition = Math.round(newPosition);

		if (newPosition < (parseInt($('rightHolder').getStyle('height')) - LayerHeight))
		{
			if ((Mul > 0 && newPosition > current) || (Mul < 0 && newPosition < current))
			{
				$('propertiesBox').setStyle(
				{
					top: newPosition + 'px'
				})
			}
		}
	}
}

function f_clientWidth()
{
	return f_filterResults(window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0, document.body ? document.body.clientWidth : 0);
}

function f_clientHeight()
{
	return f_filterResults(window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0, document.body ? document.body.clientHeight : 0);
}

function f_scrollLeft()
{
	return f_filterResults(window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0, document.body ? document.body.scrollLeft : 0);
}

function f_scrollTop()
{
	return f_filterResults(window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0, document.body ? document.body.scrollTop : 0);
}

function f_filterResults(n_win, n_docel, n_body)
{
	var n_result = n_win ? n_win : 0;

	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function setCookie(name, value, expires, path, domain, secure)
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if (expires)
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date(today.getTime() + (expires));

	document.cookie = name + "=" + escape(value) + ((expires) ? ";expires=" + expires_date.toGMTString() : "")
		+ ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : "");
}

function getCookie(check_name)
{
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split(';');
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for (i = 0; i < a_all_cookies.length; i++)
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split('=');

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if (cookie_name == check_name)
		{
			b_cookie_found = true;

			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if (a_temp_cookie.length > 1)
			{
				cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}

	if (!b_cookie_found)
	{
		return null;
	}
}

function deleteCookie(name, path, domain)
{
	if (Get_Cookie(name))
		document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

/**
This function is to keep session alive
*/
function Keepalive()
{
	sajax_remote_uri = '/aava/ajax/main.php';
	CallPhpFunction('Keepalive', function() { return true });
}

function ReloadAddressBar(currentPageId)
{
	if (typeof(currentPageId) == 'undefined')
		currentPageId = PageId;
		
	sajax_remote_uri = guiRoot + 'ajax/main.php';
	CallPhpFunction('ReloadAddressBar', currentPageId,
		function(options)
		{
			$('pageSelect').update(options);
		}
	);
}

var InfoBubble = Class.create();
InfoBubble.prototype =
{
	bubble: null,
	bubbleOrigWidth: null,
	arrow: null,
	text: 'Info text',
	
	initialize: function(newText)
	{
		this.text = newText;
		//this.createBubble();
	},
	
	createBubble: function()
	{
		/**
		* Create the two elements and hide them - even they are not part of DOM yet
		*/
		this.bubble = new Element('div', {'class':'InfoBubble'}).update(this.text);
		this.arrow = new Element('div', {'class':'InfoBubble Arrow'});
		this.bubble.hide();
		this.arrow.hide();
	},
	
	/**
	* This function can be called with
	* show(Event event) or show(bool scrolling, Event event)
	*/
	show: function()
	{
		var scrolling = false;
		var event = null;
		
		if (arguments.length == 1)
			event = arguments[0];
		else
		{
			scrolling = arguments[0];
			event = arguments[1];
		}
		
		$$('.InfoBubble').each(function(element)
		{
			element.remove();
		});
		
		this.createBubble();
		var element = Event.element(event);
		
		Element.insert(document.body, this.bubble);
		Element.insert(document.body, this.arrow);
		
		/*
		Find out bubble's original width, so
		we can move it around if it's too close to
		right edge of the window
		*/
		if (this.bubbleOrigWidth == null)
			this.bubbleOrigWidth = this.bubble.getWidth() - parseInt(this.bubble.getStyle('paddingLeft')) - parseInt(this.bubble.getStyle('paddingRight'));
		
		if (this.bubbleOrigWidth > document.viewport.getWidth() - 40)
		{
			this.bubbleOrigWidth = document.viewport.getWidth() - 40;
		}
		
		this.bubble.setStyle({width:this.bubbleOrigWidth+'px'});
		
		this.arrow.show();
		this.bubble.show();
		
		// Position arrow
		this.arrow.setStyle({
			top: element.cumulativeOffset().top - (scrolling ? element.cumulativeScrollOffset().top : 0) - this.arrow.getHeight() - 5 + 'px',
			left: element.cumulativeOffset().left + (element.getWidth() / 2 - this.arrow.getWidth() / 2) + 'px'
		});
		
		// Find out if bubble is too close to the right edge
		var bubbleLeft = this.arrow.cumulativeOffset().left - 20;
		if (bubbleLeft + 20 + this.bubbleOrigWidth - cf.scrollLeft() > cf.clientWidth())
			bubbleLeft = cf.clientWidth() + cf.scrollLeft() - this.bubbleOrigWidth - 20;
		
		// Find out if bubble is too close to the left edge
		if (bubbleLeft < 2)
			bubbleLeft = 2;
		
		// Find out if bubble is too close to the top edge
		var bubbleTop = this.arrow.cumulativeOffset().top - this.bubble.getHeight() + 2;
		
		if (bubbleTop <= 10)
		{
			this.arrow.setStyle({
				top: element.cumulativeOffset().top + element.getHeight() + 5 + 'px'
			});
			this.arrow.addClassName('Up');
			
			bubbleTop = this.arrow.cumulativeOffset().top + this.arrow.getHeight() - 2;
		}
		
		// Position bubble
		this.bubble.setStyle({
			top: bubbleTop + 'px',
			left: bubbleLeft + 'px',
			width: this.bubbleOrigWidth + 'px'
		});
		
		/**
		* Fade bubble and arrow in
		*/
		/*var fade = new fx.Opacity(this.bubble, {duration: 200});
		fade.hide();
		fade.custom(0, 1);
		
		var fade = new fx.Opacity(this.arrow, {duration: 200});
		fade.hide();
		fade.custom(0, 1);*/
		
		this.bubble.show();
		this.arrow.show();
		
		this.timeout = setTimeout(this.hide.bind(this), 10000);
	},
	
	hide: function()
	{
		clearTimeout(this.timeout);
		this.timeout = null;
		
		try
		{
			$(this.bubble).remove();
			$(this.arrow).remove();
			
			$$('.InfoBubble').each(function(element)
			{
				element.remove();
			});
		}
		catch (Exception)
		{
			//alert(Exception);
		}
	}
}

function initInfoBubbles()
{
	$$('img').each(function(element)
	{
		if (element.getAttribute('help') == '1')
		{
			var ib = new InfoBubble(element.getAttribute('title'));
			element.observe('mouseover', ib.show.curry(element.hasAttribute('scrolling')).bind(ib));
			element.observe('mouseout', ib.hide.bind(ib));
			element.setAttribute('help', '0');
			element.setAttribute('title', '');
			element.setAttribute('alt', '');
			element.setAttribute('align','absmiddle');
		}
	});
}

var CommonFunctionsClass = Class.create();
CommonFunctionsClass.prototype = 
{
	xMousePos: null,
	yMousePos: null,
	xMousePosMax: null,
	yMousePosMax: null,
	counter: 0,
	
	initialize: function()
	{
		
	}
	
	,checkForInt: function(event)
	{
		var e = window.event ? window.event : event;
		var charCode = e.keyCode ? e.keyCode : e.which;
		
		if (charCode > 31 && (charCode < 48 || charCode > 57))
			return false;

		return true;
	}
	
	,checkForUrlChars: function(event)
	{
		var e = window.event ? window.event : event;
		var charCode = e.keyCode ? e.keyCode : e.which;
		
		switch (charCode)
		{
			case Event.KEY_LEFT:
			case Event.KEY_RIGHT:
			case Event.KEY_DELETE:
			case Event.KEY_BACKSPACE:
			case Event.KEY_RETURN:
			case Event.KEY_HOME:
			case Event.KEY_END:
			case Event.KEY_TAB:
				return true;
		}
		
		if (String.fromCharCode(charCode).match(/[^a-z0-9_\-]/i))
			return false;
		
		/**
		* Try to lowercase the inserdet char.
		* I think it only works in IE.
		*/
		try
		{
			if (65 <= charCode && charCode <= 90)
			{
				charCode += 32;
				
				if (e.charCode)
					e.charCode = charCode;
				if (e.keyCode)
					e.keyCode = charCode;
				else
					e.which = charCode;
			}
		}
		catch (Exception)
		{
			//alert(Exception);
		}

		return true;
	}

	,clientWidth: function()
	{
		return this.filterResults(window.innerWidth ? window.innerWidth : 0,
			document.documentElement ? document.documentElement.clientWidth : 0, document.body ? document.body.clientWidth : 0);
	},

	clientHeight: function()
	{
		return this.filterResults(window.innerHeight ? window.innerHeight : 0,
			document.documentElement ? document.documentElement.clientHeight : 0, document.body ? document.body.clientHeight : 0);
	},

	scrollLeft: function()
	{
		return this.filterResults(window.pageXOffset ? window.pageXOffset : 0,
			document.documentElement ? document.documentElement.scrollLeft : 0, document.body ? document.body.scrollLeft : 0);
	},

	scrollTop: function()
	{
		return this.filterResults(window.pageYOffset ? window.pageYOffset : 0,
			document.documentElement ? document.documentElement.scrollTop : 0, document.body ? document.body.scrollTop : 0);
	},
	
	scrollWidth: function()
	{
	   var w = window.scrollWidth ||
	           document.body.scrollWidth ||
	           document.documentElement.scrollWidth;
	           
	   return w ? w : 0;
	},

	scrollHeight: function()
	{
	   var h = window.scrollHeight ||
	           document.body.scrollHeight ||
	           document.documentElement.scrollHeight;
	           
	   return h ? h : 0;
	},
	
	getDocumentHeight: function() { // missing from prototype?
		var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
		return Math.max(scrollHeight, document.viewport.getHeight());
	},

	getDocumentWidth: function() { // missing from prototype?
		var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
		return Math.max(scrollWidth, document.viewport.getWidth());
	},

	setOpacity: function(elem, opacity)
	{
		elem.style.opacity = (opacity / 100);
	    elem.style.MozOpacity = (opacity / 100);
	    elem.style.KhtmlOpacity = (opacity / 100);
	    elem.style.filter = "alpha(opacity=" + opacity + ")";

		return elem;
	},

	filterResults: function(n_win, n_docel, n_body)
	{
		var n_result = n_win ? n_win : 0;

		if (n_docel && (!n_result || (n_result > n_docel)))
			n_result = n_docel;
		return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
	},

	hasScrollBar: function(obj)
	{
		if (obj.scrollTop > 0)
			return true;

		obj.scrollTop = 1;

		return (obj.scrollTop > 0);
	},
	
	htmlEntities: function(str)
	{
		var htmlEntitiesString = '';
		
		for (i = 0; i < str.length; i++)
		{
			if(str.charCodeAt(i)>127)
			{
				htmlEntitiesString += '&#' + str.charCodeAt(i) + ';';
			}
			else
			{
				htmlEntitiesString += str.charAt(i);
			}
		}
		
		return htmlEntitiesString;
	},

	stopBubble : function(e)
	{
		e.cancelBubble = true; // IE
		e.returnValue = false; // IE
		if (e.stopPropagation) e.stopPropagation();
	  	if (e.preventDefault) e.preventDefault();
	},

	captureMousePosition: function(event)
	{
		var e = event ? event : window.event;

	    if (e.pageX)
	    {
	        CommonFunctions.xMousePos = e.pageX;
	        CommonFunctions.yMousePos = e.pageY;
	        CommonFunctions.xMousePosMax = window.innerWidth + window.pageXOffset;
	        CommonFunctions.yMousePosMax = window.innerHeight + window.pageYOffset;
	    }
	    else if (e.clientX)
	    {
			CommonFunctions.xMousePos = e.clientX;
	        CommonFunctions.yMousePos = e.clientY;
	        //CommonFunctions.xMousePosMax = window.innerWidth+window.pageXOffset;
	        //CommonFunctions.yMousePosMax = window.innerHeight+window.pageYOffset;
	    }
	},

	getMousePosition: function()
	{
		return {x: CommonFunctions.xMousePos, y: CommonFunctions.yMousePos};
	},

	replaceAjaxHash: function(hash, elementNumber, newElementHash)
	{
		if (typeof elementNumber == 'undefined')
			return false;

		var re = new RegExp('\\?' + elementNumber + '=[^\\?]*\\??');

		if (hash.match(re))
			var newHash = hash.replace(re, '?' + elementNumber + '=' + newElementHash);
		else
			var newHash = hash + '?' + elementNumber + '=' + newElementHash;

		return newHash;
	},

	getTarget: function(event)
	{
		var e = event ? event : window.event;
		var target;

		if (e.target)
		{
			target = e.target;
		}
		else if (e.srcElement)
		{
			target = e.srcElement;
		}

		// To defeat Safari bug
		if (target.nodeType == 3)
		{
			target = target.parentNode;
		}

		return target;
	},
	
	getHighestZindex : function()
	{
		var highestZindex = 0;
		$$('*').each(
			function(element, i)
			{
				if (element.getStyle('zIndex') > highestZindex)
					highestZindex = parseInt(element.getStyle('zIndex'));
			}
		);
		
		return highestZindex;
	}
};

var CommonFunctions = cf = new CommonFunctionsClass();
var ModuleHash = '';

var EmaModuleInterface = Class.create();
EmaModuleInterface.prototype = 
{
	initialize: function(){}
	
	,moduleId: 'NotDefined'
	,moduleName: 'not defined'
	
	,initNewElement: function(elementManager)
	{
		elementManager.addNewElement.bind(elementManager).delay(0.5);
	}
	
	,createElement: function(elementManager)
	{
		top.loader.show();
		var self = this;
    	sajax_remote_uri = '/aava/ajax/main.php';
		CallPhpFunction('CreateElement',
			elementManager.newElementOptions.module.className,
			elementManager.pageId,
			elementManager.newElementOptions.contentType,
			elementManager.newElementOptions.position,
			elementManager.newElementOptions.place,
			elementManager.newElementOptions.orderAfter,
			Object.toJSON(elementManager.newElementOptions.extraOptions),
			function()
			{
				elementManager.elementCreated(arguments[0].evalJSON());
			}
		);
	}
	
	,deleteElement: function(elementManager)
	{
		top.loader.show();
		sajax_remote_uri = '/aava/ajax/main.php';
		
		CallPhpFunction(
			'DeleteElement',
			elementManager.dropElement.options.className,
			elementManager.dropElement.options.eid,
			elementManager.dropElement.options.cid,
			function()
			{
				top.loader.hide();
				elementManager.removeElement(elementManager.dropElement);
			}
		);
	}
	
	/**
	* This function is called right after element is inserted to page.
	* By default this does nothing.
	*/
	,afterInsert: function(cid, eid)
	{
	}
	
	,edit: function(cid, eid)
	{
		//alert('Called edit() which is not implemented on this module.');
	}
	
	,getDeleteButton: function(elementManager)
	{
		// Button: delete
		var self = this;
		var button = new Element('img', {src: '/aava/img/icons/delete.png'});
		var ib = new elementManager.InfoBubble(Lang.ElementManagerElementDelete);
		button.observe('mouseover', ib.show.bind(ib));
		button.observe('mouseout', ib.hide.bind(ib));
		button.setStyle({float:'left'});
		button.observe('mousedown', function()
		{
			top.aavaWindow.topic = Lang.TopicConfirm;
			top.aavaWindow.setContent(Lang.CommonConfirmDelete);
			top.aavaWindow.buttons = new Array(
				new Element('input', {'type':'button', 'value':Lang.ButtonsYes}).observe('click', function()
				{
					top.aavaWindow.close();
					self.deleteElement(elementManager);
				}.bind(this)),
				new Element('input', {'type':'button', 'value':Lang.ButtonsNo}).observe('click', function()
				{
					top.aavaWindow.close();
				}.bind(this))
			);
			top.aavaWindow.create();
		});
		
		return button;
	}
	
	,getActionButtons: function(elementManager)
	{
		return [];
	}
}
