// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};

// Rafraichissement du comportement du site (apres requete ajax par exemple)
function refreshSiteBehaviour(containerId) {
	try {tbx_init_all(containerId);}catch(e){}
	try {tb_init_all(containerId);}catch(e){}
}

// Transformation libellé en libellé compatible Xiti
function xitify(lib) {
	var xitiLib = lib.toLowerCase();
	xitiLib = xitiLib.replace(/[éêèë]/g,"e").replace(/[îïí]/g,"i").replace(/[àâäãá]/g,"a").replace(/[úùüû]/g,"u").replace(/[ôóòõ]/g,"o").replace(/ç/g,"c").replace(/\+/g,"plus").replace(/[^a-z,0-9,-,:]/g, "_");
	return xitiLib;
}

var host = window.location.host || window.location.hostname;

$(document).ready(function() {

	var carousel_selection = null;

	if(typeof jQuery('a.tooltip').tooltip == 'function') {
		jQuery('a.tooltip').tooltip({
			track: false,
			delay: 0,
			fade:200,
			showURL: false,
			opacity: 1,
			showBody: " # ",
			fixPNG: true,
			left: -100,
			top: 1
		});
	} 

	$('a.blank').each(function(){$(this).attr('target','_blank');});
	$('a[href^=http]').not('[href*=' + host + ']').not('[href*=TB_]').attr('target','_blank');
	$('a[href^=/catalogue/][href$=/index.htm]').attr('target','_blank');
	
	// Placement des sous menu
	offset_menu = $('#menu').offset();
	$('#menu ul.menu li ul.ssmenu').each(function(){
		if(!$(this).hasClass('noauto')) {
			offset_this = $(this).parent().offset();
			offset = offset_this.left - offset_menu.left; // 0
			lr_width = ($(this).width() - $(this).parent().width()) / 2;
			if( lr_width > offset )
				lr_width = offset - 19;
			
			right_max = $('#menu').width() - offset - $(this).parent().width();
			if( lr_width > right_max )
				$(this).css({'left':'auto','right':(-right_max)});
			else
				$(this).css('left',-lr_width);
		}
	});
	
	if ($('#menu').length) {
		$('#menu .garanties-neuf').append( $('#menu .habiter-devenir-proprietaire > *') );
		$('#menu .habiter-devenir-proprietaire').remove();
		
		$('#menu .habiter-financer-logement-prets-bancaires').append( $('#menu .habiter-epargne-logement > *') );
		$('#menu .habiter-epargne-logement').append( $('#menu .habiter-financements-aides > *') );
		$('#menu .habiter-financements-aides').append( $('#menu .habiter-calculettes > *') );
		$('#menu .habiter-calculettes').remove();
		
		$('#menu .investir-neuf-comment-investir').append( $('#menu .investir-neuf-pourquoi-investir > *') );
		$('#menu .investir-neuf-pourquoi-investir').remove();
		
		$('#menu .investir-home-offre-nattendez-plus').append( $('#menu .investir-home-offre-preparez-retraite > *') );
		$('#menu .investir-home-offre-preparez-retraite').remove();
		
		$('#menu ul.menu > *').hover(function(){
			$(this).find('ul.ssmenu').show();
			var max_height = 0;
			
			if(!($(this).hasClass('espacePerso'))) {
				$(this).find('.ssmenu > *').not('.spacer,.selectOverlap').each(function(){
					max_height = ( max_height > $(this).height() ? max_height : $(this).height() );
				});
				$(this).find('.ssmenu > *').not('.spacer,.offre,.selectOverlap').height(max_height);
			} else {
				try{carousel_selection.unlock();}catch(e){}
			}
		},
		function(){
			$(this).find('ul.ssmenu').hide();
			try{carousel_selection.lock();}catch(e){}
		});
		if (jQuery.browser.msie &&
				parseInt(jQuery.browser.version) == 6) { 
			$('#menu ul.menu ul.ssmenu').activeXOverlap();
		}
	}
	
	if ($("#emailNews").length)
		$("#emailNews").focus(function(){$("#emailNews").val('')});

	if ($("#emailNewsResultats").length)
		$("#emailNewsResultats").focus(function(){$("#emailNewsResultats").val('')});
	
	$("#infosIcade").hide();
	$("#lienInfosIcade").click(function(){
		$("#infosIcade").slideToggle("slow");
		return false;
	});

	if($("#lieuxProgrammesNeufs").length) {
		$("#lieuxProgrammesNeufs ul").hide();
		$("#lieuxProgrammesNeufs .region > a").click(function(){
				$(this).blur().parent().children('ul').slideToggle('slow');
				return false;
			});
		$("#lieuxProgrammesNeufs .departement > a").click(function(){
			$(this).blur().parent().children('ul').slideToggle('slow');
			return false;
		});
	}

	$('#menu ul.menu li.espacePerso .ssmenu').show();
	try {
		carousel_selection = $('#carouselMaSelection').jcarousel({scroll:3, vertical:true});
		carousel_selection.lock();
	}catch(e){}
	$('#menu ul.menu li.espacePerso .ssmenu').hide();
	
});

jQuery.fn.activeXOverlap = function() { 
    $(this).each(function(i){
        var h   = $(this).outerHeight();
        var w   = $(this).outerWidth();
        var iframe  = '<!--[if IE 6]>' +
                      '<iframe src="javascript:false;" style="height: ' +
                      h +
                      'px; width: ' +
                      w +
                      'px" class="selectOverlap">' +
                      '</iframe>' +
                      '<![endif]-->';
        $(this).prepend(iframe);
    });
}

/**********************************************************************************************************/
/*            thickbox.js                                                                                 */
/**********************************************************************************************************/

/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "/images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){   
	tb_init_all();
});

function tb_init_all() {
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
}

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	// Xiti
	try {xt_med('C',xitin2,xitiCi[this.id]['lib'],xitiCi[this.id]['type']);} catch(e){};
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images

			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				
				// Modification : on enleve de TB_TempArray les liens identiques se suivant (cas liens identiques dans plusieurs TD d'un meme TR)
				//TB_TempArray = $("a[rel="+imageGroup+"]").get();
				TB_TempArray = new Array();
				tempArray = $("a[rel="+imageGroup+"]").get();
				urlToTest = '';
				for (i=0;i<tempArray.length;i++) {
					if (!(tempArray[i].href == urlToTest)) {
						TB_TempArray.push(tempArray[i]);
						urlToTest = tempArray[i].href;
					}
				}
				// Fin modif
				
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );
			var paramsAdd = '';
			
			TB_WIDTH = (params['width']*1) + 0 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 0 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 0;
			ajaxContentH = TB_HEIGHT - 0;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if( url.indexOf('goTo') != -1 ) {
						paramsAdd = 'goTo='+params['goTo'];
					}
					if(params['modal'] != "true"){//iframe no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+paramsAdd+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='50' hspace='0' src='"+urlNoQuery[0]+paramsAdd+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW)+"px;height:"+(ajaxContentH)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
//					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
//					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px', height: TB_HEIGHT + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}

/**********************************************************************************************************/
/*            textbox.js                                                                                 */
/**********************************************************************************************************/

/*
 * Textbox, basée sur :
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 */

var tb_pathToImage = "/images/loadingAnimation.gif";


//on page load call tb_init
$(document).ready(function(){   
	tbx_init_all();
});

function tbx_init_all(containerId) {
	var domChunk = (containerId) ? $('#'+containerId).find('a.textbox, area.textbox, input.textbox') : 'a.textbox, area.textbox, input.textbox';
	tbx_init(domChunk);//pass where to apply textbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
	
	// si on veut afficher sur le onload de la page une thickbox, donner l'id "box_shownOnload" a l'element declencheur
	if ($('#box_shownOnload').length) {
		$('#box_shownOnload').click();
	}
}

//add textbox to href & area elements that have a class of .textbox
function tbx_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	if (window.tbx_onshow) // traitement eventuel avant tbx_show
		tbx_onshow(this);
	tbx_show(t,a);
	this.blur();
	// Xiti
	//try {xitiClick(xitiCi[this.id]['type'], xitiCi[this.id]['lib'], false);} catch(e){};
	try {
		var queryString = a.replace(/^[^\?]+\??/,'');
		var params = tbx_parseQuery( queryString);
		var xitiId = this.id;
		if (params['type_contact'] != undefined)
			xitiId = params['type_contact'];
		xt_med('C',xitin2,xitiCi[xitiId]['lib'],xitiCi[xitiId]['type']);
	} catch(e){};
	return false;
	});
}
function tbx_show(caption, url) {//function called when the user clicks on a textbox link

	//try {
		var defaultLocale = 'fr_FR';
		var localizedTexts = new Array();
		localizedTexts['fr_FR'] = {'altClose':'Fermer'};
		localizedTexts['en_EN'] = {'altClose':'Close'};

		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("box_hideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='box_hideSelect'></iframe><div id='box_overlay'></div><div id='box_window'></div>");
				$("#box_overlay").click(tbx_remove);
			}
		}else{//all others
			if(document.getElementById("box_overlay") === null){
				$("body").append("<div id='box_overlay'></div><div id='box_window'></div>");
				$("#box_overlay").click(tbx_remove);
			}
		}

		if(tb_detectMacXFF()){
			$("#box_overlay").addClass("box_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#box_overlay").addClass("box_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='box_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#box_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
			   
	   //code to show html
		var queryString = url.replace(/^[^\?]+\??/,'');
		var params = tbx_parseQuery( queryString );

		//TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
		//TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
		TB_WIDTH = (params['width']*1) || 598; //598
		TB_HEIGHT = (params['height']*1) || ((url.indexOf('TB_inline') != -1) ? 160 : 440);
		//contentW = TB_WIDTH - 30;
		contentW = (params['width']*1) || 598;
		contentH = TB_HEIGHT - 45;
	
		// @todo : gerer ca avec des styles
		iframeW = params['TB_style'] ? contentW : contentW - 35;

		var altClose = params['locale'] ? localizedTexts[params['locale']]['altClose'] : localizedTexts[defaultLocale]['altClose'];
		$("#box_window").append("<div id='box_title'><div id='box_caption'>"+caption+"</div><div id='box_close'><a href='#' title='"+altClose+"'><img src='/images/bt-textbox-fermer.gif' alt='"+altClose+"'/></a></div></div>");

		if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
				urlNoQuery = url.split('TB_');
				$("#box_iframeContent").remove();
				//iframe no modal
				var scrolling = 'auto';
				if(params['TB_style']=='simple_noscrolling')
					scrolling = 'no';
				// force du scrolling uniquement pour IE6
				if(params['TB_iescrolling']=='true' && typeof document.body.style.maxHeight === "undefined")
					scrolling = 'yes';
				$("#box_window").append("<div id='box_content' style='width:"+contentW+"px;height:"+contentH+"px;'><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='box_iframeContent' scrolling='"+scrolling+"' name='box_iframeContent"+Math.round(Math.random()*1000)+"' onload='tbx_showIframe()' style='width:"+iframeW+"px;height:99%;"+(params['TB_style']?"":"margin-left:35px;")+"' > </iframe></div>");
				if(params['TB_style'])
					$("#box_window").addClass(params['TB_style']);
		}else{// not an iframe, ajax
				if($("#box_window").css("display") != "block"){
					$("#box_window").append("<div id='box_content' style='width:"+contentW+"px;height:"+contentH+"px;'></div>");
				}else{//this means the window is already up, we are just loading new content via ajax
					$("#box_content")[0].style.width = contentW +"px";
					$("#box_content")[0].style.height = contentH +"px";
					$("#box_content")[0].scrollTop = 0;
					$("#box_caption").html(caption);
				}
		}
		$("#box_close a").click(tbx_remove);
		
		if(url.indexOf('TB_inline') != -1){			 
			$("#box_content").append($('#' + params['inlineId']).children());
			$("#box_window").unload(function () {
				$('#' + params['inlineId']).append( $("#box_content").children() ); // move elements back when you're finished
			});
			tbx_position();
			$("#box_load").remove();
			$("#box_window").css({display:"block"}); 
		}else if(url.indexOf('TB_iframe') != -1){
			tbx_position();
//			if($.browser.safari){//safari needs help because it will not fire iframe onload
				$("#box_load").remove();
				$("#box_window").css({display:"block"});
//			}
		}else{
			$("#box_content").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
				tbx_position();
				$("#box_load").remove();
				tbx_init("#box_content a.textbox");
				$("#box_window").css({display:"block"});
			});
		}
			
		

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tbx_remove();
				}	
			};
		}

/*	} catch(e) {
		//nothing here
	}
*/
}

//helper functions below
function tbx_showIframe(){
	$("#box_load").remove();
	$("#box_window").css({display:"block"});
}

function tbx_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#box_close").unbind("click");
	$("#box_window").fadeOut("fast",function(){$('#box_window,#box_overlay,#box_hideSelect').trigger("unload").unbind().remove();});
	$("#box_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tbx_position() {
$("#box_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#box_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tbx_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tbx_changeContent(url, caption) {
    $("#box_iframeContent",parent.document).attr('src',url);
    if (caption != null && caption.length > 0) 
    	$("#box_caption",parent.document).text(caption);
}

/**********************************************************************************************************/
/*            swfobject.js                                                                                */
/**********************************************************************************************************/

/**
 * SWFObject v1.5.1: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept={};}if(typeof deconcept.util=="undefined"){deconcept.util={};}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil={};}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params={};this.variables={};this.attributes=[];if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10]||"";},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15]||"";},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=[];var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+(this.getAttribute("style")||"")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+(this.getAttribute("style")||"")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;

/**********************************************************************************************************/
/*            fiche.js                                                                                    */
/**********************************************************************************************************/

$(document).ready(function() {
	
	// Views des visuels de la fiche
	// @todo Transformer en fonction jquery pour reutilisation
	$('.visuels').each(function(){
		var container = $(this);
		container.find(".minis a").each(function(i,val) {
			$(val).click(function(e){
				container.find('a.zoom').hide();
				container.find('a.zoom:eq('+i+')').show();
				var img = $(this).find('img');
				container.find(".legende").html(img.attr('alt'));
				$(this).blur();
				return false;
			});
		});
	});
	
	// Liste logements
	$('.logements').each(function(){
		var container = $(this);
		container.find("h3").click(function(e){
			if(container.hasClass('closed'))
				container.removeClass('closed').addClass('opened');
			else if(container.hasClass('opened'))
				container.removeClass('opened').addClass('closed');
			$(this).blur();
			return false;
		});
	});
	
	if (jQuery.fn.tablesorter) {
		// Parser specifique au typologies de lot
	    $.tablesorter.addParser({ 
	        // set a unique id 
	        id: 'typo', 
	        is: function(s) {return false;}, 
	        format: function(s) { 
	            return s.toLowerCase().replace(/studio/,"1"); 
	        }, 
	        type: 'text' 
	    });
	    
	    $.tablesorter.addParser({ 
	        id: 'nombre', 
	        is: function(s) { 
	    		return s.match( new RegExp( /[m²€°]$/ ) );
	    	}, 
	        format: function(s) { 
	    		return $.tablesorter.formatInt( parseInt( s.match( new RegExp(/([0-9 ]+)/) )));
	        }, 
	        type: 'numeric' 
	    });
	    
		// Tableaux triables
		$("table.sortable").bind("sortEnd",function(event){
			$(this).find("tbody tr").each(function(i,tr){
				if(i%2==0)
					$(tr).removeClass('second');
				else
					$(tr).addClass('second');
			});
		}).tablesorter({
	        debug: false, // enable debug mode
	        headers:{
				0:{sorter:'typo'},
				4:{sorter:false}
			}
		});
	}
});

//Ajout a la selection (programme ou lot)
function addToSelection(obj, url, locale) {
	$.ajax({
		dataType: 'text',
		cache:false,
		url: url,
		data: {async:1},
		success: function(data) {
			// affichage textbox
			var tbUrl = '#TB_inline?inlineId=addSelection&amp;locale='+locale;
			if (data != "") {
				$("#addSelectConfirm").html(data);
			}
			tbx_show($(obj).attr('title'), tbUrl);
			$("#accesEspacePerso .submenu").show();
			return false;
		}
	});
}

/**********************************************************************************************************/
/*            programme.js                                                                                    */
/**********************************************************************************************************/

$(document).ready(function() {
	// Lien programme enrichi
	$('a.programmeEnrichi').attr('href','#').click(function(e){
		if( QT_check() ) {
			PE_start();
			$(this).blur();
			try {xt_med('C',xitin2,xitiCi[$(this).attr('id')]['lib'],xitiCi[$(this).attr('id')]['type']);} catch(e){}; // Xiti
		}
		return false;
	});
});

// ========== programme enrichi ==========
var PE_isInit = false;	// Initialisé ?
var PE_base = "";		// Le contenu de base du viewer

/**
 * Initialisation du programme enrichi 
 */
// Stockage des references des jcarousel pour utilisation ulterieure
var myjcs = [];

function PE_init() {

	PE_show();
	
	// Recuperation du contenu de base
	PE_base = $('#programmeEnrichiView').html();

	// Liste des medias
	$('#programmeEnrichiThumb').jcarousel({
		scroll:4
	});

	// Pour chaque contenu d'onglet
	$('#programmeEnrichiOngletsContainer .contentOnglet').each(function(){

		// Recuperation des visuels
		var visuels = $(this).find('.visuels');

		// Si auncun visuel et contenu non affiche
		if(visuels.size()==0 && !$(this).hasClass('on')) {
			$(this).hide();
		}

		else {

			// Liste des medias des contenus des onglets
			visuels.each(function(e) {
				var parent = $(this).parent();
				$(this).jcarousel({
					scroll:1
					,animation:200
					/*,auto:5*/
					,initCallback:function(myjc,st) {

						// Association du jcarousel avec l'objet
						myjcs[parent.attr('id')] = myjc;
	
						// lock du jcarouel si le container n'est pas sense etre afficher
						if(!parent.hasClass('on')) {
							myjc.lock();
							parent.hide();
						}
					}
				});
			});
		}
	});

	// comportement des onglets
	$('#programmeEnrichiOngletsContainer .onglets li a').click(function(e) {

		// si l'onglet est deja selectionne
		if($(this).blur().parent().hasClass('on'))
			return false;

		var id = $(this).attr('id');
		
		// lock des jcarousel pour eviter des alertes js
		$('#programmeEnrichiOngletsContainer .contentOnglet').each(function(){
			try{myjcs[$(this).attr('id')].lock();}catch(e){}
			$(this).hide();
		});

		// Affichage de l'onglet et du contenu
		$('#programmeEnrichiOngletsContainer .onglets li').removeClass('on');
		id = 'content-' + id;
		$('#' + id).show();

		// Deverouillage du jcarousel associe s'il existe
		try{
			myjcs[id].unlock();
			myjcs[id].scroll(0,false);
		}catch(e){}	

		$(this).blur().parent().addClass('on');
		return false;
	});

	// Thumbs
	$('#programmeEnrichiThumb span.titre').css('opacity',0.8);
	$('#programmeEnrichiThumb a.thumb').click(function(e){
		var href = $(this).attr('href');
		var title = $(this).attr('title');

		// Affichage du visuel principal
		if($(this).hasClass('main')) {
			$('#programmeEnrichiView').html(PE_base);
		}

		// Affichage d'un autre visuel
		else if($(this).hasClass('image')) {
			$('#programmeEnrichiView').html(
				"<img src='" + href + "' alt='' />"
				+ "<p class='alt'>" + title + "</p>"
			);
		}

		// Affichage d'un quictime
		else if($(this).hasClass('mov')) {
			$('#programmeEnrichiView').html(
				'<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="640" height="360">'
				+ '<param name="src" value="' + href + '" />'
				+ '<param name="controller" value="true" />'
				+ '<object type="video/quicktime" data="' + href + '" width="640" height="360" class="mov">'
				+ '<param name="controller" value="true" />'
				+ '<a href="http://www.apple.com/fr/quicktime/download/" class="blank" target="_blank">Télécharger Quicktime</a>' // @todo : texte qui invite au telechargement
				+ '</object>'
				+ '</object>'
			);
		}

		// Affichage d'un swf
		else if($(this).hasClass('swf')) {
			$('#programmeEnrichiView').html(''); // @todo : texte qui invite au telechargement
			var so = new SWFObject(href, "programmeEnrichiViewSwf", "640px", "360px", "8.0.0", "#ffffff");	
			so.write("programmeEnrichiView");
		}

		// Affichage d'une video flv
		else if($(this).hasClass('flv')) {
			$('#programmeEnrichiView').html(''); // @todo : texte qui invite au telechargement
			var so = new SWFObject('/images/flash/player_flv.swf', "programmeEnrichiViewSwf", "640px", "360px", "8.0.0", "#ffffff");	
			so.addParam('FlashVars','flv=' + href + '&amp;autoload=1&amp;bgcolor1=000000&amp;bgcolor2=000000');
			so.write("programmeEnrichiView");
		}
		
		// Affichage d'une iframe
		else if($(this).hasClass('iframe')) {
			$('#programmeEnrichiView').addClass('loading');
			$("#programmeEnrichiView").html( '<iframe frameborder="0" hspace="0" src="' + href + '" style="width:640px;height:360px;"> </iframe>' );
		}

		$(this).blur();
		
		// Xiti
		try{xt_med('C',xitin2,'programme_enrichi::'+xitify(title),'T');}catch(e){};

		return false;
	});

	// Fermetude du programme enrichi
	$('a.detailsProgramme').click(function(e){
		return PE_close();
	});
	
	// Avant ouverture textbox demande infos
	tbx_onshow = function(obj){PE_hide();}

	// Programme enrichi initialise
	PE_isInit = true;
}

/**
 * Demarage du programme enrichi
 */
function PE_start() {
	if(!PE_isInit) 
		PE_init();
	else
		PE_show();
}

/**
 * Affichage/desaffichage/fermeture du programme enrichi
 */
function PE_show() {
	// Affichage
	$('#programmeEnrichiBackground').css({
		opacity:0.8,
		height:$(document).height()
	}).show();
	$('#programmeEnrichi').show();
}
function PE_hide() {
	$('#programmeEnrichiBackground').hide();
	$('#programmeEnrichi').hide();
	
	// Lock de tous les jcarousel
	for(i in myjcs)
		try{myjcs[i].lock();}catch(e){}
}
function PE_close() {
	
	PE_hide();
	
	// Lock de tous les jcarousel
	/*for(i in myjcs)
		try{myjcs[i].lock();}catch(e){}*/
	return false;
}
function QT_check() {
	var minQTversion = '7,6,4,0';
	var downloadQTurl = 'http://www.apple.com/fr/quicktime/download/';
	if( PluginDetect.isMinVersion('QuickTime', minQTversion) < 0 ) {
		alert(quicktimeUpdate);
		window.location.href = downloadQTurl;
		return false;
	}
	else
		return true;
}

/**********************************************************************************************************/
/*            calculette.js                                                                               */
/**********************************************************************************************************/

//Infos suivant leur type (h,w : taille des dialog)
//Ne pas utiliser de - dans les types de calculettes
var calcInfos = {'defaut':{'h':600,'w':600,'xitiLib':'calculette::defaut'}
	,'notaire':{'h':375,'w':390,'xitiLib':'calculette::frais_de_notaire'}
	,'credit':{'h':510,'w':570,'xitiLib':'calculette::credit_3_modes'}
	,'impots':{'h':630,'w':640,'xitiLib':'calculette::credit_d_impot'}
	,'ptz':{'h':500,'w':640,'xitiLib':'calculette::pret_taux_zero'}
	,'emprunter':{'h':500,'w':640,'xitiLib':'calculette::graphique_emprunter'}
	,'rembourser':{'h':500,'w':640,'xitiLib':'calculette::graphique_rembourser'}
};

$(document).ready(function() {	
	// calculettes
	$(".calculette").each(function(){
		// infos sur dialog, pgm et lot
		var dialogH = calcInfos.defaut.h;
		var dialogW = calcInfos.defaut.w;
		var linkParams = '';
		var xitiLib = '';
		var infos = $(this).attr('name').split('-');
		if (infos.length != 0 && calcInfos[infos[0]]) {
			dialogH = calcInfos[infos[0]].h;
			dialogW = calcInfos[infos[0]].w;
			xitiLib = calcInfos[infos[0]].xitiLib;
		}
		var titleImg = new Image();
		var locale = infos[1] ? infos[1] : 'fr_FR';
		if (infos.length != 0) {
			$(titleImg).attr('src', '/images/'+locale+'/titre-calculette-'+infos[0]+'.png');
			$(titleImg).attr('alt', $(this).attr('title'));
		} else
			titleImg = null;
		
		// IE : divers bugs liés en partie à DD_roundies, certains bizarres => ré-initialisation de la dialog à chaque clic solutionne apparemment tout
		// Synthetiser si possible
		if($.browser.msie && $.browser.version < 8) {
			$(this).click( function() {
				var $container = $("<div class='dialogContainer'></div>");
				$container.append('<iframe src="'+$(this).attr('href')+linkParams+'" style="width:100%;height:99%;" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="auto" />');
				// fermeture d'autres dialogs eventuellement ouvertes
				$(".dialogContainer").each(function(){$(this).dialog('destroy');});
				
				// re-init dialog
				$container.dialog({
		   			title: ($.browser.version < 7) ? $(this).attr('title') : (titleImg != null ? titleImg : $link.attr('title')),
		   			resizable: false,
					closeOnEscape: true,
	           		height: dialogH,
	           		width: dialogW
	           		//close:function(ev, ui) { $(this).destroy(); }
	        	});
				$container.bind('dialogclose', function(event, ui) {$container.dialog('destroy');$container.remove();});
				
				//xiti
				try{xt_med('C',xitin2,xitiLib,'A');}catch(e){};
				
				return false;					
			});
		} else {
			var $container = $("<div class='dialogContainer'></div>");
			// l'iframe est chargée après un clic, ensuite, plus besoin de la charger
			var $link = $(this).one('click', function() {
				$container.append('<iframe src="'+$link.attr('href')+linkParams+'" style="width:100%;height:99%;" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="auto" />');
				
				// fermeture d'autres dialogs eventuellement ouvertes
				$(".dialogContainer").each(function(){$(this).dialog('close');});
				
				$container.dialog({
		   			//title: $link.attr('title'),
		   			title: titleImg != null ? titleImg : $link.attr('title'),
		   			resizable: false,
					closeOnEscape: true,
	           		height: dialogH,
	           		width: dialogW
	        	});
	
	   			$link.click(function() {  
	   				// xiti
	   				try{xt_med('C',xitin2,xitiLib,'A');}catch(e){};
					$(".dialogContainer").each(function(){$(this).dialog('close');});
					$container.dialog('open');
					return false;
	   			});
	   			
	   			//xiti
	   			try{xt_med('C',xitin2,xitiLib,'A');}catch(e){};
	   			
				return false;
			});
		}
	});	
});

/**********************************************************************************************************/
/*            commonGeoApp.js                                                                               */
/**********************************************************************************************************/

var baseIcon;
var programmeIcon;
var programmeOnIcon;

var host = window.location.host;

// initialisations
function geoInit() {

	// test compatibilite
	if (!GBrowserIsCompatible())
		return;

	// Icon de base
	baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.iconSize = new GSize(19, 19);
	baseIcon.shadow = "http://" + host + "/images/bg-picto-geo-programme.png"; // @todo : constantes
	baseIcon.shadowSize = new GSize(25, 27);
	baseIcon.iconAnchor = new GPoint(10, 10);
	baseIcon.infoWindowAnchor = new GPoint(3, -1);
	baseIcon.image = "http://" + host + "/images/picto-geo-programme.gif"; // @todo : constantes

	// Icon programme
	programmeIcon = new GIcon(baseIcon);
	
	// Icon programme actif
	programmeOnIcon = new GIcon(baseIcon);
	programmeOnIcon.image = "http://" + host + "/images/picto-geo-programme-on.gif"; // @todo : constantes

	// Icon BV actif
	bvOnIcon = new GIcon(baseIcon);
	bvOnIcon.image = "http://" + host + "/images/picto-geo-bv-on.gif"; // @todo : constantes
	
	// Icon de base pour les picto de services
	baseServiceIcon = new GIcon(G_DEFAULT_ICON);
	baseServiceIcon.iconSize = new GSize(25, 25);
	baseServiceIcon.shadow = "";
	baseServiceIcon.shadowSize = new GSize(38, 25);
	baseServiceIcon.iconAnchor = new GPoint(16, 25);
	baseServiceIcon.infoWindowAnchor = new GPoint(3, -1);
	
	// Transport
	transportIcon = new GIcon(baseServiceIcon);
	transportIcon.shadow = "http://" + host + "/images/picto-transport-shadow.png";
	transportIcon.image = "http://" + host + "/images/picto-transport.png"; // @todo : constantes
	
	// Ecoles
	ecoleIcon = new GIcon(baseServiceIcon);
	ecoleIcon.shadow = "http://" + host + "/images/picto-ecole-shadow.png";
	ecoleIcon.image = "http://" + host + "/images/picto-ecole.png"; // @todo : constantes
	
	// Garderie
	garderieIcon = new GIcon(baseServiceIcon);
	garderieIcon.shadow = "http://" + host + "/images/picto-garderie-shadow.png";
	garderieIcon.image = "http://" + host + "/images/picto-garderie.png"; // @todo : constantes

	// Sport
	sportIcon = new GIcon(baseServiceIcon);
	sportIcon.shadow = "http://" + host + "/images/picto-sport-shadow.png";
	sportIcon.image = "http://" + host + "/images/picto-sport.png"; // @todo : constantes
	
	// Sortie
	sortieIcon = new GIcon(baseServiceIcon);
	sortieIcon.shadow = "http://" + host + "/images/picto-sortie-shadow.png";
	sortieIcon.image = "http://" + host + "/images/picto-sortie.png"; // @todo : constantes
	
	// Commerce
	commerceIcon = new GIcon(baseServiceIcon);
	commerceIcon.shadow = "http://" + host + "/images/picto-commerce-shadow.png";
	commerceIcon.image = "http://" + host + "/images/picto-commerce.png"; // @todo : constantes
}

function resetBox(box, defaultvalue) {
	if (box.value == defaultvalue) {
		box.value = "";
	}
}

/******************************************/
/*             Week events                */
/******************************************/
$(document).ready(function() {
  $('#weekevents').each(function(){
    if($('li',events).length > 1){
			
			var events = $(this);
			
			height = $("li:first-child img", events).height();
			$('.events').height(height);
			
      // Pour chaque éléments:
	  var ind = 1;
      $('li',events).each(function(){
        var elt = $(this);
        
        // Titre des events:
        $('a',elt).append($('a',elt).attr('title')).attr('title','');
    	
        // Conteneur image et lien de elt:
    	$('img',elt).wrap('<div class="event" />').wrap('<a />');
    	
    	// Lien vers elt:
    	$('.event a',elt).attr('href',$('a:first-child',elt).attr('href'));
    	
    	// Titre event:
    	$('p',elt).appendTo($('.event a',elt));
    	$('.plus',elt).appendTo($('.event p',elt));
        
    	// Mise en place elt:
   		$('.event',elt).attr('id','event_' + ind).appendTo($('.events'));
    	ind++;
      });
      $('.event',events).hide();
      
      $("li:first-child", events).addClass('active');
      $(".event:first-child", events).addClass('active').show();

      var inter = "";
      inter = setInterval(function(){next()}, 5000);
			
      $('li a', events).click(function(){
    	  clearInterval(inter);
    	  inter = setInterval(function(){next()}, 5000);
    	  nextImage($(this).parent());
    	  return false;
      });
			
      function nextImage(elt) {
    	  // Link et image a cacher:
    	  $("li.active", events).removeClass("active");
    	  $(".events .active", events).css({zIndex:6}).fadeOut('normal').removeClass("active");

    	  id = elt.attr("id").split("_")[1];
    	  // Link et image a afficher:
    	  $("li#linkevent_"+id, events).addClass("active");
    	  $(".events #event_"+id, events).addClass("active").css({zIndex:5}).fadeIn('normal');
      }
			
      function next() {
    	  if(!$("li.active", events).is(":last-child"))
    		  elt =  $("li.active", events).next();
    	  else
    		  elt =  $("li:first-child", events);
				nextImage(elt);
      }
    }
  });
});
