/* ------------------------ VARIABLES GLOBALES ------------------------ */
var bImgAvatarSaved=true;
var bDataStep2Saved=false;

var ajaxAvatarUploader;

var speedChangeStep = 500;

var timeToRedirectToReferer = 3000;

/* ------------------------ INIT ------------------------ */
$(document).ready(function(){
	// Initialisation du hack IE6 pour le masquage de la ligne instrument du formulaire d'inscription
	if ($.browser.msie && $.browser.version < 7) {
		initHackIE6LineInstrumentInscription();
	}
	
	// on lance la step 1
	setThisStep(1);
	
	// On init les evenements
	initEvents();
	
	// On cache l'info bulle
	$(".infoBulle").hide();
	// On cache les step 2 et 3
	//$("#step02").hide();
	//$("#step03").hide();
	
	// On init les elements particulier de formulaire
	initCheckBoxes();
});

/* ------------------------ EVENEMENTS ------------------------ */
function initEvents(){
	// On init les evenements d'envoi de formulaire
	initFormEvents();
	
	// On init les evenements de verification de formulaire
	initPseudoDispoEvents();
	
	// On check les champs à afficher
	checkTypeInscription();
}

function initFormEvents(){
	// Au submit, on annule et on envoit
	$("[name=form_inscription]").submit(function(){
		return false;
	});
	$("[name=form_inscription]").submit(saveFormInscription);
	
	// Passer l'etape 2
	$(".btnNextStep IMG").click(goToStep3);
	
	// Submit de l'etape2
	$("[name=form_inscription_2]").submit(function(){
		return false;
	});
	$("[name=form_inscription_2]").submit(saveFormInscription2);
	
	// On init l'envoi de l'avatar en ajax
	initAvatarSending();
	$("[name=form_inscription_2]").submit(sendAvatar);
	
	// Click sur le "?" de l'embed
	$(".aideEmbed").click(handleClickOnAideEmbed);
	
	// Quand on click sur un choix de fausse combo, on check si on a pas changé de type d'inscription
	$('[name=form_inscription] [name=type]').change(checkTypeInscription);
}

function initPseudoDispoEvents(){
	// Au blur sur le champ du pseudo, on verifie la dispo
	$("[name=form_inscription] [name=pseudo]").blur(checkPseudoDispo);
	$("[name=form_inscription] [name=pseudo]").attr('class','inputTextPseudo');
}

function initAvatarSending(){
	ajaxAvatarUploader = new AjaxUpload("btnChooseAvatar", {
									  // Location of the server-side upload script
									  // NOTE: You are not allowed to upload files to another domain
									  action: 'ws/inscription/save_image_for_avatar.php',
									  // File upload name
									  name: "uploadedImg",
									  // Additional data to send
									  data: "",
									  // Submit file after selection
									  autoSubmit: false,
									  // The type of data that you're expecting back from the server.
									  // HTML (text) and XML are detected automatically.
									  // Useful when you are using JSON data as a response, set to "json" in that case.
									  // Also set server response type to text/html, otherwise it will not work in IE6
									  responseType: "json",
									  // Fired after the file is selected
									  // Useful when autoSubmit is disabled
									  // You can return false to cancel upload
									  // @param file basename of uploaded file
									  // @param extension of that file
									  onChange: function(file, extension){
										bImgAvatarSaved = false;
										setInfoBulleAtElement('Votre image a bien été sélectionnée.<br />Elle sera envoyée à la soumission du formulaire.', $('#btnChooseAvatar img'), 0, 21, true);
									  },
									  // Fired before the file is uploaded
									  // You can return false to cancel upload
									  // @param file basename of uploaded file
									  // @param extension of that file
									  onSubmit: function(file, extension){},
									  // Fired when file upload is completed
									  // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
									  // @param file basename of uploaded file
									  // @param response server response
									  onComplete: imgUploaded
									});
}

/* ------------------------ FONCTIONS ------------------------ */
function checkTypeInscription(){
	var currentTypeSelected = $('[name=form_inscription] [name=type]').val();
	currentTypeSelected = currentTypeSelected.toLowerCase();
	
	// On modifie le src de l'image de header en fonction du type sélectionné
	$('.visuelFullWidth img').attr('src','images/photo_inscription_'+currentTypeSelected+'.jpg');
	
	switch (currentTypeSelected) {
		case ucfirst(TYPE_INSCRIPTION_1):
		case TYPE_INSCRIPTION_1:
			setPseudoFieldLib("Ton pseudo :");
			// Hack IE6
			if ($.browser.msie && $.browser.version < 7) {
				$(".lineInstrument").css({
					"top": "-800px"
				});
				$('.contentFormWithoutInstrument').animate({
					"marginTop": "-28px"
				}, 1, initListesDeroulantes);

			}
			// Autre navigateurs
			else{
				$(".lineInstrument").hide(function(){initListesDeroulantes();});
			}
			break;
			
		case ucfirst(TYPE_INSCRIPTION_2):
		case TYPE_INSCRIPTION_2:
			setPseudoFieldLib("Nom du musicien :");
			// Hack IE6
			if ($.browser.msie && $.browser.version < 7) {
				$(".lineInstrument").css({
					"top": "0px"
				});
				$('.contentFormWithoutInstrument').animate({
					"marginTop": "0"
				}, 1, initListesDeroulantes);
			}
			// Autre navigateurs
			else{
				$(".lineInstrument").show(function(){initListesDeroulantes();});
			}
			break;
			
		case ucfirst(TYPE_INSCRIPTION_3):
		case TYPE_INSCRIPTION_3:
			setPseudoFieldLib("Nom du groupe / artiste :");
			// Hack IE6
			if ($.browser.msie && $.browser.version < 7) {
				$(".lineInstrument").css({
					"top": "-800px"
				});
				$('.contentFormWithoutInstrument').animate({
					"marginTop": "-28px"
				}, 1, initListesDeroulantes);
			}
			// Autre navigateurs
			else{
				$(".lineInstrument").hide(function(){initListesDeroulantes();});
			}
			break;
	}
}

function setPseudoFieldLib(newLib){
	$('[name=form_inscription] [name=pseudo]').siblings(".labelLineFormInscription").html(newLib);
}

function saveFormInscription(){	
	// On recupere les infos du formulaire
	aPost = {
		save_inscription: $('[name=form_inscription] [name=save_inscription]').val(),
		id_instrument: $('[name=form_inscription] [name=id_instrument]').val(),
		prenom: $('[name=form_inscription] [name=prenom]').val(),
		nom: $('[name=form_inscription] [name=nom]').val(),
		pseudo: $('[name=form_inscription] [name=pseudo]').val(),
		mdp: $('[name=form_inscription] [name=mdp]').val(),
		ville: $('[name=form_inscription] [name=ville]').val(),
		cp: $('[name=form_inscription] [name=cp]').val(),
		email: $('[name=form_inscription] [name=email]').val(),
		dt_naissance_jour: $('[name=form_inscription] [name=dt_naissance_jour]').val(),
		dt_naissance_mois: $('[name=form_inscription] [name=dt_naissance_mois]').attr("value"),
		dt_naissance_annee: $('[name=form_inscription] [name=dt_naissance_annee]').val(),
		captcha: $('[name=form_inscription] [name=captcha]').val(),
		b_newsletter: $('[name=form_inscription] [name=b_newsletter]').val(),
		b_cgu: $('[name=form_inscription] [name=b_cgu]').val(),
		type: $('[name=form_inscription] [name=type]').val()
	};

	// Action du formulaire
	curAction = $('[name=form_inscription]').attr("action");

	// On sauvegarde
	$.ajax({
		type: "POST",
		url: curAction,
		data: aPost,
		dataType:"json",
		success:function(returnedJson){			
			if (!returnedJson["b_error"]) {
				setFormInscription2IdUser(returnedJson["id_user"]);
				setThisStep(2);
			}
			else{
				setInfoBulleAtElement(returnedJson["html_err"], $('[name=form_inscription] [name=save_inscription]'), 0, 21, true);
			}
		}
	});
}

function saveFormInscription2(){	
	// On recupere les infos du deuxième formulaire
	aPost = {id_user: $('[name=form_inscription_2] [name=id_user]').val(),
		save_inscription_2: $('[name=form_inscription_2] [name=save_inscription_2]').val(),
		style_musique: $('[name=form_inscription_2] [name=style_musique]').val(),
		url_facebook: $('[name=form_inscription_2] [name=url_facebook]').val(),
		url1: $('[name=form_inscription_2] [name=url1]').val(),
		url2: $('[name=form_inscription_2] [name=url2]').val(),
		url3: $('[name=form_inscription_2] [name=url3]').val(),
		url4: $('[name=form_inscription_2] [name=url4]').val(),
		groupes_preferes: $('[name=form_inscription_2] [name=groupes_preferes]').val(),
		presentation: $('[name=form_inscription_2] [name=presentation]').val(),
		titre_video: $('[name=form_inscription_2] [name=titre_video]').val(),
		embed_video: $('[name=form_inscription_2] [name=embed_video]').val(),
		b_ltl: $('[name=form_inscription_2] [name=b_ltl]').val(),
		b_gtl: $('[name=form_inscription_2] [name=b_gtl]').val()
	};

	// Action du formulaire
	curAction = $('[name=form_inscription_2]').attr("action");

	// On sauvegarde
	bDataStep2Saved = false;
	$.ajax({
		type: "POST",
		url: curAction,
		data: aPost,
		dataType:"json",
		success:function(returnedJson){			
			if (!returnedJson["b_error"]) {
				bDataStep2Saved = true;
				if(bImgAvatarSaved)
					setThisStep(3);
			}
			else{
				setInfoBulleAtElement(returnedJson["html_err"], $('[name=form_inscription_2] [name=save_inscription_2]'), 0, 27, true);
			}
		}
	});
}

function sendAvatar(){
	ajaxAvatarUploader.setData({'id_user': $('[name=form_inscription_2] [name=id_user]').val()});
	ajaxAvatarUploader.submit();
}

function imgUploaded(filename, responseServer){
	if (!responseServer["b_error"]) {
		bImgAvatarSaved = true;
		if (bDataStep2Saved) 
			setThisStep(3);
	}
	else{
		setInfoBulleAtElement(responseServer["s_error"], $('[name=form_inscription_2] [name=save_inscription_2]'), 0, 27, true);
	}
}

function checkPseudoDispo(){
	// On recupere le pseudo
	curPseudo = $('[name=form_inscription] [name=pseudo]').val();
	
	// On check la dispo du pseudo s'il est assez long
	if (curPseudo.length >= minPseudoLength) {
		$.ajax({
			type: "POST",
			url: "ws/inscription/check_dispo_pseudo.php",
			data: "pseudo=" + curPseudo,
			dataType: "json",
			success: function(returnedJson){
				if (!returnedJson["b_error"]) {
					setDispoPseudo(returnedJson["b_dispo"]);
				}
			}
		});
	}
}

function setDispoPseudo(bDispo){
	if(bDispo){
		// On met la tick verte
		$('[name=form_inscription] [name=pseudo]').addClass("dispo");
		$('[name=form_inscription] [name=pseudo]').removeClass("noDispo");
	}
	else{
		// On met la croix rouge
		$('[name=form_inscription] [name=pseudo]').removeClass("dispo");
		$('[name=form_inscription] [name=pseudo]').addClass("noDispo");
		
		// On affiche un message d'erreur
		// libellé du pseudo en fonction du type sélectionné
		var labelPseudo = '';
		switch($('[name=form_inscription] [name=type]').val())
		{
			case ucfirst(TYPE_INSCRIPTION_1):
			case TYPE_INSCRIPTION_1:
				labelPseudo = 'pseudo';
				break;
			case ucfirst(TYPE_INSCRIPTION_2):
			case TYPE_INSCRIPTION_2:
				labelPseudo = 'nom du musicien';
				break;
			case ucfirst(TYPE_INSCRIPTION_3):
			case TYPE_INSCRIPTION_3:
				labelPseudo = 'nom du groupe / artiste';
				break;
		}
		setInfoBulleAtElement("Ce "+labelPseudo+" n'est pas<br/>disponible.", $('[name=form_inscription] [name=pseudo]'), 0, 26);
	}
}

function goToStep3(){
	setThisStep(3);
}

function setThisStep(noStep){
	switch(noStep){
		case 1:
			$("#step01").slideDown(speedChangeStep, "easeInOutExpo");
			$("#step02:visible").slideUp(speedChangeStep, "easeInOutExpo");
			$("#step03:visible").slideUp(speedChangeStep, "easeInOutExpo");
			break;
			
		case 2:
			// Selon le type en cours, on affiche pas les même formulaires
			switch($('[name=form_inscription] [name=type]').val()){
				case ucfirst(TYPE_INSCRIPTION_1):
				case TYPE_INSCRIPTION_1:
					$(".lineStyleDeMusic").hide();
					$('.lineUrlFacebook').hide();
					$('.lineGroupesPreferes').show();
					break;
					
				case ucfirst(TYPE_INSCRIPTION_2):
				case TYPE_INSCRIPTION_2:
					$(".lineStyleDeMusic").show();
					$('.lineUrlFacebook').show();
					$('.lineGroupesPreferes').hide();
					break;
					
				case ucfirst(TYPE_INSCRIPTION_3):
				case TYPE_INSCRIPTION_3:
					$(".lineStyleDeMusic").show();
					$('.lineUrlFacebook').show();
					$('.lineGroupesPreferes').hide();
					
					$('#contentFormVideo').show();
					
					if(isLTLCurrent && isGTLCurrent)
					{
						$('.lineFormSaveVideoInLtl,.lineFormSaveVideoInGTL').show();
						$('#infosLegendLTL,#infosLegendGTL').show();
						// Hack IE6
						if ($.browser.msie && $.browser.version < 7) {
							$(".lineFormInscriptionLegend").next().css({
								"marginTop": "-42px"
							});
						}
					}
					else if(isLTLCurrent)
					{
						$('.lineFormSaveVideoInLtl').show();
						$('#infosLegendLTL').show();
						// Hack IE6
						if ($.browser.msie && $.browser.version < 7) {
							$(".lineFormInscriptionLegend").next().css({
								"marginTop": "-35px"
							});
						}
					}
					else if(isGTLCurrent)
					{
						$('.lineFormSaveVideoInGTL').show();
						$('#infosLegendGTL').show().css();
						// Hack IE6
						if ($.browser.msie && $.browser.version < 7) {
							$('#infosLegendGTL').css({
								"marginTop": "-7px"
							});
							$(".lineFormInscriptionLegend").next().css({
								"marginTop": "-22px"
							});
						}
						
					}
					else
					{
						if ($.browser.msie && $.browser.version < 7) {
							$(".lineFormInscriptionLegend").next().css({
								"marginTop": "-35px"
							});
						}
					}
					break;
			}
		
			$("#step01:visible").slideUp(speedChangeStep, "easeInOutExpo");
			$("#step02").slideDown({
							duration:speedChangeStep,
							easing:"easeInOutExpo",
							complete:function(){
								initListesDeroulantes();
								}
							});
			break;
			
		case 3:
			$("#step02:visible").slideUp(speedChangeStep, "easeInOutExpo");
			$("#step03").slideDown(speedChangeStep, "easeInOutExpo");
			
			// On sauvegarde
			$.ajax({
				type: "POST",
				url: "ws/inscription/send_mail_confirmations.php",
				data: "id_user="+$('[name=form_inscription_2] [name=id_user]').val(),
				dataType:"json",
				success:function(returnedJson){			
					if (!returnedJson["b_error"]) {
						$("#info_mail_ok").slideDown("250", "easeOutExpo");
					}
					else{
						$("#info_mail_err").slideDown("250", "easeOutExpo");
					}					
				}
			});
			
			// si un referer est présent dans le formulaire (et non vide),
			// on affiche un message de redirection et lance une redirection
				// on récupère le referer
				curReferer = $('[name=form_inscription_2] [name=referer]').val();
				var reg = new RegExp("([^\?]*)?");
				aMatches = reg.exec(curReferer);

				curRefererToTest = (aMatches[1] != '') ? aMatches[1] : curReferer;
				if(curReferer != '')
				{
					// selon le referer, le nom de la page affichée sera différent
					switch(curRefererToTest){
						case "lance_toi_en_live_inscription.php":
						case "lancetoienlive/inscription":
							curNamePage = "Inscription au concours Lance Toi en Live";
							break;
						case "qcm.php":
						case "jeux_concours":
							curNamePage = "Jeu Concours";
							break;
						default:
							break;
					}
					// on met la bonne phrase dans le bloc de redirection
					$("#redirect_to_referer").html('Vous allez être redirigé vers la page '+curNamePage+' dans quelques secondes...<br />Si rien ne se passe, cliquez <a href="'+curReferer+'">ici</a>.');
					// on affiche le bloc de redirection
					$("#redirect_to_referer").slideDown("250", "easeOutExpo");
					// On programme la redirection dans X secondes
					commande = "redirectToReferer('"+curReferer+"');";
					setTimeout(commande, timeToRedirectToReferer);
				}
			
			break;
	}
}

function setFormInscription2IdUser(idUserToSet){
	$('[name=form_inscription_2] [name=id_user]').val(idUserToSet);
}

function handleClickOnAideEmbed(e){
	// Message
	sHtmlMsg = "Le code de votre vidéo se situe dans le descriptif de votre vidéo.<br/>Ce code commence généralement par <br/>«&lt;object width='560' ».<br/>Copiez tout le code et collez-le dans le champs.";

	setInfoBulleAtElement(sHtmlMsg, e.target, -27, 14, false);
}

function redirectToReferer(link){
	document.location.href=link;
}