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

var LOG_ENABLED = false;

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() {
		jQuery(this).hover(
			function() {
				jQuery(this).attr("src", jQuery(this).attr("src").replace("-off","-on"));
			},
			function () {
				jQuery(this).attr("src", jQuery(this).attr("src").replace("-on","-off"));
			}
		);
	});
}

/* SUCKERFISH DROPDOWN MENUS */
function mySuperfish(elt) {
	jQuery(elt).superfish({
		pathClass : 'current',
		animation: {callback: 'toggle'}
	});
}

/* 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.msie) {
			if (parseInt(jQuery.browser.version) <= "6") {
				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
			}
		} 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();
}

/* FILE BOX FORM SELECT CHAINING */
function fileBoxChaining(elt1,elt2) {
	jQuery(elt1).change(function () {
		var elt1SelectedValue = jQuery(elt1).selectedValues();
        if (elt1SelectedValue == '0') {
	        jQuery(elt2).removeOption(/./);
		} else if (elt1SelectedValue == '1') {
	        jQuery(elt2).removeOption(/./);
			var myOptions = {
				"1-1" : "Dossier 1-1",
				"1-2" : "Dossier 1-2",
				"1-3" : "Dossier 1-3"
			}
			jQuery(elt2).addOption(myOptions, false);
		} else if (elt1SelectedValue == '2') {
	        jQuery(elt2).removeOption(/./);
            var myOptions = {
				"2-1" : "Dossier 2-1",
				"2-2" : "Dossier 2-2",
				"2-3" : "Dossier 2-3",
				"2-4" : "Dossier 2-4",
				"2-5" : "Dossier 2-5"
			}
			jQuery(elt2).addOption(myOptions, false);
        } else if (elt1SelectedValue == '3') {
	        jQuery(elt2).removeOption(/./);
            var myOptions = {
				"3-1" : "Dossier 3-1",
				"3-2" : "Dossier 3-2"
			}
			jQuery(elt2).addOption(myOptions, false);
		} else if (elt1SelectedValue == '4') {
	        jQuery(elt2).removeOption(/./);
    		var myOptions = {
				"4-1" : "Dossier 4-1",
				"4-2" : "Dossier 4-2",
				"4-3" : "Dossier 4-3",
				"4-4" : "Dossier 4-4"
			}
			jQuery(elt2).addOption(myOptions, false);
		}

	}).change();
}

/* 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"];
  
  /*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() {

    /* ADD hasJS CLASS TO BODY FOR ABS/REL POSITIONNING */
	jQuery("body").addClass("hasJS");

    /* HIDE QUICK LINKS */
	jQuery('#quickAccess').addClass('offLeft');

    /* SUCKERFISH DROPDOWN MENUS */
    if (jQuery('ul#navHeader').size() > 0) {
			jQuery('#navHeader').addClass('offLeft');
			initMainNav = mySuperfish("ul#navHeader");
			jQuery('#navHeader').removeClass('offLeft');
		}

    /* ENABLE ROLLOVER ON INPUT TYPE BUTTONS IN IE & AGENDA TITLES */
    if (jQuery.browser.msie && parseInt(jQuery.browser.version) <= "6" && jQuery('.inputSubmit').size() > 0) { initSubmitRollOver = submitRollOver('.inputSubmit'); }
    if (jQuery.browser.msie && parseInt(jQuery.browser.version) <= "6" && jQuery('.inputSubmitSpecial').size() > 0) { initSubmitRollOver = submitRollOver('.inputSubmitSpecial'); }
    if (jQuery.browser.msie && parseInt(jQuery.browser.version) <= "6" && jQuery('#agendaAccordion h3').size() > 0) { initSubmitRollOver = submitRollOver('#agendaAccordion h3'); }

    /* ENABLE ROLLOVER ON LOGOS IN FOOTER (ALL BROWSERS) */
	if (jQuery('.swapImg').size() > 0) { initFooterLogosRollover = footerLogosRollover('.swapImg'); }

	/* SAME HEIGHT FOR ALL FOOTER ELEMENTS */
	if (jQuery('#footerMain .colsFooter').size() > 1) { initSameHeight = sameHeight('#footerMain .colsFooter'); }

    /* SAME HEIGHT FOR NEWSBOX ELEMENTS */
	if (jQuery('.secondLine .newsBoxInside').size() > 1) { initSameHeight = sameHeight('.secondLine .newsBoxInside'); }

    /* SAME HEIGHT FOR TOOLSBOXES ELEMENTS */
	if (jQuery('.secondLine .toolsBoxInside').size() > 1) { initSameHeight = sameHeight('.secondLine .toolsBoxInside'); }

    /* SAME HEIGHT FOR ORGANIGRAMME ELEMENTS */
	if (jQuery('.conseilAdmin .infosPeopleOrganigramme').size() > 1) { initSameHeight = sameHeight('.conseilAdmin .infosPeopleOrganigramme'); }

    /* SAME HEIGHT FOR INTRO EXPLOITOEUVRE ELEMENTS */
	if (jQuery('#introExploitOeuvre ul').size() > 1) { initSameHeight = sameHeight('#introExploitOeuvre ul'); }

    /* SAME HEIGHT FOR INTROS (DOTTED BACKGROUND) */
	if (jQuery('.introBox').size() > 1) { initSameHeight = sameHeight('.introBox'); }

    /* SAME HEIGHT FOR RESSOURCES BOXES */
	if (jQuery('.ressTelListing .ressourcesBoxContent').size() > 1) { initSameHeight = 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'); }

    /* FILE BOX CHAINING */
	if (jQuery('#fileBoxForm').size() > 0) { initFileBoxChaining = fileBoxChaining('#fileTheme','#fileChoice'); }


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

	// Ouvrerture des liens pdfs dans une nouvelle fenêtre #2207
	jQuery('.dldPDF').click(function(event){
		if(event.target){
			window.open(event.target);
		}
		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 + '=' + escape(this.elements[i].value);
			}
		}

		$.ajax({
			type: 'POST',
			url: SACD.actionUrl,
			data: parameters.substr(1, parameters.length - 1),
			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;
	}
};
