
// CONSTANTS FOR HTTL URL PARAMETERS
var C_PARAM_BUTTONNAME    = "a";
var C_PARAM_EVENT         = "b";
var C_PARAM_DATE          = "c";
var C_PARAM_LANGUAGE_CODE = "l";
var C_PARAM_LOCKDATELIST  = "d";

// OTHER CONSTANTS
C_DEFAULT_LANGUAGE_CODE = "fr";

var IS_IE = navigator.appVersion.indexOf("MSIE") != -1;
//var IS_IE_5 = (document.all && document.getElementById) != top.undefined;
var IS_IE_5 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 5.") != -1));
var IS_IE_6 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 6.") != -1));
var IS_IE_7 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 7.") != -1));
var IS_IE_8 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 8.") != -1));
var IS_IE_9 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 9.") != -1));
var IS_NS_6 = (!document.all && document.getElementById);
var IS_OPERA = navigator.appName.indexOf("Opera") != -1;
var IS_FIREFOX = navigator.userAgent.toLowerCase().indexOf("firefox") != -1;
var IS_CHROME = navigator.userAgent.toLowerCase().indexOf("chrome") != -1;

var BROWSER_VERSION = (!IS_IE) ? parseFloat(navigator.appVersion) : parseFloat(navigator.appVersion.substring(navigator.appVersion.indexOf("MSIE")+"MSIE".length));

// GLOBAL VARIABLES
var bgFaderOpacityCounter;
var bgFaderIntervalHandle;
var formFaderOpacityCounter;
var formFaderIntervalHandle;
var formHeightCounter;
var formHeightIntervalHandle;

var g_emails = new Array();
g_emails['pf'] = 'agence@pierrefeu-immo.com';
g_emails['am'] = 'amplepuis@pierrefeu-immo.com';
g_emails['or'] = 'agence@oriol-immo.com';
g_emails['ti'] = 'agence@tourimmo.com';

var g_tels = new Array();
g_tels['pf'] = '04 74 05 05 75';
g_tels['am'] = '04 74 89 34 34';
g_tels['or'] = '04 77 72 46 00';
g_tels['ti'] = '04 78 48 88 28';

var g_faxs = new Array();
g_faxs['pf'] = '04 74 05 05 75';
g_faxs['am'] = '04 74 13 03 95';
g_faxs['or'] = '04 77 72 41 36';
g_faxs['ti'] = '04 78 48 88 29';

function getUrlParameter(paramName)
{
    paramsString = self.location.search;
    pos = paramsString.indexOf(paramName);
    if (pos == -1)
        return null;

    // REMOVE THE PIECE BEFORE THE PARAM
    paramsString = paramsString.slice(pos);

    // REMOVE THE PIECE AFTER THE PARAM VALUE
    pos = paramsString.indexOf('&');
    if (pos != -1)
        paramsString = paramsString.slice(0, pos);

    // EXTRACT THE PARAM VALUE
    pos = paramsString.indexOf('=');
    paramsString = paramsString.slice(pos+1);

    // RETURN THE FINAL VALUE
    return paramsString;
}


function storeDemoAccessCookie(form)
{
    setCookie('demoAccessFormFilledUp', 'true', 90);
    setCookie('NAME', form.NAME.value, 90);
    setCookie('COMPANY', form.COMPANY.value, 90);
    setCookie('TELEPHONE', form.TELEPHONE.value, 90);
    setCookie('email', form.replyemail.value, 90);
}


function getCookie(NameOfCookie)
{
    if (document.cookie.length > 0) {

        begin = document.cookie.indexOf(NameOfCookie+"=");
        if (begin != -1) {
            begin += NameOfCookie.length+1;

            end = document.cookie.indexOf(";", begin);
            if (end == -1)
                end = document.cookie.length;

            return unescape(document.cookie.substring(begin, end));
        }
    }

    return null;
}


function setCookie(NameOfCookie, value, expiredays)
{
    var ExpireDate = new Date();
    ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
    document.cookie = NameOfCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString() + "; path=/");
}


function delCookie(NameOfCookie)
{
    if (getCookie(NameOfCookie))
        document.cookie = NameOfCookie + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}


/* CROSS-BROWSER INNER WIDTH & HEIGHT */
function viewport()
{
  var x,y;

  // all except Explorer.
  if (self.innerHeight) {
    x = self.innerWidth;
    y = self.innerHeight;
  }
  else
  // Explorer 6 Strict Mode.
  if (document.documentElement && document.documentElement.clientHeight) {
    x = document.documentElement.clientWidth;
    y = document.documentElement.clientHeight;
  }
  else
  // other Explorers.
  if (document.body) {
    x = document.body.clientWidth;
    y = document.body.clientHeight;
  }

  return {width: x, height: y};
}


/* CROSS-BROWSER SCROLLING OFFSET */
function scrolling()
{
  var x,y;

  // all except Explorer.
  if (self.pageYOffset) {
    x = self.pageXOffset;
    y = self.pageYOffset
  }
  else
  // Explorer 6 Strict Mode.
  if (document.documentElement && document.documentElement.scrollTop) {
    x = document.documentElement.scrollLeft;
    y = document.documentElement.scrollTop;
  }
  else
  // other Explorers.
  if (document.body) {
    x = document.body.scrollLeft;
    y = document.body.scrollTop;
  }

  return {XOffset: x, YOffset: y};
}


/* CROSS-BROWSER PAGE HEIGHT */
function page()
{
  var x,y;
  var test1 = document.body.scrollHeight;
  var test2 = document.body.offsetHeight

  // all but Explorer Mac.
  if (test1 > test2) {
    x = document.body.scrollWidth;
    y = document.body.scrollHeight;
  }
  // Explorer Mac;
  // would also work in Explorer 6 Strict, Mozilla and Safari.
  else {
    x = document.body.offsetWidth;
    y = document.body.offsetHeight;
  }

  return {width: x, height: y};
}


function switchLanguage(langCode)
{
  langCode = langCode || 'en';

  if (langCode == 'en')
    document.location.href = document.location.href.replace('/fr/', '/en/');
  else
  if (langCode == 'fr')
    document.location.href = document.location.href.replace('/en/', '/fr/');
}


function delay(millis)
{
  var date = new Date();
  var curDate = null;

  do { curDate = new Date(); }
  while(curDate-date < millis);
}


function setDivOpacity(divId, opacity)
{
//  if(IS_IE_5) document.getElementById(divId).filters.alpha.opacity = opacity;
//  if(IS_NS_6) document.getElementById(divId).style.MozOpacity = opacity/100;
  $(divId).setOpacity(opacity/100);
}


function setDivHeight(divId, height)
{
  document.getElementById(divId).style.height = height;
}


function fadeInDiv(isFadeIn, divId, opacitySteps, opacityThreshold, opacityCounterVarName, fadeIntervalHandleVarName)
{
  if (isFadeIn) {

    document.getElementById(divId).className = 'class_visible';

    if(eval(opacityCounterVarName) < opacityThreshold){
      eval(opacityCounterVarName + '+=' + opacitySteps);
      setDivOpacity(divId, eval(opacityCounterVarName));
    }
    // RESET OPAC VAR FOR NEXT USE.
    else {
      clearInterval(eval(fadeIntervalHandleVarName));
    }
  }
  else {
    if(eval(opacityCounterVarName) > opacityThreshold){
      eval(opacityCounterVarName + '-=' + opacitySteps);
      setDivOpacity(divId, eval(opacityCounterVarName));
    }
    // RESET OPAC VAR FOR NEXT USE.
    else {
      document.getElementById(divId).className = 'class_hidden';
      clearInterval(eval(fadeIntervalHandleVarName));
    }
  }
}


function rollDiv(divId, endHeight, step, divHeightCounterVarName, divHeightIntervalHandleVarName)
{
  eval(divHeightCounterVarName + '+=' + step);

  if ( (step > 0 && eval(divHeightCounterVarName) > endHeight) || (step < 0 && eval(divHeightCounterVarName) < endHeight)) {
    clearInterval(eval(divHeightIntervalHandleVarName));
    return;
  }

  setDivHeight(divId, eval(divHeightCounterVarName)+'em');
}

function hideDropDownLists(bool)
{
  if (IS_IE) {
    try {
      if (bool) {
        $('rechercheDeBiensForm_champ_typeDeBien').hide();
        $('biens_resultats_liste_tri').hide();
      }
      else {
        $('rechercheDeBiensForm_champ_typeDeBien').show();
        $('biens_resultats_liste_tri').show();
      }
    }
    catch (ex) {}

  }
}

function demandeDeRappelFormShow(bool)
{
	jQuery.scrollTo(0, 0);

	if (bool == true) {
	    hideDropDownLists(true);
	  	jQuery('#fadedBackground')
		  	.css({opacity: '0'}).show().animate({opacity: '0.7'}, 'slow')
		  	.unbind('click').click(function(){demandeDeRappelFormShow(false);})
		jQuery('#demandeDeRappelFormDiv').slideDown('slow');
	    setTimeout('try {if (!IS_IE) jQuery("#listeOffresDiv").hide();} catch(ex){}; jQuery("#demandeDeRappelForm_champ_nom").focus()', 1000);
	}
	else {
		try {if (!IS_IE) jQuery("#listeOffresDiv").show();} catch(ex){}
		setTimeout('hideDropDownLists(false)', 1000);
		jQuery('#fadedBackground')
			.animate({opacity: '0'}, 'slow', function(){jQuery(this).hide()});
		jQuery('#demandeDeRappelFormDiv').slideUp('slow');
	}
}


function demandeDeQuestionFormShow(bool, text, destEmail, subject, clientId, offreId)
{
	jQuery.scrollTo(0, 0);

	if (text)
		$('demandeDeQuestionForm_champ_Question').value = text;

	if (destEmail)
		$('demandeDeQuestionForm_champ_destemail').value = destEmail;

	if (subject)
		$('demandeDeQuestionForm_champ_subject').value = subject;

	if (bool == true) {

	    if (IS_IE_7) {
			window.location = '#';
			$('bodyElement').up().setStyle({overflow : 'hidden'});
			g_overrideOffreClientId = clientId;
			g_overrideOffreId = offreId;
	    }

		hideDropDownLists(true);
	  	jQuery('#fadedBackground')
		  	.css({opacity: '0'}).show().animate({opacity: '0.7'}, 'slow')
		  	.unbind('click').click(function(){demandeDeQuestionFormShow(false);})
		jQuery('#demandeDeQuestionFormDiv').slideDown('slow');
	    setTimeout('try {if (!IS_IE) jQuery("#listeOffresDiv").hide();} catch(ex){}; jQuery("#demandeDeRappelForm_champ_nom").focus()', 1000);
	}
	else {
		try {if (!IS_IE) jQuery("#listeOffresDiv").show();} catch(ex){}

    	setTimeout('hideDropDownLists(false)', 800);

		jQuery('#fadedBackground')
			.animate({opacity: '0'}, 'slow', function(){jQuery(this).hide()});
		jQuery('#demandeDeQuestionFormDiv').slideUp('slow');

		if (IS_IE_7) {
			$('bodyElement').up().setStyle({overflow : 'auto'});
			setTimeout('jumpToCurrentOffre(); g_overrideOffreClientId = null; g_overrideOffreId = null;', 1000);
		}

  }
}

function IE6FIX_footer_track()
{
  var documentObj;

  // FOR IE 6
  if (document.documentElement && document.documentElement.scrollTop)
    documentObj = document.documentElement;
  else
  // FOR IE 5
  if (document.body)
    documentObj = document.body;

  document.getElementById('footerDiv').style.top =
    (documentObj.scrollTop + documentObj.clientHeight - 12) + 'px';
}

function mainPageOnLoadHandler()
{
  // FOOTER TRACKING FIX FOR IE 5 AND 6 ONLY.
  if (IS_IE_5 && !IS_IE_7) {
    document.getElementById('footerDiv').style.position = 'absolute';
    setInterval('IE6FIX_footer_track()', 20);
  }

  $('footerDiv').show();

  // HANDLES
  if (getUrlParameter('msgid') == 'DemandeAppelEnvoyee')
    alert("Votre demande a bien été envoyée.\n\nMerci.");
  else
  if (getUrlParameter('msgid') == 'QuestionEnvoyee')
    alert("Votre question a bien été envoyée.\n\nMerci.");
  else
  if (getUrlParameter('msgid') == 'CandidatureEnvoyee') {
    alert("Votre candidature a bien été envoyée.\n\nMerci.");
    // RETOUR A LA PAGE DE GARDE.
    location.href = "/";
  }

  try {
    onLoadHandler();
  }
  catch (ex) {
  }
}


function noNumbers(e)
{
  var keynum;
  var keychar;
  var numcheck;

  if(window.event) // IE
    keynum = e.keyCode;
  else if(e.which) // Netscape/Firefox/Opera
    keynum = e.which;

  if (keynum == 8 || keynum == top.undefined)
    return true;

  keychar = String.fromCharCode(keynum);
  numcheck = /\d/;

  return !numcheck.test(keychar);
}



function noLetters(e)
{
  var keynum;
  var keychar;
  var numcheck;

  if(window.event) // IE
    keynum = e.keyCode;
  else if(e.which) // Netscape/Firefox/Opera
    keynum = e.which;

  if (keynum == 8 || keynum == top.undefined)
    return true;

  keychar = String.fromCharCode(keynum);
  numcheck = /\d/;

  //window.status = "e.which: " + e.which + " |a e.keyCode: " + e.keyCode + " | e.charCode: " + e.charCode + " | String.fromCharCode(e.which): " + String.fromCharCode(keynum);
  return numcheck.test(keychar) || (e.keyCode >= 96 && e.keyCode <= 105) ;
}


function preventLetterAndGetNbOfResults(e)
{
  if (noLetters(e) == true) {
    setTimeout('getNbResults()', 100);
    return true;
  }

  return false;
}


function browsePhotoOffre(clientId, offreId)
{
  g_overrideOffreClientId = clientId;
  g_overrideOffreId = offreId;

  new Ajax.Request(
    'biensalavente.php',
    {
    asynchronous : false,
    method:'get',
    parameters: { ff_action: 'setCurrentOffreInSessionOnly', offreAgId: clientId, offreId: offreId},
    onSuccess: function(transport){ /*alert(transport.responseText);*/ }
    });

//  new Ajax.Request(
//    'images.php',
//    {
//    asynchronous : false,
//    method:'get',
//    onSuccess: function(transport){ alert(transport.responseText); }
//    });

  $('bodyElement').setStyle({overflow: 'hidden'});

  if (IS_IE_7)
    $('bodyElement').up().setStyle({overflow : 'hidden'});

  // IE 8 AND BELOW
  if (IS_IE & BROWSER_VERSION <= 7) {
    $('photoBrowserTopBarDiv').setStyle({position: 'absolute', width: (viewport().width)+'px', top: '-6em', left: '-14em'});
    $('photoBrowserDiv').setStyle({top: '-4em', height: (viewport().height-40)+'px', width: (viewport().width)+'px'});
    $('photoBrowserFlashContentDiv').setStyle({height: (viewport().height-40)+'px'});
  }
  else {
    $('photoBrowserDiv').setStyle({height: (viewport().height)+'px', width: (viewport().width)+'px'});
  }

  // IE 8 AND UP
  if (IS_IE & BROWSER_VERSION >= 8) {
    $('photoBrowserFlashContentDiv').setStyle({right: '-16px'});
  }

//  setTimeout("$('photoBrowserFlashContentDiv').update('<object type=\"application/x-shockwave-flash\" data=\"../browser.swf\" width=\"100%\" height=\"100%\"><param name=\"movie\" value=\"../browser.swf\" /></object>')", 100);

  hideDropDownLists(true);
  try {
    $('rechercheDeBiensFormDiv').hide();
    $('logoTrefleDiv').hide();
    $('listeOffresDiv').hide();
  }
  catch (ex) {}

  var flashBgColor = '#A69581';
  $('photoBrowserDiv').show();
  $('photoBrowserTopBarDiv').show();
  $('photoBrowserFlashContentDiv').update('<object type=\"application/x-shockwave-flash\" bgcolor=\"'+flashBgColor+'\" data=\"../browser.swf\" width=\"100%\" height=\"100%\" wmode=\"opaque\"><param name=\"movie\" value=\"../browser.swf\" /><param name=\"bgColor\" value=\"'+flashBgColor+'\" /><param name=\"wmode\" value=\"opaque\" /></object>');
}


function closePhotoBrowser()
{
  hideDropDownLists(false);
  try {
    $('rechercheDeBiensFormDiv').show();
    $('logoTrefleDiv').show();
    $('listeOffresDiv').show();
  }
  catch (ex) {}

  $('photoBrowserDiv').hide();
  $('photoBrowserTopBarDiv').hide();

  $('photoBrowserFlashContentDiv').update('');
  $('bodyElement').setStyle({overflow: 'visible'});

  if (IS_IE_7)
    $('bodyElement').up().setStyle({overflow : 'auto'});

  setTimeout('jumpToCurrentOffre(); g_overrideOffreClientId = null; g_overrideOffreId = null;', 100);
}


function biensTriListe_Onchange_Handler(listObj, isListeInteret)
{
  listeOffres_loading();

  if (isListeInteret)
    $('rechercheDeBiensForm_champ_showListeInteretOnly').value = 'true';

  $('rechercheDeBiensForm_champ_tri').value = listObj.value;
  $('rechercheDeBiensFormId').submit();
}


function offreToListeDinteret(clientId, offreId, doAdd)
{
  var actionStr = doAdd ? 'addOffreToListeDinteret' : 'removeOffreToListeDinteret';

  new Ajax.Request(
    'biensalavente.php',
    {
    asynchronous : false,
    method:'get',
    parameters: { ff_action: actionStr, offreAgId: clientId, offreId: offreId},
    onSuccess: function(transport)
      {
        var offreIdsArray = transport.responseText.evalJSON();

        $('nbOffresDansListeDInteretSpan').update(offreIdsArray.length);

        if (offreIdsArray.length == 0)
          $('listeDInteretBlockSpan').hide();
        else
          $('listeDInteretBlockSpan').setStyle({display : 'block'});
      }
    });
}

var g_slideshowImgIndex = 0;
var g_slideshowImgHtmlArray;

function showMentionsLegales()
{
  jQuery.scrollTo(0, 0);

  jQuery('#fadedBackground')
  	.css({opacity: '0'}).show().animate({opacity: '0.7'}, 'slow')
  	.unbind('click')
  	.click(function(){hideMentionsLegales();})

  jQuery('#mentionsLegalesDiv').fadeIn('slow');
}


function hideMentionsLegales()
{
  jQuery.scrollTo(0, 0);

  jQuery('#fadedBackground')
  		.animate({opacity: '0'}, 'slow', function(){jQuery(this).hide()});

  jQuery('#mentionsLegalesDiv').fadeOut('slow');
}

var g_showBigPhotoPreview_imgIsLandscapeArray = new Array();

function showBigPhotoPreview(imgUrl, clientId, offreId)
{
  // FUNCTION DISABLED FOR TEST PURPOSES...
  return;

  if (g_showBigPhotoPreview_imgIsLandscapeArray[clientId+'_'+offreId] == top.undefined) {

    new Ajax.Request(
      'biensalavente.php',
      {
      asynchronous : false,
      method:'get',
      parameters: { ff_action: 'imgIsLandscape', imgUrl: imgUrl},
      onSuccess: function(transport){g_showBigPhotoPreview_imgIsLandscapeArray[clientId+'_'+offreId]=transport.responseText;}
      });
  }

  var imgAttrib = 'height="400"';

  if (g_showBigPhotoPreview_imgIsLandscapeArray[clientId+'_'+offreId] == 'true')
    imgAttrib = 'width="400"';

  $('listeOffresPhotoBigPreviewDiv').update('<img '+imgAttrib+' src="'+imgUrl+'" />');
  $('listeOffresPhotoBigPreviewDiv').show();
}


function hideBigPhotoPreview()
{
  // FUNCTION DISABLED FOR TEST PURPOSES...
  return;

  $('listeOffresPhotoBigPreviewDiv').hide();
}


// Global counter used to determine when all photo thumbnails are
// loaded so that we can start the slideshow (we need all thumbnails
// to be loaded because we need to determine each pictures's orientation (isLandscape)
// to set their movement direction ('up', 'left', ...) in the slideshow.
var g_nbOfThumbnailsLoaded;

// FOLLOWING FUNCTION IS EXECUTED WHEN DOM IS READY.
function ficheGenerateThumbnailsThenSlideshow()
{
	g_nbOfThumbnailsLoaded = 0;

	// For each photo,
	for (var i = 0; i < g_photos.length; i++) {

		// For each thumbnail, generate a <DIV><A/><IMG/></DIV>
		// DIV has the thumbnail image set as centered background
		// A is for a clickable link to the large version of the picture; The click is bound to the Shadowbox viewer
		// IMG is hidden and only used to be notified when the image is done loading so that we can start a fadeIn animation of the thumbnail.
		jQuery('#ficheBienPhotoThumbnailsDiv')
		   .append('<div id="thumbnailDiv_'+i+'" class="thumbnail" style="background-image: url(\''+g_photos[i].urlSmall+'\');">'
			 + '<a href="'+g_photos[i].urlHigh+'" title="'+jQuery('#ficheBienTitreDiv').text()+'">&nbsp;</a>'
			 + '<img id="thumbnailImg_'+i+'" src="'+g_photos[i].urlSmall+'" />'
		     + '</div>');

		// Create a 'loaded' event for the thumbnail img.
		// When an thumbnail image is loaded, we make it appear.
		// We also keep track on the total number of loaded
		// thumbnails and generate/start the slideshow when they
		// are ALL loaded.
	 	jQuery('#thumbnailImg_'+i).onImagesLoaded(function(imgElem){

	 		// Increment the global counter.
			g_nbOfThumbnailsLoaded++;

			// FadeIn the thumnail DIV container with some timing randomness.
			jQuery(imgElem).parent().hide().delay(Math.floor(Math.random()*3000)).fadeTo(6000, 1);

			// When all thumbnails are loaded
			if (g_nbOfThumbnailsLoaded == g_photos.length)
				// Workaround : delay slideshow work so that size of
				// loaded images can be reflected to the DOM and used to determine pictures' orientation.
				setTimeout(ficheGenerateAndStartSlideshow, 1000);
	      });
	}

	if (g_photos.length < 16)
		jQuery('#ficheBienPhotoThumbnailsDiv .thumbnail').css({width: '80px', height: '80px'});
	if (g_photos.length > 28)
		jQuery('#ficheBienPhotoThumbnailsDiv .thumbnail').css({width: '45px', height: '45px'});

	// Bind Shadowbox to thumbnail links
	//Shadowbox.clearCache();
	Shadowbox.setup(jQuery("#ficheBienPhotoThumbnailsDiv a"), {gallery: "galleryBien"});

	jQuery("#ficheBienPhotoThumbnailsDiv a").attr('title', 'Cliquez pour voir les photos en plein écran...');

	// Bind a mouseenter event to each thumbnails' A element to preview
	// a larger image in the slideshow area.
	jQuery('#ficheBienPhotoThumbnailsDiv a').mouseenter(
		function() {

			// Determine the index of the thumbnail on which the mouse just entered.
			var thumbnailIndex = jQuery(this).index('#ficheBienPhotoThumbnailsDiv a');

			// Show the photo preview container DIV.
			jQuery('#ficheBienPhotoPreviewDiv').show();

			// Update with the new photo with some animation fx
			jQuery('#ficheBienPhotoPreviewDiv img')
				.clearQueue()                                    // Clear any pending animation on this preview img element
				.fadeOut(0)                                      // Make img element transparent
				.attr('src', g_photos[thumbnailIndex].urlLarge)  // Set the img src with the wanted url
				.fadeTo(500, 1)                                  // Make the img fadeIn
				.animate((g_photos[thumbnailIndex].isLandscape) ? // Fit (with animation) the container according the orientation of the image
							{'width': '450px', 'left': '0', 'top': '56px'}
							:
							{'width': '337px', 'left': '56px', 'top': '0'}
						);

			// FadeOut (make transparent, not display:none) the slideshow container in order to get transparent preview background if needed.
			jQuery('#ficheBienMainPhotoSlideshow').fadeTo(0, 0);

			// IE Fix : Also hide children <img> of ficheBienMainPhotoSlideshow.
			// For some reason IE does not hide the children elements of the
			// #ficheBienMainPhotoSlideshow DIV when faded out (see fadeTo above);
			if (IS_IE)
				jQuery('#ficheBienMainPhotoSlideshow img').hide();

			jQuery('#ficheBienMainPhotoSlideshow').crossSlidePause();

			jQuery(this).parent().parent().find('div.thumbnail').removeClass('thumbnailSelected');
			jQuery(this).parent().addClass('thumbnailSelected');
		});

	// Bind a mouseleave event to each thumbnails' A element.
	jQuery('#ficheBienPhotoThumbnailsDiv a').mouseleave(
		function() {
			jQuery(this).parent().removeClass('thumbnailSelected');
		});

	// Bind a mouseleave event to the thumbnails parent DIV container to hide the photo preview.
	jQuery('#ficheBienPhotoThumbnailsDiv').mouseleave(
		function() {

			// Restore the slideshow container to full visibility.
			jQuery('#ficheBienMainPhotoSlideshow').fadeTo(0, 1);

			// IE Fix : Also restore visibility of previously hidden children <img>
			//          of ficheBienMainPhotoSlideshow. (see IE Fix note above).
			if (IS_IE)
				jQuery('#ficheBienMainPhotoSlideshow img').show();

			// FadeOut (make transparent, not display:none) the photo preview.
			jQuery('#ficheBienPhotoPreviewDiv').fadeOut(500);
			jQuery('#ficheBienMainPhotoSlideshow').crossSlideResume();
		});

}


// FOLLOWING FUNCTION IS EXECUTED WHEN DOM IS READY.
// AND IS EXECUTED WHEN ALL THUMBNAILS ARE LOADED (see
// comment on the g_nbOfThumbnailsLoaded global var).
// Executed from the ficheGenerateThumbnails() function.
var r = -1;
function ficheGenerateAndStartSlideshow()
{
    // Update global photo array by adding .src and .dir
    // members expected by crossSlide (slideshow jQuery plugin)
    // array of objects as follows :
    //  [ { src: 'http://abc.jpg', dir: 'up' },
	//    { src: 'http://cde.jpg', dir: 'down' } ]
//	for (var i=0; i < g_photos.length; i++) {
 		// Set the 'isLandscape' members of the global photos information array.
// 		var imgElem = jQuery('#thumbnailImg_'+i);
//		g_photos[i].isLandscape = imgElem.width() > imgElem.height();
		//console.log(imgElem.width());
//		g_photos[i].src = g_photos[i].urlLarge;                    // url of image
//		g_photos[i].dir = g_photos[i].isLandscape ? 'left' : 'up'; // animation direction
//	}

	// CrossSlide (slideshow jQuery plugin) expects an array of objects as follows :
	//  [ { src: 'http://abc.jpg', dir: 'up' },
	//    { src: 'http://cde.jpg', dir: 'down' } ]
	jQuery('#ficheBienMainPhotoSlideshow').crossSlide(
	  { speed: 25, fade: 1 /*, easing: 'jswing'*/ },
	  g_photos,
	  function (curImgIndex, curImgElem, nextImgIndex, nextImgElem){
	  	jQuery('#ficheBienPhotoThumbnailsDiv .thumbnail').removeClass('thumbnailSelected');
	  	jQuery('#thumbnailDiv_'+curImgIndex).addClass('thumbnailSelected');
	  }
	);

	// Pause slideshow when hovering on it.
	var inFunc = function(){jQuery('#ficheBienMainPhotoSlideshow').crossSlidePause();};
	var outFunc = function(){jQuery('#ficheBienMainPhotoSlideshow').crossSlideResume();};
	jQuery('#ficheBienMainPhotoSlideshow').hover(inFunc, outFunc);

	jQuery('#ficheBienPhotoPreviewDiv').fadeOut('slow');
}


/* This function must be executed when DOM is ready */
function bindClickLinkToOffreDivs()
{
	// Bind a click event to each offre Div to access the bien fiche.
/*
	jQuery('.offre').each(
		function(index, value)
		{
			var href = jQuery(this).find('a.offreRefLink').attr('href');
			jQuery(this).click(function() {location.href=href;});
		}
	);
*/
	jQuery('.offre table, .offre h2').each(
		function(index, value)
		{
			var href = jQuery(this).parent('.offre').find('a.offreRefLink').attr('href');
			jQuery(this).click(function() {location.href=href;});
		}
	);



	// Prevent click from bubbling up to the parent DIV for the following elements :
	// <label> : ajouter cette offre à ma liste d'intérêt
//	jQuery('.offreFooter label').click(function(event) {event.stopPropagation();});
	// <input type="checkbox"> for : ajouter cette offre à ma liste d'intérêt
//	jQuery('.offreFooter input[type=checkbox]').click(function(event) {event.stopPropagation();});
}

function listeOffres_loading()
{
	jQuery('#listeOffresDiv').html('<img style="padding-left: 25em; padding-top: 5em;" src="images/loading1.gif"/>');
}

function secteursSlideshow_loading()
{
	closeSecteurMap();
	jQuery('#pageSecteurs_slideshowWrapper').html('<img style="padding-left: 270px; padding-top: 200px; height: auto!important;" src="images/loading1.gif"/>');
}


function closeSecteurMap()
{
	//jQuery('#googleMapIFrame, #googleMapNoteDiv').hide();
	jQuery('#googleMapDiv, #googleMapNoteDiv').hide();
	jQuery('#pageSecteurs_slideshowWrapper, #pageSecteurs_slideshow_nav').show();
}


g_pageSecteurs_slideshow_currentSlideUrl = null;
function pageSecteurs_startSlideshow()
{
	jQuery('#pageSecteurs_slideshowWrapper').cycle({
	    fx: 'scrollHorz',
	    prev: '#googleMapIFrameDiv .prev',
        next: '#googleMapIFrameDiv .next',
	    delay: 1000,
	    timeout: 3000,
	    before: function(currEl, nextEl, opts ,fwd)
	    		{
	    			g_pageSecteurs_slideshow_currentSlideUrl =
	    				jQuery(nextEl).find('a').attr('href');
	    		}

	});

	// Pause testimonial slideshow when hovering on slideshow and on navigation buttons.
	var inFunc = function(){jQuery('#pageSecteurs_slideshowWrapper').cycle('pause');};
	var outFunc = function(){jQuery('#pageSecteurs_slideshowWrapper').cycle('resume');};
	jQuery('#pageSecteurs_slideshowWrapper, #pageSecteurs_slideshow_nav a').hover(inFunc, outFunc);
}


function secteursDiapoFullScreen()
{
	Shadowbox.open({
		content: g_pageSecteurs_slideshow_currentSlideUrl,
		player: 'img',
		gallery: 'secteurs'
	});
}


function pageSecteurs_reSetupSlideshowLinksAfterUpdate()
{
	// Remove any old objects from Shwadow box cache.
	Shadowbox.clearCache();
	// Have Shadowbox relink to all <a rel="shadowbox"> element present in the DOM
	Shadowbox.setup();

	// Now redefine click action on each image in the slideshow to access
	// the fiche of the bien.
	jQuery('#pageSecteurs_slideshowOffreContent a').each(
		function(index, value)
		{
			jQuery(this).attr('title', 'Cliquez pour accéder à la fiche de cette offre...');
			jQuery(this).unbind('click');
			jQuery(this).click(function(){
								  jQuery(this).blur();
								  var offreAgId = jQuery(this).attr('offreAgId');
								  var offreId = jQuery(this).attr('offreId');
								  document.location.href = "/biensalavente.php?ff_action=fiche&offreAgId="+offreAgId+"&offreId="+offreId;
								  return false;
								});
		}
	);

	console.log("pageSecteurs_reSetupSlideshowLinksAfterUpdate() DONE");
}


function disableContextMenuOnImages()
{
	jQuery('img').live('contextmenu', function(e){return false;});
}

function urlDecode(utftext)
{
	utftext = unescape(utftext.replace(/\+/g, ' '));

	var string = "";
	var i = 0;
	var c = c1 = c2 = 0;

	while ( i < utftext.length ) {

		c = utftext.charCodeAt(i);

		if (c < 128) {
			string += String.fromCharCode(c);
			i++;
		}
		else if((c > 191) && (c < 224)) {
			c2 = utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		}
		else {
			c2 = utftext.charCodeAt(i+1);
			c3 = utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}

	}

	return string;
}

