// -----------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------
// RDC - Jquery document ready ///////////////////////////////////////////////////////
// -----------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------

// -----------------------------------------------------------------------------------
// Set interval (mot de passe enregistre) ////////////////////////////////////////////
// -----------------------------------------------------------------------------------
(function($) {
	jQuery.fn.setIntervalPass = function(params) {
		var params = $.extend({
			clear : false
		}, params);
		if (params.clear) clearInterval($.passout);
		else
		$.passout = setTimeout(function(){
			$('#login-area-password').trigger('focusout');
			$().setIntervalPass();
		},100);		
	};	
})(jQuery);

/////////////////////////////////////////////////////
// JQUERY Onload
/////////////////////////////////////////////////////
jQuery (function($) {

	// ----------------------------------------------
	// Partager sur facebook
	// ----------------------------------------------

	$('#sheet-facebook a').click(function() { 
		var url = $(this).attr('href');
		window.open(url, "Facebook", "toolbar=0, scrollbars=0, resizable=0, width=600, height=450, menubar=0");
		return false;
	});

	// ----------------------------------------------
	// Insertion des vidéos (fiches)
	// ----------------------------------------------

	if ($('#embed-video')) {
		if ($.chapPlayer) 	var chap = '%26chapitre='+$.chapPlayer;
		else				var chap = '';
		var flashvars	= { xml : $.root+'/medias/flash/player.php?sid='+$.sid+chap };
		var params 		= { allowFullScreen : 'true', wmode : 'transparent' };
		var attributes 	= {};
		swfobject.embedSWF($.root+'/medias/flash/playerVideo.swf', 'embed-video', '660', '370', '9.0.115', $.root+'/medias/flash/expressInstall.swf', flashvars, params, attributes);
	}

	// ----------------------------------------------
	// Composer les formulaires
	// ----------------------------------------------
	
	$('input, select, textarea').formComposer();
	
	// ----------------------------------------------
	// Affiche le contenu du ALT dans input[text]
	// ----------------------------------------------
	
	$('input[type=text], input[type=password]').placeholder();
	$('#login-area-email').bind('focusin', function(event) {
		$().setIntervalPass();
	});		
	$('#login-area-email').bind('focusout', function(event) {
		$().setIntervalPass({ clear : true });
	});		

	// ----------------------------------------------
	// Carrousel des push "conseils pratiques"
	// ----------------------------------------------
	
	var countPushSlider = $('#push-tip li').length;
	if(countPushSlider > 1) {
		$('#push-tip ul').bxSlider({
			mode			: 'fade',
			pause			: 4000,
			speed			: 600,
			auto			: true,
			autoControls	: false,
			autoHover		: true,
			pager			: false,
			controls		: false
		});
	}

	// ----------------------------------------------
	// Carrousel des Fiches
	// ----------------------------------------------
	
	var countSheetSlider = $('#sheet-media li').length;
	if(countSheetSlider > 1) {
		$('#sheet-media ul').bxSlider({
			mode			: 'fade',
			pause			: 3000,
			speed			: 600,
			auto			: true,
			autoControls	: false,
			autoHover		: true,
			pager			: false,
			controls		: false
		});
	}

	// ----------------------------------------------
	// Categories sélectionnées du menu principal
	// ----------------------------------------------
	
	$('#main-menu a').bind('click', function() { 
		var pid = $(this).attr('id');
		if (pid != $.mainActive) {
			$.mainActive = pid;
			$('#main-menu a').removeAttr('class');
			$(this).addClass('active');
			if ($('#categ-menu').length != 0) {
				$('#categ-menu').stop().animate(
					{ height : 0 }, 
					{ duration : 300, complete : function() { 
						$().loadCategMenu({ pid : pid });
					}
				});		
			} else {
				$().loadCategMenu({ pid : pid });
			}
		} else {
			$('#categ-menu').stop().animate(
				{ height : 0 }, 
				{ duration : 300, complete : function() { 
					$(this).remove();
					$('#main-menu a').removeAttr('class');
					if ($.mainSelected) $('#'+$.mainSelected).addClass('selected');
					$.mainActive = null;
				}
			});			
		}
		return false;
	});
	
	// ----------------------------------------------
	// DOCK effect sur la zone push deco
	// ----------------------------------------------
	
	// Event
	$('#push-deco li div')
	.bind('mouseenter', function(){
		$().setIntervalPushDeco({ clear : true });
		if ('push-deco-item-'+$.pushDecoSelect != $(this).attr('id')) {
			$('#push-deco-item-'+$.pushDecoSelect).hidePushDeco();
			$.pushDecoSelect = ($(this).parent().index()+1);
			$(this).showPushDeco();			
		} else if ($(this).attr('class') != 'active') {
			$.pushDecoSelect = ($(this).parent().index()+1);
			$(this).showPushDeco();				
		}
	})
	.bind('mouseleave', function(){
		$(this).hidePushDeco();
		$().setIntervalPushDeco();
	});
	
	// Init
	$.lastPushDecoAnim = $.pushDecoImg[0];
	$('#push-deco').css( 'backgroundImage', 'url('+$.lastPushDecoAnim+')');			
	$('#push-deco li').hide().delayQueue({
		effect		: function() {
			if ($.browser.msie && parseInt($.browser.version) == 7)	$(this).fadeIn(300);	
			else													$(this).show('drop', { direction: 'down' }, 300);
		},
		callback 	: function() {
			$().setIntervalPushDeco();
			$('#push-deco-item-'+$.pushDecoSelect).showPushDeco();
		}
	});	
	
	// ----------------------------------------------
	// TABS sheet
	// ----------------------------------------------
	
	// Init
	if ($.browser.msie && parseInt($.browser.version) == 7)
		$('#sheet-tabs').tabs();
	else
		$('#sheet-tabs').tabs({ fx: { opacity: 'toggle', duration: 150 } });
	
	// Event
	$('#sheet-tabs').bind('tabsshow', function(event, ui){
		var id 		= ui.panel.id;
		if ($.chapPlayer) 	var chap = '?chapitre='+$.chapPlayer;
		else				var chap = '';
		var locat	= $(document).attr('location').pathname+chap+'#'+id;
		var hash 	= ui.tab.hash;
		hash = hash.replace(/^#/,'');
		var node = $('#'+hash);
		if (node.length) node.attr('id','');
		document.location = locat;
		if (node.length) node.attr('id',hash);
		return false;
	});
	
	// Clean class
	$('#sheet-tabs').removeAttr('class');	
	$('#sheet-tabs ul').removeClass('ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');
	$('#sheet-tabs li').removeClass('ui-corner-top');
	$('#sheet-tabs div').removeClass('ui-widget-content ui-corner-bottom');
	
	// ----------------------------------------------
	// SLIDERS
	// ----------------------------------------------
	
	// M2
    var m2RealValue = [10, 25, 50, 75, 100];
    var m2Step 		= [0, 28, 49, 70, 100];
	$('#m2 .slider').slider({
		animate	: true,
		range	: true,
		min		: 0,
		max		: 100,
		step	: 1,
		values	: [getStep(m2Step, m2RealValue, $.minM2), getStep(m2Step, m2RealValue, $.maxM2)],
		stop	: function(event, ui) { 
			$('#min-m2-value').attr('value', getRealValue(m2Step, m2RealValue, ui.values[0])); 
			$('#max-m2-value').attr('value', getRealValue(m2Step, m2RealValue, ui.values[1])); 
		},
        slide: function(event, ui) {
			var cl 	= event.keyCode != $.ui.keyCode.RIGHT;
			var cr 	= event.keyCode != $.ui.keyCode.LEFT;
			var val	= findNearest(cl, cr, ui.value, m2Step);
			if (ui.value == ui.values[0])	$(this).slider('values', 0, val);
			else							$(this).slider('values', 1, val);
			return false;
        }			
	});	
	$('#m2').append('<ul class="scale">'+
						'<li class="first">< 10m<sup>2</sup></li>'+
						'<li>25m<sup>2</sup></li>'+
						'<li>50m<sup>2</sup></li>'+
						'<li>75m<sup>2</sup></li>'+
						'<li class="last">> 100m<sup>2</sup></li>'+
					'</ul>');	
	
	// Price
    var priceRealValue 	= [10000, 15000, 20000, 50000];
    var priceStep		= [0, 35, 61, 100];	
	$('#price .slider').slider({
		animate	: true,
		range	: true,
		min		: 0,
		max		: 100,
		step	: 1,
		values	: [getStep(priceStep, priceRealValue, $.minPrice), getStep(priceStep, priceRealValue, $.maxPrice)],
		stop	: function(event, ui) { 
			$('#min-price-value').attr('value', getRealValue(priceStep, priceRealValue, ui.values[0])); 
			$('#max-price-value').attr('value', getRealValue(priceStep, priceRealValue, ui.values[1])); 
		},
        slide: function(event, ui) {
			var cl 	= event.keyCode != $.ui.keyCode.RIGHT;
			var cr 	= event.keyCode != $.ui.keyCode.LEFT;
			var val	= findNearest(cl, cr, ui.value, priceStep);
			if (ui.value == ui.values[0])	$(this).slider('values', 0, val);
			else							$(this).slider('values', 1, val);
			return false;
        }
	});	
	$('#price').append('<ul class="scale">'+
						'<li class="first">< 10 000 €</li>'+
						'<li>15 000 €</li>'+
						'<li>20 000 €</li>'+
						'<li class="last">> 50 000 €</li>'+
					'</ul>');

	// Trouver la valeur autorisée la plus proche
	function findNearest(cl, cr, value, values) {
		var nearest = null;
		var diff 	= null;
		for (var i = 0; i < values.length; i++) {
			if ((cl && values[i] <= value) || (cr && values[i] >= value)) {
				var newDiff = Math.abs(value - values[i]);
				if (diff == null || newDiff < diff) {
					nearest = values[i];
					diff 	= newDiff;
				}
			}
		}
		return nearest;
	}
	
	// Retourne la valeur du step
    function getStep(step, values, value) {
        for (var i = 0; i < values.length; i++)
            if (values[i] >= value)
                return step[i];
        return 0;
    }
	
	// Retourne la valeur à envoyer
    function getRealValue(step, values, value) {
        for (var i = 0; i < step.length; i++)
            if (step[i] >= value)
                return values[i];
        return 0;
    }	
	
	// Init		
	$('.ui-slider-range').append('<span><span></span></span>');

	// ----------------------------------------------
	// RECHERCHE
	// ----------------------------------------------
	
	// Mot rechercher
	$('#advanced-search').submit( function() { 
		if ($('#search-word').val() == 'Votre recherche') 	$value = '';
		else 												$value = $('#search-word').val()
		$('#hidden-search-word').val($value);
	});

	// ----------------------------------------------
	// CARNET DE PROJET
	// ----------------------------------------------

	// switcher pour le champ téléphone
	$('input[name=user_optin2]').bind('click', function() { 
		if ($(this).val() == 1 && $('input[name=user_optin3]:checked').val() != 1) $('#mcp_tel').removeAttr('disabled').trigger('blur');
		else if ($('input[name=user_optin3]:checked').val() != 1) $('#mcp_tel').attr('disabled', 'disabled').trigger('blur');
	});
	$('input[name=user_optin3]').bind('click', function() { 
		if ($(this).val() == 1 && $('input[name=user_optin2]:checked').val() != 1) $('#mcp_tel').removeAttr('disabled').trigger('blur');
		else if ($('input[name=user_optin2]:checked').val() != 1) $('#mcp_tel').attr('disabled', 'disabled').trigger('blur');
	});

	// sélection des fiches et études
	$('.sheet-cart li, .etu-cart li').bind('click', function() {
		if ($(this).find('input:checkbox').is(':checked')) {
			$(this).removeClass('active');
			var checkbox	= $(this).find('input:checkbox');
			var checkId 	= checkbox.attr('id');
			checkbox.attr('checked',false);				
			$(this).find('.input-checkbox').formClassComposer({ 
				eventClass	: 'checked',
				realInput	: checkId,
				action		: 'remove'					
			});					
		} else {
			$(this).addClass('active');		
			var checkbox	= $(this).find('input:checkbox');
			var checkId 	= checkbox.attr('id');
			checkbox.attr('checked',true);				
			$(this).find('.input-checkbox').formClassComposer({ 
				eventClass	: 'checked',
				realInput	: checkId,
				action		: 'add'					
			});	
		}
	});

	// vérification qu'une fiche (au moins) est checked
	function checkForButton() {
		var ret = null;
		$('.selectbox input:checkbox').each(function() { 
			if ($(this).is(':checked')) ret = true;	
		});
		return ret;
	}
	// ouverture de la boite de dialogue d'erreur si aucune fiche n'est checked
	function openDialogButtonError() {
		var dialog = $('<div id="ButtonError"><p class="dialog-info">Merci de sélectionner au moins une fiche !</p></div>').appendTo('body');	
		dialog.dialog({
			show		: 'fade',
			hide		: 'fade',
			title		: 'Information',
			modal		: true,
			minHeight	: false,
			resizable	: false,
			buttons		: { ok : function() { $(this).dialog('close'); }},		
			close		: function() { $(this).dialog('destroy'); dialog.remove(); },
			open		: function() {
				$('.ui-widget-overlay').css('opacity',0).animate({ opacity: 0.6 }, { duration: 300 });
			}
		});
		return false;
	}
	// IE hack - la value d'un <button> n'est jamais retournée sous IE7/IE6		
	$('#selection-send').click(function() 		{ if (!checkForButton()) { openDialogButtonError(); return false; } else {  $('#cmd-hack').val('send') 		} });
	$('#selection-download').click(function() 	{ if (!checkForButton()) { openDialogButtonError(); return false; } else {  $('#cmd-hack').val('download') 	} });
	$('#selection-print').click(function() 		{ if (!checkForButton()) { openDialogButtonError(); return false; } else {  $('#cmd-hack').val('print'); 	} });
	$('#selection-delete').click(function() 	{ if (!checkForButton()) { openDialogButtonError(); return false; } else {  $('#cmd-hack').val('delete'); 	} });

	// options de sélections
	$('#etude-select-option').prepend('<span id="etude-select-all">Sélectionner toutes mes études</span><span id="etude-unselect-all">Annuler la sélection</span>');
	$('#deco-select-option').prepend('<span id="deco-select-all">Sélectionner toutes les ambiances déco</span><span id="deco-unselect-all">Annuler la sélection</span>');
	$('#tip-select-option').prepend('<span id="tip-select-all">Sélectionner tous les conseils pratiques</span><span id="tip-unselect-all">Annuler la sélection</span>');
	// tous sélectionner
	$('#etude-select-all, #deco-select-all, #tip-select-all').bind('click', function() { 
		$(this).parents('.selectbox').find('li').each(function() {
			$(this).addClass('active');																
			var checkbox	= $(this).find('input:checkbox');
			var checkId 	= checkbox.attr('id');
			checkbox.attr('checked',true);				
			$(this).find('.input-checkbox').formClassComposer({ 
				eventClass	: 'checked',
				realInput	: checkId,
				action		: 'add'					
			});																				
		});
	});
	// tous désélectionner
	$('#etude-unselect-all, #deco-unselect-all, #tip-unselect-all').bind('click', function() { 
		$(this).parents('.selectbox').find('li').each(function() {
			$(this).removeClass('active');																
			var checkbox	= $(this).find('input:checkbox');
			var checkId 	= checkbox.attr('id');
			checkbox.attr('checked',false);				
			$(this).find('.input-checkbox').formClassComposer({ 
				eventClass	: 'checked',
				realInput	: checkId,
				action		: 'remove'					
			});																				
		});
	});

	// ----------------------------------------------
	// ETUDE PERSONNALISEE
	// Quelle(s) pièce(s) souhaitez-vous créer ?
	// ----------------------------------------------		
	// ajouter une pièce
	$('#add-room').click(function() { 
		var lib	= $('option:selected', '#room').text();
		var val	= $('option:selected', '#room').val();
		var nb	= $('option:selected', '#nb-room').val();
		if (val == 'ue_multipiece') {
			$('option[value="1"]', '#nb-room').attr('disabled','disabled');
			if (nb == '1') {
				$('option[value="2"]', '#nb-room').attr('selected','selected');
				$('#select_nb-room .select-button').text('2');
				nb = '2';
			}
			$('#select-list_nb-room').trigger('blur');
		} else {
			$('option[value="1"]', '#nb-room').removeAttr('disabled');
			$('#select-list_nb-room').trigger('blur');			
		}	
		if ($('#'+val).length != 0) {
			$('#'+val).html('<input type="hidden" value="'+nb+'" name="'+val+'" />'+lib+' ('+nb+')');	
		} else {
			$('#room-box').append('<span id="'+val+'" class="delete-room" title="Supprimer cette sélection">'+
								  	'<input type="hidden" value="'+nb+'" name="'+val+'" />'+lib+' ('+nb+')'+
								  '</span>');
		}
	});
	// supprimer une pièce
	$('.delete-room').live('click',function() { 
		$(this).remove();
	});
	// première sélection d'une pièce
	$('#room').bind('change', function() { 
		var val	= $('option:selected', '#room').val();
		var nb	= $('option:selected', '#nb-room').val();
		if (val == 'ue_multipiece') {
			$('option[value="1"]', '#nb-room').attr('disabled','disabled');
			if (nb == '1') {
				$('option[value="2"]', '#nb-room').attr('selected','selected');
				$('#select_nb-room .select-button').text('2');
				nb = '2';
			}
			$('#select-list_nb-room').trigger('blur');
		} else {
			$('option[value="1"]', '#nb-room').removeAttr('disabled');
			$('#select-list_nb-room').trigger('blur');			
		}
		if ($('#room-box').children().length == 0) {
			var lib	= $('option:selected', '#room').text();
			var val	= $('option:selected', '#room').val();
			var nb	= $('option:selected', '#nb-room').val();						
			$('#room-box').append('<span id="'+val+'" class="delete-room" title="Supprimer cette sélection">'+
								  	'<input type="hidden" value="'+nb+'" name="'+val+'" />'+lib+' ('+nb+')'+
								  '</span>');		
		}	
	});
	// nombre de pièce
	$('#nb-room').bind('change', function() { 
		var lib	= $('option:selected', '#room').text();
		var val	= $('option:selected', '#room').val();
		var nb	= $('option:selected', '#nb-room').val();									   
		if (val == 'ue_multipiece') {
			$('option[value="1"]', '#nb-room').attr('disabled','disabled');
			if (nb == '1') {
				$('option[value="2"]', '#nb-room').attr('selected','selected');
				$('#select_nb-room .select-button').text('2');
				nb = '2';
			}
			$('#select-list_nb-room').trigger('blur');
		} else {
			$('option[value="1"]', '#nb-room').removeAttr('disabled');
			$('#select-list_nb-room').trigger('blur');			
		}
		if ($('#'+val).length != 0)
			$('#'+val).html('<input type="hidden" value="'+nb+'" name="'+val+'" />'+lib+' ('+nb+')');	
		
	});	
	
	// ----------------------------------------------
	// ETUDE PERSONNALISEE
	// slider hauteur sans entrave
	// ----------------------------------------------	
	$.heIndex = $('#ue_haut_entr option:selected').index();
	var heSelect = $('#ue_haut_entr');
	var he = Array("Moins d'1m", "Entre 1m et 1,50m", "Entre 1,50m et 1,80m", "Entre 1,80m et 2m");	
	$('#slider-ue_haut_entr').slider({
		min		: 0,
		max		: 7,
		range	: 'min',
		value	: $.heIndex,
		slide	: function( event, ui ) {
			if (ui.value >= 4)	return false;
			if (ui.value == 3)	$('.ui-slider-handle',this).css('right',0);
			else				$('.ui-slider-handle',this).css('right','');
			$('.ui-slider-handle',this).text(he[ui.value]);
			heSelect[0].selectedIndex = ui.value;
			$.heIndex = ui.value;
		}		
	});
	$('#slider-ue_haut_entr .ui-slider-handle').text(he[$.heIndex]);

	// switcher le statut du slider
	$('input[name=ue_debout]').bind('click', function() { 
		if ($(this).val() == 'n') 	he_switcher('enabled', heSelect, he);
		else						he_switcher('disabled', heSelect, he);	
	});
	$('input[name=ue_debout]:checked').trigger('click');

	// fonction switch du slider
    function he_switcher(statu, heSelect, he) {
		if (statu == 'enabled') {
			$('#ue_haut_entr').parents('fieldset').removeClass('disabled');
			$('#ue_haut_entr').removeAttr('disabled').trigger('blur');
		} else {
			$('#ue_haut_entr').parents('fieldset').addClass('disabled');
			$('#ue_haut_entr').attr('disabled','disabled').trigger('blur');
		}
		if ($('#ue_haut_entr').is(':disabled')){ 
			$('#slider-ue_haut_entr').slider('disable');
			$('#slider-minus').unbind('click');
			$('#slider-plus').unbind('click');
		} else {
			$('#slider-ue_haut_entr').slider('enable');
			$('#slider-minus').bind('click', function() { 
				if ($.heIndex > 0) 	$.heIndex = $.heIndex-1;
				if ($.heIndex == 3)	$('#slider-ue_haut_entr .ui-slider-handle').css('right',0);
				else				$('#slider-ue_haut_entr .ui-slider-handle').css('right','');
				$('#slider-ue_haut_entr .ui-slider-handle').text(he[$.heIndex]);
				$('#slider-ue_haut_entr').slider('value',$.heIndex);
				heSelect[0].selectedIndex = $.heIndex;
			});
			$('#slider-plus').bind('click', function() { 
				if ($.heIndex < 3) 	$.heIndex = $.heIndex+1;
				if ($.heIndex == 3)	$('#slider-ue_haut_entr .ui-slider-handle').css('right',0);
				else				$('#slider-ue_haut_entr .ui-slider-handle').css('right','');
				$('#slider-ue_haut_entr .ui-slider-handle').text(he[$.heIndex]);
				$('#slider-ue_haut_entr').slider('value',$.heIndex);
				heSelect[0].selectedIndex = $.heIndex;
			});		
		}
    }

	// ----------------------------------------------
	// ETUDE PERSONNALISEE
	// switch de la réponse à Vos combles sont-ils isolés ?
	// ----------------------------------------------	
	// switcher le statut de la question Voit-on la charpente et la couverture ?
	$('input[name=ue_isole]').bind('click', function() { 
		if ($(this).val() == 'nsp') {
			$('input[name=ue_charp_couv]:first').parents('fieldset').removeClass('disabled');
			$('input[name=ue_charp_couv]').each( function() { $(this).removeAttr('disabled').trigger('blur'); });				
		} else {
			$('input[name=ue_charp_couv]:first').parents('fieldset').addClass('disabled');
			$('input[name=ue_charp_couv]').each( function() { $(this).attr('disabled','disabled').trigger('blur'); });
		}
	});
	$('input[name=ue_isole]:checked').trigger('click');

	// ----------------------------------------------
	// BOITES DE DIALOGUE
	// ----------------------------------------------

	// Lexique
	$('#lexique-box').hide();
	$('#context-lexique h2').click(function() { 
		$('#lexique-box').dialog({
			dialogClass	: 'lexique',								 
			show		: 'fade',
			autoOpen	: false,
			height		: 430,
			width		: 600,
			hide		: 'fade',
			title		: 'Lexique',
			modal		: true,
			resizable	: false,
			open		: function() { 
				$('.ui-widget-overlay').css('opacity',0).animate({ opacity: 0.6 }, { duration: 300 });
				$('#lexique-scroller').scrollComposer();
			}
		});												
		$('#lexique-box').show().dialog('open');
	});	
	$('#lexique').listnav({ 
		includeAll	: false,  
		noMatchText	: 'Aucun mot trouvé.',
		showCounts	: false,
		onClick		: function() { $('#lexique-scroller').scrollComposer(); }
	});

	// Inscription à la newsletter
	if ($.inAjax) {
		$('#subscribe-newsletter a').click(function() { 
			var dialog = $('<div id="dialog"/>').appendTo('body');
			dialog.load($.root+'/page/newsletter-page.php', { viaAjax : 1 } , function() {										
				dialog.dialog({
					show		: 'fade',
					hide		: 'fade',
					title		: 'Newsletter',
					modal		: true,
					resizable	: false,
					close		: function() { $(this).dialog('destroy'); dialog.remove(); },
					open		: function() {
						$('input, select, textarea', this).formComposer();
						$('input[type=submit]', this).trigger('mouseover');
						$('.ui-widget-overlay').css('opacity',0).animate({ opacity: 0.6 }, { duration: 300 });
						$('form', this).submit(function() { 
							if (dialog) {
								var data = $(this).serializeArray();
								data.push({ name : 'viaAjax', value : '1' });								
								$('#dialog-notify').load($(this).attr('action'), data, function() { 
									if($('.dialog-valid').length != 0) $('#dialog-form').hide();
								});
								return false;
							}
						});
					}				
				});												
			});
			return false;
		});
	}

	// Mot de passe oublié
	if ($.inAjax) {	
		$('#login-area-forget a').click(function() { 
			var dialog = $('<div class="dialog"/>').appendTo('body');
			dialog.load($.root+'/page/forgotpass-page.php', { viaAjax : 1 } , function() {										
				dialog.dialog({
					show		: 'fade',
					hide		: 'fade',						  
					title		: 'Mot de passe oublié',
					modal		: true,
					resizable	: false,
					close		: function() { $(this).dialog('destroy'); dialog.remove(); },
					open		: function() {
						$('input, select, textarea', this).formComposer();
						$('input[type=submit]', this).trigger('mouseover');
						$('.ui-widget-overlay').css('opacity',0).animate({ opacity: 0.6 }, { duration: 300 });
						$('form', this).submit(function() { 
							if (dialog) {
								var data = $(this).serializeArray();
								data.push({ name : 'viaAjax', value : '1' });
								$('#dialog-notify').load($(this).attr('action'), data);
								return false;
							}
						});
					}			
				});												
			});
			return false;
		});
	}
	
	// Envoyé à un ami
	if ($.inAjax) {	
		$('#sheet-mailtofriend a').click(function() { 
			var dialog = $('<div class="dialog"/>').appendTo('body');
			dialog.load($.root+'/page/mailtofriend-page.php', { viaAjax : 1, sid : $.sid } , function() {										
				dialog.dialog({
					dialogClass	: 'mailto',		  
					show		: 'fade',
					hide		: 'fade',						  
					title		: 'Envoyer à un ami',
					modal		: true,
					width		: 575,
					resizable	: false,
					close		: function() { $(this).dialog('destroy'); dialog.remove(); },
					open		: function() {
						$('input, select, textarea', this).formComposer();					
						$('input[type=submit]', this).trigger('mouseover');
						$('.ui-widget-overlay').css('opacity',0).animate({ opacity: 0.6 }, { duration: 300 });
						$('form', this).submit(function() { 
							if (dialog) {
								var data = $(this).serializeArray();
								data.push({ name : 'viaAjax', value : '1' });
								if($('#dialog-notify').length < 1) $(this).prepend('<div id="dialog-notify"/>');
								$('#dialog-notify').load($(this).attr('action'), data);
								return false;
							}
						});
					}			
				});												
			});
			return false;
		});
	}

	// Email ou mot de passe vide
	$('#login-area').submit( function() {						 
		if ($('#login-area-email').val() == '' || $('#login-area-password').val() == '') {
			var dialog = $('<div id="loginError"><p class="dialog-error">Veuillez saisir une adresse email et un mot de passe !</p></div>').appendTo('body');	
			// Erreur d'authentification
			dialog.dialog({
				show		: 'fade',
				hide		: 'fade',
				title		: 'Erreur',
				modal		: true,
				minHeight	: false,
				resizable	: false,
				buttons		: { ok : function() { $(this).dialog('close'); }},		
				close		: function() { $(this).dialog('destroy'); $('#login-area-email').trigger('blur'); },
				open		: function() {
					$('.ui-widget-overlay').css('opacity',0).animate({ opacity: 0.6 }, { duration: 300 });
				}
			});
			return false;
		}
	});

	// Erreur d'authentification
	$('#loginError').dialog({
		show		: 'fade',
		hide		: 'fade',
		title		: 'Erreur',
		modal		: true,
		minHeight	: false,
		resizable	: false,
		buttons		: { ok : function() { $(this).dialog('close'); }},	
		close		: function() { $(this).dialog('destroy'); $('#login-area-email').trigger('focus'); },
		open		: function() {
			$('.ui-widget-overlay').css('opacity',0).animate({ opacity: 0.6 }, { duration: 300 });
		}
	});

	// ----------------------------------------------
	// premier paragraphe fiche tendance
	// ----------------------------------------------	
	
	$('#tab-one.tendance p:first').addClass('intro');
		
	// ----------------------------------------------
	// Force l'ouverture en target _blank
	// ----------------------------------------------
	
	$("a[href^='http:']").not("[href*='"+$.serv+"']").click(function() { 
		$(this).attr('target','_blank');
	});

});
// -----------------------------------------------------------------------------------
// RDC - Function
// -----------------------------------------------------------------------------------
// Equal height //////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------------
(function($) {
	$.fn.equalHeights = function(minHeight, maxHeight) {
		tallest = (minHeight) ? minHeight : 0;
		this.each(function() {
			if($(this).height() > tallest) {
				tallest = $(this).height();
			}
		});
		if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
		return this.each(function() {
			$(this).height(tallest).css("overflow","auto");
		});
	}
})(jQuery);
// -----------------------------------------------------------------------------------
// load categ Menu ///////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------------
(function($) {
	jQuery.fn.loadCategMenu = function(params) {
		var params = $.extend({
			pid		: null
		}, params);
		if ($('#categ-menu').length != 0) $('#categ-menu').remove();
		$('#content-block').prepend('<div id="categ-menu"/>');		
		$('#categ-menu').css('height', 0).load($.root+'/inc/categ-menu.inc.php', { pid : params.pid } , function(data) {
			$('.sheet-list li').equalHeights();									 
			var ch = $('#categ-list').outerHeight();
			var sh = $('.sheet-list').outerHeight();
			if (ch > sh)	var h = ch;
			else			var h = sh;
			$('.sheet-item').hide();
			$('.categ-item').hide().delayQueue({
				effect		: function(){ $(this).fadeIn(300); },
				callback 	: function() {
					$('.sheet-item').delayQueue({ 
						effect	: function(){ $(this).fadeIn(300); }						
					});
					$('.categ-item > a').not('.self').bind('click', function() {
						$(this).loadCategSheetMenu();
						return false;								  
					});
				}
			});			
			$('#categ-menu').stop().animate(
				{ height : h }, 
				{ duration : 300}
			);
		});	
	};
})(jQuery); 
// -----------------------------------------------------------------------------------
// load categ sheet Menu /////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------------
(function($) {
	jQuery.fn.loadCategSheetMenu = function() {
		var bt			= $(this);
		var url			= bt.attr('href');
		var lastActive = $('.sheet-list');
		var selected	= bt.parent();
		$('#categ-list a').removeClass('active');
		$(this).addClass('active');
		$('.sheet-item', lastActive).delayQueue({
			invert		: true,
			effect		: function(){ $(this).fadeOut(300); },
			callback 	: function() {
				var h = $('#categ-list').outerHeight();
				$('#categ-menu').stop().animate(
					{ height : h }, 
					{ duration : 300, complete : function() { 
						lastActive.remove();
						var ul = $('<ul class="sheet-list"/>').appendTo(selected);
						ul.load($.root+'/inc/sheet-list.inc.php', { url : url } , function(data) {																		
							$('.sheet-list li', selected).equalHeights();									 
							var ch = $('#categ-list').outerHeight();
							var sh = $('.sheet-list', selected).outerHeight();
							if (ch > sh)	var h = ch;
							else			var h = sh;
							$('.sheet-item',selected).hide();
							$('.categ-item',selected).hide().delayQueue({
								effect		: function(){ $(this).fadeIn(300); },
								callback 	: function() {
									$('.sheet-item', selected).delayQueue({ 
										effect		: function(){ $(this).fadeIn(300); }						
									});
								}
							});			
							$('#categ-menu').stop().animate(
								{ height : h }, 
								{ duration : 300}
							);
						});									
					}
				});
			}
		});		
	};
})(jQuery); 		
// -----------------------------------------------------------------------------------
// delay queue ///////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------------
(function($) {
	jQuery.fn.delayQueue = function(params) {
		var params = $.extend({
			effect		: function(){ $(this).show('drop', { direction: 'down' }, 300)},
			delay		: 50,
			invert		: null,
			callback	: function(){}
		}, params);
		var stack = {
			'delay'		: params.delay,
			'actions'	: [],
			'run'		: function() {
				if (stack.actions.length) {
					stack.actions.shift()();
					setTimeout(stack.run, stack.delay);
				}
			}
		};
		$(this).each(function(){
			var that = this;
			stack.actions.push(function(){
				params.effect.call(that);
			});
		});
		if (params.invert) stack.actions.reverse();
		stack.actions.push(function(){
			params.callback.call(this);
		});
		stack.run();	
	};
})(jQuery); 
// -----------------------------------------------------------------------------------
// Set interval push deco ////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------------
(function($) {
	jQuery.fn.setIntervalPushDeco = function(params) {
		var params = $.extend({
			clear : false
		}, params);
		var total = $('#push-deco li').size();		
		if (params.clear) clearInterval($.timeout);
		else
		$.timeout = setTimeout(function(){
			if ($.pushDecoSelect == total) {
				$('#push-deco-item-'+$.pushDecoSelect).hidePushDeco();
				$.pushDecoSelect = 1;
				$('#push-deco-item-'+$.pushDecoSelect).showPushDeco();		
			} else {
				$('#push-deco-item-'+$.pushDecoSelect).hidePushDeco();
				$.pushDecoSelect = $.pushDecoSelect+1;
				$('#push-deco-item-'+$.pushDecoSelect).showPushDeco();			
			}
			$().setIntervalPushDeco();
		},4000);		
	};	
})(jQuery);
// -----------------------------------------------------------------------------------
// Show push deco ////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------------
(function($) {
	jQuery.fn.showPushDeco = function() {
		var img = $.pushDecoImg[$(this).parent().index()];
		var bt 	= $(this);	
		bt.addClass('active').attr('style', '');
		$('span, strong',bt).attr('style', ''); 
		$('strong',bt).stop().animate(
			{ fontSize: '280%' }, 
			{ duration: 300	}
		);			
		$('span',bt).css('display','block');
		var h = $('span',bt).height();
		var w = $('span',bt).width();
		$('span',bt).stop().css({'opacity': 0,'width':0, 'height':0 }).animate(
			{ width : w , height : h }, 
			{ duration : 300 }
		).animate(
			{ opacity : 1 }, 
			{ duration : 300 }
		);
		var visual = setTimeout(function(){
			$('<div id="push-deco-anim" />').insertAfter($('#push-deco'));
			$('#push-deco').css( 'backgroundImage', 'url('+img+')');
			$('#push-deco-anim').css('backgroundImage', 'url('+$.lastPushDecoAnim+')').stop().animate(
				{ opacity : 0}, 
				{ duration : 600, complete : function() { 
					$.lastPushDecoAnim = img;
					$('#push-deco-anim').remove();			
				}
			});
		},300);		
	};
})(jQuery);
// -----------------------------------------------------------------------------------
// Hide push deco ////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------------
(function($) {
	jQuery.fn.hidePushDeco = function() {
		var bt = $(this);
		bt.removeClass('active');
		$('strong',bt).stop().animate(
			{ fontSize: '140%' }, 
			{ duration: 150 }
		);		
		$('span',bt).stop().animate(
			{ opacity:0 }, 
			{ queue:false, duration: 150 }
		).animate(
			{ width: 0 , height: 0 }, 
			{ duration: 150 }
		);	
		bt.stop().animate(
			{ width: '120px' }, 
			{ duration: 300, complete : function() { bt.attr('style', ''); $('span, strong',bt).attr('style', ''); }
		});					
	};
})(jQuery);
// -----------------------------------------------------------------------------------
// Preload des images ///////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------------
(function($) {
	jQuery.fn.preLoadImages = function(params) {
		var params = $.extend({
			imgs : []
		}, params);		
		var args_len = params.imgs.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = params.imgs[i];
			$.cache.push(cacheImage);
		}
	};
})(jQuery);

