var genere = 0;
var debug = true;
var lastCodeErreur = 0;
var obj = null;
var secondesB4actu = 20;
var lastIdClicked = 0;
var tourPromo = 0;
var compteurMessage = 0;
var tempsHistorique = 'none';
var firstDFE = true;
var prixUnitaireBid = 50;
var finDeVente = false;

/*Parametre autobid*/
var seuilMini = 0;
var seuilMaxi = seuilMini+100;
var nbBidsMin = 2;

$(function() {
	$.ajaxSetup({
		cache:false
	});
	$.setupJMPopups({
				screenLockerBackground:"#066EB9",
				screenLockerOpacity:"0.8"
			});
	$('#Nav > li').hover(function() {
		$(this).find('ul').stop(true, true);
		if (obj) {

			obj.find('ul').slideUp('normal');
			obj = null;
		}

		$(this).find('ul').slideDown('normal');
	}, function() {
		obj = $(this);
		setTimeout(
			"checkHover()",
			0);
	});
	actualisePage();
	$(document).everyTime(1000, function(){
		genere++;
		actualisePage();
	});
	switch(page)
	{
		case 4 : {
			$("#present .pageNonActive").eq(0).addClass("pageActive").removeClass("pageNonActive");
			$("#futur .pageNonActive").eq(0).addClass("pageActive").removeClass("pageNonActive");
			$("#passe .pageNonActive").eq(0).addClass("pageActive").removeClass("pageNonActive");
			actualiseCategorieFull();
			$(".pagination span").click(function(){
				if($(this).hasClass("pageNonActive"))
				{
					var thePage = $(this).text();
					var theSpan = $(this);
					thePage = parseInt(thePage) - 1;
					switch($(this).parent().attr("id"))
					{
						case "present": {
							$("#liste_live").load(
								"GenereInfosVentesParCategories.php",
								{ t:0,p:thePage,c:categorie},
								function(){
									$("#present .pageActive").addClass("pageNonActive").removeClass("pageActive");
									$(theSpan).addClass("pageActive").removeClass("pageNonActive");
									actualiseBidComposant();
								}
							);
						}; break;
						case "futur":{
							$("#liste_futur").load(
								"GenereInfosVentesParCategories.php",
								{ t:2,p:thePage,c:categorie},
								function(){
									$("#futur .pageActive").addClass("pageNonActive").removeClass("pageActive");
									$("#liste_futur .bid").removeClass("btn").addClass("grise").attr("disabled","disabled");
									$(theSpan).addClass("pageActive").removeClass("pageNonActive");
								}
							);
						}; break;
						case "passe":{
							$("#liste_end").load(
								"GenereInfosVentesParCategories.php",
								{ t:1,p:thePage,c:categorie},
								function(){
									$("#passe .pageActive").addClass("pageNonActive").removeClass("pageActive");
									$("#liste_end .bid").removeClass("btn").addClass("grise").attr("disabled","disabled");
									$(theSpan).addClass("pageActive").removeClass("pageNonActive");
								}
							);
						};
					}
				}
			});
		};
		case 1 : {
			actualiseBidComposant();
			$(".menu a").eq(0).addClass("menu_on").removeClass("menu_off");
		}; break;
		case 2 : {
			var theId = $(".nomFiche").attr("id");
			$("#bid").click(function(){
				$(this).effect("bounce", { times:2, distance:8 }, 250);
				lastIdClicked = theId;
				var theOffset = $(this).offset();
				$.ajax({
					type: "GET",
					url: "Action.php",
					data: { id:theId, action:1},
					success: function(xml){
						/* do some graphic stuff  here + controle success*/
						switch($(xml).find("ReponseAction").text())
						{
							case "0" : {
								$("#bids").text(parseInt($("#bids").text())-1);
							}; break;
							default: lastCodeErreur=$(xml).find("ReponseAction").text(); msgErreur("erreurCode", theOffset);
						}
						$("#bandeauLimite").load("GenereBandeauLimite.php");
					}
				});
			});
			$("#GotoLogin").click(function(){
				window.location.href="Index.php?pasConnecte=1&idRedirection="+theId;
			});


			$("#PopUpVSR").click(function(){
				if($(this).hasClass("grise"))
				{
					var theOffset = $(this).offset();
					lastCodeErreur=10;
					msgErreur("erreurCode",theOffset);
				}
				else
				{
					$.openPopupLayer({
						name:"InfosVSR",
						target:"PopUpVSRContent"
					});
				}
			});

			$("#autobid button.autobid").click(function(){
				seuilMini = parseInt($("input[name='prix_centime']").val());
				seuilMaxi = seuilMini + 100;
				var seuilInferieur = $("#seuilInferieur").val().replace(',', '.');
				var seuilInferieur = Math.round(parseFloat(seuilInferieur)*100);
				var seuilSuperieur = $("#seuilSuperieur").val().replace(',', '.');
				var seuilSuperieur = Math.round(parseFloat(seuilSuperieur)*100);
				var nbBids = parseInt($("#nombreBids").val());
				if(seuilInferieur < seuilSuperieur && seuilSuperieur >= seuilMaxi && nbBids >= nbBidsMin)
				{
					var theId = $(".nomFiche").eq(0).attr("id");
					var theOffset = $(this).offset();
					$.ajax({
						type: "GET",
						url: "Action.php",
						data: { action:2, seuilInferieur:seuilInferieur, seuilSuperieur:seuilSuperieur, nombreBids:nbBids, idVente:theId},
						success: function(xml){
							switch($(xml).find("ReponseAction").text())
							{
								case "0" : {
									var idAutobid = 0;
									actualiseAutobid();
									$("#bids").text(parseInt($("#bids").text())-nbBids);
									var $tabs = $('#tabs').tabs();
									$tabs.tabs('select', 1);
									$("#bandeauLimite").load("GenereBandeauLimite.php");
								}; break;
								default: lastCodeErreur=$(xml).find("ReponseAction").text(); msgErreur("erreurCode", theOffset);
							}

						}
					});
				}
				else if(seuilInferieur >= seuilSuperieur)
				{
					msgErreur("ab1", $(this).offset());
				}
				else if(seuilSuperieur < seuilMaxi)
					msgErreur("ab2", $(this).offset());
				else if(nbBids < nbBidsMin)
					msgErreur("ab3", $(this).offset());
				else
					msgErreur("", $(this).offset());
			});
			actualiseAutobid();
			actualiseBidComposant();
			$("#tabs > ul").tabs();
		}; break;
		case 3 : {
			$("#submit").click(function(){
				/*var isGood = true;
				var regex_login = /^([a-zA-Z](?:(?:(?:\w[\.\_]?)*)\w)+)([a-zA-Z0-9])$/;
				var regex_email = /[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
				if(!regex_login.test($("#nomUser").val()))
				{
					msgErreur("sub1", $("#nomUser").offset());
					isGood = false;
				}
				if(!regex_email.test($("input[name='email']").val()))
				{
					isGood = false;
					msgErreur("sub2", $("input[name='email']").offset());
				}
				if($("input[name='motDePasse']").val() != $("input[name='confirmeMotDePasse']").val())
				{
					isGood = false;
					msgErreur("sub3", $("input[name='confirmeMotDePasse']").offset());
				}
				if(isGood)
					document.formInscription.submit();
				*/
			});
		}; break;
		case 5 : {
			$(".menu a").eq(1).addClass("menu_on").removeClass("menu_off");
			actualiseBidComposant();
		};
		case 6 : {
			var infosArticlesTP = new Array();

			infosArticlesTP[20] = "10.00";
			infosArticlesTP[50] = "25.00";
			infosArticlesTP[100] = "50.00";
			if(page == 6)
				$(".menu a").eq(3).addClass("menu_on").removeClass("menu_off");
			$("#DisplayPaypal").css("backgroundPosition", "center top");
			$("#DisplayPaypal").click(function(){
				$(".TableauMoyensDePaiement").each(function(){
					if($(this).attr("id") != "BidsPaypal")
					{
						$(this).css("display", "none");
					}
					else
					{
						$(this).css("display", "block");
					}
				});
				$("#DisplayPaypal").css("backgroundPosition", "center top");
				$("#DisplayTicketSurf").css("backgroundPosition", "");
				$("#DisplayMP").css("backgroundPosition", "");
			});
			$("#DisplayTicketSurf").click(function(){
				$(".TableauMoyensDePaiement").each(function(){
					if($(this).attr("id") != "BidsTicketPremium")
					{
						$(this).css("display", "none");
					}
					else
					{
						$(this).css("display", "block");
					}
				});
				$("#DisplayPaypal").css("backgroundPosition", "");
				$("#DisplayTicketSurf").css("backgroundPosition", "center top");
				$("#DisplayMP").css("backgroundPosition", "");
			});
			$("#DisplayMP").click(function(){
				$(".TableauMoyensDePaiement").each(function(){
					if($(this).attr("id") != "BidsMP")
					{
						$(this).css("display", "none");
					}
					else
					{
						$(this).css("display", "block");
					}
				});
				$("#DisplayMP").css("backgroundPosition", "center top");
				$("#DisplayPaypal").css("backgroundPosition", "");
				$("#DisplayTicketSurf").css("backgroundPosition", "");
			});
			$(".OpenLayerTSP").click(function(){
				var nbBids = $(this).attr("id").substr(3);
				$("#LayerTSP img").attr("src", "images/pack" + nbBids + ".png");
				$("#LayerTSP input[name='PD']").val("Megagong " + nbBids + " " + lang['offres']);
				$("#LayerTSP input[name='TC']").val(infosArticlesTP[nbBids]);
				$("#LayerTSP input[name='PID']").val(nbBids);
				$.openPopupLayer({
						name:"PopupLayerTSP",
						target:"LayerTSP"
					});
			});
			if($("#Retry").val() == 'OUI')

			{
				$.openPopupLayer({
						name:"PopupLayerTSP",
						target:"LayerTSP"
					});
			}
		}; break;
		case 7 : {
			$(".menu a").eq(2).addClass("menu_on").removeClass("menu_off");
		}; break;
		case 8 : {
			$(".tabs > ul").tabs();
		}; break;
		case 9 : {
			$(".menu a").eq(1).addClass("menu_on").removeClass("menu_off");
			$("#desinscription").click(function(){
				if(confirm(lang['ConfirmeQuitter']))
					document.goodbye.submit();
			});
		}; break;
	}
});

function checkHover() {
	if (obj) {
		obj.find('ul').fadeOut('slow');
	}
}



function actualisePage(){
	switch(page)
	{
		case 5:
		case 1: actualiseAccueil(); break;
		case 2: actualiseFiche(); break;
		case 4: actualiseCategorie();
	}
}

function actualiseAccueil()
{
	if(tourPromo ==4)
	{
		if($('.contenuFiche').css("left") == '-852px')
		{
			$('.contenuFiche').animate({
				left:"0px"
			}, "normal");
		}
		else
		{
			$('.contenuFiche').animate({
				left:"-=213px"
			}, "normal");
		}
		tourPromo=0;
	}
	else
		tourPromo++;
	var ids_prod = '';
	var first = true;
	$("#blocks div.blockProduit, .contenu_encheres_horizontal, .contenu_encheres_mini").each(function(){
		if(first)
		{
			ids_prod += $(this).attr("id");
			first = false;
		}
		else
		{
			ids_prod += ','+$(this).attr("id");
		}
	});
	$.ajax({
		url: "GenereInfosVentes.php",
		type: "GET",
		dataType:"xml",
		data: {i:ids_prod},
		success: function(xml){
			$(xml).find("Vente").each(function(){
				var unId = $(this).find("ID").text();
				var tempsRestant = $(this).find("TempsRestant").text();
				if(tempsRestant < 0)
					if(tempsRestant>-9)
						$("#"+unId+" .TempsRestant").html(lang["verification"]);
					else
						$("#"+unId+" .TempsRestant").html(lang["vendu"]);
				else
					$("#"+unId+" .TempsRestant").text(formatTemps(tempsRestant));
				if($("#"+unId+" .Prix").text() != formatPrix($(this).find("Prix").text()))
				{
					$("#"+unId+" .Prix").text(formatPrix($(this).find("Prix").text()));
					if(genere > 1)
						$("#"+unId+" .Prix").effect("highlight", {color:"red"}, 700);
					$("#"+unId+" .LoginDernierBidder").text(ucFirst($(this).find("LoginDernierBidder").text()));
				}
			});
		}
	});
}

function actualiseAutobid()
{
	var theId = $(".nomFiche").eq(0).attr("id");
	$.ajax({
		type: "GET",
		url: "GenereBidButlers.php",
		data: { i:theId },
		dataType: "xml",
		success: function(xml){
			$("#autobid_running").html("<tr><th>"+lang["inf"]+"</th><th>"+lang["sup"]+"</th><th>"+lang["offres"]+"</th><th></th></tr>");
			$(xml).find("BidButler").each(function(){
				var seuilInferieur = formatPrix($(this).find("SeuilInferieur").text());
				var seuilSuperieur = formatPrix(parseInt($(this).find("SeuilSuperieur").text()));
				var NbBids = $(this).find("Bids").text();
				var idAutobid = $(this).find("ID").text();
				$("#autobid_running").append("<tr><td>"+seuilInferieur+"</td><td>"+seuilSuperieur+"</td><td>"+NbBids+"</td><td><button id='autobid_" + idAutobid + "' class='autobid_del'></button></td></tr>");
			});
			/*$(".contenuLimite").jScrollPane();*/
			$(".autobid_del").click(function(){
				var theId = $(this).attr("id").substr(8);
				var theOffset = $(this).offset();
				$.ajax({
					type: "GET",
					url: "Action.php",
					data: { action:2, idSuppression: theId},
					success: function(xml){
						switch($(xml).find("ReponseAction").text())
						{
							case "0" :
								actualiseAutobid();
								$("#bandeauLimite").load("GenereBandeauLimite.php");
								break;
							default: lastCodeErreur=$(xml).find("ReponseAction").text(); msgErreur("erreurCode", theOffset);

						}
					}
				});
			});
		}
	});
}



function actualiseFiche()
{
	var theId = $(".nomFiche").eq(0).attr("id");
	$.ajax({
		url: "GenereInfosVentes.php",
		type: "GET",
		dataType: "xml",
		data: { i: theId},
		success: function(xml){
			var produit = $(xml).find("Vente");
			var histo = $(xml).find("Historique");
			var tempsRestant = $(produit).find("TempsRestant").text();
			if(firstDFE)
			{
				if(tempsRestant < 14400)
				{
					$("#finEnchereMessage").empty();
					firstDFE = false;
				}
			}
			if (tempsHistorique == 'none')
			{
				tempsHistorique = tempsRestant;
			}
			if($(xml).find("AchatVSRPossible").text()=="N")
				$("#PopUpVSR").addClass("grise");
			else
				$("#PopUpVSR").removeClass("grise");

			var prix = formatPrix($(produit).find("Prix").text());
			var ecart = ($(produit).find("Prix").text())-($("input[name='prix_centime']").val());
			if(prix != $("#Prix").text())
			{
				compteurMessage = 0;
				if (($("input[name='prix_centime']").val() != 0) && (ecart > 0))
				{
					if (ecart%10 == 0)
						ecart = ecart / 10;
					var tRtH = tempsRestant-tempsHistorique;
					if((tRtH)<= 0)
						tRtH = 1;
					if (ecart == 1)
						$("#messageEnchere").text(lang['UneOffre']+formatTemps(tRtH)+lang['AuTemps']);
					else
						$("#messageEnchere").text(ecart+lang['XOffres']+formatTemps(tRtH)+lang['AuTemps']);
				}
				$("#Prix").text(prix);
				$("#Prix2").text(prix);
				var reduc = $(xml).find("NmbBidsJoueur").text()*prixUnitaireBid;
				var prixAchat = $("#PrixPublicCentime").val()-reduc;
				$(".BidRebate").text($(xml).find("NmbBidsJoueur").text()+"x"+formatPrix(prixUnitaireBid)+" : "+formatPrix(reduc));
				$(".PrixAchatVSR").text(formatPrix(prixAchat));
				$("#PrixTotalVSR").text(formatPrix(prixAchat+parseInt($("#FraisPortCentime").val())));
				$("input[name='prix_centime']").val($(produit).find("Prix").text());
				$("#LoginDernierBidder").text(ucFirst($(produit).find("LoginDernierBidder").text()));
				if(genere > 1)
					$("#Prix").effect("highlight", {color:"red"}, 700);
				$(".historique-ligne").remove();
				$(histo).find("Bid").each(function(){
					var prix = formatPrix($(this).find("Prix").text());
					var bidder = ucFirst($(this).find("Joueur").text());
					var type = $(this).find("TypeBid").text();
					$("#historique").append("<tr class='historique-ligne'><td>"+prix+"</td><td>"+bidder+"</td><td>"+type+"</td></tr>");
				});
				$(".contenuLimite2").jScrollPane();
				actualiseAutobid();
			}
			else if(compteurMessage < 4)
				compteurMessage++;
			else
			{
				$("#messageEnchere").html("&nbsp;");
				compteurMessage = 0;
			}
			tempsHistorique = tempsRestant;
			if($(xml).find("IDOffreVenteReelle").size() > 0)
			{
				$("#TempsRestant").html(lang["vendu"]);
				$("#LoginDernierBidder").html(lang["achatGain"] + "<a href='?m=6&o="+$(xml).find("IDOffreVenteReelle").text()+"'>" +  lang["achatGain2"] + "</a>");
			}
			else if(tempsRestant < 0)
			{
				$("#finEnchereMessage").removeClass("finEnchereMessage");
				if(tempsRestant>-9)
					$("#TempsRestant").html(lang["verification"]);
				else
				{
					if(!finDeVente)
					{
						finDeVente = true;
						actualiseAutobid();
					}
					$("#TempsRestant").html(lang["vendu"]);
					$("#LoginDernierBidder").html(lang["felicitation"]+ucFirst($(produit).find("LoginDernierBidder").text()));
				}
				/*if(ucFirst($(produit).find("LoginDernierBidder").text()) ==  $("#login").text())
					$("#LoginDernierBidder").text(lang["encours"]);
				else*/

			}
			else
			{
				$("#economie").text(formatPrix($("input[name='pbc_centime']").val()-$("input[name='prix_centime']").val()));
				$("#TempsRestant").text(formatTemps(tempsRestant));
				if (tempsRestant < 20)
				{
					$("#finEnchereMessage").addClass("finEnchereMessage");
					if (tempsRestant < 10)
						$("#TempsRestant").removeClass("temps").addClass("tempsUrgent");
					else
						$("#TempsRestant").removeClass("tempsUrgent").addClass("temps");
				}
				else
				{
					$("#finEnchereMessage").removeClass("finEnchereMessage");
					$("#TempsRestant").removeClass("tempsUrgent").addClass("temps");
				}
			}
		}
	});
	actualiseAccueil();
}


function actualiseCategorie(){
	var ids_prod = '';
	var first = true;
	$("#liste_live .contenu_encheres_horizontal").each(function(){
		if(first)
		{
			ids_prod += $(this).attr("id");
			first = false;
		}
		else
		{
			ids_prod += ','+$(this).attr("id");
		}
	});
	$.ajax({
		url: "GenereInfosVentes.php",
		type: "GET",
		data: {i:ids_prod},
		success: function(xml){
			$(xml).find("Vente").each(function(){
				var unId = $(this).find("ID").text();
				var tempsRestant = $(this).find("TempsRestant").text();
				if(tempsRestant < 0)
					$("#"+unId+" .TempsRestant").html(lang["vendu"]);
				else
					$("#"+unId+" .TempsRestant").text(formatTemps(tempsRestant));
				if($("#"+unId+" .Prix").text() != formatPrix($(this).find("Prix").text()))
				{
					$("#"+unId+" .Prix").text(formatPrix($(this).find("Prix").text()));
					if(genere > 1)
						$("#"+unId+" .Prix").effect("highlight", {color:"red"}, 700);
					$("#"+unId+" .LoginDernierBidder").text(ucFirst($(this).find("LoginDernierBidder").text()));
				}
			});
		}
	});
}


function actualiseCategorieFull(){
	$("#liste_live").load(
		"GenereInfosVentesParCategories.php",
		{ t:0,p:0,c:categorie},
		function(){
			actualiseBidComposant();
		}
	);
	$("#liste_futur").load(
		"GenereInfosVentesParCategories.php",
		{ t:2,p:0,c:categorie},
		function(){
			$("#liste_futur .bid").removeClass("btn").addClass("grise").attr("disabled","disabled");
		}
	);
	$("#liste_end").load(
		"GenereInfosVentesParCategories.php",
		{ t:1,p:0,c:categorie},
		function(){
			$("#liste_end .bid").removeClass("btn").addClass("grise").attr("disabled","disabled");
		}
	);
}


function actualiseBidComposant(){
	$(".bid").click(function(){
		var theOffset = $(this).offset();
		var theId = $(this).parent().eq(0).parent().attr("id");
		lastIdClicked = theId;
		$(this).effect("bounce", { times:2, distance:8 }, 250);
		$.ajax({
			type: "GET",
			url: "Action.php",
			data: { id:theId, action:1},
			success: function(xml){
				/* do some graphic stuff  here + controle success*/
				switch($(xml).find("ReponseAction").text())
				{
					case "0" : {
						$("#bids").text(parseInt($("#bids").text())-1);
					}; break;
					default: {
						lastCodeErreur=$(xml).find("ReponseAction").text();
						msgErreur("erreurCode", theOffset);
					}
				}
				$("#bandeauLimite").load("GenereBandeauLimite.php");
			}
		});
	});
}


function msgErreur(code, pos){
	if((code != "")&&(lang[code]!=undefined))
	{
		if(code == "erreurCode")
		{
			switch(parseInt(lastCodeErreur))
			{
				case 98: document.location.href="?pasConnecte=1&idRedirection="+lastIdClicked; break;
				case 1 : message = lang["erno1"]; break;
				case 2 : message = lang["erno2"]; break;
				case 3 : message = lang["erno3"]; break;
				case 8 : message = lang["erno8"]; break;
				case 9 : message = lang["erno9"]; break;
				case 10 : message = lang["erno10"]; break;
				default: message = lang[code] + " " + lastCodeErreur;
			}
		}
		else
			message = lang[code];
	}
	else if(code != "")
		message = lang["erreur"];
		if(lastCodeErreur != 7 && lastCodeErreur != 97)
		{	$('<div class="erreur"><span class="close_box"></span><br />'+message+'</div>').appendTo($("body")).css({
				position:"absolute",
				top: pos.top,
				left: pos.left
			});
		}
	actualiseCloseBox();
}

function actualiseCloseBox(){
	$(".close_box").click(function(){
		$(this).parent().remove();
	});
	$(".erreur").click(function(){
		$(this).remove();
	});
}

function formatPrix(prix){
	var entier = Math.floor(prix/100);
	var virgule = prix%100;
	if(virgule<10)
		virgule = '0' + virgule;
	return entier + "," + virgule + " " + String.fromCharCode(8364);
}


function formatTemps(reste){
	var tempsSec = reste;
	var heures=Math.floor(reste/3600);
		reste=reste%3600;
		var minutes=Math.floor(reste/60);
		if(minutes < 10){
			minutes = '0' + minutes;
		}
	if(tempsSec<86400)
	{
		var secondes=reste%60;
		if(secondes < 10){
			secondes = '0' + secondes;
		}
		return heures + ":" + minutes + ":" + secondes;
	}
	else
	{
		var jours = Math.floor(heures/24);
		heures = heures%24;
		return jours + "j " + heures + "h " + minutes + "m";
	}
}

function ucFirst(str){
	return str.substr(0,1).toUpperCase() + str.substr(1,str.length);
}