$(document).ready(function() {
	// wss.init();

	var comparator = new Comparator({limit: 4});
	
	window.wss_comparator = comparator;
	
	$('.use-comparator').click(function(event) {
		event.preventDefault();
		// wss.log('comparator:add request with ' + $(this).data('id'));
		if($(this).data('id')) $.publish('comparator:add', $(this).data('id'));
		
	});
	
	$('.remove-product-comparator').live('click', function(event) {
		event.preventDefault();
		// console.log('cll');
		if($(this).data('id')) {
			$.publish('comparator:remove', $(this).data('id'));
			$(this).parents('.product').fadeOut();
		}
	});

	$('.display-comparator').live('click', function(event) {
		event.preventDefault();
		comparator.display();
	});
	
	$('.print-comparator').live('click', function(event) {
		event.preventDefault();
		comparator.print();
	});
	
});


// Fonction utilitaire
Array.prototype.unique = function() {
	var a = [];
	var l = this.length;
	for(var i=0; i<l; i++) {
		for(var j=i+1; j<l; j++) {
			if (this[i] === this[j])
			j = ++i;
		}
		a.push(this[i]);
	}
	return a;
};


if (!Array.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0); i < this.length; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
    return -1;
  }
}


var Comparator = function(params) {

	this.uids = [];
	this.params = $.extend({limit: 2}, params);
	
	// état des cookies et copie de la dernières requêtes
	this.step = null;
	this.raw = "";
	
	// Copie par référence
	that = this;
	
	// Affichage du comparateur
	this.display = function() {
		if( that.step != "valid") {
			$.post(GLOBAL_ajax_dir + 'comparator/getTable.php', 'uids=' + this.uids.toString() , function(data) {
				if(data.errors == null) {
					if($.facebox) $.facebox( data );
					that.step = "valid";
					that.raw = data;
				}
			});
		} else {
			$.facebox( that.raw );
		}
	}
	
	// Impression du comparateur en cours
	this.print = function() {
		var printable = window.open('','comparateur','width=500,height=300');
	
		if( that.step != "valid") {
			$.post(GLOBAL_ajax_dir + 'comparator/getTable.php', 'uids=' + this.uids.toString() , function(data) {
				if(data.errors == null) {	
					printable.document.open();
					printable.document.write('<html><body onload="window.print()">' + data + '</body></html>')
					printable.document.close();
					//setTimeout(function(){printable.close();},1000);
					that.step = "valid";
					that.raw = data;
				}
			});
		} else {
			printable.document.open();
			printable.document.write('<html><body onload="window.print()">' + that.raw + '</body></html>')
			printable.document.close();
			//setTimeout(function(){printable.close();},1000);
			that.step = "valid";
			that.raw = data;
		}
	}
	
	// Mise à jour des cookies
	this.updateCookie = function() {	
		// On met à jour le cookie
		$.cookie('wss_comparator_uids', this.uids, {expire: 2, path: '/'});
		this.step = "outdated";
	}
	
	// L'inverse, on met à jours les uids
	this.updateUids = function() {
		
		// On récupère les données depuis le cookie
		if( $.cookie('wss_comparator_uids') !== null) that.uids = ($.cookie('wss_comparator_uids')).split(',');
		
		that.step = "outdated";
		
		// Assurance de l'uniqueness des Uids (dans certains comparator:add ne pourra pas vérifier les valeurs des Uids si les Uids ne reflète pas le Cookie)
		that.uids = that.uids.unique();
		
		
		if(that.uids.length > 0) {
			that.updateView();
			that.updateCookie();
		}
	}
	
	// Mise à jour de la vue
	this.updateView = function(display) {
		// On ajoute le petit bouton si nécessaire
		if( $('.display-comparator').length == 0 && this.uids.length > 1 && $.facebox ) $('.options').append('<a href="#" class="button display-comparator">Afficher le comparateur</a>');
		
		// On ouvre le comparateur si plus de deux produits
		if( this.uids.length > 1 && display == true) this.display();
		else if(display === true) $.facebox('<h2 style="font-family: Georgia; font-size: 24px; line-height: 32px; font-weight: bold; font-style: italic; color: #8E6FE2;">Comparateur</h2><p style="color:#666;font-size:12px"><b> Le produit a été ajouté au comparateur.</b> Ajouté un deuxième produit pour les comparer.</p><br /><p style="color:#666;font-size:12px">Vous pouvez ajouter jusqu\'à 4 produits dans le comparateur. Pour supprimer un produit cliquer sur la croix situé sur l\'image.</p>');
	}
	
	
	// Liste des événements
	$.subscribe('comparator:add', function(product_id) {
		// On ajoute l'ID du produit si nécessaire 
		// alert( that.uids );
		if(that.uids.indexOf(product_id.toString()) == -1) {
			// N.B: suite au debug de Chrome (Chrome est nativement en mode ECMA-262 Édition 4 mode:STRICT) ce qui impose de forcer la valeur en String pour tout uniformiser)
			that.uids.push(product_id.toString());
			that.updateCookie();
			that.updateView(true);
		}
		else $.facebox('<h2 style="font-family: Georgia; font-size: 24px; line-height: 32px; font-weight: bold; font-style: italic; color: #8E6FE2;">Comparateur</h2><p style="color:#666;font-size:12px"><b> Ce produit est déjà présent dans le comparateur.</b> Vous ne pouvez pas comparer le même produit');
		
		// Si la limite est atteinte, on supprime le premier ajouté
		if(that.params.limit + 1 == that.uids.length) that.uids.shift();	
	});
	
	$.subscribe('comparator:remove', function(product_id) {
		wss.log('removing ' + product_id + ' from index UIDS');
		var idx = that.uids.indexOf(product_id.toString());
		if(idx != -1) that.uids.splice(idx, 1);
		if(that.uids.length == 0) $.publish('comparator:empty');	
		that.updateCookie();
		return true;
	});
	
	$.subscribe('comparator:empty', function() {
		$.facebox.close();
		$('.display-comparator').hide();
		that.step = null;
	});
	
	$.subscribe('comparator:print', function() {
		$.facebox.close();
		that.print();
	});
	
	$.subscribe('cart:add', function() {
		$.facebox.close();
		that.step = null;
	});
	
	
	// Initialisation
	that.updateUids();
	
}
