if(window.YAHOO) {
	var windowHeight = YAHOO.util.Dom.getViewportHeight;
	var windowWidth =  YAHOO.util.Dom.getViewportWidth;
	var cookieYUI = YAHOO.util.Cookie;
	var $ = YAHOO.util.Dom.get;
	var $$ = YAHOO.util.Selector.query;	
}

var $lambda = function (value){
	return (typeof value == 'function') ? value : function(){
		return value;
	};
};

var $E = function() {
	var results = [];
    var args = Array.prototype.slice.call(arguments);

    args.forEach(function(selector) {
		results = results.concat($$(selector));
	});
	
	return results;
};

String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

String.prototype.capitalize = function() {
	return this.replace(/\b[a-z]/g, function(match){
		return match.toUpperCase();
	});
};

String.prototype.toInt = function(base) {
	return parseInt(this, base || 10);
};

Function.prototype.bind = function(bind, arguments) {
	var self = this;
	
	return function() {
		self.apply(bind, arguments);
	}
};

if (!Array.prototype.forEach) {
	Array.prototype.forEach = function(fn, bind) {
		for (var i = 0, l = this.length; i < l; i++){
			if(i in this) { fn.call(bind, this[i], i, this);}
		}
	};
}

if (!Array.prototype.map) {
	Array.prototype.map = function(fn, bind) {
		var results = [];
		for (var i = 0, l = this.length; i < l; i++) {
			if(i in this) { results[i] = fn.call(bind, this[i], i, this);}
		}
		return results;
	};
}

if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(elt /*, from*/) {
    	var len = this.length >>> 0;
	    var from = Number(arguments[1]) || 0;
	
	    from = (from < 0) ? Math.ceil(from) : Math.floor(from);
	    if (from < 0) from += len;

	    for (; from < len; from++) {
	        if (from in this && this[from] === elt) return from;
	    }
    	return -1;
  };
}

if (!Array.prototype.filter) {
	Array.prototype.filter = function(fun /*, thisp*/){
    	var len = this.length >>> 0;
		if (typeof fun != "function") throw new TypeError();

		var res = new Array();
		var thisp = arguments[1];
		for (var i = 0; i < len; i++) {
			if (i in this) {
				var val = this[i]; // in case fun mutates this
				if (fun.call(thisp, val, i, this)) res.push(val);
			}
		}
    	return res;
	};
}

function carousel(id, params) 
{
	this.id = id;
	this.params = params || {};
	this.panels = [];
	this.controls = [];
	this.controls_colors = { inactive : '#505050', active : '#ffffff' };
	this.panel_number_overlay = [];
	this.effect_time = this.params ? this.params.effect_time || 0.3 : 0;
	this.appear_time = this.params ? this.params.appear_time || 1 : 0;
	this.active_panel_idx = this.params ? this.params.active_panel_idx || 0 : 0;
	this.carousel_animation = null;
	this.carousel_animation_time = 5000;
	this.is_busy_flag = 0;
	this.is_running = 1;
	
	this.init = function()
	{
		this.panel_number_overlay = YAHOO.util.Selector.query('#' + this.id + ' div.carousel_panel_number_overlay');
		this.controls = YAHOO.util.Selector.query('#' + this.id + ' div.carousel_nav a');
		this.panels = YAHOO.util.Selector.query('#' + this.id + ' div.carousel_panel');
		
		this.move(this.controls[this.active_panel_idx + 1]);
		
		for(i = 0; i < this.controls.length; i++)
		{
			var carouselInstance = this;
			var control = this.controls[i];
			
			YAHOO.util.Event.addListener(control, "click",
				function()
				{
					carouselInstance.is_running = 0;
					carouselInstance.move(this);
					this.blur();
				}
			);
		}
	};
	this.run = function()
	{
		this.move(this.controls[this.controls.length-1]);
	};
	this.is_busy = function(status)
	{
		var self = this;
		this.is_busy_flag = status;
		if(this.is_running)
		{
			this.carousel_animation = setTimeout(
				function()
				{
					self.run();
				},
				this.carousel_animation_time
			);
		}
	};
	this.hide = function(panel)
	{
		YAHOO.widget.Effects.Fade(this.panels[panel]);
		
	};
	this.move = function(control)
	{
		if(!this.is_busy_flag)
		{
			this.is_busy(1);
			clearTimeout(this.carousel_animation);
			
			for(i = 0; i < this.controls.length; i++)
			{
				YAHOO.util.Dom.setStyle(this.controls[i], 'color', this.controls_colors.inactive);
			}
			
			var panel_idx;
			if(control.className.indexOf("prev") > 0)
			{
				panel_idx = this.active_panel_idx - 1 >= 0 ?  this.active_panel_idx - 1 : this.panels.length - 1;
			}
			else if(control.className.indexOf("next") > 0)
			{
				panel_idx = this.active_panel_idx + 1 < this.panels.length ?  this.active_panel_idx + 1 : 0;
			}
			else
			{
				panel_idx = parseInt(control.className.replace(/\D/g,'')) - 1;
			}
			YAHOO.util.Dom.setStyle(this.controls[panel_idx + 1], 'color', this.controls_colors.active);
			
			var panel_number_overlay =
			{
				width : { to : parseInt(YAHOO.util.Dom.getStyle(this.controls[panel_idx + 1], 'width')) },
				height : { to : parseInt(YAHOO.util.Dom.getStyle(this.controls[panel_idx + 1], 'height')) },
				top : { to : parseInt(YAHOO.util.Dom.getStyle(this.controls[panel_idx + 1], 'top')) },
				left : { to : parseInt(YAHOO.util.Dom.getStyle(this.controls[panel_idx + 1], 'left')) }
			}
			var move_panel_number_overlay = new YAHOO.util.Anim(this.panel_number_overlay[0].id, panel_number_overlay, this.effect_time);
			move_panel_number_overlay.animate();
			var carouselInstance = this;
			move_panel_number_overlay.onComplete.subscribe(function(){carouselInstance.is_busy(0)});
			
			for(i = 0; i < this.panels.length; i++)
			{
				YAHOO.util.Dom.setStyle(this.panels[i], 'visibility', 'hidden');
			}
			YAHOO.util.Dom.setStyle(this.panels[panel_idx], 'visibility', 'visible');
			YAHOO.widget.Effects.Appear(this.panels[panel_idx],{seconds:this.appear_time});
			this.active_panel_idx = panel_idx;
		}
	};
}

function initCarousel(id)
{
	if(document.getElementById(id))
	{
		if(!YAHOO.carousels)
		{
			YAHOO.carousels = {};
		}
		YAHOO.carousels[id] = new carousel(id);
		YAHOO.carousels[id].init();
	}
}

function modal(id, params)
{
	var self = this;
	this.id = id;
	this.params = params || {};
	this.url = document.getElementById(this.id).href;

	/* récupère le contenu à afficher */
	this.init = function()
	{
		var request = YAHOO.util.Connect.asyncRequest('GET', this.url, { success : this.show } );
	}
	
	this.show = function(o)
	{
		if(o.responseText !== undefined)
		{
			self.content = o.responseText;
			self.modal = new YAHOO.widget.Panel(self.id + "_modal",
						 {
						 	width : self.params.width + "px",
							height : self.params.height + "px",
							fixedcenter : true,
						 	constraintoviewport : true,
							underlay : "none",
							close : false,
							visible : true,
							draggable : false,
							modal : true,
							zindex : 1000
						 } );
		}
		self.modal.setBody(self.content);
		self.modal.render(document.body);
		
		self.close_link = YAHOO.util.Selector.query('#' + self.id + '_modal a.ModalClose');
		
		YAHOO.util.Event.addListener(self.close_link, "click", self.hide);
	}
	this.hide = function()
	{
		self.modal.hide();
	}
	this.init();
}

function openModal(id,width,height)
{
	new modal(id, {width:width, height:height});
}


// JavaScript Document
var isIE=navigator.appName.indexOf("Explorer")!=-1;
var isNN6=!document.all && document.getElementById;
var isNN4=!isIE && !isNN6;
var browser=navigator.appName;
var b_version=navigator.appVersion;
var navig_version=parseFloat(b_version);
var nbrFilters=4;


function initGenLoader(){
	var myHeight = windowHeight();
	var loaderheight = YAHOO.util.Dom.getStyle($('genloader'), 'height').toInt();
	document.getElementById("genloader_shadow").style.height=YAHOO.util.Dom.getDocumentHeight() + "px";
	document.getElementById("genloader").style.top = YAHOO.util.Dom.getViewportHeight() / 2 + loaderheight + "px";
}

function displayGenLoader(){
	if(document.getElementById("genloader") && document.getElementById("genloader_shadow")) {
		document.getElementById("genloader").style.display ='block';
		document.getElementById("genloader_shadow").style.display ='block';
	}
}

function hideGenLoader(){
	if(document.getElementById("genloader") && document.getElementById("genloader_shadow")) {
		document.getElementById("genloader").style.display ='none';
		document.getElementById("genloader_shadow").style.display ='none';
	}
}


/*N'affiche la partie "Téléchargement de toolbar" qu'avec IE*/
function showSearhToolbar(){
	if ((browser=="Microsoft Internet Explorer") && (navig_version>=4)){
		try {
			if(document.getElementById("euro_tools_home"))
				document.getElementById("euro_tools_home").style.display = "block";
			if(document.getElementById("euro_tools_result"))
				document.getElementById("euro_tools_result").style.display = "block";	
		}catch(e){}
	}
}

/**
 * Recuperer la position de l'objet passé en paramètre
 * @param {Object} obj : objet passé en paramètre
 */
function findPos(obj){
   var curleft = curtop = 0;
   if (obj && obj.offsetParent){
       curleft = obj.offsetLeft;
       curtop = obj.offsetTop;
       while (obj = obj.offsetParent){
	   curleft += obj.offsetLeft;
	   curtop += obj.offsetTop;
       }
   }
   return [curleft,curtop];
}
/**
 * 	Positionnner un objet par rapport a un autre
 *  @param {Object} parent_id : id du conteneur
 *  @param {Object} child_id : id du contenu
 *  @param {Integer} pas obligatoire: longueur ajoutée sur le paramètre top
 *  @param {Integer} pas obligatoire: longueur ajoutée sur le paramètre left
 */
function positionBox(parent_id,child_id,more_top,more_left){
	if( more_top == null || more_top == '')
		more_top =0;
	if( more_left == null || more_left == '')
		more_left =0;
	if( ($(parent_id) != null) && ($(child_id) != null)) {		
	    var parent_id1 = document.getElementById(parent_id);
	    var pos1 = findPos(parent_id1);
		$(child_id).style.top = ( pos1[1]+ more_top )+ "px";
	   	$(child_id).style.left = (pos1[0]+ more_left) + "px";
		$(child_id).style.display= 'block';
	}	
	return true;	
	
}
function openPopup(URL,winName,width_pop,height_pop,scroll)
{	
	var top_pop, left_pop;
	var b_version1=navigator.appVersion;
	var navig_version1=b_version1.indexOf("MSIE 6.0");
	
	if(navigator.appName=="Microsoft Internet Explorer") {	
		top_pop = window.screenTop;
		left_pop = window.screenLeft;
	} else {
		top_pop = window.screenY;
		left_pop = window.screenX;
	}
	if(scroll=='') scroll ='no';
	
	top_pop = top_pop + (windowHeight() - height_pop) / 2;
	left_pop = left_pop + (windowWidth() - width_pop) / 2;
	window.open(URL,winName,'toolbar=no ,resizable=yes,directories=no, location=no, width='+width_pop+', height='+height_pop+', top='+top_pop+ ', left='+left_pop+ ',status=no, scrollbars='+scroll+', menubar=no');
} 

/**
 * fonction qui cache ou montre un bloc 
 * @param {Object} idElement
 * @param (Object) displ : pour savoir si on met l'élément inline ou block
 */
function cacheBlock(id) {	
	var el = $(id);
	if(el){
		el.style.display = (el.style.display == 'block' ? 'none' : 'block' );
		return true;
	}
}
/**
 * Cache les liens du footer avec les id homepage_link et searchbar_link 
 */
function displayLinkFooter(id1,id2){
	/* set home page undisplay for firefox */
	if( document.getElementById(id1) && (navigator.appName !="Microsoft Internet Explorer" ))
		document.getElementById(id1).style.display="none";
	if( document.getElementById(id2) && (navigator.appName !="Microsoft Internet Explorer" ))
		document.getElementById(id2).style.display="none";	
}
/**
 * @param {String} targ
 * @param {String} selObj
 * @param {String} restore
 */
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}


/**
 * @name FilterManager
 */

var FilterManager = function(conditions) {
	this.conditions = conditions || [];
};

FilterManager.prototype.add_condition = function(condition) {
	this.conditions.push(condition);
	return this.sort_conditions();
};

FilterManager.prototype.sort_conditions = function() {
	return this.conditions
	.sort(function(a, b){
		return a.priority > b.priority;
	})
	.filter(function(condition){
		return condition.expression() === true;
	});
};

FilterManager.prototype.run_condition = function() {
	this.sort_conditions();
	return this.sort_conditions()[0].value();
};


/**
 * @name FontsizeManager
 */


var FontsizeManager = function (base, options) {
	this.base = $(base);
	this.current_size = 0;
	this.options = options || {
		sizes : ['', '80%', '95%', '105%']
	};
	
	this.load();
};

FontsizeManager.prototype.increase = function() {
	return this.set(1);
};

FontsizeManager.prototype.decrease = function() {
	return this.set(-1);
};

FontsizeManager.prototype.set = function(size) {
	if(this.size_in_range(this.current_size + size)) {
		this.apply(this.current_size + size);
		this.save();
		return true;
	}
};

FontsizeManager.prototype.size_in_range = function() {
	var predicate = this.current_size + arguments[0];
	return predicate > -1 && predicate <= this.options.sizes.length + 1;
};

FontsizeManager.prototype.apply = function(size) {
	this.current_size = size;
	YAHOO.util.Dom.setStyle(this.base, 'font-size', this.options.sizes[size]);
};

FontsizeManager.prototype.load = function() {
	var size = cookieYUI.getSub('Europages', 'FontSize') || '0';
	this.apply(size.toInt());
};

FontsizeManager.prototype.save = function() {
	cookieYUI.setSub('Europages', 'FontSize', this.current_size, {path : '/', domain : location.hostname});
};

function initCookies(){
	if(!cookieYUI)  
		cookieYUI=YAHOO.util.Cookie;
	if(cookieYUI.getSub("EuropagesCook","Filter")!=null)
			cookieYUI.removeSub("EuropagesCook","Filter"); 	
			
}

function displayFilter(filter){
	var panel = $E('.' + filter)[0];
	if(panel)
		formfilterAccordion.openPanel($E('.yui-accordion-panel').indexOf(panel));
}

function updateFilterCookie(filter_id){
	cookieYUI.setSub("Europages", "FilterID", filter_id, {path : '/', domain : location.hostname.split(/\.(.*)/)[1]});
}


/*Envoie du form nameForm et mise à jour du cookie via num (utiliser dans la pagination et Filter )
@param {string}: nameForm
TODO update this
*/
function submitSearchForm(nameForm, mode){
	displayGenLoader();
	
	if(mode)
		updateFilterCookie(mode)
	else
		cookieYUI.removeSub("Europages","FilterID")

	document.forms[nameForm].submit();
}
/*Si submit valide, appel de submitSearchForm
@param {String} id de l'input
@param {String} event.keyCode
*/
function validSearchForm(id,keycode){
 	if(keycode=='13' && document.getElementById(id).value!=''){
 		if(id.indexOf("querystring")!=-1) 
 			submitSearchForm(document.getElementById(id).form.name, "by_type");
 		else
 			submitSearchForm(document.getElementById(id).form.name, null);
 	}
	return false;
}


function initSizeManager() {	
	var fsmanager = new FontsizeManager('table_list');
	
	YAHOO.util.Event.on($E('li.puce_aplus')[0], 'click', fsmanager.increase.bind(fsmanager));
	YAHOO.util.Event.on($E('li.puce_aminus')[0], 'click', fsmanager.decrease.bind(fsmanager));
}

function initFilters(){
	//This rule select all <a> and <input> that will modifiy the state of the application
	$$('#filtersform div table:first-child td > *').forEach(function(element){
		YAHOO.util.Event.on(element, 'click', function(){
			var parent_panel = YAHOO.util.Dom.getAncestorByClassName(this, formfilterAccordion.CLASSES.PANEL);
			var filter_name = parent_panel.className.match(/by_[^\s]+/)[0];
			updateFilterCookie(filter_name);
		});
	});
	
	$$('a.keyword').forEach(function(element){
		YAHOO.util.Event.on(element, 'click', function(){
			updateFilterCookie('by_type');
		});
	});
	
	$$('.yui-accordion-toggle').forEach(function(element) {
		YAHOO.util.Event.on(element, 'click', function(){
			YAHOO.util.Dom.removeClass($('filtersform'), 'unfolded');
		});
	});
	
	YAHOO.util.Event.on($('less_choices'), 'click', function(){
		YAHOO.util.Dom.removeClass($('filtersform'), 'unfolded');		
	});
	
	YAHOO.util.Event.on($('more_choices'), 'click', function(){
		YAHOO.util.Dom.addClass($('filtersform'), 'unfolded');
	});
	
	var filter_id = cookieYUI.getSub("Europages","FilterID");
	var manager = new FilterManager([
		{
			'expression' : $lambda($E('.by_type')[0] == null),
			'value' : $lambda('by_country'),
			'priority' : 1,
			'description' : 'Type filter does not exists so open the country filter'
		},
		{
			'expression' : $lambda($E('.by_type')[0] != null),
			'value' : $lambda('by_type'),
			'priority' : 1,
			'description' : 'Type filter exists so open it'
		},
		{
			'expression' : $lambda(!Europages.international_query),
			'value' : $lambda('by_country'),
			'priority' : 0,
			'description' : 'An national query was done so open the country filter'
		}
	]);
	
	if(!Europages.international_query || filter_id == null || $E('.by_type')[0] == null) {
		updateFilterCookie(manager.run_condition());
	}
	displayFilter(cookieYUI.getSub("Europages","FilterID"));
}

function attachBusinessSectorEvents() {
	$E('#menudxsearch a[rel=tag]','#menudxsearch input[name^=heading]','#allsector').forEach(function(element) {
		YAHOO.util.Event.on(element, 'click', function() {
			updateFilterCookie('by_country');
			if(this.rel == 'tag') {
				window.scrollTo(0,0);
			}
		});
	});
}

function onloadCommon() {
	displayLinkFooter('homepage_link','searchbar_link');
	showSearhToolbar();	
	initGenLoader();
	YAHOO.util.Event.on(window, 'resize', initGenLoader);
	YAHOO.util.Event.on(window, 'submit', displayGenLoader);
}

function onloadBusinessSector() {
	onloadCommon();
	attachBusinessSectorEvents()
}

function onloadHome(){
	onloadCommon();
	if($('edito')) { initCarousel('edito'); }
}

function onloadSearchPage(){
	onloadCommon();
	if($('filtersform')) { initFilters(); }
	if($('table_list')) { initSizeManager(); }
	
	if($('block_unit6') && $('box_unit6'))	positionBox('block_unit6','box_unit6');
}