$(document).ready(function() {
	
	/* Navigation */
	function megaHoverOver(){
		$(this).find(".sub").show();
				
		/* if ($("div.sub", this).length > 0) {
			var finalW = 0;
			
			$("div.subCol", this).each(function(){			
				var childW = 0;
				var biggestChild = 0;	
				
				$("li.subnav", this).each(function(){				  
					childW = $(this).width();
					
					if(childW > biggestChild) {
						biggestChild = childW;
					}
				});	

				$("div.subCol", this).css({'width' : (biggestChild)});				
				finalW = finalW+biggestChild;
			});
			$("div.sub", this).css({'width' : (finalW+($("div.subCol", this).length*20))});				
			
		} */
	}
	
	function megaHoverOut(){ 
		$(this).find(".sub").hide();
	}

	var config = {    
		 sensitivity: 2,
		 interval: 0,
		 over: megaHoverOver,
		 timeout: 500,
		 out: megaHoverOut
	};

	//if($.browser.msie) { $('ul.topnav li').css('line-height','37px'); }
	$("ul.topnav li.topnav").hoverIntent(config);
	
	/* Connexion / Mot de passe perdu */
	$('#FormLoggerUtilisateur input').focus(function() {
		$('#LoggerUtilisateur_Err').slideUp('fast');
	});
		
	
	
	$('#FormMDPUtilisateur input').focus(function() {
		$('#MDPUtilisateur_Err').slideUp('fast');
	});
	
	
	
	$('#GoMDP').click(function() {
		InitialiserFormLoggerUtilisateur();
		InitialiserFormMDPUtilisateur();
		$('#LoggerUtilisateur').slideUp('fast', function() {
			$('#MDPUtilisateur').slideDown('fast', InitLabels);
		});
	});
	
	$('#GoLogger').click(function() {
		InitialiserFormLoggerUtilisateur();
		InitialiserFormMDPUtilisateur();
		$('#MDPUtilisateur').slideUp('fast', function() {
			$('#LoggerUtilisateur').slideDown('fast', InitLabels);
		});
	});
	
	/* Newsletter */	
	InitialiserPreFooterNewsletter();
	InitialiserPreFooterNewsletterByeBye();
	
	$('#FormPreFooterNewsletter input').click( function() {						
		$('#FormPreFooterNewsletterErr').slideUp('fast', function() {  $('#FormPreFooterNewsletterConsignes').slideDown('fast');});
	});
	
	$('#FormPreFooterNewsletterByeBye input').click( function() {						
		$('#FormPreFooterNewsletterByeByeErr').slideUp('fast', function() {  $('#FormPreFooterNewsletterByeByeConsignes').slideDown('fast');});
	});
	
	$("#FormPreFooterNewsletterByeByeLink").click(function() {
		InitialiserPreFooterNewsletterByeBye();
		$('#FormPreFooterNewsletterForm').slideUp('fast', function() {
			$('#FormPreFooterNewsletterFormByeBye').slideDown('fast', InitLabels);
		});
	});
	
	$("#FormPreFooterNewsletterLink").click(function() {
		InitialiserPreFooterNewsletter();
		$('#FormPreFooterNewsletterFormByeBye').slideUp('fast', function() {
			$('#FormPreFooterNewsletterForm').slideDown('fast', InitLabels);
		});
	});    
	
	/* Archives */
	ChangeAnneeArchive();
	
	/* Stuff */
	jQueryUI();
	jFancy();
		
	InitializeCufon();
	InitLabels();
});

function ChangeAnneeArchive()
{
	var annee_archive = $('#annee_archive').val();
	
	// Formatage les données
	var dataString = "&FormAction=MoisArchives&annee_archive="+annee_archive;	

	// Execution du formulaire
	$.ajax({
	  type: "POST",
	  url: "./op_archives.php",  
	  data: dataString,
	  dataType : 'html',
	  cache: false,
	  async: true,
	  success: function(data) { eval(data); return(false); },      	  
	  error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	 });
 
	return false;
}

function InitLabels()
{
	$("#LoggerUtilisateurIdentifiant, #LoggerUtilisateurMDP, #nom_contact_newsletter, #prenom_contact_newsletter, #email_contact_newsletter, #email_contact_newsletter_byebye").each(function(){
		$(this).Watermark($(this).attr('title'),"#848484");
	});
}

/* Form Newsletter */
function InitialiserPreFooterNewsletter() {
	
	$('#FormPreFooterNewsletterConsignes').show();
	$('#FormPreFooterNewsletterErr').html('').hide();
	
	$('#FormPreFooterNewsletter #nom_contact_newsletter').val('');   
	$('#FormPreFooterNewsletter #prenom_contact_newsletter').val('');   
	$('#FormPreFooterNewsletter #email_contact_newsletter').val('');   
}

function PreFooterNewsletter() {		
	
	// Formatage les données
	var dataString = $("form#FormPreFooterNewsletter").serialize();		
	dataString += "&FormAction=Inscription";	

	// Execution du formulaire
	$.ajax({
	  type: "POST",
	  url: "./op_newsletter.php",
	  beforeSend: function() { $.Watermark.HideAll(); $('#FormPreFooterNewsletterForm').hide(0, function () { $('#FormPreFooterNewsletterLoad').show(); } );  },	  
	  data: dataString,
	  dataType : 'html',
	  cache: false,
	  async: true,
	  success: function(data) {  $.Watermark.ShowAll(); $('#FormPreFooterNewsletterLoad').hide(0, function () { eval(data); $('#FormPreFooterNewsletterForm').show(); } );  return(false); },      	  
	  error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	 });
 
	return false;
}

function InitialiserPreFooterNewsletterByeBye() {	
	
	$('#FormPreFooterNewsletterByeByeConsignes').show();
	$('#FormPreFooterNewsletterByeByeErr').html('').hide();
	
	$('#FormPreFooterNewsletterByeBye #email_contact_newsletter_byebye').val('');   
}

function PreFooterNewsletterByeBye() {			
	
	// Formatage les données
	var dataString = $("form#FormPreFooterNewsletterByeBye").serialize();		
	dataString += "&FormAction=Desinscription";	

	// Execution du formulaire
	$.ajax({
	  type: "POST",
	  url: "./op_newsletter.php",
	  beforeSend: function() { $('#FormPreFooterNewsletterFormByeBye').hide(0, function () { $('#FormPreFooterNewsletterLoad').show(); } );  },	  
	  data: dataString,
	  dataType : 'html',
	  cache: false,
	  async: true,
	  success: function(data) {  $.Watermark.ShowAll(); $('#FormPreFooterNewsletterLoad').hide(0, function () { eval(data); $('#FormPreFooterNewsletterFormByeBye').show(); } );  return(false); },      	  
	  error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	 });
 
	return false;
}

function TelechargerDocument(id_document)
{
	// Execution du formulaire
	$.ajax({
	  type: "POST",
	  url: "./p_documents.php",		  
	  data: '&FormAction=TelechargerDocument&id_document='+id_document,
	  dataType : 'html',
	  cache: false,
	  async: true,
	  success: function(data) {	eval(data); return(false); },      
	  error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	 });
}

// Visionner une video
function VisionnerVideo(id_video)
{
	// Execution du formulaire
	$.ajax({
	  type: "POST",
	  url: "./p_videos.php",		  
	  data: '&FormAction=VisionnerVideo&id_video='+id_video,
	  dataType : 'html',
	  cache: false,
	  async: true,
	  success: function(data) {	$.fancybox(data, {overflow:'hidden'}); return(false); },      
	  error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	 });
}

function InitialiserFormLoggerUtilisateur() {					
	$('#LoggerUtilisateur_Err').slideUp('fast');
	$('#LoggerUtilisateurIdentifiant').val('Identifiant');
	$('#LoggerUtilisateurMDP').val('motdepasse');
}

function LoggerUtilisateur(gotoURL) {			
	
	// Formatage les données
	var dataString = $("form#FormLoggerUtilisateur").serialize();		
	dataString += "&FormAction=LoggerUtilisateur";
	if (gotoURL != "") dataString += "&gotoURL="+gotoURL+"&";	

	// Execution du formulaire
	$.ajax({
	  type: "POST",
	  url: "./op_connexion.php",
	  beforeSend: function() { $('#FormLoggerUtilisateurForm').hide(0, function () { $('#FormLoggerUtilisateurLoad').show(); } );  },
	  data: dataString,
	  dataType : 'html',
	  cache: false,
	  async: true,
	  success: function(data) {  eval(data); return(false); },      
	  error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	 });
 
	return false;
}

function InitialiserFormMDPUtilisateur() {					
	$('#MDPUtilisateur_Err').slideUp('fast');
	$('#MDPUtilisateurEmail').val('Adresse e-mail');
}

function MDPUtilisateur() {			
	// Formatage les données
	var dataString = $("form#FormMDPUtilisateur").serialize();		
	dataString += "&FormAction=MDPUtilisateur";		
		
	// Execution du formulaire
	$.ajax({
	  type: "POST",
	  url: "./op_connexion.php",
	  beforeSend: function() { $('#FormMDPUtilisateurForm').hide(0, function () { $('#FormMDPUtilisateurLoad').show(); } );  },
	  data: dataString,
	  dataType : 'html',
	  cache: false,
	  async: true,
	  success: function(data) { $('#FormMDPUtilisateurLoad').hide(0, function () { $('#FormMDPUtilisateurForm').show(); } ); eval(data); return(false); },      
	  error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	 });
 
	return false;
}

function isDefined(variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function jQueryUI() {
	
	$('form input[type=text], form input[type=password], form textarea').focus(function() { $('#'+$(this).attr('id')+"_Err").slideUp('fast'); });	
	
	$(".uiButton").button().mouseout(function() { $(this).removeClass('ui-state-focus'); });	
	
	$("button.qteButton").hover(function() { var src = str_replace('_off','_on', $('img',this).attr('src')); $('img',this).attr('src',src); }, function() { var src = str_replace('_on','_off', $('img',this).attr('src')); $('img',this).attr('src',src); });	
	
	$(".RadioSet").buttonset();
	
	$('.tooltip, .tooltip-s, .tooltip-n, .tooltip-w, .tooltip-e, .tooltip-ne, .tooltip-nw, .tooltip-se, .tooltip-sw').mouseover(function() { $(this).css('cursor', 'help'); });
	
	$('.tooltip').tipsy({title: 'alt', gravity: 's'});
	$('.tooltip-s').tipsy({title: 'alt', gravity: 's'});
	$('.tooltip-n').tipsy({title: 'alt', gravity: 'n'});
	$('.tooltip-w').tipsy({title: 'alt', gravity: 'w'});
	$('.tooltip-e').tipsy({title: 'alt', gravity: 'e'});
	
	$('.tooltip-ne').tipsy({title: 'alt', gravity: 'ne'});
	$('.tooltip-nw').tipsy({title: 'alt', gravity: 'nw'});
	
	$('.tooltip-se').tipsy({title: 'alt', gravity: 'se'});
	$('.tooltip-sw').tipsy({title: 'alt', gravity: 'sw'});
	
	
	$.datepicker.setDefaults($.datepicker.regional['fr']);
	$.datepicker.setDefaults({showWeek: true, dateFormat: 'dd/mm/yy', constrainInput: true}); 

		
	$('form.jqTransform').jqTransform();
}

function jFancy() {
	$('a.fancy').fancybox({ title: $('img',this).attr('alt') ,titlePosition : 'inside', 'zoomOpacity'	: true,	'zoomSpeedIn'	: 500, 'zoomSpeedOut'	: 500 , centerOnScroll : true});
	
	$('a.zoomable').each(function() {
		$(this).prepend('<div class="fancyMagnifier"></div>');
	});
	$('a.zoomable').hover(function() {
		$('.fancyMagnifier', this).show();
	}, function() {
		$('.fancyMagnifier', this).hide();
	});
}

/* SESSIONIZE */
function Sessionize(SessionVar, SessionVal, SessionArray, callBack) {
	var dataString = "FormAction=Sessionize&SessionVar="+SessionVar+"&SessionVal="+SessionVal+"&SessionArray="+SessionArray;		
		
	// Execution du formulaire
	$.ajax({
		type: "POST",
		url: "./includes.php",
		data: dataString,
		dataType : 'html',
		cache: false,
		async: true,
		success: function(data) { if ($.isFunction(callBack)) { callBack(); } else { eval(data); } return(false); },
		error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	});
	
	return false;
}

function UnSessionize(SessionVar, SessionArray, callBack) {
	var dataString = "FormAction=UnSessionize&SessionVar="+SessionVar+"&SessionArray="+SessionArray;		
		
	// Execution du formulaire
	$.ajax({
		type: "POST",
		url: "./includes.php",
		data: dataString,
		dataType : 'html',
		cache: false,
		async: true,
		success: function(data) { if ($.isFunction(callBack)) { callBack(); } else { eval(data); } return(false); },
		error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	});
	
	return false;
}

/* CUFON */
function InitializeCufon()
{		
	if ((Cufon != "undefined") && (true)) {

		Cufon.set('forceHitArea',true);
		
		Cufon.replace($('.NavigationInButton'), { fontFamily: 'gotham-narrow-bold', hover: { color: '#1F3650' } });			
		Cufon.replace($('.NavigationAutreButton'), { fontFamily: 'gotham-narrow-bold', hover: { color: '#1F3650' } });			
		
		Cufon.replace($('.CategorieTitre'), { fontFamily: 'gotham-narrow-ultra' });			
		Cufon.replace($('.CategorieResume'), { fontFamily: 'gotham-narrow-bold' });			
		
		Cufon.replace($('.ConfirmationCompteTitre'), { fontFamily: 'gotham-narrow-bold' });			
		Cufon.replace($('.ConfirmationCompteSsTitre'), { fontFamily: 'gotham-narrow-bold' });			
		
		//Cufon.replace($('li.topnav, li.subnav'), { fontFamily: 'Swiss721CondensedBT' });		
		Cufon.replace($('.BigTitre, .BigSsTitre, .SmlTitre, .SmlSsTitre, .ModuleVerticalTitre, .ModuleVerticalSsTitre, .DateAgenda, .EvtAgendaTitre, .EvtAgendaDate'), { fontFamily: 'gotham-narrow-bold' });					
		
	}
}

function Deconnexion(gotoURL)
{
	var dataString = "FormAction=Deconnexion&";		
	if (gotoURL != "") dataString += "gotoURL="+gotoURL+"&";
		
	// Execution du formulaire
	$.ajax({
		type: "POST",
		url: "./op_deconnexion.php",
		data: dataString,
		dataType : 'html',
		cache: false,
		async: true,
		success: function(data) { eval(data); return(false); },
		error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	});
	
	return false;
}


function getUrlVars()
{
    var vars = [], hash;
    
    //var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    
	var QString = $.address.queryString();
	var hashes = QString.split('&');
	
 
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
 
    return vars;
}

function trim (str, charlist) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6
    var whitespace, l = 0,
        i = 0;
    str += '';

    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }

    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }

    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }

    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}


function str_replace (search, replace, subject, count) {
   
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}
