﻿/***
* function : Parse Boolean
**/

function afficheContenuDiv(div) 
{ 
	if (!div.html().trim())
	{
				div.css('padding', '0px'); 
	}
}

parseBoolean = function(string) {
	switch (string.toLowerCase()) {
		case "vrai":case "true": case "yes": case "1": return true;
		case "faux":case "false": case "no": case "0": case "": case null: return false;
		default: return Boolean(string);
	}
};

debug = function (message, sans_popup) {
	if (typeof(console) != 'undefined') {
		console.log(message);
	} else if (typeof(sans_popup) == 'undefined') {
		window.alert(message);
	}
};

round = function (valeur, nb_chiffre) {
	var retour = Math.round(valeur * Math.pow(10, nb_chiffre)) / Math.pow(10, nb_chiffre);
	var tab = retour.toString().split(".");
	if (nb_chiffre > 0) {
		var ecart = nb_chiffre;
		if (tab[1]) {
			ecart -= tab[1].length
		} else {
			retour += ".";
		}
		
		for (i = ecart ; i > 0 ; i--) {
			retour += "0";
		}
	}
	return retour.toString().replace(".", ",");
};

countChecked = function () {
	var n = $("input:checked").length;
	//alert(n);
	var checkwomen = $("input[name*='ep0cbnl_women']");
	var checkmen = $("input[name*='ep0cbnl_men']");
	var nlvalid = $("input[name*='ep0itnl_valid']");
	if ((checkwomen.attr("checked") == true) || (checkmen.attr("checked") == true)) {
		nlvalid.attr("value", 1);
	}
	else {
		nlvalid.attr("value", 0);
	}
}

cacherSelectSousDiv = function (div) {
	if (navigator.appVersion.indexOf('MSIE 6.0') > 0) {
		// Récuperation des valeurs liés à notre div
		var largeur = div.innerHeight();
		var hauteur = div.innerWidth();
		var position = div.offset();
		
		var taille = new Array(position.top, position.left, (position.top + hauteur), (position.top + largeur));
		// On cherche tous les selects
		$('select').each( function () {
			position_select = $(this).offset()
			if ((position_select.top >= taille[0]) && (position_select.top <= taille[2])) {
				if ((position_select.left >= taille[1]) && (position_select.left <= taille[3])) {
					$(this).addClass('cachebydiv');
				}
			}
		});
	}
};

montrerSelectSousDiv = function (div) {
	if (navigator.appVersion.indexOf('MSIE 6.0')) $('.cachebydiv').removeClass('cachebydiv');
};

strrev = function (str) {
  return str.split("").reverse().join("");
};

/***
* jQuery Plugin – scroll
* author: Samuel GUINÉ
**/
(function($) {
	jQuery.fn.scroll = function() {
		return this.each(function() {
			$('html, body').animate({ scrollTop: $(this).offset().top });
		});
	};
})(jQuery);

/***
* jQuery Plugin – OpenPopup
* author: Samuel GUINÉ
**/
(function($) {
	jQuery.fn.OpenPopup = function(name, width, height) {
		return this.each(function() {
			$(this).click(open);
		});
		function open() {
			var params = $.format("width={0},height={1},resizable=0,toolbar=0,scrollbars=0,status=0,menubar=0", width, height);
			window.open($(this).attr("href"), name, params);
			return false;
		}
	};
})(jQuery);

/***
* jQuery Plugin – clickServer
* author: Samuel GUINÉ
**/
(function($) {
	jQuery.fn.clickServer = function() {
		return this.each(function() {
			$(this).click(eventHref).click();
		});
		function eventHref(ev) {
			if (!ev.isDefaultPrevented()) {
				$(location).attr("href", this.href);
			}
		}
	};
})(jQuery);

/***
* jQuery Plugin – keyPressEnter
* author: Samuel GUINÉ
* Ex : $("#checkout_register INPUT").keyPressEnter("A[id$='submitregister']");
**/
(function($) {
	jQuery.fn.keyPressEnter = function(submit) {
		var $submit = $(submit).eq(0);
		if (!$submit.length) {
			return this;
		}
		return this.each(function() {
			//Make sure we're dealing with text-based form fields
			if (this.type != "text" && this.type != "password" && this.type != "textarea")
				return;
			$(this).keypress(keyPressEnter);
		});
		function keyPressEnter(ev) {
			if (ev.which == 13) {
				$(this).blur(); //Blur to execute action like hidden_login
				$submit.unbind('click.keyPressEnter').bind('click.keyPressEnter', eventHref).click();
				return false;
			}
			return true;
		}
		function eventHref(ev) {
			if (!ev.isDefaultPrevented()) {
				$(location).attr("href", this.href);
			}
		}
	};
})(jQuery);

/***
* jQuery Plugin – ToggleImage
* author: Samuel GUINÉ
* Ex : $("IMG.imgtog]").ToggleImage();
**/
(function($) {
	jQuery.fn.ToggleImage = function() {
		return this.each(function() {
			var imageOnMouseOver = function() {
				var newsrc = $(this).attr("src").replace("_OFF.", "_ON.");
				$(this).attr("src", newsrc);
			};
			var imageOnMouseOut = function() {
				var newsrc = $(this).attr("src").replace("_ON.", "_OFF.");
				$(this).attr("src", newsrc);
			};
			var $this = $(this);
			if ($this.attr("src").indexOf("_OFF." > -1)) {
				$this.mouseover(imageOnMouseOver).mouseout(imageOnMouseOut);
			}
		});
	};
})(jQuery);

/***
* jQuery Plugin – Form Field Default Value
* Ex : $("#myfield").DefaultValue("My Default Value..");
**/
(function($) {
	jQuery.fn.DefaultValue = function(text) {
		var $this = $(this);
		return this.each(function() {
			//Make sure we're dealing with text-based form fields
			if (this.type != "text" && this.type != "password" && this.type != "textarea")
				return;
			setValue(); //Set value initially if none are specified
			$this.focus(removeValue).blur(setValue);
			//Remove field values that are still default on form submit
			$("form").submit(removeValue);
		});
		function removeValue() {
			if ($this.val() == text || $this.val() == "") {
				$this.val("");
			}
		}
		function setValue() {
			if ($this.val() == text || $this.val() == "") {
				$this.val(text);
			}
		}
	};
})(jQuery);

/***
* jQuery Function - Format
* Info : Replaces {n} placeholders with arguments.
* Ex: $.format("Hello {0}, this is {1}","Joe","Sam");
**/
(function(jQuery) {
	jQuery.format = function(source, params) {
		if (arguments.length == 1)
			return function() {
				var args = jQuery.makeArray(arguments);
				args.unshift(source);
				return jQuery.validator.format.apply(this, args);
			};
		if (arguments.length > 2 && params.constructor != Array) {
			params = jQuery.makeArray(arguments).slice(1);
		}
		if (params.constructor != Array) {
			params = [params];
		}
		jQuery.each(params, function(i, n) {
			source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
		});
		return source;
	};
})(jQuery);

/***
* jQuery Plugin – Quick Paginate
* EX : $(".body_content_item").quickpaginate({ pager: $("#body_paging"), seealltext: loc.paging.seeall, countertext: loc.paging.counter });
**/
(function($) {

	jQuery.fn.quickpaginate = function(settings) {

		settings = jQuery.extend({
			perpage: 10,
			countertext: "Results <span class=\"blue_search\">{0}</span>",
			seealltext: "see all",
			//spacernth: "3n+1",
			spacernth: "3",
			spacerclass: "body_content_item_spacer",
			pager: null,
			lineperpage: 6
		}, settings);
		
		var allItems = $(this);
		var nb_lignes_par_page = settings.lineperpage;
		var nb_max_par_ligne = settings.spacernth;
		var nb_total_pages = 0;
			
		var init = function () {
			$('.separation_paging').hide();
			formatagePage();
			affichagePage(1);
		};
		
		var formatagePage = function () {
			var compteur_element = 0; /* Le premier espace sur le 4eme */
			var compteur_ligne = 0;
			var compteur_page = 0;
			var titre_tampon = $('<span></span>');
			var debut_de_page = true;
			
			
			allItems.each(function (numero) {
				// On ajoute une classe spécifique à tous les éléments
				$(this).addClass('element_paging_courant');

				// Element
				if ( $(this).hasClass('body_content_item') ) {
					// Si début de page sur un élément, on copie le titre d'avant
					if ( debut_de_page ) {
						$(this).before(titre_tampon);
						$(this).prev().addClass('element_paging_courant');
						debut_de_page = false;
					}
					
					// Entraine un sant de ligne : max nb éléments par ligne ou nouvelle catégorie
					if ( (++compteur_element == nb_max_par_ligne) || ($(this).next().hasClass('body_category_subtitle')) ) {
						compteur_element = 0; /* Les autres 3 par 3 */
						compteur_ligne++;
						$(this).after('<div class="clear_both"></div>');
						$(this).next().addClass('element_paging_courant');
					}
	
				// Titre
				} else if ( $(this).hasClass('body_category_subtitle') ) {
					// Si début de page sur un titre, on oublie celui d'avant
					debut_de_page = false;
					
					// Le titre doit être répété sur la page suivante la catégorie est coupée
					titre_tampon = $(this).clone();
				}
				
		
				// Fin de page
				if (compteur_ligne == nb_lignes_par_page) {
					compteur_ligne = 0;
					compteur_page++;
					$('.element_paging_courant').wrapAll('<div class="conteneur_page" id="conteneur_page_' + compteur_page + '"></div>');
					// On enlève les classes pour la page suivante
					$('.element_paging_courant').removeClass('element_paging_courant');
					debut_de_page = true;
				}
			});
			
			// Traitement du reliquat comme dernière page
			if ( $('.element_paging_courant').size() ) {
				compteur_page++;
				$('.element_paging_courant').wrapAll('<div class="conteneur_page" id="conteneur_page_' + compteur_page + '"></div>');
				$('.element_paging_courant').removeClass('element_paging_courant'); // On enlève les classes pour la page suivante
			}
	
			nb_total_pages = compteur_page;
		};
		
		affichagePage = function (page_courante) {
			$('.conteneur_page').hide(); // On cache toutes les pages
			$('#conteneur_page_' + page_courante).show();
			if (nb_total_pages > 1) {
				affichagePaging(page_courante);
				$('.separation_paging').show();
			}
		};
		
		affichagePaging = function (page_courante) {
			$(settings.pager).find('#paging_bloc').remove('');
			var nb_elements_total = allItems.filter('.body_content_item').size();
			var nb_elements_passes = 0;
			$('.conteneur_page').each( function () {
				if ( $(this).attr('id').replace('conteneur_page_', '') < page_courante ) {
					nb_elements_passes += $(this).children('.body_content_item').size();
				}
			});
			var nb_elements_page_courante = $('#conteneur_page_' + page_courante).children('.body_content_item').size();
			var texte_paging = '<span id="paging_bloc"><span id="pagecounter">R&eacute;sultats <span id="pagingcurpage"><span class="blue_search">' + (nb_elements_passes + 1) + '-' + (nb_elements_passes + nb_elements_page_courante) + '</span></span> sur <span class="total_items">' + nb_elements_total + '</span></span><span class="paging"><span class="separator_alone"> | </span> Pages ' + showPrev(page_courante);
			for (i = 0; i < nb_total_pages; i++) {
				if( i ){
					texte_paging += ' - ';
				}
				texte_paging += ' <a id="pagingpage' + (i + 1) + '" class="sort_page_link_search" href="#">' + (i + 1) + '</a>';
			}
			texte_paging += '</span>' + showNext(page_courante) + '</span>';		
			$(settings.pager).append($(texte_paging));
			// Page courante en couleur
			settings.pager.find("a[id='pagingpage" + page_courante + "']").addClass("selected_sort_page_link");
			// Evenement sur les numéros de page et les flèches
			settings.pager.find("a[id^='pagingpage'], a[id^=page_prev_], a[id^=page_next_]").click(function () {
				var page = parseInt($(this).attr('id').replace(/[^\d]/gi, ''));
				affichagePage(page);
			});
		};
		
		var showPrev = function (page) {
			retour = '';
			if (page > 1) {
				retour = '<span class="page_separator"> | </span> <a href="#" id="page_prev_' + (page - 1) + '"> <img src="../img/common/prev_page.gif" border="0" alt="Préc">Préc </a>';
			}
			return retour;
		};
		var showNext = function (page) {
			retour = '';
			if (page < nb_total_pages) {
				retour = '<span class="page_separator"> | </span> <a href="#" id="page_next_' + (page + 1) + '"> Suite<img src="../img/common/next_page.gif" border="0" alt="Suite"></a>';
			}
			return retour;
		};

		init(); // run the function
		return this; //Don't break the chain
	};
	
})(jQuery);

/***
* Supporting jQuery’s form.submit() in ASP.Net
**/
(function(jQuery) {
	jQuery(document).ready(function() {
		if (typeof (theForm) != "undefined") {
			window.isSubmit = false;
			window.__doPostBack = function(eventTarget, eventArgument) {
				var originalvalues = [theForm.__EVENTTARGET.value, theForm.__EVENTARGUMENT.value];
				theForm.__EVENTTARGET.value = eventTarget;
				theForm.__EVENTARGUMENT.value = eventArgument;
				try {
					$(theForm).submit();
				}
				finally {
					theForm.__EVENTTARGET.value = originalvalues[0];
					theForm.__EVENTARGUMENT.value = originalvalues[1];
				}
			};
			isAlreadySubmit = function() {
				if (window.isSubmit)
					return false;
				window.isSubmit = true;
				return true;
			};
			jQuery(theForm).submit(isAlreadySubmit);
		}
	});
})(jQuery);

/***
* jQuery Plugin – serializeElement
**/
(function($) {
	jQuery.fn.serializeElement = function() {
		var $this = $(this);
		$("body").append('<form id="form-to-submit" style="display:none;"></form>');
		var $form = $("#form-to-submit");
		$form.html($this.clone()); //use .clone(true) with jQuery 1.4
		//Set Value for Chrome and Firefox : remove with jQuery 1.4
		$this.find("select,textarea,input[type=text],input[type=hidden],input[type=password]").each(function(i, e) {
			$form.find("select,textarea,input[type=text],input[type=hidden],input[type=password]").eq(i).val($(e).val());
		});
		$this.find("input[type=checkbox],input[type=radio]").each(function(i, e) {
			$form.find("input[type=checkbox],input[type=radio]").eq(i).attr("checked", $(e).attr("checked"));
		});
		var data = $form.serialize();
		$form.remove();
		return data;
	};
})(jQuery);

/***
* jQuery Plugin – CopyValueTo
**/
(function($) {
	jQuery.fn.CopyValueTo = function(selector) {
		var $to = $(selector);
		return this.find("INPUT,SELECT").each(function() {
			var $this = $(this);
			var val = $this.val();
			var names = $this.attr("name").split("$");
			var name = names[names.length - 1];
			$to.find("INPUT,SELECT").filter("[name$=" + name + "]").val(val);
		});
	};
})(jQuery);
