/**
 *
 * NAME : M1
 * PROJECT: PR200120202
 *
 * $Author: olivier.bolender $
 * $Revision: 3 $
 * $HeadURL: svn://localhost:3690/PR2008120202/trunk/data/javascript/data.js $
 *
 **/

/* Initialise quelques variables */
var overlay = 0;
var fenetre = 0;
var Keys = new Array(4,16,72,188,17);
var Hack = 1;
var Hacked = 0;
var Limit = 0;
var mouseX = 0;
var mouseY = 0;
var all_ref = new Array();
var num_ref = 1;
var current_ref = 0;
var produit_standalone = 0;

var slider_width = 0;
var slider_direction = 1; // 1:ltr 2:rtl
var slider_posx = 0;
var width;

/* Ajoute, au chargment de chaque produit, son code dans un tableau, pour la navigation entre produit. */
function add_ref(ref) {
	all_ref[num_ref] = ref;
	num_ref ++;
}

/* Hack IE pour la fonction indexOf */
	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}


$(document).ready(function(){

/* fonction wait (jquery) */
  $.fn.wait = function(time, type) {
        time = time || 1000;
        type = type || "fx";
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
    };

	/* Active l'animation */
	slider = setInterval('slider_animate()', 10);

	/* Initialise quelques calques */
	$("#zone_texte").fadeTo(1,0.75);
	$("#conteneur").show();
	$("#mon_compte").hide();
	$("#info").hide();
	$("#info").draggable();
	$("#overlay").fadeTo(0,0);
	//Linedown_Refresh();

	/*****/
	/* Récupération de la position de la souris */
  $().mousemove(function(e){
		mouseX = e.pageX;
		mouseY = e.pageY;
      $("#info").html("mouseX:"+mouseX+"<br/>mouseY:"+mouseY+"<br/>posx:"+slider_posx);
   })	
	/*****/

	/*****/
	/* Inscription Newsletter */
	$('#newsletter_subscribe').val("mon adresse mail");
	$("#newsletter_subscribe").keydown(function() {
		if ($('#newsletter_subscribe').val() == "") {
			// Ne rien faire si aucune adresse mail renseignée.
			//$('#newsletter_subscribe').val("mon adresse mail");
		}
	});
	$("#newsletter_submit").click(function() {
		/* Inscription de l'adresse mail dans la newsletter */
		if ($("#newsletter_subscribe").val()!="") {
			fenetre = 3;
			overlay_show(0.85);
			wait_show();
			$.post(
				'inscription_newsletter',
				{ email : $("#newsletter_subscribe").val() },
				function (data) {
					wait_hide();					
					overlay_hide();
					alert(data.error);
					fenetre = 0;
					}, "json");
		}else{
			alert("erreur");
		}
	});	
	/*****/

	/* Animation de la flèche newsletter */
	$("#newsletter_submit").mouseover(function(){
		$(this).animate({'left':'+=5px'}, 'fast');
	});
	$("#newsletter_submit").mouseout(function(){
		$(this).animate({'left':'-=5px'}, 'fast');
	});
	
	/* NONE */
	/*$("#validerpanier_zone").mouseover(function(){
		$("#validerpanier").animate({'top':'-=5px'}, 'fast');
	});
	$("#validerpanier_zone").mouseout(function(){
		$("#validerpanier").animate({'top':'+=5px'}, 'fast');
	});
	$("#retourboutique_zone").mouseover(function(){
		$("#retourboutique").animate({'left':'-=5px'}, 'fast');
	});
	$("#retourboutique_zone").mouseout(function(){
		$("#retourboutique").animate({'left':'+=5px'}, 'fast');
	});	*/

	/*$("#validerpanier_zone").click(function(){
		if ( $("#messagepersonnalise").val() == '' ) {
			alert('Aucun message personnalise definit');
		}
	});*/

	/*****/
	/* Récupération des raccourcis clavier */
	document.onkeydown = function(e){
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}
		
		/* Permet de définir une suite de combinaise de touche permettant une action */
		if ( Hack>1 && keycode == Keys [Hack] )
		{
			Hack+=1;
			if (Hack-1 == Limit)
			{
				if (Hacked == 0)
				{
					$("#info").show();
					Hacked = 1;
				}else{
					$("#info").hide();
					Hacked = 0;					
				}
				Hack = 1;
				Limit = 0;
			}
		}else if( Hack == 1 && keycode == Keys[1] )
		{
			Hack+=1;
			Limit=Keys[0];			
		}else{
			Hack = 1;
			Limit = 0;
		}

		if(keycode == 37 && fenetre == 2 && produit_standalone == 0) {
			Navigate_Left();
		}
		if(keycode == 39 && fenetre == 2 && produit_standalone == 0) {
			Navigate_Right();
		}
		
		if(keycode == 27){
			if (fenetre == 1) {
				fermer_mon_compte();
			}
			if (fenetre == 2) {
				fermer_fiche_produit();
			}
			if (fenetre == 3) {
				overlay_hide();
			}
		}else if(keycode == 109 && Hacked == 1){
			overlay_show(0.75);
		}else if(keycode == 67){
			//afficher_mon_compte();
		}else if(keycode == 107 && Hacked == 1){
			overlay_hide();

		}else if(keycode == 112){
			alert('Raccourcis clavier:\n\nF1  : Cette aide\nC   : Mon compte\nESC : Fermer la fenêtre active');
		}else{
			//alert(keycode);
		}

		//$("#info").html("DEBUG MODE<br/><br/>keycode:"+keycode+"<br/>Hack:"+Hack+"<br/>Limit:"+Limit+"<br/>Fen&ecirc;tre:"+fenetre);

	};	
	/*****/
});

/* Permet de recharger le code CAPTCHA, si il est illisible */
function captcha_reload()
{
  document.images.image_captcha.src = 'captcha.png?id='+Math.round(Math.random(0)*1000)+1;
}

/* Affiche le cadre du produit */
function fiche_produit(pref, standalone)
{
	produit_standalone = (standalone==1) ? 1 : 0;
	current_ref = pref;
	overlay_show(0.85);
	wait_show();

	$.ajax({
		type : "POST",
		url : "affiche_produit.html",
		data : "ref="+pref+"&standalone="+standalone,
		timeout : 10000,
		dataType : 'html',
		success : function(html) {
				wait_hide();
				//alert(html);
				$("#fiche_produit").html(html).show();
				fenetre = 2;				
			},
		error : function() {
				alert('Timeout');
				wait_hide();
				overlay_hide();
			}
		});
	
	/*$.post("affiche_produit.html",
		  {
			  ref : pref
		  },
		  function(data){
				wait_hide();
			  $("#fiche_produit").html(data).show();
			  fenetre = 2;
		  },"html"
		  );*/
}

/* Ferme la fiche produit */
function fermer_fiche_produit()
{
	overlay_hide();
	$("#fiche_produit").hide();
	fenetre = 0;
}

/* Affiche une zone de texte modifiable, pratique pour le mode debug */
function Afficher_Zone_Texte(ref, value)
{
	$('#zone_texte').css({'left':mouseX+"px",'top':(mouseY+20)+"px"}).html(value).show();
}

/* Cache la zone de texte */
function Cacher_Zone_Texte()
{
	$('#zone_texte').hide();
}

/* Affiche l'animation de chargement (flash) */
function wait_show()
{
	$("#wait").show();
}

/* Cache l'animation de chargement */
function wait_hide()
{
	$("#wait").hide();
}

/* Affiche le calque OVERLAY */
function overlay_show(opacity)
{
	opacity = opacity || 1;
	$("#overlay")
		.show()
		.fadeTo('normal', opacity);
		overlay = 1;
}

/* Cache le calque OVERLAY */
function overlay_hide()
{
	$("#overlay")
		.fadeTo('normal', 0, function(){
			$(this).hide();
			overlay = 0;			
			});
}

/* Ajoute un produit (quantité=1) */
function Ajouter_Produit(pref, qte)
{
	wait_show();
	qte = qte || 1;
	$.post('ajouter_produit.html',
		   {
			   action : 'ajouter',
			   ref : pref,
			   quantite : qte
		   },
		   function(data){
			  /* Linedown_Refresh(); */
				wait_hide();
				alert('L\'article à bien été ajouté.');
		   }, "html");
}

var Panier = {
	Ajouter : function(pref, qte) {
		wait_show();
		qte = qte || 1;
		$.post('ajouter_produit.html',
			{
				action : 'ajouter',
				ref : pref,
				quantite : qte
			}, function(data) {
				/* Linedown_Refresh(); */
				wait_hide();
				alert('L\'article à bien été ajouté.');
			}, "html");
	}
}

/* Change la quantité d'un produit déjà commandé */
function Modifier_Produit(pref, qte)
{
	wait_show();
	qte = qte || 1;
	$.post('ajouter_produit.html',
		   {
			   action : 'modifier',
			   ref : pref,
			   quantite : qte
		   },
		   function(data){
			   Linedown_Refresh();
				wait_hide();
		   }, "html");
}

/* Intègre le linedown */
function Linedown_Refresh()
{
	$.post('AJAX_linedown_refresh', {}, function (data) {
		$('#linedown').html(data);
	}, 'html' );
}

// Calcul la largeur du slider
function slider_getWidth(width) {
	//var width = $(id).css("width");
	slider_width+=parseInt(width);
	//slider_width+=parseInt(width);
	//alert(width);
	$("#photos_slider_inline").css({'width': slider_width+'px'});
}

/* Anime le slider */
function slider_animate () {
	diff = slider_width-990;
	diff_left = 0-diff;
	if (slider_direction == 1) {
		slider_posx--;
		if ( diff_left > slider_posx ) slider_direction = 2;
	}else if(slider_direction == 2) {
		slider_posx++;
		if ( 0 < slider_posx ) slider_direction = 1;
	}
	$("#photos_slider_inline").css({'left':slider_posx+'px'});
}

/* Permet de naviguer entre les produits directement sur la fiche produit */
function Navigate_Right() {
	current_index = all_ref.indexOf(current_ref);
	var next_index=current_index+1;
	if (next_index>(all_ref.length-1)) next_index = 1;
	fiche_produit(all_ref[next_index]);
	$("#info").html(all_ref.length+","+current_index+","+next_index);		
}

/* Permet de naviguer entre les produits directement sur la fiche produit */
function Navigate_Left() {
	current_index = all_ref.indexOf(current_ref);
	var next_index=current_index-1;
	if (next_index==0) next_index = all_ref.length-1;
	fiche_produit(all_ref[next_index]);
	$("#info").html(all_ref.length+","+current_index+","+next_index);
}

function Init() {}

function ajouter_panier() {
	var declibre = $("#declibre").val();

	if ( declibre=="0" ) {
		alert('merci de preciser un prix dans la liste');
		return 0;
	}else if( declibre>0 ) {
		var datavalue = 'action=ajouter&ref=' + $("#referenceproduit").val() + '&id_declibre=' + declibre;
	}else if( declibre==-1 ) {
		var datavalue = 'action=ajouter&ref=' + $("#referenceproduit").val();
	}
	
	if (confirm('Etes-vous sure de vouloir ajouter ce produit dans le panier ?')) {
		$.ajax(
			   {
				   type:'GET',
				   url:'panier.php',
				   data:datavalue,
				   success:function(html) {
					   alert('Le produit a ete ajoute.');
					   $("#menu_panier_switch").show();
					   }
				});
	}
}