
$(function() {
	$("#register-form").unbind("submit");
	$("#register-form").bind(
		"submit",
		function(e){checkAllModal(e);}
	);
	$("#register-form").ajaxForm({dataType:'json'});
	$("#register-form").after('<div id="modal-insc" style="display: none;"></div>');
	$(window).resize(function(){
		resizeModal();
	});
	
	// reprise de l'inscription
	// récupère juste le formulaire à valider
	if (step < 0) modalInscrLauncher();
});

/**
 * Modal inscription launcher
 */
function modalInscrLauncher() {
	var queryString = $("#register-form").formSerialize() +
		"&step=" + nextstep +
		'&zid=' + d[ct] +
		'&country_id=' + country_id +
		'&geo=' + geo +
		'&ct=' + ct;
	$.ajax({
		async: false,
		type: "POST",
		url: "modal.php",
		data: queryString,
		dataType: "json",
		success: function(data) {
			if (data.errors != false) {
				i = 0;
				while (i < data.errors.length) {
					id  = data.errors[i];
					msg = data.errors[i+1];
					displayError($('#'+id),msg);
					i = i + 2;
				}
			}
			else {
				$("body").css("overflow","hidden");
				$("#modal-insc").css("width", data.width);
				$("#modal-insc").html(data.msg);
				$("#modal-insc").modal({
					//autoResize: true,
					autoPosition: true,
					close: true,
					onOpen: function(dialog) {
						dialog.overlay.fadeIn("fast", function() {
							dialog.container.slideDown("fast", function() {
								dialog.data.fadeIn("fast");
							});
						});
					}
				});
				$(".modal-container").css("height", "auto");
				$("#simplemodal-container").css("height", "auto");
				step = nextstep;
				nextstep = data.nextstep;
				initStep();
			}
		}
	});
}


/**
 * Validations au submit du formulaire d'inscription
 * Lance tous les tests sur tous les champs
 * Remplace la méthode classique bindée sur le submit
 * du form d'incription pour intercepter l'événement 'submit'
 */
function checkAllModal(e) {
	subError = false;
	emptyFieldChecking = true;
	checkGender();
	checkBorn();
	if(correctMail == false) checkMail();
	checkLogin();
	checkPass();
	checkCGU();
	e.preventDefault();
	if(subError == false) modalInscrLauncher();
	emptyFieldChecking = false;
	subError = false;
}

//********************* Fin initialisations *************************//

/**
 * Initialise l'étape en cours
 */
function initStep() {
	$("#step" + nextstep).bind(
		"click",
		function(e) {
			e.preventDefault();
			validModal();
			m_errors = $(".modal-container .err");
			if (m_errors.length === 0) {

				// Données du formulaire en cours
				$("#xform").ajaxForm({dataType:'json'});
				serializedform = $('#xform').formSerialize();
				queryString = (serializedform != "")? serializedform + '&step=' + nextstep:'step=' + nextstep;

				// Demande du step suivant
				$.ajax({
					async: false,
					type: "POST",
					url: "modal.php",
					data: queryString,
					dataType: "json",
					success: function(data) {

						// Traitement des erreurs du form s'il y en a
						if (data.errors != false) {
							if (data.errors == 'nosession') window.location = "http://" + d[ct];
							i = 0;
							while (i < data.errors.length) {
								err = new Array;
								err.push(data.errors[i]);
								err.push(data.errors[i+1]);
								showError(err);
								i = i + 2;
							}
							resizeModal();
						}
						else {
							$("#simplemodal-container").css("width", data.width);
							$('#modal-insc').html(data.msg);
							$("#modal-insc").css("width", "auto");
							$("#modal-insc").css("height", "auto");
							resizeModal();
							step = nextstep;
							nextstep = data.nextstep;
							// Cas où on est sur la dernière étape, on post sur la page de login
							if (nextstep === false) {
								$("#step" + step).unbind("click");
								$("#xform").attr("action", "http://" + d[ct] + "/login.php");
							}
							else initStep();
						}
					}
				});
			}
			else resizeModal();
		}
	);
}

/**
 * Gestion des erreurs formulaire du profil en javascript
 */
function checkSrchgender() {
	test = 0;
    $("#srchgender input:checkbox").each(
		function(){
			if ($(this).attr('checked')) test = test + 1;
		}
	);
	res = new Array("srchgender");
	if (test > 0) res.push(false);
	else res.push(u_srchgender);
	showError(res);
}
function checkMeetlenght() {
	test = 0;
    $("#meetlenght input:checkbox").each(
		function(){
			if ($(this).attr('checked')) test = test + 1;
		}
	);
	res = new Array("meetlenght");
	if (test > 0) res.push(false);
	else res.push(u_meetlenght);
	showError(res);
}
function checkLocation() {
	res = new Array("location");
	if ($("#location #location_id").val() != "" && $("#location #city").val() != "") res.push(false);
	else res.push(u_location);
	showError(res);
}
function checkJob() {
	res = new Array("job");
	if ($("#job select")[0].selectedIndex > 0) res.push(false);
	else res.push(u_job);
	showError(res);
}
function checkEyes() {
	res = new Array("eyes");
	if ($("#eyes select")[0].selectedIndex > 0) res.push(false);
	else res.push(u_eyes);
	showError(res);
}
function checkHairs() {
	res = new Array("hairs");
	if ($("#hairs select")[0].selectedIndex > 0) res.push(false);
	else res.push(u_hairs);
	showError(res);
}
function checkWebcam() {
	test = 0;
	$("#webcam input:radio").each(
		function(){
			if ($(this).attr('checked')) test = test + 1;
		}
	);
	res = new Array("webcam");
	if (test > 0) res.push(false);
	else res.push(u_webcam);
	showError(res);
}
function checkGsm() {
	var gsm = $("#gsm input").val();
	res = new Array("gsm");
	if (gsm != '') {
		var regexp = new RegExp("^(0|(\\+|00)33)(6|7)[0-9]{8}$","g");
		if (regexp.test(gsm) == false){
			res.push(u_gsm);
		}
		else res.push(false);
	}
	else res.push(false);
	showError(res);
}
function check15Chars() {
	var strlen = parseInt($("#msgPres").val().length);
	res = new Array("welcome");
	if (strlen < 15)
		res.push(u_welcome_l);
	else
		res.push(false);
	showError(res);
}
function check1Char() {
	var strlen = parseInt($("#msgPres").val().length);
	res = new Array("welcome");
	if (strlen < 1)
		res.push(u_welcome_n);
	else
		res.push(false);
	showError(res);
}

function showError(row) {
	if (row[1] !== false) {
		if ($("#err" + row[0]).length == 0) {
			$("#" + row[0]).addClass('bgalert');
			$("#" + row[0]).after('<tr id="err'+row[0]+'" class="bgalert err"><td colspan="2" height="22">'+row[1]+'</td></tr>');
		}
	}
	else {
		if ($("#err" + row[0]).length == 1) {
			$("#" + row[0]).removeClass('bgalert');
			$("#err" + row[0]).remove();
		}
	}
}

/**
 * Pratique
 */
function resizeModal() {
	if ( $('#modal-insc').css('display') != 'none' ) {
		$.modal.setPosition();
		$(".modal-container").css("height","auto");
		var wh = $(window).height();
		var ww = $(window).width();
		var mh = $("#simplemodal-container").height();
		var mw = $("#simplemodal-container").width();
		var mch= $(".modal-container").height();
		var mcw= $(".modal-container").width();
		var top = parseInt($("#simplemodal-container").css("top").replace("px", ""));
		var left = parseInt($("#simplemodal-container").css("left").replace("px", ""));
		var diff_h = wh - (mh + 10);
		if ((mh + 2*top + 10) < wh) {
			new_top = (wh - mch - 116) / 2;
			$("#simplemodal-container").css('top',new_top);
		}
		if (diff_h < 0 || (top + mh) > wh) {
			new_mch = mch - 20 + diff_h;
			new_top = (wh - ((new_mch <= mch)? new_mch:mch) - 116) / 2;
			$("#simplemodal-container").css('top',new_top);
			$(".modal-container").css("height",((new_mch <= mch)? new_mch:mch));
			$(".modal-container").css("overflow-y","auto");
			$(".modal-container").css("overflow-x","hidden");
		}
		if ((2*left + mw) > ww) {
			new_left = (ww - mcw - 10) / 2;
			$("#simplemodal-container").css('left',new_left);
		}
	}
}
