/* --- JavaScript --- */
/* ---- main.js ----- */

/* ============== */
/* === EVENTS === */
/* ============== */

/* === addEvent/removeEvent written by Dean Edwards (2005) with input from Tino Zijdel, Matthias Miller, Diego Perini: http://dean.edwards.name/weblog/2005/10/add-event/ === */
function addEvent( element, type, handler ) {
    if (!element) element = window; // fix: sometimes element does not seem to exist, even though one is passed
    // assign each event handler a unique ID
    if (!handler.$$guid) handler.$$guid = addEvent.guid++;
    
	if ( element.addEventListener ) {
	    element.addEventListener(type, handler, false);
	    
	    if (!element.events) element.events = {};
	    // create a hash table of event handlers for each element/event pair
	    var handlers = element.events[type];
	    if (!handlers) {
	        handlers = element.events[type] = {};
	    }
	    handlers[handler.$$guid] = handler;
	} else {
		
		// create a hash table of event types for the element
		if ( !element.events ) element.events = {};
		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[ type ];
		if ( !handlers ) {
			handlers = element.events[ type ] = {};
			// store the existing event handler (if there is one)
			if ( element[ "on" + type ] ) {
				handlers[ 0 ] = element[ "on" + type ];
			}
		}
		// store the event handler in the hash table
		handlers[ handler.$$guid ] = handler;
		// assign a global event handler to do all the work
		element[ "on" + type ] = handleEvent;
	}
};
// a counter used to create unique IDs
addEvent.guid = 1;

function removeEvent(element, type, handler) {
	if ( element.removeEventListener ) {
		element.removeEventListener( type, handler, false );
	} else {
		// delete the event handler from the hash table
		if ( element.events && element.events[ type ] ) {
			delete element.events[ type ][ handler.$$guid ];
		}
	}
};

function handleEvent( event ) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent( (( this.ownerDocument || this.document || this ).parentWindow || window ).event );
	// get a reference to the hash table of event handlers
	var handlers = this.events[ event.type ];
	// execute each event handler
	for ( var i in handlers ) {
		this.$$handleEvent = handlers[ i ];
		if ( this.$$handleEvent( event ) === false ) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent( event ) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};
/* --- /addEvent/removeEvent --- */

function stopDefault( e ) {
	if ( e && e.preventDefault ) e.preventDefault();	// Prevent default browser action (W3C)
	else window.event.returnValue = false;					// IE version
	return false;
}

function normEvent( e ) {
	e = e || window.event;
	if ( !e.target ) e.target = e.srcElement;
	return e;
}

/* =============== */
/* === PRELOAD === */
/* =============== */

function preloadImage(src) {
	var img = new Image();
	img.src = src;
	return img.src;
}

/* =========== */
/* === DOM === */
/* =========== */

function domReady( f ) {
	if ( domReady.done ) return f();							// If DOM is already loaded, execute the function right away
	
	if ( domReady.timer ) {										// If wwe've already added a function
		domReady.ready.push( f );								// Add it to the list of functions to execute
	} else {
		addEvent( window, "load", isDOMReady );			// Attach an event for when the page finishes loading, just in case it finishes first.
		domReady.ready = [ f ];									// Initialize the array of functions to execute;
		domReady.timer = setInterval( isDOMReady, 13 );	// Check to see if the DOM is ready as quickly as possible
	}
}

function isDOMReady() {																										// Checks to see if the DOM is ready for navigation
	if ( domReady.done ) return false;																					// If we already figures out that the page is ready, ignore
	
	if ( document && document.getElementsByTagName && document.getElementById && document.body ) {	// Check to see if a number of functions and elements are able to be accessed
		clearInterval( domReady.timer );																					// If they're ready, we can stop checking
		domReady.timer = null;
		
		for ( var i = 0; i < domReady.ready.length; i++ ) domReady.ready[ i ]();							// Execute all functions that were waiting	
		domReady.ready = null;
		domReady.done = true;
	}
}

/* --- nodes --- */

function create( elem ) {
	return document.createElementNS ? document.createElementNS( 'http://www.w3.org/1999/xhtml', elem ) : document.createElement( elem );
}

function before( parent, before, elem ) {
	if ( elem == null ) {										// Check to see if no parent was provided
		elem = before;
		before = parent;
		parent = before.parentNode;
	}
	parent.insertBefore( checkElem( elem ), before );
}

function append( parent, elem ) {
	parent.appendChild( checkElem( elem ));
}

function checkElem( elem ) {
	return elem && elem.constructor == String ? document.createTextNode( elem ) : elem;	// if a string was provided, convert it into a text node
}

function remove( elem ) {
	if ( elem ) elem.parentNode.removeChild( elem );
}

function empty( elem ) {
	while ( elem.firstChild ) remove( elem.firstChild );
}

/* --- finding elements --- */
function id( name ) {
	return document.getElementById( name );	// -> HTML element
};

	/* === fix document.getElementById for IE - based on code by J. Max Wilson: http://www.sixteensmallstones.org/ie-javascript-bugs-overriding-internet-explorers-documentgetelementbyid-to-be-w3c-compliant-exposes-an-additional-bug-in-getattributes === */ 
	document.nativeGetElementById = document.getElementById;
	document.getElementById = function( id ) {
	    if ( document.all ) {   // only override when document.all is supported (IE + Opera)
	
	        document.getElementById = function( id ) {
	            var elem = document.nativeGetElementById( id );
	            if ( !elem ) return null;
	            if ( elem.attributes['id'] && elem.attributes['id'].value == id ) return elem;							// make sure that it is a valid match on id
	
	            for ( var i = 1; i < document.all[ id ].length; i++ ) {															// otherwise find the correct element
	                if ( document.all[ id ][ i ].attributes[ 'id' ].value == id ) return document.all[ id ][ i ];
	            }
	        };
	    } else {    // otherwise change back to original
	        document.getElementById = document.nativeGetElementById;
	        document.nativeGetElementById = null;  																						// we don't need it anymore
	    }
	};
	document.getElementById();																													// run document.getElementById() once to let it rewrite itself
	/* --- /fix document.getElementById for IE --- */

function tag( name, elem ) {
	return ( elem || document ).getElementsByTagName( name );	// -> Array
};

function withClass( name, sel, sel2 ) {														// sel and sel2 are both optional and can be either an element or a tag (one of each)
	var haveClass = [];
	var regExp = new RegExp( "(^|\\s)" + name + "(\\s|$)" );								// allows for multiple class names
	var tagName = sel.constructor == String ? sel : sel2;
	var elem = sel.constructor == String ? sel2 : sel;
	var elements = ( elem || document).getElementsByTagName( tagName || "*" );		// use document if no element has been specified and get all elements if no tag name has been specified
	for ( var e = 0; e < elements.length; e++) {
		var element = elements[ e ];
		if ( hasClass( element, name )) haveClass[ haveClass.length ] = element;
	}
	return haveClass;																					// -> Array
};

function hasClass( elem, name ) {
	if ( !name && elem.className != "") return true;			// if no className has been specified any className will do | -> Boolean
	var regExp = new RegExp( "(^|\\s)" + name + "(\\s|$)" );	// allows for multiple class names
	if ( regExp.test( elem.className )) return true;			// -> Boolean
	return false;															// -> Boolean
};

function prev( elem ) {
	do {
		elem = elem.previousSibling;
	} while ( elem && elem.nodeType != 1 );
	return elem;
}

function next( elem ) {
	do {
		elem = elem.nextSibling;
	} while ( elem && elem.nodeType != 1 );
	return elem;
}

function first( elem ) {
	elem = elem.firstChild;
	return elem && elem.nodeType != 1 ? next( elem ) : elem;
}

function last( elem ) {
	elem = elem.lastChild;
	return elem && elem.nodeType != 1 ? next( elem ) : elem;
}


/* --- get/set attributes --- */
function attr( elem, attrib ) {															// attrib can be a String (get) or an Object (set)
	if ( attrib.constructor == String ) {
		name = validName( attrib );
		return elem[ name ] || elem.getAttribute( name ) || '';					// -> String (attribute value)
	}
	else if ( attrib.constructor == Object ) {
		for ( n in attrib ) {
			var value = attrib[ n ];
			name = validName( n );
			if ( name == "className" || name == "rel" || name == "rev" ) {
				addToAttr( elem, name, value );
			} else {
				elem[ name ] = value;														// do it quick if possible
				if ( elem.setAttribute ) elem.setAttribute( name, value );		// XML fallback
			}
		}
		return true;																			// -> Boolean (values are set)
	}
	function validName( name ) {
		return { 'for': 'htmlFor', 'class': 'className' }[ name ] || name;	// rename in case of 'for' or 'class' attribute
	};
	return '';																					// -> String (empty: attrib was neither a String or Object)
};

function addClass( elem, name ) {
	addToAttr( elem, "className", name );
}

function removeClass( elem, name ) {
	removeFromAttr( elem, "className", name );
}

function addToAttr( elem, attr, value ) {	// can be used for class, rel and rev attributes
	removeFromAttr( elem, attr, value );	// make sure there won't be any doubles
	elem[ attr ] += " " + value;
}

function removeFromAttr( elem, attr, value ) {									// can be used for class, rel and rev attributes
	var remain = [];
	var values = elem[ attr ].split(/\s+/);										// seperate class names (devided by one or more whitespaces)
	for ( var v = 0; v < values.length; v++ ) {
		if ( values[ v ] != value ) remain[ remain.length ] = values[ v ];
	}
	elem[ attr ] = remain.join( " " );
}

/* ============= */
/* === STYLE === */
/* ============= */

/* --- check for CSS support --- */
function cssSupport() {
	if ( !document.styleSheets ) return false;									// styleSheets object is not supported
	var css = document.styleSheets;
	for ( var s = 0; s < css.length; s++) {
		if ( s == 0 ) {
			if ( !( css[ 0 ].cssRules || css[ 0 ].rules )) return false;	// both methods (cssRules/rules) are not supported
		}
		if ( !css[ s ].disabled ) return true;										// at least one of the stylesheets is not disabled
	}
	return false;																			// stylesheets are all disabled or not supported at all
}


/* ================================== */
/* ============= CUSTOM ============= */
/* ================================== */

////////// INIT OVERLABEL //////////

/* --- overLabel --- place labels over corresponding form control --- */
/* --- based on http://www.alistapart.com/articles/makingcompactformsmoreaccessible/ ---*/
function initOverLabel() {
	var labels = withClass( "overLabel", "label" );
	if ( !labels ) return;
	
	for ( var l = 0; l < labels.length; l++ ) {
		var label = labels[ l ];
		if ( !label.htmlFor ) continue;
		
		var overControl = id( label.htmlFor );
		if ( !overControl ) continue;
		
		label.forControl = overControl;																												// make reference from label to corresponding control
		
		if ( overControl.value === "" ) addClass( overControl.parentNode, "inactive" );												// make sure label is only placed on top of control in case it has no value which is not always the case after a reload
		
		addEvent( overControl, "focus", function() { removeClass( this.parentNode, "inactive" )} );
		addEvent( overControl, "blur", function() { if ( this.value === "" ) addClass( this.parentNode, "inactive" )} );
		addEvent( label, "click", function() { this.forControl.focus()} );																// give focus to corresponding control (needed for Safari)
	}
	
	addClass( document.body, "jsLabelsOn" );																										// CSS hook to turn it on
}


///////////// INIT CLICKABLE ITEMS /////////////

/* --- clickableItems --- make entire itemes clickable --- */
function initClickableItems() {
	// content section -|- add section for every clickable item type
	var content = id( "siteBody" );
	if ( content ) {
	
		var items;
	
		items = withClass( "clickableItem", "div", content );
		if ( items && items.length > 0 ) clickAllOver( items );
		
		items = withClass( "clickableItem", "li", content );
		if ( items && items.length > 0 ) clickAllOver( items );
	}
	// end content section
	
	// home section -|- add section for every clickable item type
	var home = id( "homeContent" );
	if ( home ) {
	
		var items;
	
		items = withClass( "clickableItem", "div", home );
		if ( items && items.length > 0 ) clickAllOver( items );
	}
	// end home section
}

/* --- clickAllOver --- */
function clickAllOver( elems ) {													// elem can be a single element or an array of elements
	var items = ( elems.constructor == Array ) ? elems : [ elems ];	// if elem is a single element, put it in an array

	for ( var i = 0; i < items.length; i++ ) {
		var item = items[ i ];
		
		item.getUrl = function() {
			var url = tag( "a", this )[0];
			return ( url ) ? url.href : false; 
		}
		
		item.url = item.getUrl();
		if (!item.url) return;

		var link = tag("a", item)[0];
		addEvent(link, "click", function(e) {
		 
		    stopDefault(e);
		    return false;
		});
		
		item.getTarget = function() {
			var url = tag( "a", this )[0];
			return ( url ) ? url.target : false; 
		}
		item.target = item.getTarget();

		///////////////////////////////////////////////
		
		if (Boolean(item.events && item.events["click"])) {
		    for (var hndl in item.events["click"]) {
		        if (item.removeEventListener) {
		            item.removeEventListener("click", item.events["click"][hndl],false);
		        }
		        delete item.events["click"][hndl];
		       
	        }
	    }



	    addEvent(item, "click", function() {
	  
	        if (this.target && this.target == '_blank') {
	            window.open(this.url, '');
	        
	        } else {
	            window.location.href = this.url;
	        }
	    });
		
		addEvent( item, "mouseover", function() { addClass( this, "jsHoverItem" )} );
		addEvent( item, "mouseout", function() { removeClass( this, "jsHoverItem" )} );
		
		addClass( item, "jsClickable" );
	}
}


///////////// INIT SELECT NAVIGATION /////////////

/* --- initSelectNav --- initializes autosubmit on <select>s that have class="selectNav", works with keyboard too (in IE, FX and Op) --- */
function initSelectNav() {
	var content = id( "contentBody" );
	if ( !content ) return;
	
	var selects = withClass( "selectNav", "select", content );
	for ( var s = 0; s < selects.length; s++ ) {
		var selectNav = selects[ s ];
		
		addEvent( selectNav, "focus", function() { this.origVal = this.value; } );
		addEvent( selectNav, "change", function() { 
			if ( this.newVal ) this.origVal = this.newVal;
			this.newVal = this.value;
		});
		
		addEvent( selectNav, "blur", function() { if ( this.newVal && this.newVal != this.origVal ) this.form.submit(); } );
		addEvent( selectNav, "click", function() { if ( this.newVal && this.newVal != this.origVal ) this.form.submit(); } );
	}
	if ( selectNav ) addClass( document.body, "jsSelectNavOn" );
}


///////////// INIT SPOTLIGHT NAVIGATION /////////////

/* --- initSpotlightNav --- */
function initSpotlightNav() {
	var selectSpotlight = id( "selectSpotlight" );
	var submitSpotlight = id( "submitSpotlight" );
	if ( !selectSpotlight || !submitSpotlight ) return;
	
	addEvent( submitSpotlight, "click", function( e ) { 
		if ( selectSpotlight ) window.location = selectSpotlight.value;
		return stopDefault( e );
	} );
}


///////////// GALLERY /////////////

function initGallery() {
	var thumbPrefix = "thumb_";	// prefix of thumb fileNames

	var gallery = id( "miniGallery" );
	if ( !gallery ) return;
	
	var galleryImg = tag( "img", gallery )[0];
	if ( !galleryImg ) return;
	
	galleryImg.path = galleryImg.src.substring( 0, galleryImg.src.lastIndexOf( '/' ) + 1 );
	
	var thumbs = tag( "ul", gallery )[ 0 ];
	
	var thumbImgs = tag( "img", thumbs );
	for ( var t = 0; t < thumbImgs.length; t++ ) {
		var thumbImg = thumbImgs[ t ];
		thumbImg.gallerySrc = preloadImage( galleryImg.path + thumbImg.src.substring( thumbImg.src.lastIndexOf( '/' ) + 1 + thumbPrefix.length ) );
	}
	
	thumbs.prefix = thumbPrefix;
	
	/* --- commented because of different way of loading images in CMS  --- */
	/*addEvent( thumbs, "click", function( e ) {
		e = e = normEvent( e );
		var target = e.target;
		
		if ( !( target.tagName == "A" || target.tagName == "IMG" ) ) return;
		if ( target.tagName == "A" ) {
			var target = tag( "img", target )[ 0 ];
			if ( !target ) return;
		}
		
		var tmpSrc = galleryImg.src;
		galleryImg.src = target.gallerySrc;
		target.gallerySrc = tmpSrc;
		target.src = galleryImg.path + thumbs.prefix + target.gallerySrc.substring( target.gallerySrc.lastIndexOf( '/' ) + 1 );
		
		return stopDefault( e );
	} );*/
}


///////////// MAGNIFY /////////////

/* --- commented because of different way of magnifying images in CMS. Replaced with inline onclick events and doMagnify(...) function. --- */

/*function initMagnify() {
	var popupPrefix = "large_";
	var popupWidth = "690px";	// size in pixels
	var popupHeight = "370px";	// size in pixels

	var contentBody = id( "contentBody" );
	if ( !contentBody ) return;

	var imgs = withClass( "magnifyImage", contentBody, "div" );
	for ( var i = 0; i < imgs.length; i++ ) {
		var magnifyImage = imgs[ i ];
		
		var galleryImg = tag( "img", magnifyImage )[0];
		if ( !galleryImg ) continue;
	
		galleryImg.path = galleryImg.src.substring( 0, galleryImg.src.lastIndexOf( '/' ) + 1 );
		
		var magnify = tag( "a", magnifyImage )[ 0 ];
		magnify.galleryImg = galleryImg;
		magnify.popupWidth = popupWidth;
		magnify.popupHeight = popupHeight;
		magnify.prefix = popupPrefix;

		addEvent( magnify, "click", function( e ) {
			this.href = this.galleryImg.path + this.prefix + this.galleryImg.src.substring( this.galleryImg.src.lastIndexOf( '/' ) + 1 );
			if ( !this.target ) this.target = "magnify";
			var popup = window.open( this.href, this.target, "width=" + this.popupWidth + ",height=" + this.popupHeight );
			popup.focus();
			return stopDefault( e );
		} );
	}
}*/

function doMagnify(e, link) {

	var popupWidth = "690px";	// size in pixels
	var popupHeight = "370px";	// size in pixels

	var contentBody = id( "contentBody" );
	if ( !contentBody ) return;

	var imgs = withClass( "magnifyImage", contentBody, "div" );
	for ( var i = 0; i < imgs.length; i++ ) {
		var magnifyImage = imgs[ i ];
		
		var galleryImg = tag( "img", magnifyImage )[0];
		
		if ( !galleryImg ) continue;
				
		if(link.parentNode != galleryImg.parentNode)
		    continue;
	
        this.href = galleryImg.src.substring( galleryImg.src.indexOf( '~' ) - 1 , galleryImg.src.lastIndexOf( '?' ) );
		if ( !this.target ) this.target = "magnify";
		var popup = window.open( this.href, this.target, "width=" + popupWidth + ",height=" + popupHeight );
		popup.focus();
		break;
	}
	return stopDefault( e );
}

/* --- new function because of different way of switching images in CMS. Replaced with inline onclick events and  doSwitchImages(...) function. --- */

function doSwitchImages(e, link) {
	var bigWidth = "280";
	var bigHeight = "150";
	var smallWidth = "90";
	var smallHeight = "48";
	
    var contentBody = id( "contentBody" );
	if ( !contentBody ) return;

	var imgs = withClass( "magnifyImage", contentBody, "div" );
	
	for ( var i = 0; i < imgs.length; i++ ) {
		var magnifyImage = imgs[ i ];
		
		var galleryImg = tag( "img", magnifyImage )[0];
		
		if ( !galleryImg ) continue;
		
		var mainSrc = galleryImg.src.substring( galleryImg.src.indexOf( '~' ) - 1 , galleryImg.src.lastIndexOf( '?' ) );
		
		var smallSrc = link.src.substring( link.src.indexOf( '~' ) - 1 , link.src.lastIndexOf( '?' ) );
		
		link.src = mainSrc + "?w=" + smallWidth + "&h=" + smallHeight;
		galleryImg.src = smallSrc + "?w=" + bigWidth + "&h=" + bigHeight;
		break;
	}
	return stopDefault( e );
}

///////////// OPEN POPUP /////////////

function initOpenPopup() {
	var popupWidth = "709px";	// size in pixels
	var popupHeight = "534px";	// size in pixels

	var siteBody = id( "siteBody" );
	if ( !siteBody ) return;
	
	var popLinks = withClass( "popup", "a", siteBody );
	for ( var p = 0; p < popLinks.length; p++ ) {
		var popLink = popLinks[ p ];
		
		popLink.popupWidth = popupWidth;
		popLink.popupHeight = popupHeight;
		
		addEvent( popLink, "click", function( e ) {
			if ( !this.target ) this.target = "popup";
			var popup = window.open( this.href, this.target, "width=" + this.popupWidth + ",height=" + this.popupHeight );
			popup.focus();
			return stopDefault( e );
		} );
	}
}


///////////// CLOSE POPUP /////////////

function initClosePopup() {
	if ( !hasClass( document.body, "popup" ) || !window.opener ) return;
	
	var header = tag( "h1" )[ 0 ];
	if ( !header || !hasClass( header, "close") ) return;
	
	var closeLink = create( "a" );
	attr( closeLink, { "href": "#", "class": "closeLink" } );
	var altText = closeText ? closeText : "Close window";
	closeLink.innerHTML = "<img src='/images/eden/layout/ico_close_popup.gif' width='13' height='13' alt='" + altText + "' />";
	addEvent( closeLink, "click", function( e ) {
		window.close();
		return stopDefault( e );
	} );
	append( header.parentNode, closeLink );
	
}


///////////// KEYWORD MATCH /////////////

function initKeywordMatch() {
	var outOf = 10;	// number of ranks
	var rankWidth = 6; // width per rank in pixels

	var searchResults = id( "searchResults" );
	if ( !searchResults ) return;
	
	var rankImg = create( "img" );
	attr( rankImg, { "src": "/images/eden/layout/ico_searchresult_ranks.gif", "width": "61", "height": "10" } ); 
	
	var ranks = withClass( "rank", "p", searchResults );
	for ( var r = 0; r < ranks.length; r++ ) {
		var rank = ranks[ r ];
		
		var rankResult = tag( "span", rank )[ 0 ];
		if ( !rankResult ) continue;
		
		var percentage = rankResult.innerHTML.replace( /\D/, "" );
		var ranking = Math.round( parseInt( percentage ) / outOf );
		
		var visualRank = rankImg.cloneNode( true );
		visualRank.alt = percentage;
		visualRank.style.backgroundPosition = -rankWidth * ( outOf - ranking ) + "px 0";
		rankResult.innerHTML = "";
		append( rankResult, visualRank );
		
		addClass( rankResult, "visual" );
	}
}


///////////// LANGUAGE SWITCH /////////////

function initLanguageSwitch() {
	var serviceBar = id( "serviceBar" );
	var siteLanguage = id( "siteLanguage" );
	var languageSwitch = tag( "select", siteLanguage )[ 0 ];
	if ( !serviceBar || !siteLanguage || !languageSwitch ) return;
	
	var langList = create( "ul" );
	
	var options = tag( "option", siteLanguage );
	for ( var opt = 0; opt < options.length; opt++ ) {
		var option = options[ opt ];
		
		if ( ( languageSwitch.value == option.value ) || ( !languageSwitch.value && opt == 0 ) ) {
			var currentLang = create( "a" );
			attr( currentLang, { "href": "#", "class": option.lang } );
			addEvent( currentLang, "click", function( e ) { return stopDefault( e ) } );
			append( currentLang, option.innerHTML );
			
			for ( var s = 0; s < 3; s++ ) {
				var span = create( "span" );
				append( span, currentLang );
				currentLang = span;
			}
		} else {
			var langItem = create( "li" );
			var language = create( "a" );
			attr( language, { "href": option.value, "class": option.lang, "xml:lang": option.lang, "lang": option.lang } );
			
			append( language, option.innerHTML );
			append( langItem, language );
			append( langList, langItem );
		}
	}
	
	addEvent( siteLanguage, "mouseover", function() { addClass( this, "jsHover" ) } );
	addEvent( siteLanguage, "mouseout", function() { removeClass( this, "jsHover" ) } );
	addEvent( siteLanguage, "focusin", function() { addClass( this, "jsHover" ) } );
	addEvent( siteLanguage, "focusout", function() { removeClass( this, "jsHover" ) } );
	if ( siteLanguage.addEventListener ) {
		siteLanguage.addEventListener( "focus", function() { addClass( this, "jsHover" ) }, true );
		siteLanguage.addEventListener( "blur", function() { removeClass( this, "jsHover" ) }, true );
	}
	
	siteLanguage.innerHTML = "";
	append( siteLanguage, currentLang );
	append( siteLanguage, langList );
	
	addClass( serviceBar, "jsServiceOn" );	// CSS hook
}


///////////// OPEN FLYOUT /////////////

function initOpenFlyout() {
	var tools = id( "tools" );
	if ( !tools ) return;
	
	addEvent( tools, "click", function( e ) {
		e = normEvent( e );
		var target = e.target;
		if ( !( target.tagName == "LI" || target.tagName == "A" ) ) return;
		if ( target.tagName == "A" ) var target = target.parentNode;
		
		var tools = id( "tools" );
		
		var itemName = target.id;
		if ( hasClass( tools, itemName ) ) {
			removeClass( tools, itemName );
		} else {
			removeClass( tools, "newsletter" );
			removeClass( tools, "mailPage" );
			addClass( tools, itemName );
		}
		
		return stopDefault( e );
	} );
}


///////////// CLOSE FLYOUT /////////////

function initCloseFlyout() {
	var header = id( "header" );
	if ( !header ) return;
	
	var closeButtons = withClass( "closeFlyout", "p", header );
	for ( var c = 0; c < closeButtons.length; c++ ) {
		var closeButton = closeButtons[ c ];
		
		addEvent( closeButton, "click", function( e ) {
			var parent = this.parentNode;
			while ( !( parent == document.body || hasClass( parent, "flyout" ) ) ) {
				parent = parent.parentNode;
			}
			if ( parent.id == "quickResults" ) {
				removeClass( parent, "show" );
			} else {
				var tools = id( "tools" );
				if ( tools ) {
					removeClass( tools, "newsletter" );
					removeClass( tools, "mailPage" );
				}
			}
			
			return stopDefault( e );
		} );
	}
}

/* --- closing tools, to be used called from other scripts --- */
function closeTools() {
	var tools = id( "tools" );
	if ( !tools ) return;
	
	removeClass( tools, "newsletter" );
	removeClass( tools, "mailPage" );
}


/* --- call functions only if the used methods are supported --- */
/* --- commented because of bad work of events. Replaced with body.onload event and onBodyLoad function. --- */
/*domReady( function() {
	
	if ( cssSupport() ) {
		initOverLabel();
		initLanguageSwitch();
		initClickableItems();
		initSelectNav();
		//initKeywordMatch();
		initSpotlightNav();
		initGallery();
		//initMagnify();
		initOpenPopup();
		initClosePopup();
		initOpenFlyout();
		initCloseFlyout();
	}
} );*/

function IsIE8Browser() {

    var rv = -1;

    var ua = navigator.userAgent;

    var re = new RegExp("Trident\/([0-9]{1,}[\.0-9]{0,})");

    if (re.exec(ua) != null) {

        rv = parseFloat(RegExp.$1);

    }

    return (rv == 4);

}

function onBodyLoad() {
		initOverLabel();
		initLanguageSwitch();
		initClickableItems();
		initSelectNav();
		//initKeywordMatch();
		initSpotlightNav();
		initGallery();
		//initMagnify();
		initOpenPopup();
		initClosePopup();
		initOpenFlyout();
		initCloseFlyout();
		if(navigator.appName.indexOf('Explorer') > 0) { //load IE ctyles
		    IEinlineLinks();
	
			if (IsIE8Browser()) {
			            var ie8fixFooter = document.getElementById("footerBar");
				    if (ie8fixFooter) {
					var preHeight = ie8fixFooter.offsetHeight;
					//alert(ie8fixFooter.offsetHeight + " " + document.body.scrollHeight);
					ie8fixFooter.style.position = "absolute";
					ie8fixFooter.style.top = document.body.scrollHeight - ie8fixFooter.offsetHeight + "px";
					ie8fixFooter.style.backgroundColor = "dbdbdb";
					ie8fixFooter.style.height = preHeight + "px";
					//alert(ie8fixFooter.style.top);
			    	}
			}
		}
}