var TTL_ALERT_CONTACT			= "Erreur dans la saisie";
var TTL_ALERT_SEND_TO_FRIEND	= "Envoyer &agrave; un ami";
var TTL_ALERT_REPORT_ISSUE		= "Signaler un probl&egrave;me";

var TXT_ALERT_CONTACT_GENDER	= "Veuillez sélectionner une <strong>civilité</strong>.";
var TXT_ALERT_CONTACT_NAME		= "Veuillez saisir un <strong>nom / prénom</strong>.";
var TXT_ALERT_CONTACT_TELEPHONE	= "Veuillez saisir un <strong>numéro de téléphone</strong>.";
var TXT_ALERT_CONTACT_EMAIL		= "Veuillez saisir une <strong>adresse e-mail</strong> valide.";
var TXT_ALERT_CONTACT_ZIPCODE	= "Veuillez saisir un <strong>code postal</strong>.";
var TXT_ALERT_CONTACT_MESSAGE	= "Veuillez saisir un <strong>message</strong>.";
var TXT_ALERT_CONTACT_OPTIN     = "Choisissez l'une des deux case ci-dessus afin de bénéficier ou non du service d'envoi d'email.";

var TTL_ALERT_INFORMATION		= "Information";
var TXT_ALERT_SELECTION_OK		= "Cette annonce a bien été ajoutée à votre sélection.";
var TXT_ALERT_SELECTION_KO		= "Une erreur est survenue lors de l'ajout de cette annonce à votre sélection";
var TXT_ALERT_SELECTION_EXISTS	= "Cette annonce fait déjà partie de votre sélection.";

var TXT_MESSAGE_SENDING			= "Envoi du message...";
var TXT_MESSAGE_SENT			= "Votre message a bien été envoyé.";
var TXT_MESSAGE_NOTSENT			= "Une erreur est survenue lors de l'envoi de votre message.";

var ISSUE_TYPES					= ["Arnaque", "Véhicule vendu", "Coordonnées incomplètes", "Mauvaise catégorie", "Autre"];

var AD_ID = -1;
var LOGGED_DATA = null;

var lastSenderName = null;
var lastSenderEmail = null;

var photoZoom = null;

window.addEvent("domready", InitDetail);

/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function InitDetail()
{
	// ajout d'un evenement pour gerer le clic sur le lien "imprimer cette annonce"
	if ($("mxdPrintDetail"))
	{
		$("mxdPrintDetail").addEvent("click", function() { window.print(); });
	}
	// ajout d'un evenement pour gerer le clic sur le lien "envoyer à un ami"
	if ($("mxdSendToFriend"))
	{
		$("mxdSendToFriend").addEvent("click", function() { SendToFriend() });
	}
	// ajout d'un evenement pour gerer le clic sur le lien "ajouter à ma sélection"
	if ($("mxdAddToSelection"))
	{
		$("mxdAddToSelection").addEvent("click", function() { AddToSelection() });
	}
	// ajout d'un evenement pour gerer le clic sur le lien "signaler un probleme"
	if ($("mxdReportIssue"))
	{
		$("mxdReportIssue").addEvent("click", function() { ReportIssue() });
	}

	// ajout d'un evenement pour gerer le clic sur le bouton "envoyer" du formulaire de contact
	if ($("mxdContactSend"))
	{
		$("mxdContactSend").addEvent("click", CheckContactForm);

		// ajout du div utilisé dans l'affichage de la barre de progression / du texte final
		// quand le message est envoyé
		var contactSending = new Element("div", { "id" : "mxdContactSending", "class" : "mxdAjaxSend" });
		contactSending.set("html", TXT_MESSAGE_SENDING).inject($("mxdContactForm"), "after");
	}

	// ajout d'un evenement pour gerer le clic sur le bouton "envoyer" du formulaire "demande de coordonnees"
	if ($("mxdContactCookieSend"))
	{
		$("mxdContactCookieSend").addEvent("click", CheckContactCookieForm);

		var ccSending = new Element("div", { "id" : "mxdContactCookieSending", "class" : "mxdAjaxSend" });
		ccSending.set("html", TXT_MESSAGE_SENDING).inject($("mxdContactCookieSend"), "after");
	}

	// ajout des differents evenements pour la gestion de la galerie photos
	if ($("mxdDetailPhotos"))
	{
		photoZoom = new PhotoZoom(
		{
			bigContainer: "mxdDetailPhotos",
			smallContainer: "mxdDetailPhotosSmall",
			openButton: "mxdPhotoZoom",
			prevButton: "mxdPrev",
			nextButton: "mxdNext"
		});

		// si l'element mxdPhotoPrevious existe on lui ajoute un nouvel evenement "PhotoDisplay"
		if ($("mxdPhotoPrevious")) { $("mxdPhotoPrevious").addEvent("click", function() { PhotoDisplay(-1) }); }

		// si l'element mxdPhotoNext existe on lui ajoute un nouvel evenement "PhotoDisplay"
		if ($("mxdPhotoNext")) { $("mxdPhotoNext").addEvent("click", function() { PhotoDisplay(1) }); }
	}

	// si le formulaire de contact est present, on donne le focus au champ "nom et prenom"
	if ($("contact_name"))
	{
		$("contact_name").focus();
	}
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function AjaxRequest(methodName, params)
{
	var myRequest = new Request({ method : "post", url : appDirectory + "/ajax/" + methodName + ".aspx", onSuccess : function(r) { eval(methodName + "CallBack(r)") } });
	myRequest.send(Hash.toQueryString(params));
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function SendToFriend()
{
	var loggedName = "";
	var loggedEmail = "";
	if ($defined(LOGGED_DATA) && LOGGED_DATA != "")
	{
		loggedName = LOGGED_DATA.split("|")[0].hexadecode();
		loggedEmail = LOGGED_DATA.split("|")[1].hexadecode();
	}
	loggedName = (lastSenderName == null) ? loggedName : lastSenderName;
	loggedEmail = (lastSenderEmail == null) ? loggedEmail : lastSenderEmail;

	var alertContent = "<form id='mxdSendToFriendForm'><p><strong>Votre nom :</strong><br/><input type='text' id='sender_name' value=\"" + loggedName + "\"></p>";
	alertContent += "<p><strong>Votre e-mail :</strong><br/><input type='text' id='sender_email' value=\"" + loggedEmail + "\"></p>";
	alertContent += "<p><strong>E-mail du destinataire :</strong><br/><input type='text' id='sender_recipient'><p>";
	alertContent += "<p>Commentaire (facultatif) :<br/><textarea id='sender_comment'></textarea><p>";
	alertContent += "</form>";

	simpleAlert = new SimpleAlert(
	{
		btnCaption: "Envoyer",
		"onShow": function ()
		{ 
			if (loggedName == "") $("mxdSendToFriendForm").sender_name.focus();
			if (loggedName != "" && loggedEmail == "") $("mxdSendToFriendForm").sender_email.focus();
			if (loggedName != "" && loggedEmail != "") $("mxdSendToFriendForm").sender_recipient.focus();
		},
		"onValid": function()
		{
			lastSenderName = $("sender_name").value;
			lastSenderEmail = $("sender_email").value;
			
			SendMessageToFriend();
		} 
	});
	simpleAlert.show(TTL_ALERT_SEND_TO_FRIEND, "", alertContent);
	simpleAlert.addButton("Annuler", "before", function() { simpleAlert.hide(); });
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function SendMessageToFriend()
{
	var senderName = $("sender_name").value;
	var senderEmail = $("sender_email").value;
	var senderRecipient = $("sender_recipient").value;
	var senderComment = $("sender_comment").value.replace(/\n/g, " ").hexaencode();
	var detailUrl = document.location.href.hexaencode();

	var sendForm = true;
	if (senderName != "")
	{
		var goodEmail = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,3}|\d+)$/.test(senderEmail);
		if (senderEmail == "" || !goodEmail)
		{
			sendForm = false;
			alert("Merci de vérifier votre adresse email.");
			$("sender_email").focus();
		}
		goodEmail = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,3}|\d+)$/.test(senderRecipient);
		if (sendForm && (senderRecipient == "" || !goodEmail))
		{
			sendForm = false;
			alert("Merci de vérifier l'adresse email du destinataire.");
			$("sender_recipient").focus();
		}
	}
	else
	{
		sendForm = false;
		alert("Veuillez renseigner votre nom.");
		$("sender_name").focus();
	}

	if (sendForm)
	{
		simpleAlert.hide();

		senderName = senderName.hexaencode();
		senderEmail = senderEmail.hexaencode();
		senderRecipient = senderRecipient.hexaencode();

		AjaxRequest("SendToFriend", { "i": AD_ID, "sn": senderName, "se": senderEmail, "sr": senderRecipient, "sc": senderComment, "u": detailUrl });
	}
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function SendToFriendCallBack(data)
{
	simpleAlert = new SimpleAlert(
	{
		btnCaption: "OK",
		"onValid": function() {	simpleAlert.hide();} 
	});

	var message = (data == "ok") ? TXT_MESSAGE_SENT : TXT_MESSAGE_NOTSENT;

	simpleAlert.show(TTL_ALERT_SEND_TO_FRIEND, message);
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function AddToSelection()
{
	AjaxRequest("AddSel", { "i" : AD_ID });
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function AddSelCallBack(data)
{
	var simpleAlert = new SimpleAlert(
	{
		btnCaption: "OK",
		"onValid": function() { simpleAlert.hide(); }
	});

	var resultText = (data == "ok") ? TXT_ALERT_SELECTION_OK : TXT_ALERT_SELECTION_KO;

	// l'annonce est deja dans la selection, on supprime sur le lien
	if (data == "ok")
	{
		$("mxdAddToSelectionContainer").destroy();
	}

	// affichage de l'alerte d'information
	simpleAlert.show(TTL_ALERT_INFORMATION, resultText);
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function CheckContactForm()
{
	var contactForm = $("mxdContactForm");

	contactForm.setProperty("action", appDirectory + "/ajax/SendContactForm.aspx");
	//contactForm.setProperty("method", "POST");

	var contactName = $("contact_name");
	var contactTelephone = $("contact_telephone");
	var contactEmail = $("contact_email");
	var contactMessage = $("contact_message");

	var emptyField = null;
	var sendForm = true;

	simpleAlert = new SimpleAlert(
	{
		btnCaption: "OK",
		"onValid": function() { simpleAlert.hide(); emptyField.focus(); } 
	});
	
	// le nom du contact a-t-il etait renseigné ?
	if (contactName.value.trim() == "")
	{
		sendForm = false;
		emptyField = contactName;
		simpleAlert.show(TTL_ALERT_CONTACT, TXT_ALERT_CONTACT_NAME);
	}

	// le numero de telephone du contact a-t-il etait renseigné ?
	if (sendForm && contactTelephone.value.trim() == "")
	{
		sendForm = false;
		emptyField = contactTelephone;
		simpleAlert.show(TTL_ALERT_CONTACT, TXT_ALERT_CONTACT_TELEPHONE);
	}
	
	// l'adresse e-mail saisie est-elle correcte ?
	if (sendForm)
	{
		var email = contactEmail.value.trim();
		var goodEmail = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,3}|\d+)$/.test(email);
		if (email == "" || !goodEmail)
		{
			sendForm = false;
			emptyField = contactEmail;
			simpleAlert.show(TTL_ALERT_CONTACT, TXT_ALERT_CONTACT_EMAIL);
		}
	}

	// un message a-t-il ete saisi ?
	if (sendForm && contactMessage.value.trim() == "")
	{
		sendForm = false;
		emptyField = contactMessage;
		simpleAlert.show(TTL_ALERT_CONTACT, TXT_ALERT_CONTACT_MESSAGE);
	}

	// tout est ok on peut poster les informations
	if (sendForm)
	{
		contactForm.setStyle("display", "none");
		$("mxdContactSending").setStyle("display", "block");
		
		new Request(
		{
		    url: contactForm.getProperty("action"),
		    data: contactForm,
		    onComplete: function(r) { ContactSendCallBack(r); }
		}).send();
	}
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function ContactSendCallBack(r)
{
	$("mxdContactSending").removeClass("mxdAjaxSend");
	
	sentMsg = (r == "ok") ? TXT_MESSAGE_SENT : TXT_MESSAGE_NOTSENT;

	$("mxdContactSending").set("html", sentMsg);
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function CheckContactCookieForm()
{
	var ccForm = $("mxdContactCookieForm");

	ccForm.setProperty("action", appDirectory + "/ajax/SendContactCookieForm.aspx");
	ccForm.setProperty("method", "POST");

	var ccCivilite = ccForm.cc_civilite;
	var ccEmail = $("cc_email");
	var ccCp = $("cc_cp");

	var emptyField = null;
	var sendForm = true;

	simpleAlert = new SimpleAlert(
	{
		btnCaption: "OK",
		"onValid": function() { simpleAlert.hide(); emptyField.focus(); } 
	});

	// une civilite a-t-elle etait selectionnee ?
	var civilite = "";
	for (var i = 0; i < ccCivilite.length; i++)
	{
		if (ccCivilite[i].checked)
		{
			civilite = ccCivilite[i].value;
		}
	}
	if (civilite == "")
	{
		sendForm = false;
		emptyField = ccCivilite[0];
		simpleAlert.show(TTL_ALERT_CONTACT, TXT_ALERT_CONTACT_GENDER);
	}

	// l'adresse e-mail saisie est-elle correcte ?
	if (sendForm)
	{
		var email = ccEmail.value.trim();
		var goodEmail = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,3}|\d+)$/.test(email);
		if (email == "" || !goodEmail)
		{
			sendForm = false;
			emptyField = ccEmail;
			simpleAlert.show(TTL_ALERT_CONTACT, TXT_ALERT_CONTACT_EMAIL);
		}
	}

	// un code postal a-t-il été saisi ?
	if (sendForm && ccCp.value.trim() == "")
	{
		sendForm = false;
		emptyField = ccCp;
		simpleAlert.show(TTL_ALERT_CONTACT, TXT_ALERT_CONTACT_ZIPCODE);
	}

    // Vérifie qu'une option optin a été cochée
    var optin1 = $("cc_optin_1");
    var optin0 = $("cc_optin_0");
    if (sendForm && ((optin1 != null) && (optin0 != null)))
    {
        if (!optin1.checked && !optin0.checked)
        {
            sendForm = false;
            emptyField = optin1;
            simpleAlert.show(TTL_ALERT_CONTACT, TXT_ALERT_CONTACT_OPTIN);
        }
    }

	// tout est ok on peut poster les informations
	if (sendForm)
	{
		$("mxdContactCookieSend").setProperty("disabled", true);
		$("mxdContactCookieSending").setStyle("display", "block");

		new Request(
		{
		    url: ccForm.getProperty("action"),
		    data: ccForm,
		    onComplete: function(r) { ContactCookieSendCallBack(r); }
		}).send();
	}
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function ContactCookieSendCallBack(r)
{
	$("mxdContactCookieSending").destroy();
	
	if (r == "ok")
	{
		document.location.reload();
	}
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function ReportIssue()
{
	var loggedName = "";
	var loggedEmail = "";
	if ($defined(LOGGED_DATA) && LOGGED_DATA != "")
	{
		loggedName = LOGGED_DATA.split("|")[0].hexadecode();
		loggedEmail = LOGGED_DATA.split("|")[1].hexadecode();
	}
	loggedName = (lastSenderName == null) ? loggedName : lastSenderName;
	loggedEmail = (lastSenderEmail == null) ? loggedEmail : lastSenderEmail;

	var typeItems = "";
	for (var i = 0; i < ISSUE_TYPES.length; i++)
	{
		var typeName = ISSUE_TYPES[i];
		typeItems += "<option value='" + typeName + "'>" + typeName + "</option>";
	}

	var alertContent = "<form id='mxdReportIssueForm'><p><strong>Type :</strong><br/><select id='issue_type'><option value=''>Choisissez un type</option>" + typeItems + "</select><p>";
	alertContent += "<p><strong>Votre nom :</strong><br/><input type='text' id='sender_name' value=\"" + loggedName + "\"></p>";
	alertContent += "<p><strong>Votre e-mail :</strong><br/><input type='text' id='sender_email' value=\"" + loggedEmail + "\"></p>";
	alertContent += "<p>Commentaire (facultatif) :<br/><textarea id='sender_comment'></textarea><p>";
	alertContent += "</form>";

	simpleAlert = new SimpleAlert(
	{
		btnCaption: "Envoyer",
		"onShow": function ()
		{ 
			if (loggedName == "") $("mxdReportIssueForm").issue_type.focus();
			if (loggedName != "" && loggedEmail == "") $("mxdReportIssueForm").sender_email.focus();
		},
		"onValid": function()
		{
			/*
			lastSenderName = $("sender_name").value;
			lastSenderEmail = $("sender_email").value;
			
			*/
			SendIssue();
		} 
	});
	simpleAlert.show(TTL_ALERT_REPORT_ISSUE, "", alertContent);
	simpleAlert.addButton("Annuler", "before", function() { simpleAlert.hide(); });
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function SendIssue()
{
	var issueType = $("issue_type").value;
	var senderName = $("sender_name").value;
	var senderEmail = $("sender_email").value;
	var senderComment = $("sender_comment").value.replace(/\n/g, " ").hexaencode();
	var detailUrl = document.location.href.hexaencode();

	var sendForm = true;

	if (issueType == "")
	{
		sendForm = false;
		alert("Merci de choisir un type.");
		$("issue_type").focus();
	}

	if (sendForm)
	{
		if (senderName != "")
		{
			var goodEmail = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,3}|\d+)$/.test(senderEmail);
			if (senderEmail == "" || !goodEmail)
			{
				sendForm = false;
				alert("Merci de vérifier votre adresse email.");
				$("sender_email").focus();
			}
		}
		else
		{
			sendForm = false;
			alert("Veuillez renseigner votre nom.");
			$("sender_name").focus();
		}
	}

	if (sendForm)
	{
		simpleAlert.hide();

		issueType = issueType.hexaencode();
		senderName = senderName.hexaencode();
		senderEmail = senderEmail.hexaencode();

		AjaxRequest("SendIssueMessage", { "i": AD_ID, "it": issueType, "sn": senderName, "se": senderEmail, "sc": senderComment, "u": detailUrl });
	}
}
/*******************************************************************************************************************************************************************************
 * 
 *******************************************************************************************************************************************************************************
 *
 *
 *******************************************************************************************************************************************************************************/
function SendIssueMessageCallBack(data)
{
	simpleAlert = new SimpleAlert(
	{
		btnCaption: "OK",
		"onValid": function() {	simpleAlert.hide();} 
	});

	var message = (data == "ok") ? TXT_MESSAGE_SENT : TXT_MESSAGE_NOTSENT;

	simpleAlert.show(TTL_ALERT_REPORT_ISSUE, message);
}