/* SACD 2008 */
/* COMMON JAVASCRIPT FUNCTIONS */

var LOG_ENABLED = false;

jQuery.browser.msie6 = jQuery.browser.msie && (parseInt(jQuery.browser.version) == 6);
jQuery.browser.msie7 = jQuery.browser.msie && (parseInt(jQuery.browser.version) == 7);
jQuery.browser.msie67 = jQuery.browser.msie6 || jQuery.browser.msie7;

function do_log(msg){
	if (!LOG_ENABLED) {
		return false;
	}

	var layer = document.getElementById('log_layer');
	if (!layer){
		document.body.innerHTML += '<pre id="log_layer"></pre>';
		layer = document.getElementById('log_layer');
	}
	if (layer){
		layer.innerHTML = (new Date()) + ' ' + msg + '<br />' + layer.innerHTML;
	}
}


/* ENABLE ROLLOVER ON INPUT TYPE BUTTONS IN IE */
function submitRollOver(elt) {
	jQuery(elt).each( function() {
        if (jQuery(this).attr('class')) { var baseClass = jQuery(this).attr('class'); }
		else { var baseClass = ''; }
		jQuery(this).hover(
			function() {
				jQuery(this).addClass(baseClass+'Hover');
			},
			function () {
				jQuery(this).removeClass(baseClass+'Hover');
			}
		);
	});
}

/* ENABLE ROLLOVER ON LOGOS IN FOOTER (ALL BROWSERS) */
function footerLogosRollover(elt) {

    jQuery(elt).each( function() {
			var element = jQuery(this);
			var offSrc = element.attr('src');
			var onSrc = offSrc.replace('-off', '-on');

			jQuery(this).hover(
				function() {
					element.attr('src', onSrc);
				},
				function () {
					element.attr('src', offSrc);
				}
			);
	});
}

/* AGENDA ACCORDION */
function agendaAccordion(elt) {
	jQuery(elt).accordion({header:'h3',speed:'1',autoheight:true,alwaysOpen: false,active: '.selected'});
	jQuery(elt).addClass('accordionEnabled');
}

/* GLOSSARY ACCORDION */
function glossaryAccordion(elt) {
	jQuery(elt).accordion({header:'dt',speed:'1',autoheight:false,alwaysOpen: false,active: '.selected', animated: false});
	jQuery(elt).addClass('accordionEnabled');
}

/* SIMPLE SCROLLPANE */
function simpleScrollPane(elt) {
	jQuery(elt).jScrollPane({showArrows:true, scrollbarWidth : 15});
}

/* SAME HEIGHT FOR SAME CLASS ELEMENTS */
function sameHeight(elt) {
	if (!jQuery(elt).parent().hasClass('publiBox') && !jQuery(elt).parent().hasClass('thinkBox')) {
		var heightBlockMax = 0;
		jQuery(elt).each(function(){
			if(jQuery(this).height() > heightBlockMax) {
				heightBlockMax = jQuery(this).height();
			}
		}); // get max height
		if (jQuery.browser.msie6) {
			jQuery(elt).each(function(){
				jQuery(this).css("height",heightBlockMax);
			}); // assign max height
		} else {
			jQuery(elt).each(function(){
				jQuery(this).css("min-height",heightBlockMax);
			}); // assign max height
		}
		heightBlockMax = 0;
	}
}

/* FREQUENT QUESTIONS */
function frequentQuestions(elt) {
	jQuery(elt+' h3').addClass('offLeft');
	jQuery('#faqStep2, #faqStep3').addClass('disabled');
	jQuery(elt+' .themesList').addClass('offLeft');
	jQuery(elt+' .questionsList').addClass('offLeft');
	sameHeight('.faqStep1-2 .newsBoxInside');
	jQuery('#faqStep1 input:radio').click( function() {
    	jQuery('#faqStep2').removeClass('disabled');
    	jQuery('#faqStep3').addClass('disabled');
		jQuery('.themesList, .questionsList').addClass('offLeft');
		jQuery('#themesList'+jQuery(this).attr('id')).removeClass('offLeft');
		sameHeight('.faqStep1-2 .newsBoxInside');
	});
	jQuery('#faqStep2 a').click( function() {
    	jQuery('#faqStep3').removeClass('disabled');
		jQuery(elt+' .questionsList').addClass('offLeft');
		jQuery(jQuery(this).attr('href')).removeClass('offLeft');
		return false;
	});
}

/* HIDE/SHOW (OR TOGGLE OPEN/CLOSE) ELEMENTS */
function hideShow(elt) {
	jQuery(elt).addClass('offLeft');
	jQuery('.openClose').each( function() {
		jQuery(this).click( function() {
			if (jQuery(elt).hasClass('moreContentContactForm')) {
				jQuery(elt+' input').removeClass('validator-required').attr('checked','');
				jQuery(elt+' input:text').attr('value','');
				//if (jQuery(this).parent().children(elt).children('p.introContactForm').size() > 0) { jQuery(this).parent().children(elt).children('p.introContactForm').children('.inputText').addClass('validator-required'); }
				jQuery(this).parent().children(elt).children().children().children().children('.inputRadio:first').addClass('validator-required');
				jQuery(elt).addClass('offLeft').parent().removeClass('activePart');
				jQuery(this).parent().addClass('activePart').children(elt).removeClass('offLeft');
			} else if (jQuery(elt).hasClass('moreContentDemAuthForm')) {
				//alert('plaf');
				if(jQuery(this).attr("id") != "membreFedYes" && jQuery(this).attr("id") != "membreFedNo"){
					jQuery(elt+' input').toggleClass('validator-required');
					jQuery(elt+' select').toggleClass('validator-required');
					jQuery('#faxElse').removeClass('validator-required');
					jQuery('#faxRespElse').removeClass('validator-required');
					jQuery(this).parent().toggleClass('activePart').children(elt).toggleClass('offLeft');
				}
			} else if (jQuery(elt).hasClass('moreContentDemAuthFormSpecial')) {
				jQuery(this).parent().removeClass('activePart');

				if (jQuery(this).attr("id") == "membreFedYes") {
					jQuery('fedBox' + elt+' input').addClass('validator-required');
					jQuery(this).parent().parent().children(elt).removeClass('offLeft');
				} else if (jQuery(this).attr("id") == "membreFedNo") {
					jQuery('fedBox' + elt+' input').removeClass('validator-required');
					jQuery(this).parent().parent().children(elt).addClass('offLeft');
				}

			} else {
				jQuery(this).parent().toggleClass('activePart').children(elt).toggleClass('offLeft')
			}
		});
	});
}

/* PHOTO REPORTAGE DIAPORAMA */
function photoRepCarousel(elt) {
	jQuery(elt).jCarouselLite({
		btnNext: ".next",
		btnPrev: ".prev",
		visible: 4,
		speed: 800
	});    
}

/* PHOTO DIAPORAMA IN TABS */
function photoCarousel(elt) {
	jQuery(elt).jCarouselLite({
		btnNext: ".next",
		btnPrev: ".prev",
		visible: 5.4,
		speed: 800
	});

	jQuery(elt+' li a').click(function(){
		jQuery("#bigPic").attr("src",jQuery(this).attr("href")).attr("alt",jQuery(this).attr("title"));
		jQuery(".creditsBigPhoto").html(jQuery(this).attr("title"));
		return false;
	});
}

/* VIDEO DIAPORAMA IN TABS */
function videoCarousel(elt) {
	jQuery(elt).jCarouselLite({
        btnNext: ".nextVideo",
        btnPrev: ".prevVideo",
		visible: 5,
		speed: 800
    });

	 jQuery(elt+' li a').click(function(){
		jQuery("#bigVideoFrame").attr("src",jQuery(this).attr("href")).attr("title",jQuery(this).attr("title"));
		return false;
	 });
}

/* TABS IN AUTHOR STUDIO */
function tabsAuthor(elt) {
	jQuery(elt).tabs();
}

/* FORM CHECKING */
function formValidation(elt) {
	jQuery(elt).validationAideEnable(null,{summaryMessage: "<h3>Attention, vous devez remplir ou corriger le(s) champs suivant(s) :</h3>"});
}

/* LOGIN FORM CHECKING */
function loginFormValidation(elt) {
    jQuery(elt).validationAideEnable(null,{showSummary: false});
}

/* GA File Tracking */
function addLinkerEvents() {
  // List of local sites that should not be treated as an outbound link. Include at least your own domain here
  var extTrack = ["sacd.fr", "lamp", "groupe-belink.fr", "google-analytics.com"];  
  
  //List of file extensions on your site. Add/edit as you require
  var extDoc = ["doc", "xls", "exe", "zip", "pdf", "js", "txt", "mp3"];
  
  /*If you edit no further below this line, Top Content will report as follows:
    /ext/url-of-external-site
    /downloads/filename
    /mailto/email-address-clicked
  */
  
  var extFound = function(href, ignoreLocals) {
    var m;
    if (m = href.match(/^.*?:\/\/(.*?)\//)) {
      // may be an ext link
      var domain = m[1];
      if (!ignoreLocals) {
        for (var j=0; j<extTrack.length; j++) {
          if (domain.indexOf(extTrack[j]) == domain.length - extTrack[j].length) {
            // must be treated as local site
            return false;
          }
        }
      }
      return domain;
    } else {
      return false;
    }
  }
  
  jQuery('a[href]').each(function() {
    var flag = 0;
    var virtualFolder, virtualPath;
    
    // Tracking outbound links off site
    if (!virtualFolder) {
      if (extFound(this.href)) {
        var splitResult = this.href.split("//");
        virtualFolder = 'ext';
        virtualPath = splitResult[1];
      }
    }
    
    // Tracking electronic documents
    if (!virtualFolder) {
      for (var j=0; j<extDoc.length; j++) {
        if (this.href.indexOf('.' + extDoc[j]) == this.href.length - extDoc[j].length-1) {
          var domain = extFound(this.href, true);
          var splitResult;
          if (domain) {
            splitResult = this.href.split(domain + '/');
          } else {
            splitResult = ['', this.href];
          }
          virtualFolder = 'downloads';
          virtualPath = splitResult[1];
          if (this.href.match(/^\//)) {
            virtualPath = virtualPath.substring(1);
          }
          break;
        }
      }
    }
    
    // Tracking mail
    if (!virtualFolder) {
      // TODO
    }
    
    // Call pageTracker
    if (virtualFolder) {
      (function(a,v,p) {
        jQuery(a).click(function() {
          /*do_log('!');*/
					pageTracker._trackPageview('/' + virtualFolder + '/' + virtualPath);
        });
      })(this, virtualFolder, virtualPath);
    }
  });
  
}



jQuery(document).ready(function() {
	if (jQuery.browser.msie6) {
		SACD.fixPngImages();
	}
    /* ADD hasJS CLASS TO BODY FOR ABS/REL POSITIONNING */
	jQuery("body").addClass("hasJS");

	// Dropdown menu
	SACD.menus.init();

	jQuery('.toggle-member-access-form').click(function (){
		jQuery('#formLoginHeader').toggle();
	});

	/* ENABLE ROLLOVER ON INPUT TYPE BUTTONS IN IE & AGENDA TITLES */
	if (jQuery.browser.msie6) {
		submitRollOver('.inputSubmit');
		submitRollOver('.inputSubmitSpecial');
		submitRollOver('#agendaAccordion h3');
	}

	SACD.addHoverClass('#newHomeLayoutIntroBox fieldset');

	/* ENABLE ROLLOVER ON LOGOS IN FOOTER (ALL BROWSERS) */
	footerLogosRollover('#logosFooter img');

  /* SAME HEIGHT FOR ORGANIGRAMME ELEMENTS */
	sameHeight('.conseilAdmin .infosPeopleOrganigramme');
	/* SAME HEIGHT FOR INTRO EXPLOITOEUVRE ELEMENTS */
	sameHeight('#introExploitOeuvre ul');
	/* SAME HEIGHT FOR INTROS (DOTTED BACKGROUND) */
	sameHeight('.introBox');
	/* SAME HEIGHT FOR RESSOURCES BOXES */
	sameHeight('.ressTelListing .ressourcesBoxContent');

	/* SIMPLE SCROLLPANE ON AGENDA CULTURE */
	if (jQuery('.scrollPane').size() > 0) { initSimpleScrollPane = simpleScrollPane('.scrollPane'); }

	/* AGENDA CULTURE ACCORDION */
	if (jQuery('ul#agendaAccordion').size() > 0) { initAgendaAccordion = agendaAccordion('ul#agendaAccordion'); }

	/* GLOSSARY ACCORDION */
	if (jQuery('dl.glossary').size() > 0) { initGlossaryAccordion = glossaryAccordion('dl.glossary'); }

	/* HIDE ORGANIGRAMME'S SUBPARTS WHEN EXIST */
	if (jQuery('.moreContentOrganigramme').size() > 0) { initHideShow = hideShow('.moreContentOrganigramme'); }

    /* PHOTO DIAPORAMA */
    if (jQuery('#photoRepCarousel').size() > 0) { initPhotoRepCarousel = photoRepCarousel('#photoRepCarousel'); }

    /* VIDEO DIAPORAMA */
    if (jQuery('#videoCarousel').size() > 0) { initVideoCarousel = videoCarousel('#videoCarousel'); }

    /* PHOTO DIAPORAMA */
    if (jQuery('#photoCarousel').size() > 0) { initPhotoCarousel = photoCarousel('#photoCarousel'); }

    /* TABS IN AUTHOR STUDIO DETAIL */
    if (jQuery('.tabs').size() > 0) { initTabsAuthor = tabsAuthor('.tabs'); }

    /* FREQUENT QUESTIONS */
    if (jQuery('.faqBox').size() > 0) { initFrequentQuestions = frequentQuestions('.faqBox'); }

    /* SIMPLE CONTACT FORM CHECKING */
	if (jQuery('#contactSimple').size() > 0) { initformValidation = formValidation('#contactSimple'); }

    /* HIDE CONTACT FORM'S SUBPARTS WHEN EXIST */
    if (jQuery('.moreContentContactForm').size() > 0) {
			initHideShow = hideShow('.moreContentContactForm');
		}

	/* FULL CONTACT FORM CHECKING */
	if (jQuery('#contactFull').size() > 0) { initformValidation = formValidation('#contactFull'); }

	/* HIDE AUTHORIZATION REQUEST FORM'S SUBPARTS WHEN EXIST */
    if (jQuery('.moreContentDemAuthForm').size() > 0) { initHideShow = hideShow('.moreContentDemAuthForm'); }
    if (jQuery('.moreContentDemAuthFormSpecial').size() > 0) { initHideShow = hideShow('.moreContentDemAuthFormSpecial'); }

	/* AUTHORIZATION REQUEST FORM CHECKING */
	if (jQuery('#demandeAuth').size() > 0) { initformValidation = formValidation('#demandeAuth'); }

	/* BODY LOGIN FORM CHECKING */
	if (jQuery('#formLoginBody').size() > 0) { initLoginFormValidation = loginFormValidation('#formLoginBody'); }

  /* Formulaire d'identification Ajax */
	jQuery('.siteAjaxLogin').submit(SACD.onSubmitLoginbox);
  
  /* Data tables */
  jQuery('table.dataTable tr:even').addClass('alt');

	var windowHeight = 0;

	if(jQuery.browser.msie){
		windowHeight = window.document.compatMode == "CSS1Compat" ? document.documentElement.clientHeight : document.body.clientHeight;
	} else {
		windowHeight = window.innerHeight;
	}

	if(jQuery.browser.msie6){
		jQuery('#content').css('height', (windowHeight - 210) + 'px');
	} else{
		jQuery('#content').css('min-height', (windowHeight - 210) + 'px');
	}

	// Ouvrerture des liens pdfs dans une nouvelle fenêtre #2207
	jQuery('.dldPDF').click(function(event){
		if(event.target){
			window.open(event.target);
		}
		return false;
	});

	jQuery('a.xhtml-popup').click(function(event){
		window.open(this.href);
		return false;
	});

  /* GA File Tracking */
  addLinkerEvents();

	jQuery('input').each(function (){
		var item = jQuery(this);

		if(item.attr('type') == 'text' || item.attr('type') == 'password'){
			item.addClass('inputText');
		} else if(item.attr('type') == 'submit'){
			if(item.hasClass('csc-mailform-submit')){
				jQuery(this.parentNode).addClass('submit');
				item.addClass('inputSubmitSpecial');
			} else{
				item.addClass('inputSubmit');
			}
		} else if(item.attr('type') == 'file'){
			item.addClass('inputFile');
		}

	});

});


/* END */
var SACD = {
	actionUrl: '',
	onFailUrl: '',
	onFailLabel: '',
	overrideRedirectUrl: '',
	endCallBack: null,
	onSubmitLoginbox: function() {
		var parameters = {};

		tb_show('Test', false, '');

		for (i in this.elements){
			if (this.elements[i] && this.elements[i].name && this.elements[i].value) {
				parameters[this.elements[i].name] = this.elements[i].value;
			}
		}

		$.ajax({
			type: 'POST',
			url: SACD.actionUrl,
			data: parameters,
			success: function(msg, status){
				response = eval(msg);

				if (!response.login){
					var url = SACD.onFailUrl;

					url += '#KeepThis=true&TB_iframe=true&height=325&width=600';

					SACD.endCallback = function (){
						tb_show(SACD.onFailLabel, url);
					};
				} else{
					if (SACD.overrideRedirectUrl) {
						response.redirectUrl = SACD.overrideRedirectUrl;
					}
					SACD.endCallback = function (){
						document.location = response.redirectUrl;
					};
				}

				if(response.message) {
					tb_show(SACD.onFailLabel, response.message + '#?KeepThis=true&TB_iframe=true&height=325&width=600');

					var button = document.getElementById('TB_closeWindowButton');

					if (button.addEventListener) {
						button.addEventListener('click', SACD.endCallback, false);
					} else if (button.attachEvent) {
						button.attachEvent('onclick', SACD.endCallback);
					}

				} else {
					SACD.endCallback();
				}

			}
		});

		return false;
	},
	addHoverClass: function (elt, className){
		if(!className){
			className = 'sfHover';
		}
		jQuery(elt).hover(function (){
			jQuery(this).addClass(className);

			if(jQuery(this).hasClass('alt')){
				jQuery(this).addClass('alt' + className)
			}
		}, function (){
			jQuery(this).removeClass(className);

			if(jQuery(this).hasClass('alt')){
				jQuery(this).removeClass('alt' + className)
			}
		});
	},
	fixPngImages: function () {
		jQuery('img').each(function (){
			if(this.src.match(/\.png$/i)){
				this.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+this.src+'\', sizingMethod=\'image\');';
				jQuery(this).attr('src', 'clear.gif');
			}
		});
	}
};

SACD.emptyFunction = function (){}

SACD.menus = {
	init: function (){
		// Menu niveau 1 > 2
		jQuery('#navHeader').each(function (){
			SACD.menus.mouseOverMenuHandler(this, {
				hoverClass: 'menu-item-level-1-hover'
			});
		});

		var onElementDisplay = jQuery.browser.msie67 ? function (element){
			jQuery(element).find('.menu-level-3').each(function (){
				var ulWidth = jQuery(this).width();
				jQuery(this).css('width', ulWidth);

				jQuery(this).find('> li').each(function (){
					jQuery(this).css('width', ulWidth);
				});
			});
		} : SACD.emptyFunction;

		// Menu niveau 2 > 3
		jQuery('#navHeader .ssNavHeader').each(function (){
			SACD.menus.mouseOverMenuHandler(this, {
				hoverClass: 'menu-item-level-2-hover',
				disableCurrent: false,
				looseClassOnLeft: true,
				currentAddClass: 'menu-item-level-2-hover-simulated',
				onElementDisplay: onElementDisplay
			});
		});

		// Menu niveau 3
		jQuery('#navHeader .menu-level-3').each(function (){
			SACD.menus.mouseOverMenuHandler(this, {
				hoverClass: 'menu-item-level-3-hover',
				disableCurrent: true
			});
		});

		// Menu internes :
		jQuery('.intNav li.hasSubItems img').click(function (){
			jQuery(this.parentNode).toggleClass('item-clicked');
		});
	},
	mouseOverMenuHandler: function (menu, options) {
		// Merge with default options
		options = jQuery.extend({}, SACD.menus.mouseOverMenuHandler.defaultOptions, options);

		// Special inint for currentAddClass
		if(!options.currentAddClass) {
			options.currentAddClass = options.hoverClass;
		}

		// Get items
		var activePage = jQuery(menu).find('> .' + options.currentClass);
		var subItems = jQuery(menu).find('> li');

		// Auto activate "current" item
		if(!options.disableCurrent) {
			activePage.addClass(options.currentAddClass);
			//options.onElementDisplay(activePage);
		}

		// OnMouseOut menu close
		if(options.looseClassOnLeft){
			jQuery(menu).hover(SACD.emptyFunction,function (){
				subItems.removeClass(options.hoverClass);
				if(!options.disableCurrent) {
					activePage.addClass(options.currentAddClass);
				}
				//options.onElementDisplay(activePage);
			});
		}

		subItems.hover(function (){
			subItems.removeClass(options.hoverClass);
			if(!options.disableCurrent) {
				activePage.removeClass(options.currentAddClass);
			}
			jQuery(this).addClass(options.hoverClass);
			options.onElementDisplay(this);
		}, SACD.emptyFunction);
	},
	mouseClickMenuHandler: function (menu, clickedclass) {
		var subItems = jQuery(menu).find('> li');
		var wasClicked = false;
		var onElementDisplay = SACD.emptyFunction;


		// OnMouseOut menu close
		jQuery(menu).hover(SACD.emptyFunction, function (){
			subItems.removeClass(clickedclass);
			wasClicked = false;
		});
		
		// Menu persistance
		subItems.hover(function (){
			if(wasClicked){
				subItems.removeClass(clickedclass);
				jQuery(this).addClass(clickedclass);

				onElementDisplay(this);
			}
		}, SACD.emptyFunction);


		// onclick toggle
		jQuery(menu).find('> li > a').click(function (){
			var sub = jQuery(this).parent();
			var hasClass = sub.hasClass(clickedclass);
			subItems.removeClass(clickedclass);
			if(hasClass){
				wasClicked = false;
			} else {
				sub.addClass(clickedclass);
				onElementDisplay(sub);
				wasClicked = true;
			}

			return false;
		});	
	}
};

SACD.menus.mouseOverMenuHandler.defaultOptions = {
	hoverClass: 'sfHover',
	disableCurrent: false,
	looseClassOnLeft: false,
	currentClass: 'current',
	currentAddClass: false,
	onElementDisplay: SACD.emptyFunction
};

SACD.loadVideos = function (){
	jQuery('.videoContainer div').each(function (){
		var that = jQuery(this);
		var template = '';

		if(that.hasClass('dailymotion')){
			template = '<a href="http://www.dailymotion.com/video/%%%" onclick="window.open(this.href); return false"><img src="http://www.dailymotion.com/thumbnail/160x120/video/%%%" alt="" /></a>';
		} else if(that.hasClass('youtube')){
			template = '<a href="http://www.youtube.com/watch?v=%%%" onclick="window.open(this.href); return false"><img src="http://img.youtube.com/vi/%%%/2.jpg" alt="" /></a>';
		}

		if(template){
			that.html(template.split('%%%').join(that.html()));
		}

	});
}


