function autodisable(element)
{	
	if (element.getAttribute('alreadyClicked') == 1)
	{
		if(element.hasAttribute('href'))
			element.removeAttribute('href');
			
		if(element.hasAttribute('disabled'))
			element.disabled=true;
	}
	else
		element.setAttribute('alreadyClicked', 1);	
}

function addLoadEvent(func) 
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function') 
	{
		window.onload = func;
	} else {
		window.onload = function() 
		{
			oldonload();
			func();
		}
	}
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function breakout_of_frame() {
  if (top.location != location) {
    top.location.href = document.location.href ;
  }
}

function showTT(e, id, src, atImage)
{
	var obj = document.getElementById(src);
	var tt = document.getElementById(id);
	
	var curleft = curtop = 0;
	if(atImage)
	{
		if (obj.offsetParent) {
			curleft = obj.offsetLeft
			curtop = obj.offsetTop
			while (obj = obj.offsetParent) {
				curleft += obj.offsetLeft
				curtop += obj.offsetTop
			}
		}
	}
	else
	{
		var posx = 0;
		var posy = 0;
		if (!e) var e = window.event;
		if (e.pageX || e.pageY) 	{
			posx = e.pageX;
			posy = e.pageY;
		}
		else if (e.clientX || e.clientY) 	{
			posx = e.clientX + document.body.scrollLeft
				+ document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop
				+ document.documentElement.scrollTop;
		}
		
		curleft = posx - 45;
		curtop = posy - 640;	
	}

/*	obj = document.getElementById(src);
	curtop += obj.height;*/
	
	tt.style.left = curleft + "px";
	tt.style.top = curtop + "px";
	tt.style.zIndex = "100";
	tt.style.display = "block";	
}

function showHover(img)
{	
	img.style.opacity='1'; 
	img.style.mozOpacity='1'; 
	img.style.filter='alpha(opacity=100)';			
}

function hideHover(img)
{
	img.style.opacity='0'; 
	img.style.mozOpacity='0'; 
	img.style.filter='alpha(opacity=0)';	
}

function addRecipient(name)
{
	if(document.messageForm.recipient.value.length < 1)
	{
		document.messageForm.recipient.value = name;
	}
	else
	{
		document.messageForm.recipient.value += ',' + name;
	}
}

function bc_sort(listid, bytag)
{
	var taglink = document.getElementById('taglink_' + listid);
	var levellink = document.getElementById('levellink_' + listid);	
	var theList = document.getElementById(listid);
	var theListElements = theList.getElementsByTagName('li'); 
	
	if(bytag)
	{
		if(theListElements.length < 2)
		{
			return true;
		}
		
		for(var n = 1; n < theListElements.length; ++n)
		{
			/* clantag stored in the classname */
			var clantag = theListElements[n].className;

			/* insertionsort */
			for(var i = 0; i < n; ++i)
			{
				var comparetag = theListElements[i].className;
				
				if(clantag < comparetag)
				{
					theList.insertBefore(theListElements[n], theListElements[i]);
					break;
				}
			}
		}
		
		taglink.style.display = 'none';
		levellink.style.display = 'inline';		
	}
	else /* by level */
	{
		if(theListElements.length < 2)
		{
			return true;
		}
		
		for(var n = 1; n < theListElements.length; ++n)
		{
			/* original sorting (by level) stored in the id */			
			var thelevel = theListElements[n].id;
			
			for(var i = 0; i < n; ++i)
			{
				var comparelevel = theListElements[i].id;
				
				if(thelevel < comparelevel)
				{
					theList.insertBefore(theListElements[n], theListElements[i]);
					break;
				}
			}
		}		
		
		levellink.style.display = 'none';
		taglink.style.display = 'inline';		
	}
}

function isChrome()
{
	return navigator.userAgent.toLowerCase().indexOf('chrome') > -1;	
}

function resizeIFrame()
{
	_frame = parent.document.getElementById(window.name);
	_innerDoc = _frame.document;
	
    if (_frame.contentDocument)
    {
        _innerDoc = _frame.contentDocument; // For NS6
    }
    
    if (_frame.contentWindow)
    {
        _innerDoc = _frame.contentWindow.document; // For IE5.5 and IE6       
    }
    
    if(isChrome())
    {
    	_frame.height=1; //force recalculation
    	_frame.style.height="1px";
    }
    		    
    var	newHeight = _innerDoc.body.scrollHeight + (_innerDoc.body.offsetHeight - _innerDoc.body.clientHeight);
    
    _frame.style.height = newHeight + 'px';
    _frame.height = newHeight; 
        
	parent.scroll(0, 200);
}

function prepareLangTip(callerID, generatorId)
{
	$('#'+callerID).hover(
			function() {
					var t = setTimeout(function() {
							$('#'+generatorId).css(
									'left', getLangTipLeft($('#'+callerID), $('#'+generatorId))
								);
							$('#'+generatorId).css(
									'top' ,getLangTipTop($('#'+callerID))
								);			
							$('#'+generatorId).fadeIn(500);
						},
						500
					);
					$(this).data('timeout', t);
				},
			function() {
				    clearTimeout($(this).data('timeout'));
				    $('#'+generatorId).fadeOut(500); 	
				}
		);
}

function getLangTipLeft(caller, toolTip)
{
	left = caller.offset().left+toolTip.width()+10;
	if(left > $('body').width())
		left = $('body').width()-toolTip.width()-10;
	else
		left = caller.offset().left+10;	

	return Math.max(0, left);
}

function getLangTipTop(caller)
{
	return Math.max(0, caller.offset().top + 20);
}


/*
 * Function is called after a click on certain location in the shoutbox,
 * i.e. onclick="loadShoutboxMessageList('~hw/shoutbox/messagelist&st=a')"
 * see ShoutboxView.php for the onclick definitions
 */
var loadShoutboxMessageList = function(url) {

	$.get(url, {}, function(rsp){
//show(rsp);
		// don't know why I have to wrap it but it works
		var jqWrap = $('<div>').append(rsp);
		var jqNewMessageIndicators = jqWrap.find('#newMessageIndicators');

		$('.shoutbox_iframe').contents().find('.shoutbox_messages_table').replaceWith(jqWrap.find('.shoutbox_messages_table'));
		
		processMessageList(jqNewMessageIndicators);
	}, 'html');
}

//last code-snippet of:
//http://www.nczonline.net/blog/2009/09/15/iframes-onload-and-documentdomain/
/*
 * Function is called after a page load in the jQuery.ready handler
 */
var setShoutboxIframeLoadedEvent = function(jqIframe) {
	var iframe = jqIframe.get(0);
	
	if (iframe.attachEvent){
		iframe.attachEvent("onload", function(){
			processMessageList($(iframe).contents().find('#newMessageIndicators'));
		});
	} else {
		iframe.onload = function(){
			processMessageList($(iframe).contents().find('#newMessageIndicators'));
		};
	}
}

/**
 * @see HatFacelift#sprint4#91
 * @date 20101117
 * @author Harrold Korte
 * @arg node is #newMessageIndicators
 * sample structure of this node:
 * <div id='newMessageIndicators'>
 * 		<div channel='a'>true</div>  adds class .shoutbox_newmessage_button to #sbx_ta_b
 * 		<div channel='c'>false</div> removess class .shoutbox_newmessage_button from #sbx_tc_b
 * 		<div channel='t'>false</div> removess class .shoutbox_newmessage_button from #sbx_tt_b
 * </div>
 */
// #5715 20110225 broken countdowns repaired using jquery.countdown
var processMessageList = function(jqIndicators) {
//show(jqIndicators);
	var jqSbx = $('form[name=sb]');
	var jqSbxInput = jqSbx.find('input[type=text]');
	var jqSbxSubmit = jqSbx.find('input[type=submit]');	
	var jqCountdown = jqSbx.find('.countdown');
	jqCountdown.countdown('destroy');
	
	var countdown = parseInt(jqIndicators.attr('countdown'));
	if (countdown > 0) {
		jqSbxSubmit.attr('disabled', 'disabled');
		
		jqCountdown.countdown({
			until: countdown,
			format:"S",
			compact:true,
			onTick: function() {
				var sec = $(this).countdown("getTimes")[6];
				jqSbxSubmit.attr("value", $(document).data("labelSendMessage") + " (" + sec + ")");
			},
			onExpiry: function() {
				jqSbxSubmit.attr("value", $(document).data("labelSendMessage"));
				jqSbxSubmit.removeAttr("disabled");
			}
		});
	}
	else {
		jqSbxSubmit.removeAttr("disabled");
	}

	$(jqIndicators).find('div').each(function(i, elt) {
		var buttonId = '#sbx_t' + $(this).attr('channel') + '_b'; // dependend on button-id naming
		if ($(this).html() === 'true') {
			$(buttonId).addClass('shoutbox_newmessage_button');
			if ($(this).attr('channel') == "a") // bigger picture
				$(buttonId).addClass('a');
		}
		else {
			$(buttonId).removeClass('shoutbox_newmessage_button');
			if ($(this).attr('channel') == "a") // bigger picture
				$(buttonId).removeClass('a');
		}
	});
	
	$('#sbx_ta_b').trigger('test');
}


function show(node) {
	alert($('<div>').append($(node).clone()).remove().html());
}

function isUserActivated(userActivated, translation) {
	if (!userActivated)
		$('#popup_not_activated').trigger('show');
	
	return userActivated;
}

var showPopupNotActivatedOnSubmit = function() {
	$('#popup_not_activated').trigger('show');
	
	return false;
}

//var jqShoutboxTextField = $('.shoutbox_text_field').eq(0);
//jqShoutboxTextField.attr('value', translation);
//jqShoutboxTextField.attr('disabled', 'disabled');

//$('#sb_no_activation_header').show(0);

//$('.feedback').html('<b>' + translation + '</b>');
	
function textLeftCounter(field, countfieldID, maxlimit)
{
	var tmpString = field.value.replace(/(\r\n|\r|\n)/g, '\r\n');
	var tmpLength = tmpString.length;
	
	document.getElementById(countfieldID).innerHTML = maxlimit - tmpLength;
	if(tmpLength > maxlimit)
	{
		document.getElementById(countfieldID).style.color = 'red';
		document.getElementById(countfieldID).style.fontWeight = 'bold';
	}
	else
	{
		document.getElementById(countfieldID).style.color = 'white';
		document.getElementById(countfieldID).style.fontWeight = 'normal';
	}
}

function prepareToolTip(callerID, generatorId)
{	
	$('#'+callerID).hover(function(e){
		$('#'+generatorId).css('left',getToolTipLeft($('#'+callerID), $('#'+generatorId)));
		$('#'+generatorId).css('top' ,getToolTipTop($('#'+callerID), $('#'+generatorId)));			
		$('#'+generatorId).fadeIn();
	});	
	$('#'+callerID).mouseout(function(e){
		if(testMouseOverElement($('#'+generatorId), e))
			return ;		
		$('#'+generatorId).fadeOut(); 	
	});		
}

function getToolTipLeft(caller, toolTip)
{
	left = caller.offset().left+toolTip.width()+10;
	if(left > $('body').width())
		left = $('body').width()-toolTip.width()-10;
	else
		left = caller.offset().left+10;	

	if(left < 0)
		return 0;			
	return left;
}

function testMouseOverElement(jElement, jmPosition)
{
	jELeft = jElement.offset().left;
	jETop  = jElement.offset().top;
	jERight = jELeft + jElement.width();
	jEBottom = jETop + jElement.height();	
	mX = jmPosition.pageX;
	mY = jmPosition.pageY;
	
	if(mX > jELeft && mX < jERight && mY > jETop && mY < jEBottom)		
		return true;	
	return false;
}

function getToolTipTop(caller, toolTip)
{	//dont use "top" as var name, chrome also uses it		
	t = caller.offset().top-(toolTip.height()+10);

	if(t < 0)
		return 0;	
	return t;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function isRtl()
{
	return readCookie('dir') == '1';
}

function isMlWorld()
{
	if ($(document).data("isMlWorld") == "true")
		return true;
	
	return false;
}

function textFlowFlag(jqTextBlocks)
{
	if (!isMlWorld()) return true;
	
//	var flowFlag = isRtl()?'&#x81':'&#x80';
	var flowFlag = isRtl()?'&#x81;':'&#x80;';
	jqTextBlocks.each(function() {
		if ($(this).is('textarea'))
			$(this).val(flowFlag + $(this).val());
		else 
			$(this).text(flowFlag + $(this).text());
	});
	
	
	return false;
}

var show = function(node) {
	alert($('<div>').append($(node).clone()).remove().html());
}

