// Permettre l'affichage des sous-menus sous IE6
sfHover = function() {
	var sfEls = document.getElementById("menu").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) {
	window.attachEvent("onload", sfHover);
}

// Fonctions pour les cookies
function EcrireCookie(nom, valeur){
	var argv=EcrireCookie.arguments;
	var argc=EcrireCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=nom+"="+escape(valeur)+
	((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
	((path==null) ? "" : ("; path="+path))+
	((domain==null) ? "" : ("; domain="+domain))+
	((secure==true) ? "; secure" : "");
}

function getCookieVal(offset){
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1) endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function LireCookie(nom){
	var arg=nom+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen){
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg) return getCookieVal(j);
		i=document.cookie.indexOf(" ",i)+1;
		if (i==0) break;
	}
	return null;
}

// Charger une vidéo humour
function getVideo(lien) {
	$.ajax({
		type: "GET",
		url: "ajax/video_humour.php",
		data: { vid: lien },
		async: false,
		success: function(echo){
			_error = "off";
			$('#humour-video').html(echo);
		}/*,
		error: function(echo){
			_error = "on";
			alert("Error - " + echo);
		}*/
	});	
}

// Chercher les produits
function getProduits(field_rubrique) {
	$.ajax({
		type: "GET",
		url: "ajax/get_produits.php",
		data: { rubrique: $(field_rubrique).val() },
		async: false,
		success: function(echo){
			_error = "off";
			$("select[@name=produit]").html(echo);
		}/*,
		error: function(echo){
			_error = "on";
			alert("Error - " + echo);
		}*/
	});	
}

// Afficher le listing de Ma Sélection
function updateMSBox(btn_action, btn_id) {
	$.ajax({
		type: "GET",
		url: "ajax/maselection.php",
		data: { action: btn_action, id: btn_id },
		async: false,
		success: function(echo){
			_error = "off";
			$("p#nbrobjets strong").html(echo);
		}/*,
		error: function(echo){
			_error = "on";
			alert("Error - " + echo);
		}*/
	});
}

// Fonction permettant de faire défiler les photos des annonces à la une
function au_diaporama() {
	photocount = 0;
	mynbrphotos = $("input[@name=au_nbrphotos]").val();
	if (mynbrphotos > 1) {	
		$('#au_mainphoto').everyTime(4500,function() {
			photocount = photocount + 1;
			// Changer la photo
			$(this).fadeOut("slow", function () {
				$(this).attr({ 
					src: $("#au_miniphotohide_" + photocount).attr("src")
					
				});
				$(this).fadeIn("slow");
			});
			// Changer la rubrique
			$("#annoncesune_txt h3").fadeOut("slow", function () {
				$(this).html($("li#au_photoselect h4").html());
				$(this).fadeIn("slow");
			});
			// Changer le titre
			$("#annoncesune_txt h4").fadeOut("slow", function () {
				$(this).html($("li#au_photoselect h5").html());
				$(this).fadeIn("slow");
			});
			// Changer la description
			$("#annoncesune_annonce p").fadeOut("slow", function () {
				$(this).html($("li#au_photoselect p").html());
				$(this).fadeIn("slow");
			});
			if (photocount == mynbrphotos ) {
				photocount = 0;
			}
			$("li#au_photoselect").removeAttr('id');
			$("#annoncesune_liste ul li:eq(" + photocount + ")").attr("id","au_photoselect");
		});
	}
}

// ShoppingMail : récupérer les communes d'une province
function sm_getCommunes(provid) {
	$.ajax({
		type: "GET",
		url: "ajax/sm_get_communes.php",
		data: { id_province: provid },
		async: false,
		success: function(echo){
			_error = "off";
			$('#sm_communes_content').html(echo);
		}/*,
		error: function(echo){
			_error = "on";
			alert("Error - " + echo);
		}*/
	});	
}

// ShoppingMail : envoyer le formulaire
function sm_soumForm(emailVal,commuVal) {
	$.ajax({
		type: "POST",
		url: "ajax/sm_soum_form.php",
		data: { email: emailVal, commu: commuVal },
		async: false,
		success: function(echo){
			_error = "off";
		}/*,
		error: function(echo){
			_error = "on";
			alert("Error - " + echo);
		}*/
	});	
}

$(document).ready(function() {
	
	// Tester si un champs est numérique
	$('input.numeric').keyup(function(){
		
		if( typeof $(document)[0].selection != 'undefined' ) {
			
			// Insertion du code de formatage
			var range = $(document)[0].selection.createRange();
			
			// on récupère la taille d'origine du texte
			var origi_length	= $(this).val().length;
			
			var range 			= $(this)[0].createTextRange();
			range.moveToBookmark($(document)[0].selection.createRange().getBookmark());
			range.moveEnd('character', $(this).val().length);
			
			var start			= $(this).val().length - range.text.length;
			
			var range 			= $(this)[0].createTextRange();
			range.moveToBookmark( $(document)[0].selection.createRange().getBookmark() );
			range.moveStart( 'character', -$(this).val().length );
			
			var end				= range.text.length;
			
			if( end < start )
				end = start;
			
			$(this).val( $(this).val().replace(/[^0-9]/ig,"") );
				
			// on récupère la taille du texte
			var dif				= origi_length - $(this).val().length;
			
			var range 			= $(this)[0].createTextRange();
			range.moveStart( 'character', start - dif );
			range.moveEnd( 'character', -$(this).val().length + end - dif );
			range.select();
		
		} else if (typeof $(this)[0].selectionStart != 'undefined') {
			
			// on récupère la position du curseur
			var start			= $(this)[0].selectionStart;
			var end				= $(this)[0].selectionEnd;
			
			// on récupère la taille d'origine du texte
			var origi_length	= $(this).val().length;
			
			// on retire les retours à la ligne
			$(this).val( $(this).val().replace(/[^0-9]/ig,"") );
			
			// on récupère la taille du texte
			var dif				= origi_length - $(this).val().length;
			
			// si il y a une différence c'est qu'on a retiré un retour a la ligne
			if( dif > 0 )
				dif = 1;
		
			// on repositione le curseur
			$(this)[0].selectionStart	= start - dif;
			$(this)[0].selectionEnd		= end - dif;
		
		}
		
	});
	
	/*********************
	* Recherche (réduit) *
	*********************/
	
	// Cacher le type de bien et le prix si client est sélectionné
	$('input[name="sort"]').change(function(){
		if ($('input[name="sort"]:checked').val() == "client") {
			$('#recherche_small_neuve').hide();
			$('#recherche_small_prix').hide();
		} else {
			$('#recherche_small_neuve').show();
			$('#recherche_small_prix').show();
		}
	});
	
	// Envoyer le formulaire de recherche par rubrique
	$("#recherche_small_button").click(function(){
		$("input[@name=rubrique_txt]").val($("select[@name=rubrique] option:selected").text());
		$("input[@name=produit_txt]").val($("select[@name=produit] option:selected").text());
		$("input[@name=province_txt]").val($("select[@name=province] option:selected").text());
		$("input[@name=commune_txt]").val($("select[@name=commune] option:selected").text());
		$("input[@name=neuve_txt]").val($("input[@name=neuve]:checked").parent().text());
		$("form[@name=form_recherche_small]").submit();	
	});
	
	/********************
	* Annonces à la une *
	********************/
	photocount = 0;
	au_diaporama();
		
	// Effet quand on passe sur les vignettes des photos
	$('[@title^=vign_annonceune_]').mouseover(function(){
		_idselected = $(this).attr("title");
		_strlength = _idselected.length;
		_idselected = _idselected.substring(16, _strlength);	
		$('#au_mainphoto').stopTime();
		$('#au_mainphoto').attr({ 
        	src: $("#au_miniphotohide_" + _idselected).attr("src")
        });
        // Changer la rubrique
		$("#annoncesune_txt h3").html($("li[title='vign_annonceune_" + _idselected + "'] h4").html());
		// Changer le titre
		$("#annoncesune_txt h4").html($("li[title='vign_annonceune_" + _idselected + "'] h5").html());
		// Changer la description
		$("#annoncesune_annonce p").html($("li[title='vign_annonceune_" + _idselected + "'] p").html());
		// Enlever la classe d'hover à celui qui l'a
		$('li#au_photoselect').removeAttr("id");
		// Ajouter la classe d'hover à celui qui doit l'avoir
		$(this).attr("id","au_photoselect");
	});

	$('[@title^=vign_annonceune_]').mouseout(function(){
		au_diaporama();
	});	

	$('#au_mainphoto').mouseover(function(){
		$('#au_mainphoto').stopTime();
	});

	$('#au_mainphoto').mouseout(function(){
		au_diaporama();
	});
	
	/************
	* Rubriques *
	************/
	
	// Scroller les catégories vers le bas
	$("#rublist_scroll_bottom").click(function() {
		var divOffset = $("#rublist_content ul").offset().top;
		var pOffset = $("#rublist_content ul li:eq(14)").offset().top;
		var pScroll = pOffset - divOffset;
		$("#rublist_content").animate({scrollTop: "+=" + pScroll + "px"}, 1000, "easeinout");
	});
	
	// Scroller les catégories vers le haut
	$("#rublist_scroll_top").click(function() {
		var divOffset = $("#rublist_content ul").offset().top;
		var pOffset = $("#rublist_content ul li:eq(14)").offset().top;
		var pScroll = pOffset - divOffset;
		$("#rublist_content").animate({scrollTop: "-=" + pScroll + "px"}, 1000, "easeinout");
	});
	
	/*************
	* Catégories *
	*************/
	
	// Scroller les catégories vers le bas
	$("#scroll_small_bottom").click(function() {
		var divOffset = $("#cat_small").offset().top;
		var pOffset = $("#cat_small li:eq(20)").offset().top;
		var pScroll = pOffset - divOffset;
		$("#cat_small_content").animate({scrollTop: "+=" + pScroll + "px"}, 1000, "easeinout");
	});
	
	// Scroller les catégories vers le haut
	$("#scroll_small_top").click(function() {
		var divOffset = $("#cat_small").offset().top;
		var pOffset = $("#cat_small li:eq(20)").offset().top;
		var pScroll = pOffset - divOffset;
		$("#cat_small_content").animate({scrollTop: "-=" + pScroll + "px"}, 1000, "easeinout");
	});
	
	/*********
	* Humour *
	*********/
	
	// Switcher les liens de la liste
	$('#humour ul li').click(function() {
		
		$('li#video_play')
			// On ajoute le lien
			.html( '<a href="#" onclick="getVideo(\'' + $('li#video_play').attr('title') + '\');return false;">' + $('li#video_play').html() + '</a>' )
			// On retire l'id
			.removeAttr('id');
		
		$(this)
			// on rejoute l'id
			.attr('id', 'video_play')
			// on change le contenu de la balise li
			.html($(this)
						// par le contenu de la balise enfant a
						.children('a').html()
				 );
	});
	
	/***********************************
	* Top 15 / Partenaires / Avantages *
	***********************************/
	
	// Afficher la première tab par défaut
	$('#' + $('#toppartavanttabs_display').val()).show();
	
	// Switcher l'affichage dans Top 15 / Partenaires / Avantanges
	$('ul#top-part-avant_tabs li').click(function() {
	
		// On cache le calque associé
		$('#' + $('li#top-part-avant_tabs-select').attr('title')).hide();
		
		$('li#top-part-avant_tabs-select')
			// On ajoute le lien
			.html( '<a>' + $('li#top-part-avant_tabs-select').html() + '</a>' )
			// On retire l'id
			.removeAttr('id');
					
		$(this)
			// on rejoute l'id
			.attr('id', 'top-part-avant_tabs-select')
			// on change le contenu de la balise li
			.html($(this)
						// par le contenu de la balise enfant a
						.children('a').html()
				 );
			// On affiche les autres calques
			$('#' + $('li#top-part-avant_tabs-select').attr('title')).show();
	});
	
	/***************
	* Ma sélection *
	***************/
	
	updateMSBox("nombre","");
	
	$("a[@id^=boxmaselection_]").click(function() {
		_idselected = $(this).attr("id");
		_strlength = _idselected.length;
		_idselected = _idselected.substring(15,_strlength);
		if ($("a#boxmaselection_" + _idselected).attr("class") == "maselection_add") {
			$("a#boxmaselection_" + _idselected).removeAttr("class").attr("class","maselection_added");
			if (_LANG == "fr") {
				$("a#boxmaselection_" + _idselected).html("Ajouté à ma sélection");
			} else {
				$("a#boxmaselection_" + _idselected).html("Bij mijn selectie gevoegd");
			}
			updateMSBox("ajouter",_idselected);
		} else {
			$("a#boxmaselection_" + _idselected).removeAttr("class").attr("class","maselection_add");
			if (_LANG == "fr") {
				$("a#boxmaselection_" + _idselected).html("Ajouter à ma sélection");
			} else {
				$("a#boxmaselection_" + _idselected).html("Bij mijn selectie voegen");
			}
			updateMSBox("supprimer",_idselected);
		}
		updateMSBox("nombre","0");
	});
	
	$("#boxeffacerselection").click(function() {
		updateMSBox("effacer","");
		$("a[@id^=boxmaselection_]").removeAttr("class").attr("class","maselection_add");
		updateMSBox("nombre","");
	});
	
	/***************
	* ShoppingMail *
	***************/
	
	// Faire apparaitre le cadre
	var_cookie = LireCookie("ShoppingMail");
    if (var_cookie == null) {
		$("#shoppingmail").animate({top:"20px"},1500);
	}
	
	// Charger les communes au démarrage
	sm_getCommunes($("select[name='sm_province'] option:selected").val());
	
	// Charger les communes quand on change de province
	$("select[name='sm_province']").change(function() {
		sm_getCommunes($("select[name='sm_province'] option:selected").val());
	});
	
	// Fermer le cadre
	$("p#sm_close a").click(function() {
		$("#shoppingmail").fadeOut(1000);
		return false;
	});
	
	// Envoyer le formulaire
	$("input[name='sm_submit_button']").click(function() {
		// E-mail bien complété ?
		verif = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
		if ($('input[name="sm_email"]').val() == "" || verif.exec($('input[name="sm_email"]').val()) == null) {
			$("span#sm_error_email").show();
		} else {
			$("span#sm_error_email").hide();
			sm_soumForm($('input[name="sm_email"]').val(),$('select[name="sm_commune"] option:selected').val());
			$("#shoppingmail").fadeOut(1500);
		}
	});
	
	duree_cookie = 3650;         // durée de vie du cookie en jours
    expiration = new Date();    // date et heure courante en format texte
    expiration.setTime(expiration.getTime() + (duree_cookie * 24*60*60*1000)); // => on peut utiliser la variable "expiration"
	EcrireCookie("ShoppingMail","ok",expiration);
	
});

// Afficher une popup centrée
function popupcentree(page,largeur,hauteur,optionss) {
	var top = (screen.height-hauteur)/2;
	var left = (screen.width-largeur)/2;
	window.open(page,"","top="+top+",left="+left+",width="+largeur+",height="+hauteur+","+optionss);
}
