/*
 *
 *	@titre: recette.
 *	@description: javascript recette - Le Veau.
 *	@auteur: neov - http://www.neov.net.
 *	@creation: 20090511.
 *	@modification: -.
 *
*/

// rollover recette.
$.fn.rollrecette = function(o)
{
	o = $.extend (
			{
				doPos: false
			}, o || {}
		);
	
	$(this).each(
		function()
		{
			$(this).hover(
				function()
				{
					if (o.doPos)
						$(this).css({position:'relative', zIndex: 11});
					
					if ($(this).next())
						$(this).next().show();
				},
				function()
				{
					if (o.doPos)
						$(this).css({position:'', zIndex: 0});
					
					if ($(this).next())
						$(this).next().hide();
				}
			);
		}
	);
};

// pagination images.
function pagination(id)
{
	// vars.
	var iRang = chargeRangRecetteVisite();
	var $bloc = id == 0? $('.rrImage') : $('.rrListe'), nbr = $bloc.find('li').length, c = 0, step = 20;
	
	// initialisation des boutons.
	$('.arrow_bottom').find('a').show();
	
	
	// cas ou on a plus de 20 images.
	if (nbr > step) {
	    
	    $bloc.find('li').hide();
	    	    
	    if(iRang >= step) { // recette visitée se trouve aux pages suivantes
            c = parseInt(Math.floor(iRang / step));
	        // afiche le bouton precedent.
    		$('.arrow_bottom').find('a').eq(0).show();
    		
    		if ((step *c) < nbr) {
				var init = step *c;
				c++;
				
				$bloc.find('li').hide();
				
				for(i=init; i<(step*c); i++) {
					$bloc.find('li').eq(i).show();
				}
				
				if((step *c) >= nbr)
					$('.arrow_bottom').find('a').eq(1).hide();
				
			}
    		// attribution des action sur les boutons.
    		$('.arrow_bottom').find('a').eq(1).bind(
    			'click',
    			function()
    			{
    				$('.arrow_bottom').find('a').eq(0).show();
    				if ((step *c) < nbr) {
    					var init = step *c;
    					c++;
    					
    					$bloc.find('li').hide();
    					
    					for(i=init; i<(step*c); i++) {
    						$bloc.find('li').eq(i).show();
    					}
    					
    					if((step *c) >= nbr)
    						$(this).hide();
    					
    				}
    				
    				return false;
    			}			
    		);
    		
    		$('.arrow_bottom').find('a').eq(0).bind(
    			'click',
    			function()
    			{	
    				$('.arrow_bottom').find('a').eq(1).show();
    				
    				if (c > 0) {
    					c--;
    					
    					$bloc.find('li').hide();
    					
    					for(i=(step * (c - 1)); i<(step*c); i++) {
    						$bloc.find('li').eq(i).show();
    					}
    					
    					if(c==1)
    						$(this).hide();
    					
    				}
    				
    				return false;
    			}			
    		);
	    } else { // recette visitée se trouve à la preemiére page
	        // affiche seulement les 20 premieres images.
    		for(i=c; i<step; i++) {
    			$bloc.find('li').eq(i).show();
    		}
    		
    		c++;
    		
    		// cache le bouton precedent.
    		$('.arrow_bottom').find('a').eq(0).hide();
    		
    		// attribution des action sur les boutons.
    		$('.arrow_bottom').find('a').eq(1).bind(
    			'click',
    			function()
    			{
    				$('.arrow_bottom').find('a').eq(0).show();
    				
    				if ((step *c) < nbr) {
    					var init = step *c;
    					c++;
    					
    					$bloc.find('li').hide();
    					
    					for(i=init; i<(step*c); i++) {
    						$bloc.find('li').eq(i).show();
    					}
    					
    					if((step *c) >= nbr)
    						$(this).hide();
    					
    				}
    				
    				return false;
    			}			
    		);
    		
    		$('.arrow_bottom').find('a').eq(0).bind(
    			'click',
    			function()
    			{	
    				$('.arrow_bottom').find('a').eq(1).show();
    				
    				if (c > 0) {
    					c--;
    					
    					$bloc.find('li').hide();
    					
    					for(i=(step * (c - 1)); i<(step*c); i++) {
    						$bloc.find('li').eq(i).show();
    					}
    					
    					if(c==1)
    						$(this).hide();
    					
    				}
    				
    				return false;
    			}			
    		);
	    }
	
	} else {
		
		// cache tous les boutons.
		$('.arrow_bottom').find('a').hide();
		
	}
	
	
};

/**
 * jQuery.fn.sortElements
 * --------------
 * @param Function comparator:
 *   Exactly the same behaviour as [1,2,3].sort(comparator)
 *   
 * @param Function getSortable
 *   A function that should return the element that is
 *   to be sorted. The comparator will run on the
 *   current collection, but you may want the actual
 *   resulting sort to occur on a parent or another
 *   associated element.
 *   
 *   E.g. $('td').sortElements(comparator, function(){
 *      return this.parentNode; 
 *   })
 *   
 *   The <td>'s parent (<tr>) will be sorted instead
 *   of the <td> itself.
 */
jQuery.fn.sortElements = (function(){
 
    var sort = [].sort;
 
    return function(comparator, getSortable) {
 
        getSortable = getSortable || function(){return this;};
 
        var placements = this.map(function(){
 
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,
 
                // Since the element itself will change position, we have
                // to have some way of storing its original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );
 
            return function() {
 
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }
 
                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);
 
            };
 
        });
 
        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });
 
    };
 
})();

var triParTexte = function(a, b){
	var reg=new RegExp("[__]+", "g");
	var tA = ($(a).attr('id')).split(reg);
	var tB = ($(b).attr('id')).split(reg);    
    //return tA[0] > tB[0] ? 1 : -1;
    return parseInt(tA[0], 10) > parseInt(tB[0], 10) ? 1 : -1;
    //return $(a).text() > $(b).text() ? 1 : -1;
};
 
var triParNote = function(a, b){
	var reg=new RegExp("[__]+", "g");
	var tA = ($(a).attr('id')).split(reg);
	var tB = ($(b).attr('id')).split(reg);
    //return parseInt($(a).text(), 10) > parseInt($(b).text(), 10) ? 1 : -1;
    return parseInt(tA[1], 10) > parseInt(tB[1], 10) ? -1 : 1;
}

var giLastTri = 0;
var gbTriImage = true; // image triee ou non
var gbTriListe = true; // liste triee ou non

// type d'affichage, clic sur les boutons radios liste et image
$(
  	function()
	{
		// choix type d'affichage, clic sur les boutons radios liste et images.
		$('input[name=recette]').click(
			function()
			{
				$('.arrow_bottom').find('a').unbind('click');
				if( $(this).val() == 0 ) {					
					// force a checker le bouton.
					this.checked = true;
					
					if(!gbTriListe) {
						giLastTri = parseInt($('#choixTri').val (), 10);
						switch(giLastTri) {
							case 0: // alphabetique
								$('#recetteListe li').sortElements(triParTexte);
								break;
							case 1: // note
								$('#recetteListe li').sortElements(triParNote);						
								break;
						}
						gbTriListe = true;
					}
					
					// affiche ou cache le bloc selectionner.
					$('.rrImage').hide();
					$('.rrListe').show();				
						
					// creation de la pagination
					pagination(1);
					
				} else {					
					// force a checker le bouton.
					this.checked = true;
					
					if(!gbTriImage) {
						giLastTri = parseInt($('#choixTri').val (), 10);
						switch(giLastTri) {
							case 0: // alphabetique
								$('#recetteImage li').sortElements(triParTexte);														
								break;
							case 1: // note
								$('#recetteImage li').sortElements(triParNote);	;						
								break;
						}
						gbTriImage = true;
					}
					
					// affiche ou cache le bloc selectionner.
					$('.rrListe').hide();
					$('.rrImage').show();
					
					// creation de la pagination
					pagination(0);
				}
			}
		);
		
		// selection affichage par defaut 0: liste, 1: image.
		$('input[name=recette]').eq(0).click();
		
		// chargement rollover sur image.
		$('.rrImage li a').rollrecette();
		
		// chargement rollover sur liste.
		$('.rrListe li a').rollrecette({doPos:true});

	}
);


function chargeRangRecetteVisite() {
    var iRang = -1;
    $('.rrImage > li').each(function(index) {
        var img = $(this).children("a").children("img");
        if($(img).eq(1).attr("class") == "r-visite") {
            iRang =  index;
        }
    });
    
    return iRang;
}

function reecritureNomRecette(_zNomRecette) {
    zNomRecette = _zNomRecette.toLowerCase().replace(/\s+/g, "_");
    zNomRecette = str_replace('"', '', zNomRecette);
    zNomRecette = str_replace("'", "", zNomRecette);
   return zNomRecette;
}

function str_replace(search, replace, subject) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/str_replace
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var s = subject;
    var ra = r instanceof Array, sa = s instanceof Array;
    var f = [].concat(search);
    var r = [].concat(replace);
    var i = (s = [].concat(subject)).length;
    var j = 0;
    
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    }

    return sa ? s : s[0];
}

$(
  	function()
	{
		// choix type d'affichage, clic sur les boutons radios liste et images.
		var iRecettesPlusConsultees = $('#recettes_plus_consultees').val();
//		alert(iRecettesPlusConsultees);
		
		$('input[name=recette]').click(
			function()
			{
				if( $(this).val() == 0 ) {					
					// force a checker le bouton.
					this.checked = true;
	
					// affiche ou cache le bloc selectionner.
					$('.rrImage').hide();
					$('.rrListe').show();
					
					// creation de la pagination
					pagination(1);
					
				} else {					
					// force a checker le bouton.
					this.checked = true;
					
					// affiche ou cache le bloc selectionner.
					$('.rrListe').hide();
					$('.rrImage').show();
					
					// creation de la pagination
					pagination(0);
				}
			}
		);
		
		// selection affichage par defaut 0: liste, 1: image.
		var selectAffiche = $('#recetteListe').attr('name');
		if(parseInt(iRecettesPlusConsultees)>0) {
		    selectAffiche = 0;
		}

		$('input[name=recette]').eq(selectAffiche).click();
		
		// chargement rollover sur image.
		$('.rrImage li a').rollrecette();
		
		// chargement rollover sur liste.
		$('.rrListe li a').rollrecette({doPos:true});
		
		// scrollpane
		
		if ($("#ingredientRecette").length != 0) {
			$("#ingredientRecette").jScrollPane({
				showArrows:true, 
				scrollbarWidth: 19, 
				arrowSize: 11, 
				scrollbarMargin: 45
			});
		}
		
		// click bouton note
		$("#note-btn").click(function() {
		    iRecetteId = $("div.recetteListe").attr("id");
		    zRecetteTitre = $("h1.detail-titre").html();
		    var noteVal = $("[name=noteVal]").val();
		    $.post("index.php", {module:"recette", action:"recette:sauvegarderNote", iNote:noteVal, iRecetteId:iRecetteId}, function() {
//		        window.location.href = j_basepath+"index.php?iRecetteId="+iRecetteId+"&module=recette&action=recette:afficheRecette";
		        window.location.href = j_basepath+"index.php/recette/"+iRecetteId+"/"+reecritureNomRecette(zRecetteTitre);
		    }, "json");
		    
		    return false;
		});
		
		// popu notez succes
		$('.pop-notez-succes').click(function() {
		    var imgBlanc = j_basepath+"design/images/content-design/pop-etoile-bl.gif";
		    for(i=0; i<5; i++) {
	            $("img[id=image_"+i+"]").attr({"src":imgBlanc});
	        }
	        $("input[name=noteVal]").val(0);
		});
		
		// initialise la valeur de la notation
		$("#effacer").click(function() {
		    $("input[name=noteVal]").val(0);
		    var imgBlanc = j_basepath+"design/images/content-design/pop-etoile-bl.gif";
		    for(i=0; i<5; i++) {
	            $("img[id=image_"+i+"]").attr({"src":imgBlanc});
	        }
		});
		
		// hover avec coloration image jaune
		$(".vote img").hover(function() {
		    var rang = parseInt($(this).attr("id").split("_")[1]);
		    var val = rang + 1;
		    var imgJaune = j_basepath+"design/images/content-design/pop-etoile-ja.gif";
		    var imgBlanc = j_basepath+"design/images/content-design/pop-etoile-bl.gif";
		    $("input[name=noteVal]").val(val);
		    for(i=0; i<val; i++) {
	            $("img[id=image_"+i+"]").attr({"src":imgJaune});
	        }
	        for(k=i; k<6; k++) {
	            $("img[id=image_"+k+"]").attr({"src":imgBlanc});
	        }
		}/*, function()  {
    		var rang = parseInt($(this).attr("id").split("_")[1]);
		    var val = rang + 1;
		    var imgBlanc = j_basepath+"design/images/content-design/pop-etoile-bl.gif";
		    for(i=0; i<val; i++) {
	            $("img[id=image_"+i+"]").attr({"src":imgBlanc});
	        }
    	}*/);
    	$(".vote img").click(function() {
    	    var rang = parseInt($(this).attr("id").split("_")[1]);
    	    var val = rang + 1;
    	    var imgJaune = j_basepath+"design/images/content-design/pop-etoile-ja.gif";
    	    var imgBlanc = j_basepath+"design/images/content-design/pop-etoile-bl.gif";
    	    
    	    $("input[name=noteVal]").val(val);
    	});

	}
);


