/**
* Delegates a function to be used by out of context callers (like setTimeout in IE)
* @param scope Object :  The scope in which to execute the delegated function.
* @param func Function : The function to execute
* @param data Object or Array : The data to pass to the function. If the function is also passed arguments, the data is appended to the arguments list. If the data is an Array, each item is appended as a new argument.
* @param isTimeout Boolean : Indicates if the delegate is being executed as part of timeout/interval method or not. This is required for Mozilla/Gecko based browsers when you are passing in extra arguments. This is not needed if you are not passing extra data in.
*/
function delegate(scope, func, data, isTimeout)
{
    return function()
    {
        var args = Array.prototype.slice.apply(arguments).concat(data);
        //Mozilla/Gecko passes a extra arg to indicate the "lateness" of the interval
        //this needs to be removed otherwise your handler receives more arguments than you expected.
                //NOTE : This uses jQuery for browser detection, you can add whatever browser detection you like and replace the below.
        if (isTimeout && $.browser.mozilla)
            args.shift();

        func.apply(scope, args);
    }
}

function show_decrease( div, id )
{
	new Ajax.Updater( div , '/ajax.php?action=get_decrease&id=' + id, {
		method: 'get',
		onSuccess: function() { new Effect.toggle(div, 'Slide', {duration: 0.5}) }
		});
}

function toggleSlide( div )
{
	div.toggle(250);
}
function toggle( div )
{
	$(div).toggle(250);
}


function track( id_prod, id_cat, item_type )
{
	// jQuery Method
	$.fn.colorbox({href:'/ajax.php?action=track&item=' + id_prod + '&cat=' + id_cat + '&type=' + item_type, open:true});
}

var toMenu = null; // Timer du menu
var toMenuLeave = null;
var menuShown = false;

function pop_mini(page)
{
	var popup_id = 'pm_' + new Date().getTime().toString(10) + Math.floor(Math.random()*10000).toString(10);
	
	$("body").append(
		'<div id="'+popup_id+'" style="position:absolute; top:200px; left:100px; width:760px; height:400px; display:none; overflow:auto;">' +
		'</div>'
	);
	
	$("#"+popup_id).click(function()
	{
		$("#"+popup_id).remove();
	});
	
	$.ajax({
		url: page,
		success: function(html)
		{
			$("#"+popup_id).html(html).show();
		}
	});
	
	return false;
}

var hiding_rows  = false;
var showing_rows = false;

function chain_hide_rows(tbody_id)
{
	if (!hiding_rows) return;
	
	// Récursion qui cache une à une les lignes du tbody spécifié,
	// en commençant à la dernière ligne et en s'arrêtant automatiquement
	// à la première ligne.
	// Nécessite que les cellules aient leur contenu dans une div !
	var tr = $("#" + tbody_id + " > tr:visible:last");
	
	if (tr.length > 0)
	{
		divs = tr.find("> td > div");
		
		/*console.log(new Date().getTime() + ' - hide divs stop: [' + tbody_id + '] ' + divs.first().text());
		divs.stop(true, true);*/
		
		console.log(new Date().getTime() + ' - hide divs slideUp: [' + tbody_id + '] ' + divs.first().text());
		divs.slideUp(200);
		
		divs.promise().done(function(){
			console.log(new Date().getTime() + ' - hide promise done: [' + tbody_id + '] ' + this.first().text());
			tr.hide();
			chain_hide_rows(tbody_id);
		});
	}
}

function chain_show_rows(tbody_id)
{
	if (!showing_rows) return;
	
	// Récursion qui affiche une à une les lignes du tbody spécifié,
	// en commençant à la première ligne et en s'arrêtant automatiquement
	// à la dernière ligne.
	// Nécessite que les cellules aient leur contenu dans une div !
	var tr = $("#" + tbody_id + " > tr:hidden:first");
	
	if (tr.length > 0)
	{
		tr.show();
		
		divs = tr.find("> td > div");
		
		/*console.log(new Date().getTime() + ' - show divs stop: [' + tbody_id + '] ' + divs.first().text());
		divs.stop(true, true);*/
		
		console.log(new Date().getTime() + ' - show divs slideDown: [' + tbody_id + '] ' + divs.first().text());
		divs.slideDown(200);
		
		divs.promise().done(function(){
			console.log(new Date().getTime() + ' - show promise done: [' + tbody_id + '] ' + this.first().text());
			chain_show_rows(tbody_id);
		});
	}
}

// Preload de l'animation:
animationgif = new Image();
animationgif.src = "/styles/beautytech_v2/img/ajax-loader.gif";

/**
 * Centre horizontalement l'element en parametre
 * @param $element
 * @returns {Number}
 */
function CentrerHori( $element) {
	return ((($(window).width() - $( $element).width())) / 2);
}

/**
 * Centre verticalement l'element en parametre
 * @param $element
 * @returns {Number}
 */
function CentrerVerti( $element) {
	return ((($(window).height() - $( $element).width())) / 2);
}

/**
 * Positionne le div au centre de la fenetre
 * quelle que soit sa taille
 * @param string
 *
 */
function CentrerPopup( $nomDiv) {
	var x = ((($(window).width() - $( $nomDiv).width())) / 2);
	var y = ((($(window).height() - $( $nomDiv).height())) / 2);
	// Empeche le popup de dépasser en hauteur
	if (y <= 0)
	{
		// constante numerique approximative car JS ne calcule pas les
		// barres de défilement
		var divHeight = ($(window).height() - 80);
		// on réduit la taille du popup
		$( $nomDiv).height( parseInt(divHeight));
		// on egalise les marges au possible
		y = ((($(window).height() - parseInt(divHeight))) / 2);
	}
	var yheight = $( $nomDiv).height();
//	console.log('x: '+ x +'  | y: '+ y + ' | ydiv: ' + yheight);
	$( $nomDiv).css({left: parseInt(x), top: parseInt(y)});

	// Hack rafraichissant les dimensions.
	$( $nomDiv).height();
}

/**
 * Ajoute un pack avec son choix
 * @param id
 * @param qte
 * @param sPackId
 */
function addItem( id, qte, sPackId) {

	var url = '/ajax.php?action=add2cart&id=' + id + '&qte=' + qte + '&spackid=' + sPackId;
	var html = '';
	$.getJSON( url , function(json) {
		if (json.response == true) {
			html = ContenuPopupReussi( json);
		}
		if (window.location.pathname == '/cart')
		{
			$( "#close_ajax_data").css({display: 'block', marginLeft: 110});
		}
		$( divCible +"#ajax_result").html(html);
		// positionnement et dimensionnement du popup
		CentrerPopup( divCible);
		// positionner le bouton
	});

}

/**
 * Génère le html d'un popup de confirmation
 *
 * @param json
 * @returns html string
 */
function ContenuPopupReussi( $data) {
	html = '<h1>Vous avez ajout&eacute; au panier:</h1>';
	html += '<p>';
	html += '<img src="http://images.beauty-tech.fr/catalog/products/small/' + $data.id + '.jpg" />';
	html += '<strong>' + $data.libelle + '</strong><br />';
	html += 'Quantit&eacute : <strong>' + $data.qte + '</strong><br />';
	html += 'Prix : <strong>' + $data.prix + ' &euro;</strong><br />';
	html += '<br />';
	html += 'Total commande : <strong>' + $data.subtotal + ' &euro;</strong>';
	html += '</p><br class="clear" />';
	return html;
}

/**
 * Génère le html d'un popup proposant plusieurs choix de declinaisons
 *
 * @param json
 * @param int
 * @returns string
 */
function ContenuPopupChoixDecli( $json, qte) {
	html = '<img src="http://images.beauty-tech.fr/catalog/products/small/' + $json.id + '.jpg" />';
	html += '<strong>' + $json.packLabel + '</strong><br />';
	html += 'Quantit&eacute : <strong>' + qte + '</strong><br />';
	html += 'Prix : <strong>' + $json.packPrice + ' &euro;</strong><br />';
	html += '</div>';
	html += '<br class="clear" />';
	html += '<h2 class = "vert" >Veuillez choisir un produit parmi les suivants: </h2><br />';
	// liste déclinaisons à choisir
	html += '<ul>';
	for (var j in $json.decliDetails) {
		/* DecliDetails:
		 * id: 0
		 * libelle: 1
		 * qte: 2
		 *  */

		//'/ajax.php?action=add2cart&id=' + id + '&qte=' + qte + '&spackid=' + sPackId;
		html += '<li class="pack_item" onclick="javascript:addItem(\''+
		$json.decliDetails[j][0] +'\', '+ qte + ', \''+ $json.id +'\')">';
		html += '<img src="http://images.beauty-tech.fr/catalog/products/small/' + $json.decliDetails[j][0] + '.jpg" />';
		html += '<h2>' + $json.decliDetails[j][1] + '</h2><br />';
		html += '<small>' + $json.decliDetails[j][2] + ' par pack</small><br />';
		html += '</li>';
		html += '<br />\n';
	}
	html += '</ul>';
	html += '<br />';
	return html;
}


/* Nouvelles fonctions jQuery */
$(document).ready(function(){
	
	// definition du popup cible
	if ( (window.location.pathname == '/cart') == true)
	{
		divCible = "#ajax_data_cart ";

	}else {
		divCible = "#ajax_data ";
	}

	$(".add2cart").overlay({
		/*mask: {
			color: '#fff',
			loadSpeed: 200,
			opacity: 0.5
		},*/
		left: CentrerHori( divCible),
		top: CentrerVerti( divCible),
		close: '#close_ajax_data',
		closeOnClick: false,
		closeOnEsc: true,
		onClose: function() {
			$('#num_items').load('/ajax.php?action=get_num_items');
			// on reload uniquement si le produit est ajouté depuis la page cart
			if ( ( $('#ajax_result h1').text().substr(0, 4) == 'Vous') && ((window.location.pathname == '/cart') == true) ) {
				window.location.reload();
			}
		}
	});

	/**
	 * Ajout d'un element au panier
	 */
	$(".add2cart").click( function() {
		// definition du popup cible
		var divCible  = '';
		if ( (window.location.pathname == '/cart') == true)
		{
			// on cache les boutons
			$( "#close_ajax_data").css({display: 'none', marginLeft: 110});
			divCible = "#ajax_data_cart ";

		}else {
			divCible = "#ajax_data ";
		}

		if ( ((window.location.pathname == '/cart') == true) &&
				( ($(".inputable").val() == '') || $(".inputable").val() == 'undefinded') )
		{
			var html = "<h1 style='margin-left: 70px;'>Merci de remplir le champ</h1>";
			html += '<br class="clear" />';

			$( "#close_ajax_data").css({display: 'block'});
			$( divCible +"#ajax_result").html(html);
			$('.inputable').css({backgroundColor: 'pink'});
		}
		else
		{

		// loading
		var html = "<h1 style='margin-left: 30px;'>Recherche...</h1>";
		html += "<h2 style='margin-left: 30px;'>Merci de patienter</h2>";
		html += '<img src="'+ animationgif.src +'" class="animationgif"/>';
		html += '<br class="clear" />';

		// Initialisation des paramètres
		var type = '';
		var id   = '';
		var qte  = '';
		var url  = '';

		id = $(this).closest(".product").attr("rel");
		qte = $('#qte_'+id).val();

		if ( (window.location.pathname == '/cart') == true)
		{
			id = $(".inputable").val();
			qte = $(".numeric").val();
		}

		if ($(this).closest("#purchase_options").attr("rel") == "fo") {
			qte = 1;
			type = "fo";
		}

		// positionnement et dimensionnement du popup
		$( divCible +"#ajax_result").html(html);
		CentrerPopup( divCible);

		// Requete GET
		url = '/ajax.php?action=add2cart' +
			       '&id='  + $.trim( id  ) +
		           '&qte=' + $.trim( qte ) +
		           '&type='+ $.trim( type)
		           ;

		//---------------------------------------------------------------------<
		$.getJSON( url, function (json)
				{
				switch (json.ContentStyle) {
					case 'error':
						// Erreur de saisie
						html = "<h1 style='margin-left: 30px;'>Erreur de saisie</h1>";
						html += "<p style='margin-left: 30px;'>R&eacute;f&eacute;rence &#8220;<strong>" +
						         json.id + "</strong>&#8221; inexistante, ";
						html += "Veuillez recommencer.</p>";
						html += '<br class="clear" />';
						$( "#close_ajax_data").css({display: 'block'});
						break;

					case 'success':
						// template ajout effectué
						html = ContenuPopupReussi( json);
						$( "#close_ajax_data").css({display: 'block'});
						if (window.location.pathname == '/cart')
						{
							window.location.assign(window.location.href);
						}
						break;

					case 'choose':
						// template choix
						html = ContenuPopupChoixDecli( json, qte);
						break;

					default:
						// euh... inutilisé
						break;
				}
				// afficher réponse ajax popup ou erreur
				$( divCible +"#ajax_result").html(html);
				CentrerPopup( divCible);

				// mise a jour nombre d'elements du panier
				$('#num_items').load('/ajax.php?action=get_num_items');

			});
		}
	});

	$(".viderpanier").click(function(){
		$.getJSON( '/ajax.php?action=vider', function(json) {
			if (json.vide == true)
				{
					window.location.reload();
				}
		});
	});


	$(".add_input .plus").click(function(){
		var target = $(this).parent().parent().find(".qte_inp");
		var value = parseInt(target.val());
		var multiple = $(this).attr("rel");
		value += 1 * multiple;
		target.val(value);
		return false;
	});
	$(".add_input .minus").click(function(){
		var target = $(this).parent().parent().find(".qte_inp");
		var value = parseInt(target.val());
		var multiple = $(this).attr("rel");
		if (value > 1) {
			value -= 1 * multiple;
			target.val(value);
		}
		return false;
	});
	
	// Autocompleter
	function formatItem(row) {
		return row[0] + "<br /><span>" + row[1] + "</span>";
	}
	function formatResultSearch(row) {
		return row[0].replace(/(<.+?>)/gi, '');
	}
	function formatResultClient(row) {
		return row[0].replace(/(<.+?>)/gi, '');
	}
	function log(event, data, formatted) {
		$("<li>").html( !data ? "No match!" : "Selected: " + formatted).appendTo("#result");
	}
	
	// fonction autoscroll
	{{{

	(function($){
	$.fn.autoscroll = function() {
	jQuery('html,body').animate(
	{
		scrollLeft: this.offset().left,
		scrollTop: this.offset().top
	},
	500
	);
	return this;
	};
	})(jQuery);
	
	}}}
	
	// Identification par popup
	$("#identifiez_vous").overlay({
		/*mask: {
			color: '#fff',
			loadSpeed: 200,
			opacity: 0.5
		},*/
		top: "center",
		left: "center",
		closeOnClick: true,
		closeOnEsc: true
	});
	
	// Formulaire de contact produit
	$("#lien_req_info_catalogue").overlay({
		/*mask: {
			color: '#fff',
			loadSpeed: 200,
			opacity: 0.5
		},*/
		top: "center",
		left: "center",
		close: '#close_req_info_catalogue',
		closeOnClick: true,
		closeOnEsc: true
	});
	
	$("#info_rf").overlay({
		/*mask: {
			color: '#fff',
			loadSpeed: 200,
			opacity: 0.5
		},*/
		left: "center",
		top: "center",
		close: '#close_ajax_data',
		closeOnClick: true,
		closeOnEsc: true,
		onBeforeLoad: function(evt)
		{
			$("#ajax_data > iframe").attr('src', '/rf?mini_disp=1').load(function(evt)
			{
				var h = $(this).contents().height() + 30;
				$(this).attr('height', h + 'px');
			});
		}
	});
	
	$(".add2cart").overlay({
		/*mask: {
			color: '#fff',
			loadSpeed: 200,
			opacity: 0.5
		},*/
		left: "center",
		top: "center",
		close: '#close_ajax_data',
		closeOnClick: false,
		closeOnEsc: false
	});
	
	$(".add2cart").click(function() {
		$("#ajax_data #ajax_result").html('<h2>Ajout...</h2>');
		
		var id = $(this).closest(".product").attr("rel");
		var qte = $('#qte_'+id).val();
		var type = '';
		if ($(this).closest("#purchase_options").attr("rel") == "fo") {
			qte = 1;
			type = "fo";
		}
		var url = '/ajax.php?action=add2cart&item=' + id + '&qte=' + qte + '&type=' + type;
		
		$.getJSON(url, function(json){
			var html = '<h1>Ajout&eacute; au panier</h1>';
			if (json.response == true) {
				html += '<p>';
				html += '<img src="http://images.beauty-tech.fr/catalog/products/small/' + json.id + '.jpg" />';
				html += '<strong>' + json.libelle + '</strong><br />';
				html += 'Quantit&eacute : <strong>' + json.qte + '</strong><br />';
				html += 'Prix : <strong>' + json.prix + ' &euro;</strong><br />';
				html += '<br />';
				html += 'Total commande : <strong>' + json.subtotal + ' &euro;</strong>';
				html += '</p><br class="clear" />';
			}
			else {
				html += "<p>Erreur d'enregistrement dans le panier.</p>";
			}
			
			$("#ajax_data #ajax_result").html(html);
		});
		
		$("#ajax_data").addClass("ajax_response");
		
		$('#num_items').load('/ajax.php?action=get_num_items');
	});
	
	$('.overlay_close').bind("click", false); // Evite l'action du lien
	
	$('#item').autocomplete('/ajax.php?action=search_autocompletion', {
		width : 200,
		cacheLenght : 1,
		formatItem: formatItem,
		formatResult: formatResultSearch
	});
	
	$('#item2').autocomplete('/ajax.php?action=search_autocompletion', {
		width : 200,
		cacheLenght : 1,
		formatItem: formatItem,
		formatResult: formatResultSearch
	});
	
	$('#client_selector').autocomplete('/ajax.php?action=client_autocompletion', {
		width : 200,
		cacheLenght : 1,
		formatItem: formatItem,
		formatResult: formatResultClient
	});
	$("#client_data").result(log).next().click(function() {
		$(this).prev().search();
	});
	
	//prise de commande
	$('#type_liv .envoi').click(function(){
		$('#retrait').hide();
		$('#envoi').show(500);
	});
	$('#type_liv .retrait').click(function(){
		$('#retrait').show(500);
		$('#envoi').hide();
	});
	
	function showMenu()
	{
		$(".s_menu").css("z-index", "9998");
		$(this).find(".s_menu").css("z-index", "9999").show();
		menuShown = true;
	}
	
	$(".ancre_menu").mouseenter(function(eo)
	{
		var showMenuDeleg = delegate( this, showMenu, [] );
		
		window.clearTimeout(toMenu);
		
		toMenu = window.setTimeout(function(){
			showMenuDeleg();
		},
		menuShown ? 200 : 500);
	});
	
	$("#menu_catalog").mouseenter(function(eo)
	{
		window.clearTimeout(toMenuLeave);
	});
	
	$("#menu_catalog").mouseleave(function(eo)
	{
		window.clearTimeout(toMenu);
		
		toMenuLeave = window.setTimeout(function(){
			$(".s_menu").hide();
			menuShown = false;
		},
		500);
	});
	
	$('input.rad_type').change(function(){
		if ($("#rad_type_pro").attr("checked"))
		{
			hiding_rows  = false;
			showing_rows = true;
			
			$('#lignes_info_pro > tr > td > divs').stop(true, true);
			
			chain_show_rows('lignes_info_pro');
		}
		else
		{
			if (confirm("ATTENTION !\nSi vous enregistrez un compte particulier, vous n'aurez PAS DE TVA SUR LES FACTURES.\nAnnulez pour rester en compte professionnel."))
			{
				hiding_rows  = true;
				showing_rows = false;
				
				$('#lignes_info_pro > tr > td > divs').stop(true, true);
				
				chain_hide_rows('lignes_info_pro');
			}
			else
			{
				$("#rad_type_pro").attr("checked", "checked");
			}
			
		}
	});
	
});

