/************************** POPUP WINDOW MANAGEMENT **************************/

var registeredPopupWindows = new Object();

function registerPopupWindow( ns, key, popupWindow, doCallHandler )
{
	if ( ! window.onunload )
	{
		window.onunload = closeAllRegisteredPopupWindows;
	}

	if ( ! registeredPopupWindows[ ns ] )
	{
		registeredPopupWindows[ ns ] = new Object();
	}

	if ( ! registeredPopupWindows[ ns ][ key ] )
	{
		registeredPopupWindows[ ns ][ key ] = new Object();
	}

	registeredPopupWindows[ ns ][ key ][ "window" ] = popupWindow;
	registeredPopupWindows[ ns ][ key ][ "doCallHandler" ] = doCallHandler;
}

function getRegisteredPopupWindow( ns, key )
{
	var result = null;

	if ( registeredPopupWindows[ ns ] )
	{
		if ( registeredPopupWindows[ ns ][ key ] )
		{
			result = registeredPopupWindows[ ns ][ key ][ "window" ];
		}
	}

	return result;
}

function closeAllRegisteredPopupWindows()
{
	for( var ns in registeredPopupWindows )
	{
		for ( var key in registeredPopupWindows[ ns ] )
		{
			pw = registeredPopupWindows[ ns ][ key ][ "window" ];

			if ( ! pw.closed )
			{
				pw.close();
			}

			unregisterPopupWindow( ns, key, pw );
		}
	}
}

function getDoCallHandlerOnRegisteredPopupWindow( ns, key )
{
	var result = false;

	if ( registeredPopupWindows[ ns ] )
	{
		if ( registeredPopupWindows[ ns ][ key ] )
		{
			result = registeredPopupWindows[ ns ][ key ][ "doCallHandler" ];
		}
	}

	return result;
}

function findNamespaceAndKeyForRegisteredPopupWindow( popupWindow )
{
	var result = null;

	for( var ns in registeredPopupWindows )
	{
		for( var key in registeredPopupWindows[ ns ] )
		{
			if ( registeredPopupWindows[ ns ][ key ][ "window" ] == popupWindow )
			{
				result = new Array( ns, key );
				break;
			}
		}
	}

	return result;
}

function unregisterPopupWindow( ns, key, popupWindow )
{
	if ( registeredPopupWindows[ ns ] )
	{
		if ( registeredPopupWindows[ ns ][ key ] )
		{
			if ( registeredPopupWindows[ ns ][ key ][ "window" ] == popupWindow )
			{
				delete registeredPopupWindows[ ns ][ key ];
			}
		}
	}
}

/************************** BREED SELECTION DIALOG **************************/

function showDogBreedSelectionDialog( doCallHandler, url, dogBreedIdElementId, dogBreedNameElementId, dogIsBattleDogElementId )
{
	var ns = "mywuff/dogBreedPopup";
	var key = dogBreedIdElementId + ":" + dogBreedNameElementId + ":" + dogIsBattleDogElementId;
	var popupWindow = getRegisteredPopupWindow( ns, key );
	if ( popupWindow )
	{
		if ( popupWindow.closed )
		{
			unregisterPopupWindow( ns, key, popupWindow );
			popupWindow = null;
		}
	}

	if ( ! popupWindow )
	{
		var wname = dogBreedIdElementId + "_" + dogBreedNameElementId + "_" + dogIsBattleDogElementId;
		popupWindow = windowopen( url, wname );
		registerPopupWindow( ns, key, popupWindow, doCallHandler );
		popupWindow.focus();
	}
	else
	{
		popupWindow.focus();
	}
}

function selectDogBreed( popupWindow, breedId, breedName, isBattleDog )
{
	var namespaceAndKey = findNamespaceAndKeyForRegisteredPopupWindow( popupWindow );

	var doCallHandler = getDoCallHandlerOnRegisteredPopupWindow( namespaceAndKey[ 0 ], namespaceAndKey[ 1 ] );
	popupWindow.close();
	unregisterPopupWindow( namespaceAndKey[ 0 ], namespaceAndKey[ 1 ], popupWindow );
	if ( namespaceAndKey )
	{
		var keys = namespaceAndKey[ 1 ].split( ":" );
		if ( typeof keys[ 0 ] != "undefined" )
		{
			document.getElementById( keys[ 0 ] ).value = breedId;
			if ( typeof keys[ 1 ] != "undefined" )
			{
				document.getElementById( keys[ 1 ] ).innerHTML = truncateWithEllipsis( insertBreakableSpace( breedName ), 28 );

				if ( typeof selectDogBreedHandler != "undefined" && doCallHandler )
				{
					selectDogBreedHandler( breedName );
				}
			}
			if ( typeof keys[ 2 ] != "undefined" )
			{
				document.getElementById( keys[ 2 ] ).selected = isBattleDog;
			}
		}
	}
}

/************************** BREED MIXER **************************/

function breedLevelSelect( evt, elt, id, id2 )
{
	// breed level selection is only possible when there is a breed selected
	if ( document.getElementById( id2 ).value > 0 )
	{
		var eltLevelIndicator = document.getElementById( id + "_indicator" );
	
		// calculate layerLeft of elt
		var parent = elt;
		var eltLeft = calculateElementTopLeftPosition( elt )[ 0 ];
		var eltWidth = getElementClientWidth( elt );
		var mouseX = eventGetPageMouseXY( evt )[ 0 ];
		var newLevel = 100 * ( ( mouseX - eltLeft ) / eltWidth );
		newLevel = Math.ceil( newLevel );
		if ( newLevel > 100 )
		{
			newLevel = 100;
		}

		refreshDogBreedLevelIndicator( newLevel, id );
	}
}

var doBreedSelection = false;
function breedLevelSelectStart( evt, elt, id )
{
	// breed level selection is only possible when there is a breed selected
	if ( parseInt( document.getElementById( id ).value ) > 0 )
	{
		doBreedSelection = true;
	}
}

function breedLevelSelectStop( evt, elt )
{
	doBreedSelection = false;

	fixateConnectedDogBreedSelectors();
}

function breedLevelSelectSlide( evt, elt, id, id2 )
{
	if ( doBreedSelection )
	{
		breedLevelSelect( evt, elt, id, id2 );
	}
}

function refreshDogBreedLevelIndicator( level, id )
{
	if ( level > 100 )
	{
		level = 100;
	}
	else if ( level < 0 )
	{
		level = 0;
	}

	setInputLevel( id, level );
	applyMaximumTotalLevelConstraint( id );
}

var connectedLevelSelectors = new Object();
function connectDogBreedLevelSelectors()
{
	connectedLevelSelectors = new Array();

	for( var i = 0; i < arguments.length; i++ )
	{
		connectedLevelSelectors[ arguments[ i ] ] = null;
	}

	fixateConnectedDogBreedSelectors();
}

function fixateConnectedDogBreedSelectors()
{
	for( var key in connectedLevelSelectors )
	{
		connectedLevelSelectors[ key ] = getInputLevel( key );
	}
}

function applyMaximumTotalLevelConstraint( exclude )
{
	var total = getInputLevelTotal( connectedLevelSelectors, exclude );
	var current = getInputLevel( exclude );
	var remain = 100 - current;
	var grandtotal = total + current;

	for( var key in connectedLevelSelectors )
	{
		level = connectedLevelSelectors[ key ];

		if( key != exclude && level > 0 )
		{
			if ( grandtotal > 100 )
			{
				setInputLevel( key, Math.round( level * ( remain / total ) )  );
			}
			else
			{
				setInputLevel( key, level );
			}
		}
	}

	if ( ! doBreedSelection )
	{
		fixateConnectedDogBreedSelectors();
	}
}

function setInputLevel( id, level )
{
	if ( isNaN( level ) || ! isFinite( level ) )
	{
		level = 0;
	}

	var eltLevelInput = document.getElementById( id );
	var eltLevelIndicator = document.getElementById( id + "_indicator" );
	var innerWidth = getElementClientWidth( eltLevelIndicator.parentNode ) - 2;

	var newWidth = innerWidth * ( level / 100 );
	if ( innerWidth < 0 )
	{
		newWidth = 0;
	}
	else if ( newWidth > innerWidth )
	{
		newWidth = innerWidth;
	}
	eltLevelIndicator.style.width = newWidth + "px";
	eltLevelInput.value = level;
}

function getInputLevel( id )
{
	return parseInt( document.getElementById( id ).value );
}

function getInputLevelTotal( inputs, exclude )
{
	result = 0;

	for( var key in inputs )
	{
		if ( key != exclude )
		{
			result += inputs[ key ];
		}
	}

	return result;
}

/*************************** RATING **************************/

var ratingConfig = new Array();

function ratingGetText( fieldnb, pos )
{
	return ratingConfig[ fieldnb ][ 'texts' ][ Math.floor( pos / 27 ) ];
}

function ratingSelectorInit( fieldnb, pos, texts )
{
	ratingConfig[ fieldnb ] = new Object();
	ratingConfig[ fieldnb ][ 'startPos' ] = pos;
	ratingConfig[ fieldnb ][ 'texts' ] = texts;
	ratingSelectorReset( fieldnb );
}

function ratingSelectorSelect( fieldnb, pos )
{
	document.getElementById( 'ratingChart' + fieldnb ).style.width = pos + 'px';
	document.getElementById( 'ratingText' + fieldnb ).innerHTML = ratingGetText( fieldnb, pos );
}

function ratingSelectorReset( fieldnb )
{
	ratingSelectorSelect( fieldnb, ratingConfig[ fieldnb ][ 'startPos' ] );
}

/*************************** MENU **************************/

function getCurrentSelection( elt )
{
	if ( typeof document.selection != "undefined" )
	{
		var r = document.selection.createRange();
		return new Array( r.start, r.end );
	}
	else
	{
		return new Array( elt.selectionStart, elt.selectionEnd );
	}
}

function ensureBodyTextLengthConstraint( evt, elt, maxLength )
{
	var result = false;
	var strlen = elt.value.length;

	if ( strlen >= maxLength )
	{
		var code = ( evt.which ? evt.which : evt.keyCode );

		var ctrl = ( "ctrlKey" in evt ? evt.ctrlKey : ( ( evt.modifiers & Event.CTRL_MASK ) ? true : false ) );
		var alt = ( "altKey" in evt ? evt.altKey : ( ( evt.modifiers & Event.ALT_MASK ) ? true : false ) );
		var shift = ( "shiftKey" in evt ? evt.shiftKey : ( ( evt.modifiers & Event.SHIFT_MASK ) ? true : false ) );

		// active selection that will be replaced with new input characters?
		var currentSelection = getCurrentSelection( elt );
		var activeSelection = currentSelection[ 0 ] != currentSelection[ 1 ];

		// del or backspace?
		if ( code == 9 || code == 27 || code == 8 || code == 46 || activeSelection || code >= 37 && code <= 40 ) //|| ( ctrl && code == 65 ) )
		{
			result = true;
		}
		else if ( ctrl && ( code == 65 || code == 97 ) ) // enable ctrl-a
		{
			result = true;
		}
		else if ( ctrl && code == 86 ) // enable and limit ctrl-v
		{
			elt.value = elt.value.substr( 0, maxLength );
			result = true;
		}
	}
	else
	{
		result = true;
	}

	return result;
}

/*************************** MENU **************************/

function navstart1(navIsOpen, navNum)
{
	document.write('<style type="text/css">#sitemenu, #sitemenu ul ul {position: absolute} ');
	for(var i = 1; i<=navNum; i++)
	{
		if(i != navIsOpen)
			document.write(' #navlist_'+i+' {visibility: hidden} ')
	}
	document.write('</style>');
}

function navstart2(navIsOpen, navNum)
{
	for(var i = 1; i<=navNum; i++)
	{
		if(i == navIsOpen)
			document.getElementById('navlist_'+i).style.visibility = 'visible';
		else
			document.getElementById('navlist_'+i).style.visibility = 'hidden';
	}
	
	document.getElementById('navimg_'+navIsOpen).src = document.getElementById('navimg_'+navIsOpen).src.replace(/level1/, 'level1-hover');
	
}

function navchange()
{
	var s = document.getElementById('nav').getElementsByTagName("img"), i;
	for(i=0; i<s.length; i++)
	{
		if(s[i].className != 'decoration' && s[i].className != 'active')
		{			
			if(s[i].src.indexOf('level2') == -1)
				s[i].onclick = navonclick;
			s[i].onmouseover = navonmouseover;
			s[i].onmouseout = navonmouseout;
		}
	}
}

function navonclick()
{
	for(var i = 1; i<=navNum; i++)
	{
		document.getElementById('navimg_'+i).src = document.getElementById('navimg_'+i).src.replace(/level1\-hover/, 'level1');
		if(this.id == 'navimg_'+i)
		{
			document.getElementById('navlist_'+i).style.visibility = 'visible';
		}
		else
		{
			document.getElementById('navlist_'+i).style.visibility = 'hidden';
		}
	}
	
	this.src = this.src.replace(/level1/, 'level1-hover');

}

function navonmouseover()
{
	if(this.src.indexOf('level1') == -1 && this.src.indexOf('-hover') == -1)
		this.src = this.src.replace(/level2/, 'level2-hover');
}

function navonmouseout()
{
	if(this.src.indexOf('level1') == -1 && this.src.indexOf('-hover') != -1)
		this.src = this.src.replace(/level2\-hover/, 'level2');
}

navstart1(navIsOpen, navNum);

/*************************** FORM INPUT FIELDS **************************/

function enhancedDateInputMouseOverHandler( evt, elt )
{
	var baseId = elt.id.substr( 0, elt.id.indexOf( "_enhancedDateInput" ) );

	if( document.getElementById( baseId ).value != "" )
	{
		var id = baseId + "_dropdown";
	
		var dropdown = document.getElementById( id );
		if ( ! dropdown ) 
		{
			dropdown = document.createElement( "DIV" );
			dropdown.id = id;
			dropdown.style.position = "absolute";
			dropdown.style.backgroundColor = "transparent";

			var eltTopLeft = calculateElementTopLeftPosition( elt.firstChild );
			dropdown.style.verticalAlign = "top";
			dropdown.style.textAlign = "left";
			dropdown.innerHTML = "<a href='javascript:void(0);'>Datum l&ouml;schen</a>";
	
			document.body.appendChild( dropdown );
	
			dropdown.style.left = eltTopLeft[ 0 ] + "px";
			dropdown.style.top = ( eltTopLeft[ 1 ] + elt.offsetHeight + 1 ) + "px";
			dropdown.style.cursor = "default";
			dropdown.style.padding = "0px";
			dropdown.style.zIndex = "100";
	
			var evtMousePageXY = eventGetPageMouseXY( evt );

			eval( "dropdown.onclick = function( evt )" +
				  "{" +
				  "evt = evt || window.event;" +
				  "document.getElementById( \"" + baseId + "\" ).value = \"\";" +
				  "enhancedDateInputRemoveDropdown( this.id );" +
				  "}"
			);
	
			dropdown.onmouseover = function( evt )
			{
				evt = evt || window.event;
				window.clearTimeout( this.removeTimer );
				this.removeTimer = null;
			};
	
			dropdown.onmouseout = function( evt )
			{
				evt = evt || window.event;
				elt = this;
				var eltTopLeft = calculateElementTopLeftPosition( elt );
				var evtMousePageXY = eventGetPageMouseXY( evt );
	
				// the user has left the element altogether
				if ( ! ( evtMousePageXY[ 0 ] > eltTopLeft[ 0 ] && evtMousePageXY[ 0 ] < eltTopLeft[ 0 ] + elt.offsetWidth &&
					 evtMousePageXY[ 1 ] > eltTopLeft[ 1 ] && evtMousePageXY[ 1 ] < eltTopLeft[ 1 ] + elt.offsetHeight ) )
				{
					this.removeTimer = window.setTimeout( "enhancedDateInputRemoveDropdown('" + this.id + "')", 230 ); 
				}
			};
		}
		else
		{
			if ( dropdown.removeTimer != null )
			{
				window.clearTimeout( dropdown.removeTimer );
				dropdown.removeTimer = null;
			}
		}
	}
}

function enhancedDateInputRemoveDropdown( id )
{
	var dropdown = document.getElementById( id );
	if ( dropdown )
	{
		dropdown.parentNode.removeChild( dropdown );
	}
}

function enhancedDateInputMouseOutHandler( evt, elt )
{
	var id = elt.id.substr( 0, elt.id.indexOf( "_enhancedDateInput" ) ) + "_dropdown";
	elt = elt.firstChild;
	var eltTopLeft = calculateElementTopLeftPosition( elt );
	var evtMousePageXY = eventGetPageMouseXY( evt );

	// the user has left the element altogether
	if ( ! ( evtMousePageXY[ 0 ] > eltTopLeft[ 0 ] && evtMousePageXY[ 0 ] < eltTopLeft[ 0 ] + elt.offsetWidth &&
		 evtMousePageXY[ 1 ] > eltTopLeft[ 1 ] && evtMousePageXY[ 1 ] < eltTopLeft[ 1 ] + elt.offsetHeight ) )
	{
		var dropdown = document.getElementById( id );
		if ( dropdown ) 
		{
			dropdown.removeTimer = window.setTimeout( "enhancedDateInputRemoveDropdown('" + id + "')", 500 ); 
		}
	}
}

/*************************** TOOLS **************************/

/*
Usage: <a href="modul/action" onclick="return windowopen('modul/action', 'popup')">Klick to open the info Window</a>
*/

function windowopen(w, wname)
{
	var pu = window.open(w, wname, 'scrollbars=yes,status=no,toolbar=no,location=no,directories=no,resizable=yes,menubar=no,width=640,height=600,top=100,left=100');
	pu.blur();
	window.focus();

	return pu;
}


function select1to10(fieldid, action)
{
	elt = document.getElementById(fieldid);
	var e = parseInt(elt.value);

	if(isNaN(e)) e = 5;
	if(action == '+') e++; else e--;

	validate1to10( elt, e );
}

function validate1to10( elt )
{
	var e = parseInt( elt.value );
	if ( arguments.length == 2 )
	{
		e = arguments[ 1 ];
	}
	if(e < 1) e = 1; 
	if(e > 10) e = 10;

	elt.value = e;
}

function truncateWithEllipsis( text, truncate_on_length )
{
	result = text;
	
	if( truncate_on_length && truncate_on_length < text.length )
	{
		result = text.substring( 0, truncate_on_length - 2 );
		result += "&hellip;";
	}

	return result;
}

function insertBreakableSpace( text )
{
	return text.replace( /-/g, "- " );
}

// calculate top-left position of element
function calculateElementTopLeftPosition( elt )
{
	var result = new Array( 0, 0 );

	var parent = elt;
	while( parent )
	{
		result[ 0 ] += parent.offsetLeft;
		result[ 1 ] += parent.offsetTop;

		parent = parent.offsetParent;
	}

	return result;
}

/*************************** EVENTS **************************/

function eventGetScreenMouseXY( evt )
{
	result = new Array( 0, 0 );

	result[ 0 ] = evt.clientX;
	result[ 1 ] = evt.clientY;

	return result;
}

function eventGetPageMouseXY( evt )
{
	result = new Array( 0, 0 );

	if ( evt.pageX )
	{
		result[ 0 ] = evt.pageX;
		result[ 1 ] = evt.pageY;
	}
	else
	{
		var eltTopLeft = calculateElementTopLeftPosition( evt.srcElement );
		result[ 0 ] = evt.offsetX + eltTopLeft[ 0 ];
		result[ 1 ] = evt.offsetY + eltTopLeft[ 1 ];
	}

	return result;
}

function hideBlockByCheckboxChecked(checkboxid, showhideids )
{
	var checkboxstate = document.getElementById(checkboxid).checked;
	for( i = 0; i < showhideids.length; i++ )
	{
		showhide = document.getElementById(showhideids[ i ]);
		if(checkboxstate == true)
		{
			showhide.style.display = 'none';
		}
		else
		{
			showhide.style.display = 'block';
		}
	}
}

/*************************** DOM **************************/

function getElementClientWidth( elt )
{
	return elt.clientWidth;
}

function getElementClientHeight( elt )
{
	return elt.clientHeight;
}

/*************************** Flash **************************/


function swfObjectTag(url, attributes, params, text)
{	
	var default_attributes = new Object(), default_params = new Object(), content = '', name;
		
	// default-ie-attributes
	if(document.all) {
		default_attributes['classid'] = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000';
	}
	else {
		default_attributes['data'] = url;
		default_attributes['type'] = 'application/x-shockwave-flash';
	}

	// default-attributes
	default_attributes['codebase'] = 'http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0';
	
	// default-ie-params
	if(document.all) {
		default_params['movie'] = url;
	}
	
	// default-params
	default_params['quality'] = 'height';
	default_params['allowScriptAccess'] = 'sameDomain';
	
	// start object-tag	
	content += '<object';
	
	// add attributes
	for (name in attributes) {
		content += ' ' + name + '="' + attributes[name] + '"';
		if(default_attributes[name] !== undefined)
			delete default_attributes[name];
	}
	
	if(default_attributes !== undefined) {
		for (name in default_attributes) {
			content += ' ' + name + '="' + default_attributes[name] + '"';
		}
	}
	
	content += '>';
	
	// start params	
	for (name in params) {
		content += ' <param name="' + name + '" value="' + params[name] + '" />';
		if(default_params[name] !== undefined)
			delete default_params[name];		
	}	
	
	if(default_params !== undefined) {
		for (name in default_params) {
			content += ' <param name="' + name + '" value="' + default_params[name] + '" />';
		}
	}
	
	// close object tag	
	content += ' ' + text + ' </object>';
	
	return content;
}

/* functions and classes using mootools */

/* slidebox */

function slideBox(slideElementId, slideEventElementId, durationTime, hideOnStart)
{
	slideElement = $(slideElementId);
	var doSlide = new Fx.Slide(slideElement, {duration: durationTime});
	slideElement.style.display = 'block';
	if(hideOnStart) {
		doSlide.hide(); // inital hiding
	}
	
	$(slideEventElementId).addEvent('click', function(e){
		e = new Event(e);
		doSlide.toggle();
		e.stop();
	});
}

/* */

function checkCommentField(fieldId, errorMessage, toLongMessage)
{
	var comment = $(fieldId).value.length;
	if(comment == 0)
	{
		alert(errorMessage);
		return false;
	}
	else if(comment > 400)
	{
		alert(toLongMessage);
		return false;
	}
	else
	{
		return true;
	}
}