/*
 * Plugin jQuery : animation du bandeau et du fond de la page d'accueil
 */
jQuery.fn.aoFade = function (options) {

  var settings = {
    'delay'    : 2000,
    'duration' : 2000,
    'navigator': false,
    'opacity'  : 1
  };
  
  if ( options ) { 
    jQuery.extend( settings, options );
  }
  
  jQuery(this).each(function(index, element) {
    var element = jQuery(this);
    if (element.data('myplugin')) return;
    var myplugin = new MyPlugin(element, settings);
    element.data('myplugin', myplugin);
  })
  
}

var MyPlugin = function(element, settings) {
  
  var navigator;
  var current;
  var intervalId;
  var settings = settings;
  var element = element;
  var obj = this;
  
  this.goto = function(param) {
    clearInterval(intervalId);
    current.dequeue();
    obj.doIt(element.find("> img, > a").eq(param));
  }
  
  this.doIt = function(el) {
    current = el;
    if(settings.navigator) {
      navigator.find("span").removeClass("current").eq(el.index()).addClass("current");
    }
    el.fadeTo(settings.duration, settings.opacity).delay(settings.delay).fadeOut(settings.duration);
    intervalId = setTimeout(function() {
      if(jQuery(el).next("img, a").size() > 0) {
        obj.doIt(jQuery(el).next("img, a"));
      } else {
        obj.doIt(jQuery(el).parents("div").find("> img, > a").eq(0));
      }
    }, settings.duration + settings.delay);
  }
     
  if(settings.navigator) {
    navigator = jQuery("<div><div><div></div></div></div>").addClass("navigator");
    element.append(navigator);
    element.find("> img, > a").each(function(index, element) {
      jQuery(this).addClass("item_" + (index+1));
      jQuery("<span />").addClass("item_" + (index+1)).text(index + 1).appendTo(navigator.find("div div")).click(function() {
        clearInterval(intervalId);
        current.dequeue();
        obj.doIt(navigator.parent().find("> img, > a").eq(jQuery(this).index()));
        settings.click(jQuery(this).index());
      });
    });
  }
    
  element.find("> img, > a").each(function(index, element) {
    jQuery(this).addClass("item_" + (index+1));
  });
  
  this.doIt(element.find("> img, > a").eq(0));
  
}

/*
 * Plugin jQuery : initialisation des champs de formulaire
 */
jQuery.fn.fields = function() {
	this.each(function(index, element) {
		jQuery(element).data("defaultValue", jQuery(element).val());
		jQuery(element).click(function() {
			if(jQuery(this).val() == jQuery(this).data("defaultValue")) {
				jQuery(this).val("");
			}
		}).blur(function() {
			if(jQuery(this).val() == "") {
				jQuery(this).val(jQuery(this).data("defaultValue"));
			}
		});
	});
};







jQuery(function($) {
	
	// Petites annonces
	$(".home .twoColumns .left").load("actualite/aoExistenceActualite.orion?method=listAnnonceByDateAnterieur", function() {
		$(".home .twoColumns .left .newhome").slice(2).hide();
	});

	// WS Layer
	$.getJSON('layers.gnc?Destination=layer&ws_layer_pages=' + ws_layer_pages, function(data) {
		
		var onglets = $("<ul />");
		
		$.each(data, function(key, val) {
			onglets.append($("<li>" + val.titre + "</li>").data("url", val.url));
		})
		
		if(onglets.find("li").size() > 0) {
			onglets.find("li").eq(0).addClass("current").end().click(function() {
				onglets.find("li").removeClass("current");
				$(this).addClass("current");
				$(".layer").remove(".geniecube");
				chargePagePourLayer($(this).data("url"));
			});
			
			$(".layer").find("h3").html(onglets);
		} else {
			$(".layer").find("h3").html(data.layer_0.titre);
		}
		
		chargePagePourLayer(data.layer_0.url);
		
	})
	
	function chargePagePourLayer(url) {
		$("<div />").load(url + " .geniecubecontenu", function(response, status, xhr) {
			if(xhr.status != "404") {
				//console.log("Contenu chargé.");
				$(".layer").width(750).find("div").html($(this).html()).end().data("overlay").load();
				var top = $(".layer").css("top");
				var height = $(".layer").height();
				if(parseInt(top) + height > $(window).height()) {
					var y = ($(window).height()) / 2 - (height / 2);
					$(".layer").animate({top: y + "px"}, 500);
				}
			} else {
				//console.log("Erreur de chargement : " + xhr.status + " " + xhr.statusText);
			}
		});
	}
	
	// Devis, effet sur le choix de la situation
	$("#situation li").append("<span />").find("a").hover(
		function() {
			
			if($(this).parent().find("span").data("originalTop") == null) {
				$(this).parent().find("span").data("originalTop", $(this).parent().find("span").css("top"));
			}
			if($(this).parent().find("a").data("originalTop") == null) {
				$(this).parent().find("a").data("originalTop", $(this).parent().find("a").css("top"));
			}
			
			$(this).parent().find("span").stop().dequeue().animate({top: parseInt($(this).parent().find("span").data("originalTop"))+20}, 200);
			$(this).parent().find("a").stop().dequeue().animate({top: parseInt($(this).parent().find("a").data("originalTop"))-20}, 200);
		},
		function() {
			$(this).parent().find("span").stop().dequeue().animate({top: $(this).parent().find("span").data("originalTop")}, 600, "easeOutBounce");
			$(this).parent().find("a").stop().dequeue().animate({top: $(this).parent().find("a").data("originalTop")}, 600, "easeOutBounce");
		}
	);
	
	// Lightbox
	$('a[rel*=lightbox]').lightBox();
	
	// Déplacement du 1er scrollable de la page d'accueil
	if(currentPageNum == 1) {
		$(".scrollable").eq(0).remove(".navi").find(".items").unwrap().insertBefore(".twoColumns").addClass("fader").attr("id", "fade");
	}
	
	// Scrollable
	$(".scrollable").scrollable({circular: true}).autoscroll().navigator({indexed: true});
	
	// Ajout d'une méthode de validation :
	// le valeur du champ ne doit pas être égale à sa valeur par défaut
	jQuery.validator.addMethod("defaut", function(value, element) { 
		return $(element).val() != $(element).data("defaultValue"); 
	}, "Message d'erreur.");
	
	// Listes déroulantes personnalisées
	$("#formConseiller select, #formRdv select").each(function(index, element) {
		$(element).change(function() {
			$(this).prevAll("input").eq(0).val($(this).find("option:selected").text());
		});
		$(element).prevAll("input").eq(0).val($(element).find("option:selected").text());
	});
	
	// Initialisation des champs de formulaire
	$("#formConseiller input, #formRdv input, #recherche input, #rechercheAgence input").fields();
	
	// Validation du formulaire un conseiller vous rappelle
	$("#formConseiller").validate({
		invalidHandler: function(form, validator) {
			var message = "<ul>";
			for(var tmp in validator.invalid) {
				message += "<li>" + validator.invalid[tmp] + "</li>";
			}
			message += "</ul>";
			$(".layer").width(470).find("h3").html("Un conseiller vous rappelle").end().find("div").html("Le formulaire ne semble pas rempli correctement :<br/>" + message).end().data("overlay").load();
		},
		rules: {
			conseillerNom: {defaut: true},
			conseillerPrenom: {defaut: true},
			conseillerCp: {defaut: true, number: true},
			conseillerMail: {defaut: true,	email: true},
			conseillerTel: {defaut: true, number: true}
		},
		messages: {
			conseillerNom: "vous devez préciser votre nom.",
			conseillerPrenom: "vous devez préciser votre prénom",
			conseillerCp: "votre code postal ne doit comporter que des chiffres.",
			conseillerMail: "votre adresse email doit être de la forme nom@domaine.fr.",
			conseillerTel: "votre numéro de téléphone doit être uniquement composé de chiffres et sans espaces."
		}
	});
	
	// Validation du formulaire de recherche	
	$("#recherche").validate({
		invalidHandler: function(form, validator) {
			var message = "<ul>";
			for(var tmp in validator.invalid) {
				message += "<li>" + validator.invalid[tmp] + "</li>";
			}
			message += "</ul>";
			$(".layer").width(470).find("h3").html("Recherche sur le site").end().find("div").html("Le formulaire ne semble pas rempli correctement :<br/>" + message).end().data("overlay").load();
		},
		rules: {
			query: {defaut: true}
		},
		messages: {
			query: "vous devez préciser votre mot clé."
		}
	});
	

  // create custom animation algorithm for jQuery called "drop" 
  $.easing.drop = function (x, t, b, c, d) {
  	return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
  };
  
  // loading animation
  $.tools.overlay.addEffect("drop", function(css, done) { 
     
     // use Overlay API to gain access to crucial elements
     var conf = this.getConf(),
         overlay = this.getOverlay();           
     
     // determine initial position for the overlay
     if (conf.fixed)  {
        css.position = 'fixed';
     } else {
        css.top += $(window).scrollTop();
        css.left += $(window).scrollLeft();
        css.position = 'absolute';
     } 
     
     // position the overlay and show it
     overlay.css(css).show();
     
     // begin animating with our custom easing
     overlay.css("opacity", 0);
     overlay.animate({ top: '+=55',  opacity: 1}, 400, 'drop', done);
     
     /* closing animation */
     }, function(done) {
        this.getOverlay().animate({top:'-=55', opacity:0}, 300, 'drop', function() {
           $(this).hide();
           done.call();      
        });
     }
  );
  
  // Ajout de la structure du layer à la page
  $("<div class=\"layer\"><h3>Titre</h3><div></div></div>").appendTo("body");

  // Layer modale
  $(".layer").overlay({
    top: 256,
    effect: "drop",
    mask: {
      color: "#000",
      loadSpeed: 200,
      opacity: 0.8
    },
    load: false,
    onClose: function() {
    	this.getOverlay().removeAttr("style");
    }
  });

	// Ajout de la structure des infos-bulles à la page
	$("<div class='tooltip'><div class=\"content\" /><div class=\"fleche\" /></div>").appendTo("body");
	
	// Info-bulles
	$("img[src$=\"btn_aide.gif\"], img[src$=\"btn_info.gif\"]").tooltip({
		tip: ".tooltip",
		delay: 100,
		effect: "slide",
		position: "top left",
		onBeforeShow: function(e, position) {
			var text = this.getTrigger().attr("alt");
			this.getTip().find(".content").html(text);
			this.getConf().offset = [-5, 55];
		}
	});

	// Animation du retour haut de page
	$("#toTop").click(function(event) {
		event.preventDefault();
		$("body, html").animate({scrollTop:0}, 200); 
	});

	
	
	$("<div />").html($("#fade").html()).insertBefore("#bkgFade .mask").addClass("items");

	$("#fade").aoFade({
		delay: 4000,
		navigator: true,
		duration: 1000,
		click: function (param) {
			$("#bkgFade .items").data("myplugin").goto(param);
		}
	});
  
	$("#bkgFade .items").aoFade({
		duration: 2000,
		delay: 3000
	});

});
