//constant
verifMailREGEX = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;

//params
configIsOk = false;
createdBase = false;
mailIsOk = false;
smtpChecked = false;
validAdminInfos = false;
application="install";

function nextTab()
{
	if(verifyThisStep())
	{
		showStep(step+1);
	}
}
function backTab()
{
	if (step != 6) {
		showStep(step - 1);
	}
	else {
		constructInstallerTabs();
		showStep(1);
	} 
}

function showStep(aStep)
{
	step = aStep;
	
	//show the sheet
	$('div.sheet.shown').fadeOut('fast',
		function()
		{
			$($('div.sheet')[(step-1)]).fadeIn('slow').addClass('shown');
		}
	).removeClass('shown');
	
	
	
	//upgrade the tab
	$('#tabs li')
		.removeClass("selected")
		.removeClass("finished");
		if (step < 6) {
			$('#tabs li:nth-child(' + step + ')').addClass("selected");
			$('#tabs li:lt(' + (step - 1) + ')').addClass("finished");
		}
	
	//title of the window and buttons
	switch(step)
	{
		case 1 :
		document.title = Step1Title;
		$("#btBack")
			.attr("disabled", "disabled")
			.addClass("disabled")
			.show('slow');
		$("#btNext")
			.removeAttr("disabled")
			.removeClass("disabled")
			.show('slow');
		break;
		
		case 2:
		document.title = step2title;
		application = "install";
		
		verifyAndSetRequire();
		
		$("#btBack")
			.removeAttr("disabled")
			.removeClass("disabled")
			.show('slow');
		break;
		
		case 3:
		document.title = step3title;
		$("#btBack")
			.removeAttr("disabled")
			.removeClass("disabled")
			.show('slow');
		break;
		
		case 4:
		document.title = step4title;
		$("#btBack")
			.removeAttr("disabled")
			.removeClass("disabled")
			.show('slow');
		break;
		
		case 5 :
		document.title = step5title;
		$("#btBack")
			.attr("disabled", "disabled")
			.addClass("disabled")
			.hide('slow');
		$("#btNext").hide('slow');
		break;
		
	}
}

function verifyThisStep()
{
	switch (step)
	{
		case 1 :
			showStep(2);
		return false;
		break;
		
		case 2 :
		return configIsOk;
		break;
		
		case 3 :
			createDB();
			return false;
		break;
		
		case 4 :
			verifyAdminInfos();
			return validAdminInfos;
		break;
		
		case 6 :
			return true;
		break;
		
	}
	
}


function verifyAndSetRequire()
{
	$("div#"+(application == "sheet_require")+" > ul").slideUp("1500");
	
	$('#btNext').attr('disabled', 'disabled');
	$('#btNext').addClass('disabled');
			
	$.ajax(
	{
		cache: false,
		url: "model.php",
		data: "method=checkConfig",
		success: function(ret)
		{
			testLists = ret.getElementsByTagName('testList');
			
			configIsOk = true;
		
			testListRequired = testLists[0].getElementsByTagName('test');
			for (i = 0; i < testListRequired.length; i++){
				result = testListRequired[i].getAttribute("result");
				$($("div#sheet_require > ul#required .required")[i])
				.removeClass( (result == "fail") ? "ok" : "fail" )
				.addClass(result);
				if (result == "fail") configIsOk = false;
			}
			
			
			
			$("div#sheet_require > ul").slideDown("1500");
			
			if (configIsOk){
				$("#btNext").removeAttr('disabled');
				$('#btNext').removeClass('disabled');
				$("input#btNext").focus();
			}
		}
	}
	);
}

function verifyDbAccess ()
{
	$("#dbCreateResultCheck").hide('slow');
	$("#mailResultCheck").hide('slow');

	//local verifications
	if($("#dbServer[value=]").length > 0)
	{
		$("#dbResultCheck").addClass("fail").removeClass("ok").removeClass('userInfos').html(txtDbServerEmpty).show('slow');
		$("#dbServer").focus();
		return false;

	}
	else if($("#dbName[value=]").length > 0)
	{
		$("#dbResultCheck").addClass("fail").removeClass("ok").removeClass('userInfos').html(txtDbNameEmpty).show('slow');
		$("#dbName").focus();
		return false;
	}
	else if($("#dbLogin[value=]").length > 0)
	{
		$("#dbResultCheck").addClass("fail").removeClass("ok").removeClass('userInfos').html(txtDbLoginEmpty).show('slow');
		$("#dbLogin").focus();
		return false;
	}
	else if($("#dbPassword[value=]").length > 0)
	{
		$("#dbResultCheck").addClass("fail").removeClass("ok").removeClass('userInfos').html(txtDbPasswordEmpty).show('slow');
		$("#dbPassword").focus();
		return false;
	}
	else
	{
		$("#dbResultCheck").removeClass("fail").removeClass("ok").removeClass('userInfos').html('');
	}
	
	//external verifications and sets
	$.ajax(
	{
		cache: false,
		url: "model.php",
		data: 
			"method=checkDB"
			+"&type=MySQL"
			+"&server="+ $("#dbServer").val()
			+"&login="+ $("#dbLogin").val()
			+"&password="+ $("#dbPassword").val()
			+"&name="+ $("#dbName").val()
		,
		success: function(ret)
		{
			ret = ret.getElementsByTagName('action')[0];
			if (ret.getAttribute("result") == "ok")
			{
				$("#dbResultCheck")
					.addClass("ok")
					.removeClass("fail")
					.html(txtError[23])
					.show('slow');
				 $("#dbCreateResultCheck")
					.hide('slow');
			} else
			{
				$("#dbResultCheck")
					.addClass("fail")
					.removeClass("ok")
					.html(txtError[parseInt(ret.getAttribute("error"))])
					.show('slow');
				$("#dbCreateResultCheck")
					.hide('slow');
			}
		}
	 }
	 );	 
	 
}

function createDB()
{
	$("#dbResultCheck").hide('slow');
	$("#mailResultCheck").hide('slow');

	$.ajax(
	{
	   cache: false,
	   url: "model.php",
	   data:
	   	"method=createDB"
		+"&tablePrefix="+ $("#db_prefix").val()+ 
		"&server="+ $("#dbServer").val()+
		"&login="+ $("#dbLogin").val()+
		"&password="+ $("#dbPassword").val()+
		"&name="+ $("#dbName").val(),
		
	   success: function(ret)
	   {
			ret = ret.getElementsByTagName('action')[0];
			if (ret.getAttribute("result") == "ok")
			{
				showStep(step+1);
			}
			else
			{
				if(ret.getAttribute("error") == "11")
				{
					$("#dbCreateResultCheck")
						.addClass("fail")
						.removeClass("ok")
						.removeClass('userInfos')
						.html(
							txtError[11]+ "<br />\'"+
							ret.getAttribute("sqlQuery") + "\'<br/>"+
							ret.getAttribute("sqlMsgError") + "(" + txtError[18] + " : " + ret.getAttribute("sqlNumberError") +")"
						)
						.show('slow');
				}
				else
				{
					$("#dbCreateResultCheck")
						.addClass("fail")
						.removeClass("ok")
						.removeClass('userInfos')
						.html(txtError[parseInt(ret.getAttribute("error"))])
						.show('slow');
				
				}
			}
	   }
	}
	);
}


function verifyMail()
{
	$("#dbCreateResultCheck").hide('slow');
	$("#dbResultCheck").hide('slow');

	//local verifications
	if ($("#testEmail[value=]").length > 0)
	{
		$("#mailResultCheck").addClass("fail").removeClass("ok").removeClass('userInfos').html(txtError[0]).show('slow');
		return false;
	}
	else if (!verifMailREGEX.test( $("#testEmail").val() ))
	{ 
		$("#mailResultCheck").addClass("fail").removeClass("ok").removeClass('userInfos').html(txtError[3]).show('slow');
		return false;
	}
	else
	{
		
		if (smtpChecked)
		{
			//local verifications
			if($("#smtpSrv[value=]").length > 0)
			{
				$("#mailResultCheck").addClass("fail").removeClass("ok").removeClass('userInfos').html(txtSmtpSrvEmpty).show('slow');
				smtpIsOk = false;
				return false;
			}
			
			if($("#smtpLogin[value=]").length > 0)
			{
				$("#mailResultCheck").addClass("fail").removeClass("ok").removeClass('userInfos').html(txtSmtpLoginEmpty).show('slow');
				smtpIsOk = false;
				return false;
			}
			
			if($("#smtpPassword[value=]").length > 0)
			{
				$("#mailResultCheck").addClass("fail").removeClass("ok").removeClass('userInfos').html(txtSmtpPasswordEmpty).show('slow');
				smtpIsOk = false;
				return false;
			}

			if($("#smtpFrom[value=]").length > 0)
			{
				$("#mailResultCheck").addClass("fail").removeClass("ok").removeClass('userInfos').html(txtSmtpFromEmpty).show('slow');
				smtpIsOk = false;
				return false;
			}
		}
		
		
		//external verifications and sets
		$.ajax(
		{
		   url: "model.php",
		   cache: false,
		   data:
				"method=checkMail"+
		   		"&mailMethod= "+(smtpChecked ? "smtp" : "native")+
				"&smtpSrv="+ $("input#smtpSrv").val()+
				"&testEmail="+ $("#testEmail").val()+
		   		"&smtpLogin="+ $("input#smtpLogin").val()+
		   		"&smtpPassword="+ $("input#smtpPassword").val()+
				"&smtpPort="+ $("input#smtpPort").val()+
				"&smtpFrom="+ $("input#smtpFrom").val()+
				"&testMsg="+testMsg+
				"&testSubject="+testSubject
			,
		   success: function(ret)
		   {
				ret = ret.getElementsByTagName('action')[0];
				
				if (ret.getAttribute("result") == "ok")
				{
					$("#mailResultCheck").addClass("ok").removeClass("fail").removeClass('userInfos').html(mailSended).show('slow');
					mailIsOk = true;
				}
				else
				{
					mailIsOk = false;
					$("#mailResultCheck").addClass("fail").removeClass("ok").removeClass('userInfos').html(txtError[26]).show('slow');
				}
		   }
		 }
		 );
	}
}



function ajaxRefreshField(nthField, idResultField, fieldsList, inputId)
{
	var result = fieldsList[nthField].getAttribute("result");
	if (result != "ok")
	{
		$("#"+idResultField)
			.html( txtError[parseInt(fieldsList[nthField].getAttribute("error"))] )
			.addClass("fail")
			.show("slow");
		if (validAdminInfos)
			$("#"+inputId).focus();
		return false;
	}
	else
	{
		$("#"+idResultField)
			.html("")
			.removeClass("fail")
			.hide("slow");
		return true;
	}
}

function verifyAdminInfos()
{
	$.ajax(
	{
	   url: "model.php",
	   async: false,
	   cache: false,
	   data:
		"method=checkAdminInfos"+
		"&tablePrefix="+ $("#db_prefix").val()+ 
		"&infosName="+ encodeURIComponent($("input#infosName").val())+
		"&infosEmail="+ $("input#infosEmail").val()+
		"&infosPassword="+ $("input#infosPassword").val()+
		"&infosPasswordRepeat="+ $("input#infosPasswordRepeat").val()+
		"&smtpSrv="+ $("input#smtpSrv").val()+
		"&smtpLogin="+ $("input#smtpLogin").val()+
		"&smtpPassword="+ $("input#smtpPassword").val()+
		"&smtpFrom="+ $("input#smtpFrom").val()+
		"&smtpPort="+ $("input#smtpPort").val()+
		"&server="+ $("#dbServer").val()+
		"&login="+ $("#dbLogin").val()+
		"&password="+ $("#dbPassword").val()+
		"&name="+ $("#dbName").val()
	   ,
	   
	   success: function(ret)
	   {
			fieldsList = ret.getElementsByTagName('weencompanyConfig')[0].getElementsByTagName('field');
			validAdminInfos = true;
			if (!ajaxRefreshField(0, "resultInfosName", fieldsList, "infosName")) validAdminInfos = false;
			else if (!ajaxRefreshField(1, "resultInfosPassword", fieldsList, "infosPassword")) validAdminInfos = false;
			else if (!ajaxRefreshField(2, "resultInfosPasswordRepeat", fieldsList, "infosPasswordRepeat")) validAdminInfos = false;
			else if (!ajaxRefreshField(3, "resultInfosEmail", fieldsList, "infosEmail")) validAdminInfos = false;
			else
			{
				$('#endName').html($('input#infosName').val());
				$('#endEmail').html($('input#infosEmail').val());
				$('#adminPassword').html($('input#infosPassword').val());
			}
	   }
	 }
	 );
}

function autoCheckField(idField, idResultSpan, typeVerif)
{
	switch (typeVerif)
	{
		case "required" :
			$(idField).blur(function()
			{
				if($(this).val() == "")
				{
					$(idResultSpan)
						.html(txtError[38])
						.addClass("fail")
						.show("slow");
				}
				else
				{
					$(idResultSpan)
						.removeClass("fail")
						.hide("slow");
				}
			}
			);
		break;
		
		case "mailFormat" :
			$(idField).blur(
			function()
				{
					if (!verifMailREGEX.test( $(this).val() ))
					{
						$(idResultSpan)
							.html(txtError[3])
							.addClass("fail")
							.show("slow");
					}
					else
					{
						$(idResultSpan)
							.removeClass("fail")
							.hide("slow");
					}
				}
			);
		break;
		
		default : return false;
	}
}


function constructInstallerTabs()
{
	$("#tabs")
		.empty()
		.append("<li id='tab_lang' class='selected'><span class='number1' >"+txtTabInstaller1+"</span></li>")
		.append("<li id='tab_require'><span class='number2' >"+txtTabInstaller2+"</span></li>")
		.append("<li id='tab_db'><span class='number3' >"+txtTabInstaller3+"</span></li>")
		.append("<li id='tab_infos'><span class='number4' >"+txtTabInstaller4+"</span></li>")
		.append("<li id='tab_end'><span class='number5' >"+txtTabInstaller5+"</span></li>")
	;
	$(".installerVersion").show();
	$(".updaterVersion").hide();
}



//when ready....
$(document).ready(
	function()
	{
		//show container only if JS is available
		$("#noJavaScript").hide();
		$("#container").show();
		
		//ajax animation
		$("#loader").ajaxStart(
			function()
			{
				$(this).fadeIn();
				$("#btNext[disabled!=1], #btBack[disabled!=1]").attr("disabled", "disabled").addClass("disabled").addClass("lockedForAjax");
			}
		);
		$("#loader").ajaxComplete(
			function()
			{
				$(this).fadeOut();
				$(".lockedForAjax").removeAttr("disabled").removeClass("disabled").removeClass("lockedForAjax");
			}
		);
		//set actions on clicks
		$('#btNext').bind("click",nextTab);
		$('#btBack').bind("click",backTab);
		
		$('#btVerifyMail').bind("click",verifyMail);
		

		$('#req_bt_refresh').click(
			function()
			{
				verifyAndSetRequire();
			}
		);
		
		//set SMTP pannels states
		$("#set_stmp").bind("click",
			function()
			{
				switch ($("input#set_stmp:checked").length)
				{
					case 0 :
					$("div#mailSMTPParam").slideUp('slow');
					smtpChecked = false;
					$("#mailResultCheck").addClass("userInfos").removeClass("ok").removeClass('fail').html("");
					break;
					
					case 1 :
					$("div#mailSMTPParam").slideDown('slow');
					smtpChecked = true;
					$("#mailResultCheck").addClass("userInfos").removeClass("ok").removeClass('fail').html("");
					break;
				}
			}
		);
		


		//preset mail step 4
		$("#testEmail").change(
			function()
			{
				$('#infosEmail').val( $(this).val() );
			}
		);
		
		
		autoCheckField("#infosName", "#resultInfosName", "required");
		autoCheckField("#infosPassword", "#resultInfosPassword", "required");
		autoCheckField("#infosPasswordRepeat", "#resultInfosPasswordRepeat", "required");
		autoCheckField("#infosEmail", "#resultInfosEmail", "mailFormat");
		


		constructInstallerTabs();
		
		//show 1st step
		step=1;
		
		$("#btNext")
			.removeAttr("disabled")
			.removeClass("disabled")

		$("input#btNext").focus();
	}
);
