var MainWnd = parent;
var text_showhidequickhelp_show = 'Näytä ohje';
var text_showhidequickhelp_hide = 'Piilota ohje';

var browser = new GetClientBrowser();
var resizeTriggerEnabled = false;
var CurrentPageIframeTopOffset = 0;
var IframeObj;
var tempIFrame;
var currentPage;
var replaceAddressFrom = '';
var replaceAddressTo = '';

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

/**
*   Function to include js files
*/
function IncludeJavaScript(JavascriptFile)
{
	document.write('<script type="text/javascript" src="' + JavascriptFile + '"></scr' + 'ipt>');
}

var BrowserDetect =
{
	init: function()
	{
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function(data)
	{
		for (var i = 0; i < data.length; i++)
		{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;

			if (dataString)
			{
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function(dataString)
	{
		var index = dataString.indexOf(this.versionSearchString);

		if (index == -1)
			return;

		return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
	},
	dataBrowser:
	[
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{
			string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{ // for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ // for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS:
	[
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
};
BrowserDetect.init();

/**
*    Gets clients browser
*/
function GetClientBrowser()
{
	var i;
	this.isIE = false;
	this.isMozilla = false;
	this.isOpera = false;
	this.b_version = navigator.appVersion;
	this.version = parseFloat(navigator.appVersion);

	// Internet explorer
	if ((i = navigator.userAgent.indexOf("MSIE")) >= 0)
	{
		this.BrowserName = "MSIE";
		this.isIE = true;
		return;
	}

	// Gecko / Mozilla
	if ((navigator.userAgent.indexOf("Gecko")) >= 0)
	{
		this.BrowserName = "Gecko";
		this.isMozilla = true;
		return;
	}

	// Opera
	if ((navigator.userAgent.indexOf("Opera")) >= 0)
	{
		this.BrowserName = "Opera";
		this.isOpera = true;
		return;
	}
}

/**
*    Resize current_page iFrame to match clients browser window inner height
*/
function ResizeCurrentPageIframe()
{
	if (document.all || document.getElementById)
	{
		var AdminMenuHeight = parseInt(document.getElementById('aava_bars').offsetHeight);

		if (document.getElementById('quickhelp_bar'))
		{
			var QuickHelpHeight = parseInt(document.getElementById('quickhelp_bar').offsetHeight);
		}
		else
		{
			var QuickHelpHeight = 40;
		}
		var CurrentPageIFrame = document.getElementById('current_page_iframe');
		var CurrentPageIFrame = (CurrentPageIFrame.style ? CurrentPageIFrame.style : CurrentPage);
		var WindowHeight = GetBroserWindowHeight();
		var WindowHeight = document.documentElement.clientHeight;
		// *** inner broser window height - admin menu height
		CurrentPageIFrame.height = (WindowHeight - AdminMenuHeight - QuickHelpHeight) + 'px';

		// *** Attach this function to resize event
		if (resizeTriggerEnabled == false)
		{
			if (browser.isIE)
			{
				window.attachEvent('onresize', ResizeCurrentPageIframe);
				resizeTriggerEnabled = true;
			}

			if (browser.isMozilla || browser.isOpera)
			{
				window.addEventListener('resize', ResizeCurrentPageIframe, false);
				resizeTriggerEnabled = true;
			}
		}
	}
}

/**
*    Get client broser window inner height
*/
function GetBroserWindowHeight()
{
	if (document.all || document.getElementById)
	{
		if (browser.isIE)
		{
			this.WindowHeight = parseInt(document.documentElement.scrollHeight);
		}

		if (browser.isMozilla || browser.isOpera)
		{
			this.WindowHeight = parseInt(document.documentElement.clientHeight);
		}
		return this.WindowHeight;
	}
}

/**
*    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 = document.getElementById('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 (browser.isIE)
	{
		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 (document.getElementById('current_page_iframe').contentDocument.getElementById('viewWindow'))
			elem = document.getElementById('current_page_iframe').contentDocument.getElementById('viewWindow').contentWindow;
		else
			elem = document.getElementById('current_page_iframe').contentWindow;
	}

	return elem;
}

function AddressBarOpenPage(newLink)
{
	// Let's set global var currentAddress to whatever newLink is,
	// so we're able to keep user on the same page all the time
	currentPage = newLink;

	// If user is editing css, we don't wanna throw him/her
	// out of there, so we need to know if the css editor's
	// frameset is there
	var elem = getEditorWindow();

	// Now we know which element to update, so let's Just Do It
	elem.location.href = newLink;
	ChangeAddressBarLink(newLink);
}

/**
Changes the text on address bar of Aava
*/
function ChangeAddressBarLink(newLink)
{
	var ProtocolFrom = replaceAddressFrom.match(/^(http:\/\/|https:\/\/)/)[1];
	var ProtocolTo = replaceAddressTo.match(/^(http:\/\/|https:\/\/)/)[1];

	var link = newLink.replace(replaceAddressFrom, '');
	var str = '';
	var FullStr = ProtocolTo;
	var PrevLink = '';

	// currentPage is a global variable
	currentPage = newLink;

	FullStr = '<a href="' + replaceAddressTo + '" onclick="AddressBarOpenPage(\''
			+ replaceAddressFrom + '\');  return false;">' + replaceAddressTo + '</a>';

	// Loops through every /[part1]/[part2]/ etc...
	while (link.indexOf('/') != -1)
	{
		str = link.substr(0, link.indexOf('/') + 1);
		FullStr =
			FullStr +
			'<a href="' + replaceAddressTo + PrevLink + str + '" onclick="AddressBarOpenPage(\''
			+ replaceAddressFrom + PrevLink + str + '\');  return false;">' + str + '</a>';
		PrevLink = PrevLink + str;
		link = link.substr(str.length);
	}

	// And finally change the text
	document.getElementById('address_container').innerHTML = FullStr;
}

function PageIframeLoaded()
{
	if (MainWnd.document.getElementById('current_page_iframe').contentWindow)
	{
		var tmp = MainWnd.document.getElementById('current_page_iframe').contentWindow.location.href;

		if (tmp.indexOf(replaceAddressFrom) != -1)
			MainWnd.ChangeAddressBarLink(tmp);
	}
	else
	{
		var tmp = MainWnd.document.frames['current_page_iframe'].location.href;

		if (tmp.indexOf(replaceAddressFrom) != -1)
			MainWnd.ChangeAddressBarLink(tmp);
	}

	var tmp = MainWnd.getEditorWindow();
}

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

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

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

function OpenContentEditor(newLink)
{
	var elem;

	if (browser.isIE)
	{
		elem = document.frames['current_page_iframe'].window;
	}
	else
	{
		elem = document.getElementById('current_page_iframe').contentWindow;
	}

	elem.location.href = newLink;
}

function UpdateElementHmtl(ElementId)
{
	var editorWindow = getEditorWindow();
	if (editorWindow.document.getElementById('ElementHolder_' + ElementId))
	{
		window.loader.show();

		sajax_remote_uri = guiRoot + 'ajax/main.php';
		CallPhpFunction(
			'GetElementHtml',
			ElementId,
			new Function("var ew = getEditorWindow(); var e = ew.document.getElementById('ElementHolder_" + ElementId + "'); var ne = ew.document.createElement('DIV'); ne.innerHTML = arguments[0]; e.parentNode.insertBefore(ne.firstChild,e); e.parentNode.removeChild(e); 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 DeleteModuleFromPage(Id, PageId, Place, Type, ElementId)
{
	window.aavaWindow.topic = 'Varmistus';
	window.aavaWindow.text = "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)), new Function("window.loader.hide(); $(getEditorWindow().document.getElementById('ElementHolder_" + ElementId + "')).remove()"));
}

var elementSettingsEditId = null;
function EditElementSettings(elementId)
{
	elementSettingsEditId = elementId;
	sajax_remote_uri = guiRoot + 'ajax/modulesettings.php';
	CallPhpFunction('GetElementSettings', elementId, ShowEditElement);
}

function ShowEditElement(contentHtml)
{
	DivPopup.DisableScreen();
	DivPopup.ShowDivPopup('DivElementSettings', 'Elementin asetukset', contentHtml, 'ElementSettingsOk();',
		'ElementSettingsCancel();', 400, 500);
}

function ElementSettingsOk()
{
	var TimingStart = "";
	var TimingEnd = "";

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

	sajax_remote_uri = guiRoot + 'ajax/modulesettings.php';
	CallPhpFunction('SaveElementSettings', document.getElementById('elementId').value,
		document.getElementById('elementPublishTrue').checked ? '1' : '0',
		document.getElementById('elementShowTopicTrue').checked ? '1' : '0',
		urlencode(document.getElementById('elementTopic').value),
		document.getElementById('elementUseTimingTrue').checked ? '1' : '0', TimingStart, TimingEnd,
		document.getElementById('elementShowModuleDivTrue').checked ? '1' : '0', AfterSaveElementSettings);
}

function AfterSaveElementSettings(res)
{
	if (res == '')
	{
		DivPopup.CloseDivPopup('DivElementSettings');
		DivPopup.EnableScreen();

		//AlertBox = new FadingAlertBox('AlertBox');
		//AlertBox.Create(Lang.TopicSuccess, Lang.CommonSaveOk);

		UpdateElementHmtl(elementSettingsEditId);
	}
	else
	{
		AlertBox = new FadingAlertBox('AlertBox');
		AlertBox.Create(Lang.TopicError, Lang.CommonSaveFail + ': ' + res);
	}
}

function ElementSettingsCancel()
{
	DivPopup.CloseDivPopup('DivElementSettings');
	DivPopup.EnableScreen();
}

/*
*   float div
*
*/

function startFloatLayer(forceNewHeigth)
{
	// disabled in Opera, because some strange bug
	if (browser.isOpera == true)
	{
		//return;
	}

	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 = guiRoot + 'ajax/main.php';
	CallPhpFunction('Keepalive', new Function("return;"));
}

function ReloadAddressBar()
{
	sajax_remote_uri = guiRoot + 'ajax/main.php';
	CallPhpFunction('ReloadAddressBar', ReloadAddressBarContent);
}

function ReloadAddressBarContent(html)
{
	$('pagetree_content').innerHTML = html;
}

function CssEditorDisabled()
{
	alert(Lang.CommonCssEditorDisabled);
}

// Disable CSS Editor when custom html is in use
function DisableCssEditor()
{
	var elements = document.getElementsByName('CssEditorLink');

	for (var i = 0; i < elements.length; i++)
	{
		elements[i].onclick = new Function("CssEditorDisabled(); return false;");
	}
}

// Enable CSS Editor when custom html is not in use
function EnableCssEditor()
{
	var elements = document.getElementsByName('CssEditorLink');

	for (var i = 0; i < elements.length; i++)
	{
		elements[i].onclick = new Function("return true;");
	}
}

var CommonFunctionsClass = Class.create(
{
	xMousePos: null,
	yMousePos: null,
	xMousePosMax: null,
	yMousePosMax: null,
	counter: 0,

	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);
	},

	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);
	},

	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;
	}
}
);

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