$(document).ready(function() {
	
	$('body').addClass('js');
	
	/* Allows the footer to remain at the bottom */
	stickyBody();

	/**** SITE MAP *****/
	if ($('body.site-map').length > 0) {
		$('#sitemap').addClass('tree');
		
		//hide all lists inside of main list by default
		$('#sitemap li ul').hide();
			
		//iterate through all list items
		$('#sitemap li').each(function(){
			//if list-item contains a child list
			if ($(this).children('ul').length > 0) {
				//add expand/collapse control
				$(this).addClass('expandable').prepend('<span class="expand" />');
			}
		}); //end .each
			
		//handle clicking on expand/collapse control
			$('#sitemap span.expand').toggle(
				//if it's clicked once, find all child lists and expand
				function(){
					if($.browser.msie) {
						$(this).toggleClass('collapse').nextAll('ul').show();
					} else {
						$(this).toggleClass('collapse').nextAll('ul').slideDown();
					}
				},
				//if it's clicked again, find all child lists and contract
				function(){
					if($.browser.msie) {
						$(this).toggleClass('collapse').nextAll('ul').hide();
					} else {
						$(this).toggleClass('collapse').nextAll('ul').slideUp();
					}
				}
			);
			
		// expand current policy/sector/initiative
			if( $('#sitemap > li:eq(1) ul li.expandable').length > 0 ){ $('#sitemap > li:eq(1) > span.expand').trigger('click'); $('#sitemap > li:eq(1) > ul > li > span.expand').trigger('click'); }
			if( $('#sitemap > li:eq(2) ul li.expandable').length > 0 ){ $('#sitemap > li:eq(2) > span.expand').trigger('click'); $('#sitemap > li:eq(2) > ul > li > span.expand').trigger('click'); }
			if( $('#sitemap > li:eq(3) ul li.expandable').length > 0 ){ $('#sitemap > li:eq(3) > span.expand').trigger('click'); $('#sitemap > li:eq(3) > ul > li > span.expand').trigger('click'); }
	
	}
	/* end site map */
	
	
	//sets class 'on' to FAQ or Glossary entry
//	if ($('body.glossary ul#navLevel1 > li.no3 > ul > li > ul > li, body.faq ul#navLevel1 > li.no3 > ul > li > ul > li').is('.on')) {
//		$('li:parent').parent().parent('.no7').addClass('on');
//	}
	$('#navLevel1 li.no2:empty').css('display', 'none');
	
	/* HOMEPAGE */
	if ($('body.homepage').length > 0) {
		// Video launch
		homeFlash('preview1');
		
		//Homepage multicolumn
		//$('body.homepage #intro .inner div').columnize({columns:2});

		/* Equal height */
		$("body.homepage .equal_height").equalHeights(200,280);
	}
	
	/*** SECTOR PAGES ***/
	//Show/hide additional intro text on sector hp
	$('script').remove();
	
	$('#intro').find('p:first').addClass('abstract');
	//$('#intro p[class!=abstract]:not(:first)').addClass('more-info');
	last= $('#intro :last-child');
	$('#intro p.abstract').next().nextUntil(last).addClass('more-info');
	
	var more= $('.sector #more').val();
	var less= $('.sector #less').val();

	$('.more-info').wrapAll('<div class="innerMore"><div></div></div>');
	$('.innerMore').before('<span href="#" class="more plus">'+more+'</span>').hide();
	$('.more-info:last').after('<span href="#" class="more less">'+less+'</span>');

	
	$('.plus').click(function() {
		$('.innerMore').fadeIn();
		$('.plus').css('visibility', 'hidden');
	});
	$('.less').click(function() {
		$('.innerMore').fadeOut();
		$('.plus').css('visibility', 'visible');	
	});
	/**/
		
	/* COLLAPSIBLE MENU */
	//Add elements to be collapsed when loading the page here
	
	/* add class 'on' on external links("#")  */
	firstLi = $('#navLevel1 > li.expandable > ul > li:first-child, #newsroom-nav > li.expandable > ul > li:first-child');
	liOn = $('#navLevel1 > li.expandable > ul, #newsroom-nav > li.expandable > ul').find('li.on');
	 liOn.parent().parent('.expandable').addClass('on');

	firstLi2 = $('#navLevel1 > li.expandable > ul > li > ul > li:first-child');
	liOn2 = $('#navLevel1 > li.expandable > ul > li > ul, #newsroom-nav > li.expandable > ul > li').find('li.on');
	 liOn2.parent().parent().parent().parent('.expandable').addClass('on');

	if(liOn.length > 1) {
		firstLi.removeClass('on');
	}
	if(liOn2.length > 1) {
		firstLi2.removeClass('on');
	}
	
	/*Set first entry of a sub-menu in bold (to be removed)*/
	$('#newsroom-nav li.no2 > ul li:first').addClass('overview');
	var testUrl= /.+(sectors|policies)\/.+\/contracts\-grants\/(index|temp)_.*/;
	if (testUrl.test(window.location)) {
		$('#newsroom-nav_sub-2 li.no2-1').addClass('on').parent().parent().addClass('on');
	}
	
	/* hide/display menu's */	
	$('#navLevel1 > li.expandable > ul, #newsroom-nav li.expandable:not(.on) > ul').hide();
	$('body #navLevel1 li.expandable.on > ul, body #newsroom-nav li.expandable.on > ul').show();
	
	//Add elements to be expandable here
	isStandard= ($('body').hasClass('standard') && !($('body').hasClass('broker'))); //test if non-broker content page
	
	if (!isStandard) {
		$('#nav_left #navLevel1 > li > ul > li.expandable:not(.on) > ul').hide();
	} else {
		$('#nav_left #navLevel1 > li > ul > li.expandable > ul').css('background', 'none').css('padding', '0');
	}
	
	isMoreDocs= ($('body').hasClass('links') || $('body').hasClass('documents') || $('body').hasClass('contact') || $('body').hasClass('contracts-grants'));
	
   if(!($('body').hasClass('sector')) && !isStandard && !isMoreDocs && !($('body').hasClass('newsroom-list-items'))) {
	$('#navLevel1 > li.expandable > a').live('click', function (e) {
		e.preventDefault();
		//when opening a collapsible menu, removes eventual class 'on'
		previouson = ($(this).parent().hasClass('on')) ? true : false;
		$(this).data('previouson', previouson);
		$('#navLevel1 li.expandable.on').removeClass('on');
		//when opening a collapsible menu, add class 'on'
		if (!$(this).data('previouson')) $(this).parent().addClass('on');
        //In case the menu is already opens, closes it
        if ($(this).next("li.expandable > ul:visible").length != 0) {
            $(this).next("li.expandable > ul").slideUp("normal");
        }
        //In case the menu is hidden, closes the other ones and opens it
        else {
            $("#navLevel1 > li.expandable > ul").slideUp("normal");
            $(this).next("li.expandable > ul").slideDown("normal");
        }
    });
	}
	
	$('#newsroom-nav > li.on.expandable > a').live('click', function(e){
		e.preventDefault();
		$(this).next().slideUp().parent().removeClass('on');
	});
	
	$('#newsroom-nav > li:not(.on) > a').live('click', function(e){
		e.preventDefault();
		$('#newsroom-nav').find(' > li.on').removeClass('on').find('ul:visible').slideUp('fast');
		$(this).next().slideDown('fast').parent().addClass('on');
	});
		
	$("li.empty").hide();
	
	
		
	
	/*SEARCH FIELD*/
	//Fade-out effect
	if($("#searchinp").length > 0) {
      $("#searchinp").attr('value', '');
      $("#searchinp").focus(function () {
			$(this).prev().fadeOut();
		});
		$("#searchinp").blur(function () {
			if($(this).val()=='') $(this).prev().fadeIn();
		});

      //Autocomplete
      $('#searchinp').simpleAutoComplete('/enterprise/search_'+$('html').attr('lang')+'.xml',{
   		autoCompleteClassName: 'autocomplete',
         selectedClassName: 'sel',
         attrCallBack: 'rel',
         identifier: 'searchinp'
      });


   }
 
	/* BOX multilang */
	$('.multilang').click(
		function(){
			$(this).children('span').fadeIn('slow');
		}
	);
	$('.multilang').mouseleave(
		function(){
			$(this).children('span').fadeOut('slow');
		}
	);

	/* FONT SIZE */
	$("#tools a").live('click', function(){
		switch (this.className) {
			case 'text_size_big':
				$('body').addClass('big');
				$('body.sector #media').height($('body.sector #intro > div').height());
				$("body.sector #events .inner, body.sector #publications .inner").equalHeights(409,1000);
				$("body.sector #contracts .inner, body.sector #consultations .inner").equalHeights(409,1000);
				break;
			case 'text_size_small':
				$('body').removeClass('big');
				$('body.sector #media').height($('body.sector #intro > div').height());
				$("body.sector #events .inner, body.sector #publications .inner").equalHeights(230,250);
				$("body.sector #contracts .inner, body.sector #consultations .inner").equalHeights(230,250);
				break;
		 }
	}
	);

	// Filtering lists according to categories
	$("#filterList").click(function()  { 
		var selection = $("#filterCat").val(); 

		if (selection == "all") { 
			$(".item").show(); 
		} else { 
			$(".item").hide(); 
			$("."+selection).show(); 
		} 
	}); 

	//opening security flash in a new window
	$("a.security-flash").click(function(e){
		e.preventDefault();
		window.open($(this).attr('href'),'_blank','width=1035,height=590');
	});
	
	//PNG TRANSPARENCY FOR IE6
	if($.browser.msie && ($.browser.version == '6.0'))	{
		DD_belatedPNG.fix('.homepage, .title, #content_content, #intro, .inner, #imageBanner, #news, .inner_inner, .inner_inner ul, .inner ul, #media, #events, #videos, #footer, #navLevel1 li a, #tools-menu li a, #publications, #contracts, #consultations, #text, #content_content ul li, .inner div, li.selected ul, li.selected ul li, li.selected ul li a, .newsroom-item, #more-docs li.expandable a');
	}

	//EVENTS COUNTER FOR SME-WEEK
	if(isSubsiteHP('/initiatives/sme-week/')) {
/*
		var tD = new Date();
		var mnth = new Array("01","02","03","04","05","06","07","08","09","10","11","12");
		var day = tD.getDate();
		if(day < 10) day = "0" + day;
		$("li.contact").after("<li class=\"events-counter\">Events published so far ("+day+"-"+mnth[tD.getMonth()]+"-"+tD.getFullYear()+"):<a title=\"Events list\" href=\"/enterprise/intsub/sme-week/index.cfm?fuseaction=sme.searchForm\"></a></li>");
		$("li.events-counter a").load("/enterprise/intsub/sme-week/index.cfm?fuseaction=sme.eventsCounter");
		$("span.events-counter").load("http://ec.europa.eu/enterprise/intsub/sme-week/index.cfm?fuseaction=sme.eventsCounter");
*/
		$("li>a[href^='/enterprise/intsub/sme-week/index.cfm?fuseaction=sme.searchForm']").append(' <span class="events-counter">[1476]</span>');
	}
/*	
	//GALILEO LAUNCH COUNTDOWN
	if(isInSubsite('/policies/satnav/') || $('body.homepage').length > 0) {
		var launchDate = new Date(2011,10-1,20,12,34,0);		// you have to substract 1 from months as this is a 0-11 value
		var language = document.getElementsByTagName("html")[0].getAttribute("lang");
		var noTranslation = ['en'];
		
		$('#galileoCount').countdown({until: launchDate, format: 'DHMS', compact: false, 
			layout:'<span class="countDays">{dl}</span>' +
			'<span class="countHours">{hl}</span>' +
			'<span class="countMinutes">{ml}</span>' +
			'<span class="countSeconds">{sl}</span>' +
			'<span class="image{d10}"></span><span class="image{d1}"></span>' + 
			'<span class="imageSpace"></span>' + 
			'<span class="image{h10}"></span><span class="image{h1}"></span>' + 
			'<span class="imageSep"></span>' + 
			'<span class="image{m10}"></span><span class="image{m1}"></span>' + 
			'<span class="imageSep"></span>' + 
			'<span class="image{s10}"></span><span class="image{s1}"></span>'});
		
		if($.inArray(language, noTranslation) > -1)
			$('#galileoCount').countdown($.countdown.regional[language]);
	}
*/	
	//GOOGLE ANALYTICS CODE FOR TRACKING CLICKS AND DOWNLOADS
	if(typeof(_gaq) != 'undefined') {
		if($('body.sector').length > 0) {		// sector HP
			addGAtoLinks('#intro a[href]', 'ENTR Website - page content');				// links in the content
			addGAtoLinks('#key-content a[href]', 'ENTR Website - key content box');		// links in the Key Content box
			addGAtoLinks('.newsroom-item a[href]', 'ENTR Website - newsroom box');		// links in newsroom boxes
			addGAtoLinks('.custom-content a[href]', 'ENTR Website - custom box');		// links in the custom box
		} else {								// any other page
			addGAtoLinks('#content_content a[href]', 'ENTR Website - page content');	// links in the content
			addGAtoLinks('#newsroom a[href]', 'ENTR Website - newsroom box');			// links in newsroom boxes
			addGAtoLinks('#nav_right a[href]', 'ENTR Website - right menu');			// links in the right menu (HP)
		}
	
	}
	/**
	 * NEWSLETTER
	 **/
	(function () {
		
		var options = '';
		
		$('#previous-issues').nextAll('.newsletter-issues').prev('h3').each( function () {
		
			options += '<option value="' + $(this).text() + '">' + $(this).text() + '</option>';
		
		}).remove();
		
		var html = '<p>' + $('#newsletter-browse').val() + '<select id="select-newsletter-year">' + options + '</select></p>';
		
		$('#previous-issues').after(html);
		
		$('#previous-issues').nextAll('.newsletter-issues').not(':eq(0)').hide();
		
		$('#select-newsletter-year').bind( 'change' , function () {
			
			$('#previous-issues').nextAll('.newsletter-issues').hide();
			
			$('#newsletter-' + $(this).val() ).show();
			
		});
		
	}());
	
	
	

});

// function that checks if the current page is the homepage of the given subsite
function isSubsiteHP(subsitePath) {
	var pos = location.pathname.indexOf(subsitePath);
	var len = subsitePath.length;
	var isHTM = /htm$/.test(location.pathname);
	
	if(pos > 0) {
		if(location.pathname.length - len == 11 || (location.pathname.substr(pos + len).length == 12 && isHTM))
			return true;
	}
	
	return false;
}

// function that checks if the current page is in the given subsite or below
function isInSubsite(subsitePath) {
	if(location.pathname.indexOf(subsitePath) > 0)
		return true;
	else
		return false;
}

function addGAtoLinks(linkSelector, addLabel) {
	$(linkSelector).not('#gallery a').not('a.popup-link').not('a.security-flash').click(function(e){
		e.preventDefault();
		var addr = $(this).attr('href');
		var link = classifyLink(addr);

		if(link != null)
			_gaq.push(['_trackEvent', link[0], link[1] + ' - ' + addLabel, addr]);
			
		if($(this).attr("target") == "_blank")
			window.open(addr);
		else
			setTimeout('document.location = "' + addr + '"', 100);
	});
}

function classifyLink(addr) {
	var linkType = '';
	var linkAction = '';

	if(addr.match(/^#/i))
		return null;
		
	if(addr.match(/enterprise/i) || (!addr.match(/^\//i)) && !addr.match(/^http/i))
		linkType = 'Link Internal';
	else
		linkType = 'Link External';

	if(addr.match(/\.(zip|exe|pdf|doc*|xls*|ppt*|flv|mp4|mov|jpg)$/i))
		linkAction = 'Download';
	else
		linkAction = 'Click';
		
	return new Array(linkType,linkAction);
}

// this function will parse xml and return as a array of string
function parseXML(xml) {
   var results = "";
   $.ajax({
      type: "GET",
      url: xml,
      dataType: "xml",
      success: function(x){
         $(x).find("item").each(function(){ results += $(this).text() + " "; });
         return results;
      }
   });
}

function findValue(li) {
   var sValue;
   if( li == null ) return alert("No match!");
   // if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) sValue = li.extra[0];
	// otherwise, let's just display the value in the text box
	else sValue = li.selectValue;

//   return alert("The value you selected was: " + sValue);
}

function selectItem(li) { findValue(li); }

function lookupAjax(){
   var oSuggest = $("#searchinp").autocompleter;
   oSuggest.findValue();
   return false;
}

function lookupLocal(){
	var oSuggest = $("#searchinp").autocompleter;
	oSuggest.findValue();
	return false;
}

//NEWSROOM
function load_dynamic_panel_v2(url, defaultUrl, panelId, substrAfterStartup, substrAfter, substrBefore, substrBeforeStartup, pLastIndexOfBefore, executeScript, pLoadingImg) {
	if(location.href.indexOf('wcmcom-ec-europa-eu-wip') == -1) {

		if(window.XMLHttpRequest) var xmlHttpReq = new XMLHttpRequest();
		else if (window.ActiveXObject) var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");

		xmlHttpReq.onreadystatechange = function set_dynamic_panel() {
			if (xmlHttpReq.readyState == 4) {
				var problem;
				if (xmlHttpReq.status != 200 && xmlHttpReq.status != 304) {
					/* error getting URL */
					problem = true;
				} else {
					problem = false;
					/* URL reached, search content */
					var response = xmlHttpReq.responseText;

					/* execute a substring-before and substring-after on the response if it's necessary */
					if(substrAfter != '') {
						if(substrAfterStartup != ''){
							if(response.indexOf(substrAfterStartup)>=0){
								response = response.substring(response.indexOf(substrAfterStartup), response.length);
							}
						}

						if(response.indexOf(substrAfter)>=0){
							response = response.substring(response.indexOf(substrAfter), response.length);
						}
						else {
							substrAfter = substrAfter.replace('&gt;', '>');
							substrAfter = substrAfter.replace('&lt;', '<');
							/*try in another format */
							if(response.indexOf(substrAfter, lIndex)>=0){
								response = response.substring(response.indexOf(substrAfter), response.length);
							}
							else
							{
								response = "";
							}
						}
					}
					if(substrBefore != '') {
						if(substrBeforeStartup != ''){
							if(response.indexOf(substrBeforeStartup)>=0){
								response = response.substring(0, response.lastIndexOf(substrBeforeStartup));
							}
						}

						if(response.indexOf(substrBefore)>=0) {
							if(pLastIndexOfBefore){
								response = response.substring(0, response.lastIndexOf(substrBefore));
							}
							else{
								response = response.substring(0, response.indexOf(substrBefore));
							}
						}
						else {
							substrBefore = substrBefore.replace('&gt;', '>');
							substrBefore = substrBefore.replace('&lt;', '<');
							/*try in another format */
							if(response.indexOf(substrBefore)>=0) {
								response = response.substring(0, response.indexOf(substrBefore));
							}
							else
							{
								response = "";
							}
						}
					}

					/*check if there's no error in the feed*/
					var errorMessage = response.indexOf('Newsroom error');
					if(errorMessage >= 0)
						problem = true;
					else {
						var pID = document.getElementById(panelId);
						if(pID) {
							var responseContainer = '<' + pID.tagName.toLowerCase() + ' id="' + panelId + '">';
							if(response.indexOf(responseContainer)!= -1) {
								response = response.replace(responseContainer, '');
								response = response.replace(response.lastIndexOf('</' + pID.tagName.toLowerCase() + '>'), '');
							}
//                  $("#"+panelId).html(response, function(){
//                     adaptFontSize('tab_panel_select');
//                     newsroomEqualHeights();
//                  });
							pID.innerHTML = response;
							setTimeout('newsroomEqualHeights()', 500);

							if(executeScript){
								/*extract javascript*/
								var lFlagScript = '<script language="JavaScript" type="text/javascript">';
								var lIndexScriptTag = response.lastIndexOf(lFlagScript);
								if(lIndexScriptTag >= 0) {
									/* skip variable declaration 'var' for compatibility with Internet Explorer 6 and ajax evaluation script */
									var localscript = response.substring(lIndexScriptTag+lFlagScript.length, response.lastIndexOf('</script>'));
									if(localscript!='')
										global.eval(localscript);
								}
							}
						}
					}
				}
				if (problem == true) {
					/* do something with problem*/
					$(panelId).addClassName('dynPanel_notFound')
					/*addClassName(panelId, "dynPanel_notFound");*/

					/* try with the default url */
					if(defaultUrl != '')
						return load_dynamic_panel_v2(defaultUrl, '', panelId, substrAfter, substrBefore);
					else
						return true;
					}
				}
			}
		var myRand=parseInt(Math.random()*99999999); // cache buster
		if(url.indexOf("?")>0){
			url= url + "&rand=" + myRand;
		}else{
			url= url + "?rand=" + myRand;
		}

		var lhtml = xmlHttpReq.open("GET", url, true);
		xmlHttpReq.setRequestHeader("Cache-Control", "no-cache");
		xmlHttpReq.send(null);
	}
}


/* SCRIPT  GLOSSARY & ACRONYM */
var glossary_mutex = false;

function glossary_closeAll(ContainerID) {
  if (!glossary_mutex) {
    glossary_mutex = true;
    var ContainerObject = document.getElementById(ContainerID);		
    if (ContainerObject) {
			var lListChild = ContainerObject.childNodes;			
   		for (var i = 0; i < lListChild.length; i++) {     
				if (lListChild[i].tagName == 'DL' && lListChild[i].parentNode.getAttribute('id') == ContainerObject.id) {
					lListChild[i].style.display = '';
				}                        			
			}
    }
    glossary_mutex = false;
  }
}

function glossary_showTab(ContainerID, dlID) {
  if (!glossary_mutex) {
    glossary_mutex = true;
    var ContainerObject = document.getElementById(ContainerID);		
    if (ContainerObject) {
			var lListChild = ContainerObject.childNodes;			
   		for (var i = 0; i < lListChild.length; i++) {
   			if (lListChild[i].tagName == 'DL' && lListChild[i].parentNode.getAttribute('id') == ContainerObject.id) {
					if(lListChild[i].id == dlID) {
						lListChild[i].style.display = 'block';
					}
				}
			}
		}
		glossary_mutex = false;
  }
}

function glossaryOpenTab(UlAlphabet, ContainerID, dlID) {
	glossary_closeAll(ContainerID);
	glossary_showTab(ContainerID, dlID);

	var ListeLi = [];
	ContainerObject = document.getElementById(UlAlphabet);
	ListeLi = ContainerObject.getElementsByTagName('a');
	for(var i = 0; i < ListeLi.length; i++) {
		ListeLi[i].className = '';
   }
	if(dlID!='') {
		document.getElementById('letter_'+dlID).className = 'on';
	}
}

function getIdUrlGlossary(UlAlphabet, ContainerID) {	
	var urlCourant = location.href;
	var indiceDepart = urlCourant.lastIndexOf('#')+1; // Plus 1 car on ne veut pas le '#'.
	var indiceArrivee = urlCourant.length;
	
	if(indiceDepart != 0) {
		var IdUrl = urlCourant.substring(indiceDepart, indiceArrivee);		
		this.location = "#";
		glossaryOpenTab(UlAlphabet, ContainerID, IdUrl);
	}
	else {
		var ListeLi = [];
		ContainerObject = document.getElementById(UlAlphabet);
		ListeLi = ContainerObject.getElementsByTagName('a');
		glossaryOpenTab(UlAlphabet, ContainerID, ListeLi[0].id.substring(7,8));		
	}
}

function getQuery() {
	var url = '' + window.location;
	var queryStart = url.indexOf('?') + 1;
	if (queryStart > 0) {
	var parts = url.substr(queryStart).split('&');
	for (var i = 0; i < parts.length; i++) {
		if (parts[i].substr(0, 1) == 'q') {
		//alert(decodeURI(parts[i].split('=')[1].replace(/\+/g, ' ')));
		return decodeURI(parts[i].split('=')[1].replace(/\+/g, ' '));
		}
	}
	}
	return '';
}


/* SITEMAP */

function doSiteMap(sID){
	var imgCollapsed	= '/enterprise/images/sitemap-collapsed.gif';
	var imgExpanded		= '/enterprise/images/sitemap-expanded.gif';
	var imgAlt				= 'expand/collapse this entry';
	var imgClass			= 'col-exp';

	var sitemap = document.getElementById(sID);
	if(sitemap) {
		this.listItem = function(li) {
			if(li.getElementsByTagName('ul').length > 0) {
				var ul = li.getElementsByTagName('ul')[0];
				ul.style.display = 'none';
				var img = document.createElement('img');
				img.src = imgCollapsed;
				img.alt = imgAlt;
				img.className = imgClass;
				if(sID!='sitemap'){
					li.onclick = function() {
						if( ul.style.display == 'none' ) {
							var lListChild = sitemap.getElementsByTagName('ul');
				      for(var j = 0; j < lListChild.length; j++) {
								lListChild[j].style.display = 'none';
							}
							var lImgChild = sitemap.getElementsByTagName('img');
				      for(var k = 0; k < lImgChild.length; k++) {
								lImgChild[k].src = imgCollapsed;
							}
							if(sID == 'sectors-contacts-1' || sID == 'sectors-contacts-2') {
								var sectorbis = '';
								if(sID == 'sectors-contacts-1') { sectorbis = 'sectors-contacts-2' }
								else { sectorbis = 'sectors-contacts-1'; }
								var sectorbisc = document.getElementById(sectorbis);
								var lListChildSectors = sectorbisc.getElementsByTagName('ul');
					      for(var l = 0; l < lListChildSectors.length; l++) {
									lListChildSectors[l].style.display = 'none';
								}
								var lImgChildSectors = sectorbisc.getElementsByTagName('img');
					      for(var m = 0; m < lImgChildSectors.length; m++) {
									lImgChildSectors[m].src = imgCollapsed;
								}
							}
						}
						ul.style.display = (ul.style.display == 'none') ? 'block' : 'none';
						img.src = (ul.style.display == 'none') ? imgCollapsed : imgExpanded;
					}
				} else {
					img.onclick = function() {
						$(this).parent().children("ul").each(function(){
							if ($(this).css('display')=='none') {
								$(this).css('display', 'block');
							} else {
								$(this).css('display', 'none');
							}
						})
						img.src = ($(this).prev().css('display') == 'none') ? imgCollapsed : imgExpanded;
					}
				}
				li.appendChild(img);
			}
		}

		var items = sitemap.getElementsByTagName('li');
		for(var i=0; i<items.length; i++) {
			listItem(items[i]);
		}
	}
}


/* GLOSSARY ENTRIES: displays glossary items in content pages */

function openInternalItem(url, defaultURL, subAfter, subAfterId, subBefore, seeker) {
	stop = false;
	var isIE = (navigator.userAgent.indexOf("MSIE") != -1) ? true : false;
	if (!isIE) document.captureEvents(Event.CLICK);
	document.onclick = getMouseXY;
	var tempX;
	var tempY;

	function getMouseXY(e) {
		if (isIE) {
	  	tempX = event.clientX + document.body.scrollLeft;
	    tempY = event.clientY + document.body.scrollTop;
	  } else {
	  	tempX = e.pageX;
	    tempY = e.pageY;
	  }  
	  if(stop == false) {
			if (isIE) tempY += topPosition();
	  	insert_AjaxRequest(url, defaultURL, subAfter, subAfterId, subBefore, seeker, tempX-136, tempY-105);
	  	stop = true;
	  }
	}
}

function insert_AjaxRequest(url, defaultURL, subAfter, subAfterId, subBefore, seeker, posX, posY) {
  /* build the new container */
	var isIE = (navigator.userAgent.indexOf("MSIE") != -1) ? true : false;
	var newContainerTag = 'div';
	var newContainerId = 'ajax-item';
	var innerNewContainerId = '<div id="ajax-bottom">';
	var newContainerClassName = '';
	var newContainerWidth = 300;
	var hScroll = (posX + newContainerWidth > pageWidth()) ? true : false;
	if(hScroll) {
		posX = posX - newContainerWidth - 15;
		newContainerClassName = 'reverse';
	}
	var posTop = posY + 'px';
	var posLeft = posX + 'px';
	var newContainer = '<'+ newContainerTag + ' id="' + newContainerId + '" class="'+ newContainerClassName +'" style="top: ' + posTop + '; left: ' + posLeft + '">';
	var closeImg = '<img id="close-ajax" src="/enterprise/images/close.jpg" onclick="closeInternalItem(\'' + newContainerId + '\')" />';
	var divInOnclick = '\'</div>\'';
	var sameBox = false;
	var aboveSeeker = seeker.parentNode;
	while(aboveSeeker) {
		if (aboveSeeker.id) {
			if(aboveSeeker.id.indexOf('ajax-')!=-1) sameBox = true;
		}
		aboveSeeker = aboveSeeker.parentNode;
	}
	/* load the content of the page and paste it into the new container */	
	var xhr = null;
	if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
	else if (window.ActiveXObject) xhr = new ActiveXObject("Microsoft.XMLHTTP");

	xhr.onreadystatechange = function dyn_insert(){
		if(xhr.readyState == 4) {
			var error_getting_url;
			if (xhr.status != 200 && xhr.status != 304) {
				var error_getting_url = true;
			}
			else {
				if(xhr.responseText.indexOf('id="'+subAfterId+'"')==-1) {
					error_getting_url = true;
				}
				else {
					error_getting_url = false;
					if(!sameBox) closeInternalItem(newContainerId);

					var response = xhr.responseText;
					if(subAfterId != '') {
						var tmp = subAfter;
						tmp = tmp.replace('>', '');
						subAfter = tmp + ' id="' + subAfterId + '">';
					}
					if(subAfter != '') {
						response = response.substring(response.indexOf(subAfter), response.length);
						response = response.replace(subAfter, '');
					}
					if(subBefore != '') {
						var exception = response.substring(response.lastIndexOf(divInOnclick), response.length);
						if(exception != response) {
							exception = exception.replace(divInOnclick, '');
							exception = exception.substring(0, exception.indexOf(subBefore));
							var content_before = response.substring(0, response.indexOf(divInOnclick));
							response = content_before + divInOnclick + exception;
						}
						else response = response.substring(0, response.indexOf(subBefore));
					}
					var c_main = document.getElementById('content_main');
					var insert = newContainer + innerNewContainerId + response + closeImg + '</div></' + newContainerTag + '>';
					if(!sameBox) {
						c_main.innerHTML += insert;
					} else {
						document.getElementById(newContainerId).innerHTML = innerNewContainerId + response + '</div>' + closeImg;	 
					}
				}
			}
		}
		if (error_getting_url == true) {
			if(defaultURL != '') return insert_AjaxRequest(defaultURL, '', subAfter, subAfterId, subBefore, sameBox, posX, posY);
			else return true;
		}
	}
	/* anti-cache system */
	var myRand=parseInt(Math.random()*99999999);
	if(url.indexOf("?")>0) {url = url + "&rand=" + myRand;}
	else {url = url + "?rand=" + myRand;}
	
	var targetHTML = xhr.open("GET", url, true);
	xhr.setRequestHeader("Cache-Control", "no-cache");
	xhr.send(null);
}

function closeInternalItem(createdContainerId) {
	var existingItem = document.getElementById(createdContainerId);
	if(existingItem) existingItem.parentNode.removeChild(existingItem);
}

function homeFlash(id) {
   var vid = $('#'+id).find('a').attr('href');
   var vidpic = vid.replace('.flv', '.jpg');
	var s1 = new SWFObject('http://ec.europa.eu/wel/players/jwflvplayer/player.swf','player','400','320','9');
	s1.addParam('allowfullscreen','true');
	s1.addParam('allowscriptaccess','always');
	s1.addParam('allownetworking','all');
	s1.addParam('wmode','opaque');
	s1.addParam('flashvars','&file='+vid+'&image='+vidpic+'&plugins=../../../../enterprise/flash/jw-plugins/gapro-1.swf&gapro.accountid=UA-16319747-1');
	s1.write(id);
}

function loadDynamicLink(url, targetId) {
	if(location.href.indexOf('wcmcom-ec-europa-eu-wip') == -1) {
		if(window.XMLHttpRequest) var xmlHttpReq = new XMLHttpRequest();
		else if (window.ActiveXObject) var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");

		xmlHttpReq.onreadystatechange = function dyn() {
			if (xmlHttpReq.readyState == 4) {
				var problem;
				if (xmlHttpReq.status != 200 && xmlHttpReq.status != 304) {
					problem = true;
				} else  {
					problem = false;
					var response = xmlHttpReq.responseText;
					//var xmlDoc=xmlHttpReq.responseXML;

					var rssTag = '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">';
					var isRSS = (response.indexOf(rssTag)!=-1) ? true : false;

					if(isRSS) {
						var rssItemSTag = '<item>';
						var rssItemETag = '</item>';
						var dummy = response.substring(0, response.indexOf(rssItemSTag));
						response = response.replace(dummy, '');
						var nbItems = response.split(rssItemSTag).length - 1; 
						var items = new Array(nbItems);
						var toInsert, item, lL, lT, lD;
						toInsert = '';
						for(i=0; i<nbItems; i++) {
							item = response.substring(response.indexOf(rssItemSTag), response.length);
							item = item.substring(0, item.indexOf(rssItemETag));
							items[i] = item.replace(rssItemSTag, '');
							response = response.replace(rssItemSTag+items[i]+rssItemETag, '');

							lL = items[i].substring(items[i].indexOf('<link>'), items[i].length);
							lL = lL.substring(0, lL.indexOf('</link>'));
							lL = lL.replace('<link>', '');
							lT = items[i].substring(items[i].indexOf('<title>'), items[i].length);
							lT = lT.substring(0, lT.indexOf('</title>'));
							lT = lT.replace('<title>', '');
							lD = items[i].substring(items[i].indexOf('<description>'), items[i].length);
							lD = lD.substring(0, lD.indexOf('</description>'));
							lD = lD.replace('<description>', '');
							lD = cleanRSSitem(lD);
							items[i] = '<div class="rss-item"><h3><a href="'+lL+'" target="_blank" title="'+lT+'">'+lT+'</a></h3>'+lD+'</div>';
							toInsert += items[i];
						}
						response = toInsert;
					}
					var pID = document.getElementById(targetId);
					pID.innerHTML = response;
				}
			}
			if(problem==true) document.getElementById(targetId).className += ' nofound';
		}
		var myRand=parseInt(Math.random()*99999999); // cache buster
		if(url.indexOf("?")>0) url= url + "&rand=" + myRand;
		else url= url + "?rand=" + myRand;
		
		var lhtml = xmlHttpReq.open("GET", url, true);
		xmlHttpReq.setRequestHeader("Cache-Control", "no-cache");
		xmlHttpReq.send(null);
}
}

function pageHeight() {return window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;}
function topPosition() {return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;}
function pageWidth() {return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;}
function leftPosition() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;}
function leftPosition() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;}

function jumpMenu(item){location.href=item;}

jQuery(window).resize( function($) {
	stickyBody();
});

function stickyBody() {
	if ($(window).height() < $('#top').height()) {
		$('body').css({'height': 'auto'});
		
	} else {
		winH = $(window).height(); 
		$('body').css('min-height',winH+'px');
	}
}

jQuery.fn.sitemap = function() {
	return this.each(function(){
		var $tree = $(this);
    var $li = $tree.children('li');
		$tree.addClass('tree');
		//hide all lists inside of main list by default
		$tree.find('ul').hide();
		
		//iterate through all list items
		$li.each(function(){
			//if list-item contains a child list
			if ($(this).children('ul').length > 0) {
				//add expand/collapse control
				$(this).addClass('expandable').prepend('<span class="expand" />');
			}
		}); //end .each
		
		//handle clicking on expand/collapse control
		$('span.expand').toggle(
			//if it's clicked once, find all child lists and expand
			function(){
				if($.browser.msie) {
					$(this).toggleClass('collapse').nextAll('ul').show();
				} else {
					$(this).toggleClass('collapse').nextAll('ul').slideDown();
				}
			},
			//if it's clicked again, find all child lists and contract
			function(){
				if($.browser.msie) {
					$(this).toggleClass('collapse').nextAll('ul').hide();
				} else {
					$(this).toggleClass('collapse').nextAll('ul').slideUp();
				}
			}
		);
	});
};
