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

jQuery (function($) {
	
	// ----------------------------------------------
	// Menu principal
	// ----------------------------------------------
	
	$.mms = new Array();
	$('#main-menu li.select').each(function() { 
		$.mms.push($(this).attr('id'));
	});	
	var cmm = $('#main-menu li:visible').size();
	var mmw = Math.floor(965/cmm);
	var dmm = 965-((cmm-1)*mmw);
	$('#main-menu .drop-down ul li').css('min-width', dmm);
	$('#main-menu li:visible').width(mmw);
	$('#main-menu li:visible').eq(0).addClass('first-child');	
	$('#main-menu li:visible').eq(cmm-1).width(dmm).addClass('last-child');
	$('#main-menu li:visible').find('span:first').equalHeights();
	
	/* Menu principal + DROPDOWN
	$('#main-menu .drop-down ul li').hover(
		function () {
			$(this).addClass('hover');
			$('a:first', this).addClass('hover');
		},
		function () {
			$(this).removeClass('hover');
			$('a:first', this).removeClass('hover');
		}
	);		
	$('#main-menu').bind('mouseleave', function() {
		$.each($.mms, function(key, value) { 
			if($.inArray(value,$.mms) > -1) $('#'+value).addClass('select');
		});
		$('#main-menu .select span').removeClass('forceShadow');
	});
	$('#main-menu li')
	.bind('mouseenter', function() {
		$('#main-menu .select.main-section span:first').removeClass('forceShadow');
		if ($(this).hasClass('select')) $(this).removeClass('select');		
		else $('#main-menu .select.main-section span:first').addClass('forceShadow');
		var pos		= $(this).position().left;
		var _this 	= $('.drop-down:first', this);	
		var h 		= _this.outerHeight();
		var w 		= _this.width();
		if (pos + w > 965)	_this.css({'right' : 0, 'left' : 'auto'});	
		_this.css({'height' : 0, 'width' : w}).show();		
		_this.animate(
			{ height : h }, 
			{ duration : 300}
		);
	})
	.bind('mouseleave', function() {
		if($.inArray($(this).attr('id'),$.mms) > -1) $(this).addClass('select');
		$('#main-menu .select.main-section span:first').removeClass('forceShadow');	
		$('.drop-down:first', this).animate(
			{ height : 0, opacity : 0 },
			{ duration : 300, complete : function() { 
				$(this).css({'height' : '', 'width' : '', opacity : ''}).hide();
			}
		});		
	});
	*/
	
	// ----------------------------------------------
	// Naviguer dans les sections
	// ----------------------------------------------
	$('#section-root a:last').css('background','none');
	$('#section-nav a:last').css('background','none');

	// ----------------------------------------------
	// Fil d'Ariane
	// ----------------------------------------------
	$('#breadcrumbs a').hover(
		function () {
			if ($(this).hasClass('home')) $(this).parent('div').parent('div').css('backgroundPosition','5px -189px');
			$('#breadcrumbs *').removeClass('divider-prev divider-next');
			$(this).prev().addClass('divider-prev');
			$(this).next().addClass('divider-next');
		},
		function () {
			$(this).parent('div').parent('div').removeAttr('style');
			$('#breadcrumbs *').removeClass('divider-prev divider-next');
		}
	);	

	// ----------------------------------------------
	// API de gestion de compte izibook
	// ----------------------------------------------
	$.ajax({
		url		: $.root+'/inc/sso.inc.php',
		data	: { 
			nuid	: $.nuid,
			url		: 'http://numerique.odilejacob.fr/store/account_links'
		},
		success	: function(data){
			$('#account').html($('p', data).html()); 
		}
	});	

 	// ----------------------------------------------
	// API googlemap
	// ----------------------------------------------
	if($('#form-gmap').length == 1) {
		var geocoder = new google.maps.Geocoder();
		function codeAddress() {
			var address = document.getElementById("address").value;
			geocoder.geocode({"address": address}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					var ll	= results[0].geometry.location.lat();
					var spn = results[0].geometry.location.lng();
					$('#gmap').attr('src', 'http://maps.google.fr/maps?q=category:LIBRAIRIES&ie=UTF8&hq=category:LIBRAIRIES&t=m&vpsrc=0&output=embed&near='+address+'&hnear='+address+'&ll='+ll+'&spn='+spn);
					$('#zoom-gmap a').attr('href', 'http://maps.google.fr/maps?q=category:LIBRAIRIES&ie=UTF8&hq=category:LIBRAIRIES&t=m&vpsrc=0&source=embed&near='+address+'&hnear='+address+'&ll='+ll+'&spn='+spn);
				} else {
					alert("Le géocodage n\'a pu être effectué pour la raison suivante : " + status);
				}
			});
			return false;
		}
		$('#form-gmap').submit(function(){
			codeAddress();
			return false;
		});		
	}

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

	// ----------------------------------------------
	// PIED DE PAGE
	// ----------------------------------------------	
	var cfn = $('#footer-nav').children('li').size();
	var fnw = Math.floor(943/cfn);
	var dfn = 943-((cfn-1)*fnw);
	$('#footer-nav').children('li').width(fnw);
	$('#footer-nav').children('li').eq(cfn-1).width(dfn);	
	$('#footer-nav ul').each(function() {
		 $('li:last', this).addClass('last-child');	
	});

 	// ----------------------------------------------
	// Pagination années / mois
	// ----------------------------------------------
	$('#yearSelect').change(function() {
		$('#monthSelect').attr('disabled', 'disabled');
		$(this).parents('form').submit();
	});
	$('#monthSelect').change(function() { 
		$(this).parents('form').submit();
	});	

	// ----------------------------------------------
	// Insertion des vidéos
	// ----------------------------------------------
	if ($('#embed-video')) {
		var type = $('a', '#embed-video').attr('class');
		var id	 = $('a', '#embed-video').attr('id');
		if (type == 'dailymotion') {
			var url			= 'http://www.dailymotion.com/swf/'+id+'?enableApi=1&hideInfos=1&width=210&foreground=%23FFFFFF&highlight=%23CC0000&background=%23222222';
			var flashvars	= { };
			var params 		= { allowScriptAccess : 'always', allowFullScreen : 'true', wmode : 'transparent' };
			var attributes 	= { id: 'embed-video' };
		}
		swfobject.embedSWF(url, 'embed-video', '210', '120', '9', $.root+'/medias/flash/expressInstall.swf', flashvars, params, attributes);		
	}

 	// ----------------------------------------------
	// Tooltips
	// ----------------------------------------------
	// livres
	$('.tooltip-book').each(function() { 
		var url = $(this).attr('href');
		if ($(this).hasClass('show-visual')) url = url+'&visual=true';
		$(this).cluetip({ 
			data : $.root+'/ajax/tooltip-book-ajax.php?url='+url  
		});  
	});
	// auteurs
	$('.tooltip-author').each(function() { 
		var url = $(this).attr('href');
		$(this).cluetip({ 
			data 	: $.root+'/ajax/tooltip-author-ajax.php?url='+url,
			width	: 150 
		});  
	});

	// ----------------------------------------------
	// Zoom des couvertures
	// ----------------------------------------------
	$('.zoom').lightBox();
	
	// ----------------------------------------------
	// Carousels
	// ----------------------------------------------
	// home
	$('#home-page #mag-event .carousel').carousel({
		scroll	: 1,
		visible	: 1
	});
	// home
	$('#home-page #mag-new .carousel, #home-page #mag-best .carousel, #home-page #mag-comeOut .carousel').carousel({
		scroll	: 3,
		visible	: 3
	});	
	// page magazine
	$('.mag-box .carousel').carousel({
		scroll	: 4,
		visible	: 4
	});
	// fiche livre
	$('#book-same-keyword .carousel').carousel({
		scroll	: 6,
		visible	: 6
	});

	// ----------------------------------------------
	// Accordions
	// ----------------------------------------------	
	// page home
	$('#home-page #mag-actus .actu-book').accordion({
		header		: 'h3',
		autoHeight 	: false,
		clearStyle 	: true,
		active 		: false,
		collapsible : true
	});
	// page magazine
	$('#mag-actus .actu-book').accordion({
		header		: 'h4',
		autoHeight 	: false,
		clearStyle 	: true,
		active 		: false,
		collapsible : true
	});
	// page faq
	$('#faq').accordion({
		header		: 'h2',
		autoHeight 	: false,
		clearStyle 	: true,
		active 		: false,
		collapsible : true
	}).accordion('activate', $.accordionActive);	

 	// ----------------------------------------------
	// Tabs (onglets)
	// ----------------------------------------------
	// page magazine
	$('#mag-tabs').tabs();
	// fiche livre
	$('#library').tabs({
		show : function(event, ui) { 
			var pane = $(ui.panel).attr('id');
			if (pane =='find-library' && $('#gmap').attr('src') == undefined) codeAddress();		
		}	
	});

 	// ----------------------------------------------
	// Tree (arbo)
	// ----------------------------------------------
	// page plan du site
	$("#site-map").treeview({ 
		animated: "fast"
	});	

 	// ----------------------------------------------
	// Formulaires
	// ----------------------------------------------
	$('.form .buttonset').buttonset();
	$('.form select').selectmenu({ 
		maxHeight	: 240
	});
	$('.form input[type=submit]').button();
	$('form.viaAjax').submit(function() { 
		var form = $(this);
		var loader = $('<div class="bar-loader"><div></div></div>').appendTo(form);
		loader.css({ 'width' : form.width(), 'height' : form.height() });
		var data = form.serializeArray();
		data.push({ name : 'viaAjax', value : '1' });
		if ($('#notify').length < 1) form.prepend('<div id="notify"/>');
		$('#notify').load($(this).attr('action'), data, function() {
			loader.remove();
			$('html, body').animate({ scrollTop: $('#notify').offset().top }, 0);
		});
		return false;
	});

	// ----------------------------------------------
	// Ajustement hauteur
	// ----------------------------------------------
	$('#auteurs-page .book').equalHeights();
	$('#sites-des-auteurs-page .site').equalHeights();
});
// -----------------------------------------------------------------------------------
// OJ - Function
// -----------------------------------------------------------------------------------
// Equal height //////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------------
(function($) {
	$.fn.equalHeights = function(minHeight, maxHeight) {
		$(this).css('height','');
		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);
		});
	}
})(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); 
// -----------------------------------------------------------------------------------
// cascade select ////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------------
(function($) {
	jQuery.fn.cascadeSelect = function(params) {
		var childOptions = params.child.find('option:not(.static)');
		params.child.data('options', childOptions);
		params.parent.change(function(){
			childOptions.remove();
			params.child.append(params.child.data('options').filter('.sub_' + this.value)).change();
		});
		childOptions.not('.static, .sub_' + params.parent.val()).remove();	
	};
})(jQuery);
// -----------------------------------------------------------------------------------
// placeholder ///////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------------
(function($){
    $.fn.placeholder = function(settings) {
        settings 		= settings || {};
        var key			= settings.dataKey			|| 'placeholderValue';
        var attr 		= settings.attr 			|| 'alt';
        var className	= settings.className 		|| 'placeholder';
        var values		= settings.values 			|| [];
        var block 		= settings.blockSubmit 		|| false;
        var blank 		= settings.blankSubmit 		|| false;
        var submit 		= settings.onSubmit 		|| false;
        var value		= settings.value 			|| "";
        var position	= settings.cursor_position	|| 0;
        return this.filter(':input').each(function(index) { 
            $.data(this, key, values[index] || $(this).attr(attr)); 
        }).each(function() {
            if ($.trim($(this).val()) === '')
                $(this).addClass(className).val($.data(this, key));
        }).focus(function() {
            if ($.trim($(this).val()) === $.data(this, key)) 
                $(this).removeClass(className).val(value)
                if ($.fn.setCursorPosition) {
                  $(this).setCursorPosition(position);
                }
        }).blur(function() {
            if ($.trim($(this).val()) === value)
                $(this).addClass(className).val($.data(this, key));
        }).each(function(index, elem) {
            if (block)
                new function(e) {
                    $(e.form).submit(function() {
                        return $.trim($(e).val()) != $.data(e, key)
                    });
                }(elem);
            else if (blank)
                new function(e) {
                    $(e.form).submit(function() {
                        if ($.trim($(e).val()) == $.data(e, key)) 
                            $(e).removeClass(className).val('');
                        return true;
                    });
                }(elem);
            else if (submit)
                new function(e) { $(e.form).submit(submit); }(elem);
        });
    };
})(jQuery); 

