// Menu
$(document).ready(function(){	
	var decalageMenu = 20;
	// Init onglet
	var ongletInit = $("#menu_item_"+sIdMenuSelected).position();															// position LI selectionné
	if(ongletInit)$("#onglet_menu").css({"left": ongletInit.left + decalageMenu, "top": "175px","opacity": 1}, "slow"); 		// Left + top pour l'onglet
	$("#onglet_menu_texte").append($("#menu_item_"+sIdMenuSelected).html());
	
	// Reset position de l'onglet
	function resetOnglet()
	{
		var ongletInit = $("#menu_item_"+sIdMenuSelected).position();		
		$("#onglet_menu").animate({"left": ongletInit.left + decalageMenu, "opacity": 1},500, "linear");
		$("#onglet_menu_texte").html($("#menu_item_"+sIdMenuSelected).html());
	}
	// Animation bounce onglet + deploi sous menu
	$("#menu-anim > li").each(function (index, domEle) {
		var newPosOnglet = $(this).position();		// Coordoné LI survolé
		
		$(this).mouseenter(function(event){ // Animation onglet
			$("#onglet_menu").stop();
			var posLeftOnglet = newPosOnglet.left + decalageMenu;
			
			$("#onglet_menu_texte").html($("#menu_item_"+index).html());
			$("#onglet_menu").animate({"left": posLeftOnglet, "opacity": 1},300, "linear", function() {});
		});
	});
	
	$("#herbe").mouseenter(function(event){ $("#onglet_menu").stop();resetOnglet();	});
	$(".cengo-contenu").mouseenter(function(event){$("#onglet_menu").stop();	resetOnglet();	});
	$(".width").mouseleave(function(event){$("#onglet_menu").stop();	resetOnglet();	});

	$(".light").mouseenter(function(event){$(this).addClass("red");	});
	$(".light").mouseleave(function(event){$(this).removeClass("red");	});
	$(".click").each(function (index, domEle) { $(this).click(function() { $(location).attr("href",$(this).attr("link")); return false; }); });
	$(".preload").each(function () { $(this).attr("src",$(this).attr("rel")); });
});

function goTo(url) {
	$(location).attr("href",url);
}

/* Ajout aux favoris */
function addFavorite(idParcours)
{
	$.ajax({
			url: '/cengo/ajax/favoriteparcours/id/'+idParcours,
			success: function(data) {
				$('#dialog_blank').html(data);
			}
		});

	// Dialog
	$('#dialog_blank').dialog({
		autoOpen: false,
		width: 350,
		height:130,
		draggable: false,
		modal: true,
		buttons: {
			"Ok": function() {
				$.ajax({
					url: '/cengo/ajax/favoriteparcours?id='+idParcours+'&do=1',
					success: function(data) {
						$('#dialog_blank').html(data);
					}
				});
				$('#dialog_blank').dialog("destroy");
			},
			"Annuler": function() {
				$('#dialog_blank').dialog("destroy");
			}
		}
	});
	
	$('#dialog_blank').dialog('open');
}

/* Ajout aux favoris */
function formvideobib(url,idVideo,idRubrique,urlBack)
{
	// Post
	var params = { url:url,id_vid:idVideo,id_rub:idRubrique};
	var dataString = jQuery.param(params);
	$.ajax({ type: "POST", url: "/cengo/videos/formvideobib", data: dataString, success: function(msg){ $('#dialog_blank').html(msg);} });

	// Dialog
	$('#dialog_blank').dialog({autoOpen: false,width: 800,height:600,draggable: false,modal: true,
		buttons: {
			"Annuler": function() {
				$('#dialog_blank').dialog("destroy");
			},
			"Envoyer": function() {
				var params_vid = {
					id_rubrique:$("#videobib").find("#id_rubrique").val(),
					id_user:$("#videobib").find("#id_auteur").val(),
					titre:$("#videobib").find("#titre").val().replace(/</g,'&lt;').replace(/>/g,'&gt;'),
					url:$("#videobib").find("#url").val(),
					tag:$("#videobib").find("#tags").val(),
					description:$("#videobib").find("#description").val().replace(/</g,'&lt;').replace(/>/g,'&gt;'),
					form:"1",
					id_video:$("#videobib").find("#id_video").val()
				};
				var dataString_vid = jQuery.param(params_vid);
				$.ajax({ type: "POST", url: "/cengo/videos/formvideobib", data: dataString_vid, success: function(msg){$('#dialog_blank').html(msg);} });
			}
		}
	});

	$('#dialog_blank').dialog('open');
}

/* Montre les avis */
function showAvis(idDiv,idParcour,nbAvis)
{
	var divHide = '<div id="'+idDiv+'-hide" style="cursor:pointer"> Consulter les avis ('+nbAvis+') <img src="/cengo/public/images/admin/hide-avis.gif" /></div>';
	$('#'+idDiv).hide();
	$('#'+idDiv).parent().append(divHide);
	
	$('#'+idDiv+'-hide').click(function(event){
				$("#"+idDiv).show();
				$('#'+idDiv).parent().html($('#'+idDiv));
	});

	$.ajax({
		url: '/cengo/avis/viewparcours?id_parcours='+idParcour,
		success: function(data) {
			$('#'+idDiv).parent().append(data);
		}
	});
}

/* Toolbar fiche golf */
function ficheGolfToolbar(oObj,module,id_parcours)
{
	// Recup valeurs pour l'onglet score
	var args='';
	if(module=='score')
	{
		args+='&genre='+ $('#genre').val();
		args+='&index_golf='+ $('#index_golf').val();
		args+='&boule='+ $('#boule').val();
	}

	$('#toolbar-contenu').html(waitAjax);
	// Onglet - Reset toutes les ico
	$("div.toolbar-fiche").find("td").each(function (index, domEle) {
		var imgTd = $(this).html();
		testResetImg = imgTd.search('-on','');

		if(testResetImg >=1)
		{
			resetImg = imgTd.replace('-on','');
			$(this).html(resetImg);
		}
	});

	// Onglet - Active l'ico clickÃ©
	var TdSelected = $("#"+oObj).html();
	$("#"+oObj).html(TdSelected.replace('.jpg','-on.jpg'));

	// Appel ajax + injecte le contenu
	if(module =='parcours') {$('#toolbar-contenu').css({'padding':'0'});}
	else{$('#toolbar-contenu').css({'padding':'5px'});}

	$.ajax({
		url: '/cengo/parcours/toolbar'+module+'?id_parcours='+id_parcours+args,
		success: function(data) {
			$('#toolbar-contenu').html(data);
			if(module=='score') window.scrollTo(0,520);
			else window.scrollTo(0,200);
		}
	});
}

function showCommentaireListe(idDiv,sUrl)
{
	$(".info-bulle-erreur").hide();
	$.ajax({
				url: sUrl,
				success: function(data) {
					
					$("#"+idDiv).parent().append(data);
					$("#"+idDiv).parent().find("input.rating").rating();
					$("#"+idDiv).parent().find("input.star").rating();
					$("#"+idDiv).parent().find("#button-envoi-cmt").button();
					$("#"+idDiv).hide();
				}
			});
}

// Fonction qui deplie un div + appel en ajax une URL donné
function showDivAjax(idDiv,sUrl)
{
	$(".info-bulle-erreur").hide();
	if($("#"+idDiv).queue("fx") == 'inprogress'){return(false);}
	// $("#"+idDiv).animate({'height':'200px'},'fast',function(){ //height: 'toggle'
	$("#"+idDiv).slideToggle('fast',function(){
				$.ajax({
				url: sUrl,
				success: function(data) {
					$("#"+idDiv).parent().append('<div style="height:40px;cursor:pointer;" id="'+idDiv+'hide">'+$("#"+idDiv).html()+'</div>');
					$("#"+idDiv).parent().append(data);
					
					$("#"+idDiv).parent().find("input.rating").rating();
					$("#"+idDiv).parent().find("input.star").rating();
					$("#"+idDiv).parent().find("#button-envoi-cmt").button();
					$("#"+idDiv).css({'height':'40px'});

					
					$("#"+idDiv).hide();

					$("#"+idDiv+'hide').click(function(event){
								$("#"+idDiv).parent().html($("#"+idDiv));
								$("#"+idDiv).show();
								$(".info-bulle-erreur").hide();
								$("#"+idDiv).animate({'height':'13px'},'fast');
					});
					
				}
			});
	});
	return(true);
}
// function appeller pour tourner les pages en ajax
function showDivAjaxPager(idDiv,sUrl)
{
		$.ajax({
				url: sUrl,
				success: function(data) {
					var divAvis = $("#"+idDiv).parent().find("#cmt-liste-avis");
					divAvis.html(data);
					$("#"+idDiv).parent().find("input.star").rating();
					$("#"+idDiv).parent().find("#cmt-pager:first").hide();
				}
			});
}
// Submit la form commentaire + refresh liste
function submitFormAjax(idForm,action)
{
	$(".info-bulle-erreur").hide();
	
	// Verif champs
  var reg= /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/; 
  var test_mail = reg.test($("#"+idForm).find("#user-mail").val());
	var test_login = $("#"+idForm).find("#user-login").val().replace(/^\s+/g,'').replace(/\s+$/g,'');
	var test_avis = $("#"+idForm).find("#user-avis").val().replace(/^\s+/g,'').replace(/\s+$/g,'');

	var erreur=0;
	if(test_mail == false){showDivErreur(idForm,"user-mail","L'adresse e-mail est invalide.");var erreur="1";}
	if(test_login == ""){showDivErreur(idForm,"user-login","Vous n'avez pas saisie de login.");var erreur="1";}
	if(test_avis == ""){showDivErreur(idForm,"user-avis","Vous n'avez pas saisie d'avis.");var erreur="1";}
	if(erreur=="1"){return false;}

	// Module
	var typeLibelle = $("#"+idForm).find("#type-libelle").val();
	var typeId = $("#"+idForm).find("#type-id").val();
	var template = $("#"+idForm).find("#template").val();
	var idDivOld = "cmt-"+typeLibelle+"-"+typeId;
	var sUrlOld = "/cengo/commentaires/view?type="+typeLibelle+"&id_type="+typeId+"&avis_add=off&template="+template;

	// Post
	var params = { avis:$("#"+idForm).find("#user-avis").val().replace(/</g,'&lt;').replace(/>/g,'&gt;'),
								 note:$("#"+idForm).find("#user-note:checked").val(),
								 type_cmt:$("#"+idForm).find("#type-libelle").val(),
								 id_type:$("#"+idForm).find("#type-id").val(),
								 pseudo_auteur:test_login,
								 mail_auteur:$("#"+idForm).find("#user-mail").val(),
								 id_cmt:$("#"+idForm).find("#id_cmt").val(),
								 id_auteur:$("#"+idForm).find("#user-id").val()
							 };
	var dataString = jQuery.param(params);
	
	$.ajax({
   type: "POST",
   url: "/cengo/commentaires/"+action+"commentaire",
   data: dataString,
   success: function(msg){
		 if(action =='add')
		 {
				var dialog = $("#dialog_cmt");
				if(dialog.html() ==null)
				{
					var dialogBox ="<div id='dialog_cmt' title='Information' style='display:none;'><p>Votre commentaire à bien été enregistré.</p></div>";
					$("body").append(dialogBox);
				}
				// Dialog
				$('#dialog_cmt').dialog({autoOpen: false,width: 350,height:130,draggable: false,modal: true});
				$('#dialog_cmt').dialog('open');
		 }
		 showDivAjaxPager(idDivOld,sUrlOld);
		 $("#"+idForm).find("#user-avis").val('');
   }
 });
 return(true);
}
// Control saisie
function showDivErreur(idForm,inputId,texteErreur)
{
	var champErreur = $("#"+idForm).find("#"+inputId);
	var champErreurPos = champErreur.offset();
	var champErreurPosX = champErreurPos.left + champErreur.width() + 5;
	var champErreurPosY = champErreurPos.top - 2; 

	var imgBulle ="<img src='/cengo/public/images/cengo-erreur-info-bulle.gif' border='0'/>";
	var divEr = $("#"+inputId+"-erreur");
	if(divEr.html() !=null)
	{
		divEr.css({'top':champErreurPosY+'px'});
	}
	else
	{
		var divErreur="<div style='left:"+champErreurPosX+"px;top:"+champErreurPosY+"px;position:absolute;display:none;z-index:1002;' id='"+inputId+"-erreur' class='info-bulle-erreur'><div style='float:left;padding-top:5px'>"+imgBulle+"</div><div style='border:1px solid #CE0008;display:block;background-color:#E9C2C7;padding:5px;margin-left:9px;color:#CE0008'>"+texteErreur+"</div></div>";
		$("body").append(divErreur);
	}
	
	$("#"+inputId+"-erreur").fadeIn('slow');	
}
// Supprimer un commentaire
function deleteCommentaire(idCmt,idDiv,sUrl)
{
	// Dialog
	$('#dialog_del_cmt').dialog({
		autoOpen: false,
		width: 350,
		height:130,
		draggable: false,
		modal: true,
		buttons: {
			"Annuler": function() {
				$('#dialog_del_cmt').dialog("destroy");
			},
			"Ok": function() {
				$.ajax({
					url: '/cengo/commentaires/deletecommentaire?id_cmt='+idCmt
				});
				$('#dialog_del_cmt').dialog("destroy");
				showDivAjaxPager(idDiv,sUrl); // refresh div
			}
			
		}
	});
	
	$('#dialog_del_cmt').dialog('open');
}
// Editer un commentaire
function editCommentaire(idCmt,idDiv,template)
{
	$("#dialog_edit_cmt").html(waitAjax());
	// Affiche le formulaire d'edition
	$.ajax({
				url: '/cengo/commentaires/editcommentaire?id_cmt='+idCmt+template,
				success: function(data) {
						$("#dialog_edit_cmt").html(data);
						$("input.rating").rating();
				}
	});
	// Dialog
	$('#dialog_edit_cmt').dialog({
		autoOpen: false,
		width: 450,
		height:310,
		draggable: false,
		modal: true,
		buttons: {
			"Annuler": function() {
				//$(this).dialog("close");
				$('#dialog_edit_cmt').dialog('destroy');
				$("#dialog_edit_cmt").html('');
			},
			"Envoyer": function() {
					submitFormAjax('cmt-edit-'+idCmt,'edit');
					$('#dialog_edit_cmt').dialog('destroy');
					$("#dialog_edit_cmt").html('');
			}
		}
	});
	$('#dialog_edit_cmt').dialog('open');
	
}
// Signaler un abus
function alertModerateur(sUrl,idDiv,sUrlDivAjax)
{
	$("#dialog_blank").html('<p>Signalement envoyé, merci de votre contribution.</p>');
	$.ajax({
					url: sUrl,
					success: function(data) {
							showDivAjaxPager(idDiv,sUrlDivAjax);
					}
		});
	// Dialog
	$('#dialog_blank').dialog({autoOpen: false,width: 350,height:130,draggable: false,modal: true});
	$('#dialog_blank').dialog('open');
}
// Supprimer un avis
function deleteAvis(idAvis,idParcours,idDiv,sUrl)
{
	// Dialog
	$('#dialog_del_avis').dialog({
		autoOpen: false,
		width: 350,
		height:130,
		draggable: false,
		modal: true,
		buttons: {
			"Annuler": function() {
				$('#dialog_del_avis').dialog("destroy");
			},
			"Ok": function() {
				$.ajax({
					url: '/cengo/avis/deleteavisparcours?id_avis='+idAvis+'&id_parcours='+idParcours
				});
				$('#dialog_del_avis').dialog("destroy");
				showDivAjaxPager(idDiv,sUrl); // refresh div
			}
		}
	});

	$('#dialog_del_avis').dialog('open');
}
// Editer un commentaire
function editAvis(idAvis)
{
	$("#dialog_edit_avis").html(waitAjax());
	// Affiche le formulaire d'edition
	$.ajax({
				url: '/cengo/avis/editavisparcours?id_avis='+idAvis,
				success: function(data) {
						$("#dialog_edit_avis").html(data);
						$("input.rating").rating();
				}
	});
	// Dialog
	$('#dialog_edit_avis').dialog({
		autoOpen: false,
		width: 740,
		height:500,
		draggable: false,
		modal: true,
		buttons: {
			"Annuler": function() {
				//$(this).dialog("close");
				$('#dialog_edit_avis').dialog('destroy');
				$("#dialog_edit_avis").html('');
			},
			"Envoyer": function() {
					submitFormAvis('form-avis-'+idAvis,'edit');
					$('#dialog_edit_avis').dialog('destroy');
					$("#dialog_edit_avis").html('');
			}
		}
	});
	$('#dialog_edit_avis').dialog('open');
}
// submit Avis
function submitFormAvis(idForm,action)
{
	$(".info-bulle-erreur").hide();
	// Verif champs
	var test_avis = $("#"+idForm).find("#user-avis").val().replace(/^\s+/g,'').replace(/\s+$/g,'');
	var erreur=0;
	if(test_avis == ""){$("#"+idForm).find("#error").html("Vous n'avez pas saisie d'avis.");$("#"+idForm).find("#error").show();var erreur="1";}
	if(erreur=="1"){return false;}
	var params = {	avis:$("#"+idForm).find("#user-avis").val().replace(/</g,'&lt;').replace(/>/g,'&gt;'),
									id_parcours:$("#"+idForm).find("#id_parcours").val(),
									id_avis:$("#"+idForm).find("#id_avis").val(),
									accueil:$("#"+idForm).find("#user-note-accueil:checked").val(),
									golf: $("#"+idForm).find("#user-note-parcours:checked").val(),
									prix: $("#"+idForm).find("#user-note-prix:checked").val(),
									resto: $("#"+idForm).find("#user-note-restaurant:checked").val()
	};
	var dataString = jQuery.param(params);
	var id_parcours = $("#"+idForm).find("#id_parcours").val();
	$.ajax({
   type: "POST",
   url: "/cengo/avis/"+action+"avisparcours",
   data: dataString,
   success: function(msg){
		  if(action =='add')
			{
				var dialog = $("#dialog_avis_add");
				if(dialog.html() ==null)
				{
					var dialogBox ="<div id='dialog_avis_add' title='Information' style='display:none;'><p>Votre avis à bien été enregistré.</p></div>";
					$("body").append(dialogBox);
				}
				// Dialog
				$('#dialog_avis_add').dialog({autoOpen: false,width: 350,height:130,draggable: false,modal: true});
				$('#dialog_avis_add').dialog('open');
		 }
		 $('#avis-liste').load('/cengo/avis/viewparcours?id_parcours='+id_parcours+'&avis_add=off');
   }
 });
 return(true);
}
// Formulaire message privé
function sendMessagePrive(idUser,action)
{
	if(action !='post') // Affiche le formulaire d'envoie
	{
		$("#dialog_mp").html(waitAjax());
		if (action.match(/rep-.*?/))
		{
			var id_message = action.replace('rep-','');
			var param = '&id_message='+id_message;
		}
		else{param='';}

		$.ajax({
					url: '/cengo/user/mpaddajax?id_user='+idUser+param,
					success: function(data) {
							$("#dialog_mp").html(data);
					}
		});
	}
	else
	{
		var params = {	id_user:idUser,
										titre_mp:$("#mpadd").find("#titre_mp").val().replace(/^\s+/g,'').replace(/\s+$/g,''),
										contenu_mp:$("#mpadd").find("#contenu_mp").val().replace(/^\s+/g,'').replace(/\s+$/g,''),
										id_message:$("#mpadd").find("#id_message").val()
		};
		var dataString = jQuery.param(params);
			
		$.ajax({
				type: "POST",
				url: "/cengo/user/mpaddajax",
				data: dataString,
				success: function(msg){
					$('#dialog_mp').dialog('destroy');
					$("#dialog_mp").html('OK');
				}
		});
	}
	// Dialog
	$('#dialog_mp').dialog({
		autoOpen: false,
		width: 780,
		height:350,
		draggable: false,
		modal: true,
		buttons: {
			"Annuler": function() {
				$('#dialog_mp').dialog('destroy');
				$("#dialog_mp").html('');
			},
			"Envoyer": function() {
					if($("#mpadd").find("#titre_mp").val().replace(/^\s+/g,'').replace(/\s+$/g,'') == ''){var erreur=1;}
					if($("#mpadd").find("#contenu_mp").val() ==''){var erreur=1;}
					if(erreur==1){return(false);}
					else
					{
						sendMessagePrive(idUser,'post');
					}
			}
		}
	});
	$('#dialog_mp').dialog('open');
}
function waitAjax()
{
	var divWait = '<div id="loading" align="center"><img src="/cengo/public/images/ajax-loader.gif" border="0"/></div>';
	return(divWait);
}

function preview(sChamp)
{
		var params = {d:$("#"+sChamp).val().replace(/^\s+/g,'').replace(/\s+$/g,'')};
		var dataString = jQuery.param(params);

		$.ajax({
				type: "POST",
				url: "/cengo/forum/preview",
				data: dataString,
				success: function(msg){
					$("#dialog_blank").html(msg);
					$(".preload").each(function () { $(this).attr("src",$(this).attr("rel")); });
				}
		 });

	// Dialog
	$('#dialog_blank').dialog({
		autoOpen: false,
		width: 700,
		height:320,
		draggable: true,
		modal: true
	});
	$('#dialog_blank').dialog('open');
}

function log(texte)
{
	$("#barre-nav").append(texte+'<br/>');
}

function getInfoTrou(oObj)
{
	// Set style div selectioné
	var divSelected = $("#schema_trou_selected");
	liPos = $(oObj).position();
	posLeftDivSel = liPos.left - 29;
	divSelected.css({'left' : posLeftDivSel, 'top' : liPos.top,'display' : 'block'});
	
	if(!oObj.id)nbTrou=0;
	else{nbTrou = oObj.id.replace('schema_trou_','');}
	if(nbTrou =="0"){divSelected.html("Parcours");}
	else{divSelected.html(nbTrou);}

	// Slope + par + hcp + photo;
	$("#schema_info_sss_noir").html($("#schema_info_trou_sss_noir_"+nbTrou).html());
	$("#schema_info_sss_blanc").html($("#schema_info_trou_sss_blanc_"+nbTrou).html());
	$("#schema_info_sss_jaune").html($("#schema_info_trou_sss_jaune_"+nbTrou).html());
	$("#schema_info_sss_bleue").html($("#schema_info_trou_sss_bleue_"+nbTrou).html());
	$("#schema_info_sss_rouge").html($("#schema_info_trou_sss_rouge_"+nbTrou).html());
	$("#schema_info_hcp").html('<span style="font-size:14px;">Hcp '+ $("#schema_info_trou_hcp_"+nbTrou).html() + '</span>');
	$("#schema_info_par").html('<span style="font-size:14px;">Par ' + $("#schema_info_trou_par_"+nbTrou).html() +'</span>');
	if(nbTrou =="0"){$("#schema_info_trou").html("");} else {$("#schema_info_trou").html(nbTrou);}
	
	// Conseil du Pro
	$("#content_cdp").hide();
	if($("#schema_info_conseil_pro_"+nbTrou).html()!=""){$("#content_cdp").fadeIn('slow');$("#trou_conseil_pro").html($("#schema_info_conseil_pro_"+nbTrou).html());}

	// Les schemas
	$("#schema_info_trou_photo_schema_"+nbTrou+" > .preload").each(function () {$(this).attr("src",$(this).attr("rel"));});
	$("#schema_info_photo_schema").html($("#schema_info_trou_photo_schema_"+nbTrou).html());
	
	// Les photos trou par trou
	$("#schema_info_trou_photo_"+nbTrou+" > .preload").each(function () { $(this).attr("src",$(this).attr("rel")); });
	$("#schema_info_photo").html($("#schema_info_trou_photo_"+nbTrou).html());	
}

function showBigSize(url)
{
	/* Dialog
	$('#dialog_blank').html('<img src="'+url+'" border="0"/>');
	$('#dialog_blank').dialog({
		autoOpen: false,
		modal: true
	});

	$('#dialog_blank').dialog('open'); */
	afficher_image(url);
}

function FicheParcoursEffect(oObj)
{
	var divParcour = $(oObj);
	if(divParcour)
	{
		divParcour.css({'border': '1px solid #C33D00'});
		divParcour.mouseleave(function(event){
			divParcour.css({'border': '1px solid #CACFD5'});
		});
	}
}

/* BBcode */
function storeCaret (textarea) { 
if (document.getElementById(textarea).createTextRange) document.getElementById(textarea).caretPos = document.selection.createRange().duplicate(); 
}
function insertAtCaret (textarea, icon) { 
if (document.getElementById(textarea).createTextRange && document.getElementById(textarea).caretPos) { 
var caretPos = document.getElementById(textarea).caretPos; 
selectedtext = caretPos.text; 
caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == '' ? icon + '' : icon; 
caretPos.text = caretPos.text + selectedtext; }
else if (document.getElementById(textarea).textLength > 0){
Deb = document.getElementById(textarea).value.substring( 0 , document.getElementById(textarea).selectionStart );
Fin = document.getElementById(textarea).value.substring( document.getElementById(textarea).selectionEnd , document.getElementById(textarea).textLength );
document.getElementById(textarea).value = Deb + icon + Fin; }
else{ document.getElementById(textarea).value = document.getElementById(textarea).value + icon; }
document.getElementById(textarea).focus(); 
}
function PopupinsertAtCaret (textarea, icon) { 
if (opener.document.getElementById(textarea).createTextRange && opener.document.getElementById(textarea).caretPos) { 
var caretPos = opener.document.getElementById(textarea).caretPos; 
selectedtext = caretPos.text; 
caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == '' ? icon + '' : icon; 
caretPos.text = caretPos.text + selectedtext; }
else if (opener.document.getElementById(textarea).textLength > 0){
Deb = opener.document.getElementById(textarea).value.substring( 0 , opener.document.getElementById(textarea).selectionStart );
Fin = opener.document.getElementById(textarea).value.substring( opener.document.getElementById(textarea).selectionEnd , opener.document.getElementById(textarea).textLength );
opener.document.getElementById(textarea).value = Deb + icon + Fin; }
else{ opener.document.getElementById(textarea).value = opener.document.getElementById(textarea).value + icon; }
}


function substr_count(str, ssstr) {
num = 0;
while(str.indexOf(ssstr) != -1) 
{
str = str.substr(str.indexOf(ssstr) + ssstr.length, str.length - (str.indexOf(ssstr)+ssstr.length));
num++;
}
return num;
}


function backslash(textarea) {
texte = document.getElementById(textarea).value;
texte = texte.replace(/\\/g,"\\\\");
document.getElementById(textarea).value=texte;
}

function BBcode_close(textarea) {
texte = document.getElementById(textarea).value;
bbtags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote','[/quote]','[code]','[/code]','[li]','[/li]','[img','[/img]','[url','[/url]','[email]','[/email]','[center]','[/center]','[flash','[/flash]','[color','[/color]','[font','[/font]','[size','[/size]','[align','[/align]','[blink]','[/blink]','[strike]','[/strike]','[marquee]','[/marquee]','[updown]','[/updown]','[flip]','[/flip]','[blink]','[/blink]','[blur]','[/blur]','[glow','[/glow]','[shadow','[/shadow]');
size= bbtags.length;

for (var i =0; i < size; i+=2) {
nb_open=substr_count(texte, bbtags[i]);
nb_close=substr_count(texte, bbtags[i+1]);
                         
if (nb_open>nb_close) {
for (var z =nb_open; z > nb_close; z--){
texte+=bbtags[i+1];}
}
if (nb_open < nb_close) {
for (var a =nb_open; a < nb_close; a++){
texte=bbtags[i]+texte;}
}
}  
document.getElementById(textarea).value=texte;    
}

function upload_img()
{
	if($("#upload_img").is(":visible"))
	{
		$("#upload_img").hide();
	}
	else
	{
		$.ajax({
					url: '/cengo/forum/upload',
					success: function(data) {
							$("#upload_img p").html(data);
					}
		});
		
	  var pos = $("#bbcode").position();
		$("#upload_img").css({'top': pos.top+25, 'left' : pos.left+250});
		$("#upload_img").show();
	} 
}

function upload_image_close()
{
	$("#upload_img").hide();
}

function ajout_url(textarea, texturl, textname){
VarUrl = window.prompt(texturl,'http://');
VarNom = window.prompt(textname,'');
if (VarUrl.indexOf('http://') == -1) VarUrl = 'http://'+VarUrl;
if ((VarUrl != null) && (VarUrl != '') && (VarNom != null) && (VarNom != '')) {
insertAtCaret(textarea, '[url='+VarUrl+']'+VarNom+'[/url]');}
}
	

function ajout_img(textarea, textimgturl){
VarImg = window.prompt( textimgturl,'http://' );
if (VarImg.indexOf('http://') == -1) VarImg = 'http://'+VarImg;
if ((VarImg != null) && (VarImg != '')) {
insertAtCaret(textarea, '[img]'+VarImg+'[/img]');}
}
	
function ajout_flash(textarea, textflashurl, textflashwidth, textflashheight){
Varflash = window.prompt(textflashurl,'http://');
if (Varflash.indexOf('http://') == -1) Varflash = 'http://'+Varflash;
if ((Varflash != null) && (Varflash != '')) {
insertAtCaret(textarea, '[flash=425x350]'+Varflash+'[/flash]');}
}

function ajout_text(textarea, entertext, tapetext, balise){
if (document.selection && document.selection.createRange().text != ''){
document.getElementById(textarea).focus();
VarTxt = document.selection.createRange().text;
document.selection.createRange().text = '['+balise+']'+VarTxt+'[/'+balise+']';}
else if (document.getElementById(textarea).selectionEnd && (document.getElementById(textarea).selectionEnd - document.getElementById(textarea).selectionStart > 0)){
valeurDeb = document.getElementById(textarea).value.substring( 0 , document.getElementById(textarea).selectionStart );
valeurFin = document.getElementById(textarea).value.substring( document.getElementById(textarea).selectionEnd , document.getElementById(textarea).textLength );
objectSelected = document.getElementById(textarea).value.substring( document.getElementById(textarea).selectionStart , document.getElementById(textarea).selectionEnd );
document.getElementById(textarea).value = valeurDeb+'['+balise+']'+objectSelected+'[/'+balise+']'+valeurFin;}
else{
VarTxt = window.prompt(entertext,tapetext);
if ((VarTxt != null) && (VarTxt != '')) insertAtCaret(textarea, '['+balise+']'+VarTxt+'[/'+balise+']');}
}


function color(couleur, textarea, entertext, tapetext){
if (document.selection && document.selection.createRange().text != ''){
document.getElementById(textarea).focus();
VarTxt = document.selection.createRange().text;
document.selection.createRange().text = '[color='+couleur+']'+VarTxt+'[/color]';}
else if (document.getElementById(textarea).selectionEnd && (document.getElementById(textarea).selectionEnd - document.getElementById(textarea).selectionStart > 0)){
valeurDeb = document.getElementById(textarea).value.substring( 0 , document.getElementById(textarea).selectionStart );
valeurFin = document.getElementById(textarea).value.substring( document.getElementById(textarea).selectionEnd , document.getElementById(textarea).textLength );
objectSelected = document.getElementById(textarea).value.substring( document.getElementById(textarea).selectionStart , document.getElementById(textarea).selectionEnd );
document.getElementById(textarea).value = valeurDeb+'[color='+couleur+']'+objectSelected+'[/color]'+valeurFin;}
else{
if (couleur != null && couleur != '') VarTxt = window.prompt(entertext,tapetext);
if (VarTxt != null && VarTxt != '' && couleur != '') insertAtCaret(textarea, '[color='+couleur+']'+VarTxt+'[/color]');}
}


function taille(size, textarea, entertext, tapetext){
if (document.selection && document.selection.createRange().text != ''){
document.getElementById(textarea).focus();
VarTxt = document.selection.createRange().text;
document.selection.createRange().text = '[size='+size+']'+VarTxt+'[/size]';}
else if (document.getElementById(textarea).selectionEnd && (document.getElementById(textarea).selectionEnd - document.getElementById(textarea).selectionStart > 0)){
valeurDeb = document.getElementById(textarea).value.substring( 0 , document.getElementById(textarea).selectionStart );
valeurFin = document.getElementById(textarea).value.substring( document.getElementById(textarea).selectionEnd , document.getElementById(textarea).textLength );
objectSelected = document.getElementById(textarea).value.substring( document.getElementById(textarea).selectionStart , document.getElementById(textarea).selectionEnd );
document.getElementById(textarea).value = valeurDeb+'[size='+size+']'+objectSelected+'[/size]'+valeurFin;}
else{
if (size != null && size != '') VarTxt = window.prompt(entertext,tapetext);
if (VarTxt != null && VarTxt != '' && size != '') insertAtCaret(textarea, '[size='+size+']'+VarTxt+'[/size]');}
}


function police(font, textarea, entertext, tapetext){
if (document.selection && document.selection.createRange().text != ''){
document.getElementById(textarea).focus();
VarTxt = document.selection.createRange().text;
document.selection.createRange().text = '[font='+font+']'+VarTxt+'[/font]';}
else if (document.getElementById(textarea).selectionEnd && (document.getElementById(textarea).selectionEnd - document.getElementById(textarea).selectionStart > 0)){
valeurDeb = document.getElementById(textarea).value.substring( 0 , document.getElementById(textarea).selectionStart );
valeurFin = document.getElementById(textarea).value.substring( document.getElementById(textarea).selectionEnd , document.getElementById(textarea).textLength );
objectSelected = document.getElementById(textarea).value.substring( document.getElementById(textarea).selectionStart , document.getElementById(textarea).selectionEnd );
document.getElementById(textarea).value = valeurDeb+'[font='+font+']'+objectSelected+'[/font]'+valeurFin;}
else{
if (font != null && font != '') VarTxt = window.prompt(entertext,tapetext);
if (VarTxt != null && VarTxt != '' && font != '') insertAtCaret(textarea, '[font='+font+']'+VarTxt+'[/font]');}
}


function ajout_mail(textarea, textmail){
VarMail = window.prompt(textmail,'webmaster@lapassiondugolf.fr');
if ((VarMail != null) && (VarMail != '')) {
insertAtCaret(textarea, '[email]'+VarMail+'[/email]');}
}

function stopEvent(ev) 
{
  ev.stopPropagation();
}

/* AFFICHAGE IMAGES */
function afficher_image(sUrl)
{
	if(!sUrl)
	{
		alert("Grande image non disponible.");
		return;
	}
	afficher_fond_gris(true);
	oBoite=document.getElementById("img_boite");
	if(!oBoite)
	{
		oBoite=document.createElement("div");
		oBoite.setAttribute("id","img_boite");
		oBoite.setAttribute("style","display:block;position:absolute;background-color:#ffffff;");
		document.body.appendChild(oBoite);
	}
	// Patience
	sHtml='<center><table style="margin-top:40px"><tr><td class="notice_patience" style="text-align:right;width:15px"><img src="' + imagesUrl + 'patience.gif"';
	sHtml+='border="0"></td><td><b>&nbsp;Veuillez patienter chargement en cours...</b></td></tr></table>';
	oBoite.innerHTML=sHtml;
	centrer_image(oBoite,300,100, false);

	// Charger image
	oImage = new Image();
  oImage.src=sUrl;
	oImage.onError = function()
								{
									oBoite.style.display="none";
									afficher_fond_gris(false);
									alert("Une erreur s'est produite au chargement de l'image.");
								};
setTimeout( 'image_completed(oImage)', 100 );
}

function image_completed()
{
	if(oImage.complete == true)
	{
		sOnclick='document.getElementById(\'img_boite\').style.display=\'none\';afficher_fond_gris(false);';
		sHtml='<div style="height:30px;width:100%;text-align:right;margin-top:5px;"><a href="#" onclick="' + sOnclick + '">'
		sHtml+='&raquo&nbsp;Fermer l\'image&nbsp;&nbsp;</a></div>';
		sHtml+='<img border="0" id="img_image" style="margin:10px;margin-top:0px;border:1px solid;border-color:#bfbfbf;cursor:pointer;"';
		sHtml+=' src="' + oImage.src + '" onclick="' + sOnclick + '">';
   	oBoite=document.getElementById('img_boite');
   	oBoite.innerHTML=sHtml;
 		centrer_image(oBoite,(oImage.width + 20) ,(oImage.height + 50), true);
	}
	else setTimeout( 'image_completed(oImage)', 100 );
}

function centrer_image(oBoite, nLargeur, nHauteur, bProgressif)
{
	oBoite.style.display="none";
	// Positionnement
	var left = parseInt((screen.availWidth/2) - (nLargeur/2));
  var top = parseInt((screen.availHeight/2) - (nHauteur/2));
  if(left < 0 ) left=0;
  if(top < 0) top=0;
  oBoite.style.left=left + "px";
	oBoite.style.top=document.documentElement.scrollTop + top + "px";
	oBoite.style.width=nLargeur + "px";
	oBoite.style.height=nHauteur + "px";
	// Si image plus grande que fonds gris on agrandit le fond gris
	if((nHauteur + top + document.documentElement.scrollTop) > document.getElementById("img_fond").height)
	{ 
		nHauteurFond=nHauteur + parseInt(oBoite.style.top);
		document.getElementById("img_fond").style.height=nHauteurFond + "px";
	}
	if(bProgressif == false )
	{
		oBoite.style.display="block";
		return;
	}
	
	// Affichage progressif
	oBoite.style.opacity =0;
	oBoite.style.filter = 'alpha(opacity=1)';
	oBoite.style.display="block";
	for( var i = 0; i <= 100; i++ )
  setTimeout( 'setOpacity("img_boite",' + (i / 10) + ')' , 20 * i );
}

// Fond pour modal dialog 
function afficher_fond_gris(bMode)
{
	oFondGris=document.getElementById("fond_gris");
	if(!oFondGris)
	{
		oFondGris=document.createElement("div");
		oFondGris.setAttribute("id","fond_gris");
		document.body.appendChild(oFondGris);
	}
	oFondGris.style.display="none";
	if(bMode == false) return;
	oFondGris.style.position="absolute";
	oFondGris.style.opacity="0.4";
	oFondGris.style.filter = 'alpha(opacity="40")';
	oFondGris.style.top="0px";
	oFondGris.style.left="0px";
	oFondGris.style.width="100%";
 	sHauteur=document.body.clientHeight + "px"; 
  sHtml='<img id="img_fond" src="' + imagesUrl + 'fond-gris.gif" width="100%" height="' + sHauteur + '">';
  oFondGris.innerHTML=sHtml;
	oFondGris.style.display="block";
	//$('fond_gris').tween('opacity',0,0.4);
	return;
}

function setOpacity( sIdBoite, value ) 
{
 oObj=document.getElementById(sIdBoite);
 oObj.style.opacity = value / 10;
 oObj.style.filter = 'alpha(opacity=' + value * 10 + ')';
}

// Encodage utf8
function utf8_encode(string) 
{
	string = string.replace(/\r\n/g,"\n");
	var utftext = "";
	for (var n = 0; n < string.length; n++) 
	{
		var c = string.charCodeAt(n);
		if (c < 128) utftext += String.fromCharCode(c);
		else if((c > 127) && (c < 2048)) 
		{
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		}
		else 
		{
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}
 	}
	return utftext;
}

//-----------------------------------------
// Champs suggestion
//-----------------------------------------
var sLastSuggestCherche;

// Appel champ suggestion
function getSuggest(sChamp,sUrl,sChampLie,sJs)
{
	// Si la valeur n'a pas change on sort
	oChamp=document.getElementById(sChamp);
	if(oChamp.value == sLastSuggestCherche) return;

	var oChampPos = $("#"+sChamp).position();

	// Positionner le deroulant
	nX=oChampPos.left;
	nY=oChampPos.top + oChamp.clientHeight +1;

	// Requete ajax
	sUrl=sUrl + "?cherche=" + encodeURI(oChamp.value) + "&champ=" + sChamp;
	if(sChampLie) sUrl=sUrl + "&champ_lie=" + sChampLie;
	if(sJs) sUrl=sUrl + "&js=" + sJs;
	$('#suggest_' + sChamp).load(sUrl).show();
}

// Renvoie valeur cliquee dans la liste
function clickSuggest(sChamp,sValeur)
{
	$('#'+sChamp).val(sValeur);
	sLastSuggestCherche="";
	oSuggest=document.getElementById("suggest_" + sChamp);
	oSuggest.style.display="none";
	oSuggest.innerHTML="";
}



//-----------------------------------------
// cacher le watermark pour les stats
//-----------------------------------------
function hideWatermark(objet)
{
	var position=$('#'+objet).offset();
	var left=parseInt(position.left)+2;
	var top=parseInt(position.top)+2;
	$('#'+objet).append('<div style="position:absolute;left:'+left+'px;top:'+top+'px;background-color:#ffffff;width:145px;padding-top:9px">&nbsp</div>');
}
//
//-------------------------------------------------------------
// Affiche la roulette patience avec une hauteur en parametre
//-------------------------------------------------------------
function getPatience(hauteur)
{
	if(hauteur==0) hauteur=50;
	hauteur=parseInt((hauteur / 2)-16);
	var patience='<div width="100%" align="center" style="margin-top:'+hauteur+'px;margin-bottom:'+hauteur+'px"><img src="'+imagesUrl+'loading.gif"></div>';
	return patience;
}
