/*
 * jQuery mSelect Plugin 1.1 (15 avril 2010)
 * requires jQuery v1.4.2 or later
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Auteur : Samuel Mandonnaud <mandonnaud.s gmail com> http://www.le-pret-a-surfer.com
 */

(function($) {
  $.fn.mSelect = function(options) {
		var opts = $.extend({}, $.fn.mSelect.defaults, options);

		$(this).each(function() {

			// Verification que l'ensemble du
			if (!$(this).is('select') && !$(this).is('ul')) {
				$.fn.mSelect.debug('Seul les Ã©lÃ©ments "select" et "ul" sont acceptÃ© : '+this);
				return;
			}

			// Recherche de l'attribut "name" des elements du fomrulaire
			// pour le conserver au moment de l'envoi
			var attrName = '';
			if ($(this).is('select') && $(this).attr('name')) {
				attrName = $(this).attr('name');
			} else if ($(this).children('li').children('input[type=radio]').attr('name')) {
				attrName = $(this).children('li').children('input[type=radio]').attr('name');
			}
			if (attrName == '') {
				attrName = 'mSelect'+Math.random();
			}

			// Recherche de l'id pour le conserver
			var id='';
			if ($(this).attr('id')) {
				var id='id = "'+$(this).attr('id')+'" ';
			}
			// Creation du div conteneur general
			$(this).wrap('<div class="mSelect" '+id+' style="display:inline-block;" />');
			// Creation du div conteneur de l'option selectionnÃ©
			$(this).parent().append('<div class="mFleche"></div><div class="mSelected">'+opts.defaut+'</div>');

			// CrÃ©ation des options
			if ($(this).is('select')) {

				$(this).children('option').each(function() {

					// CrÃ©ation de la valeur soit par l'ancien value soit par le contenu
					var attrValue='';
					if ($(this).attr('value')) {
						attrValue=$(this).attr('value');
					} else {
						attrValue=$(this).html();
					}

					// verification de l'existance de "class" pour la garder
					var attrClass='';
					if ($(this).attr('class')) {
						attrClass=' '+$(this).attr('class');
					}
					// on conserve l'element selectionnÃ©
					var attrSelected='';
					if ($(this).attr('selected')) {
						attrSelected='checked="checked" ';
						$(this).parent().parent().children('.mSelected').html($(this).html());
					}
					// on ajoute l'option
					$(this).parent().parent().append('<div class="mOption'+attrClass+'"><input type="radio" '+attrSelected+'value="'+attrValue+'" class="mRadio" name="'+attrName+'" />'+$(this).html()+'</div>');

				});

			} else {
				$(this).children('li').each(function() {
					// Chaque ligne doit contenir un element input radio
					if (!$(this).children('input[type=radio]')) {
						$.fn.mSelect.debug('Input Radio manquand');
						return;
					}
					// Chaque ligne doit contenir un element label
					if (!$(this).children('label')) {
						$.fn.mSelect.debug('Label manquand');
						return;
					}
					// CrÃ©ation de la valeur soit par l'ancien value soit par le contenu
					var attrValue='';
					if ($(this).children('input[type=radio]').attr('value')) {
						attrValue=$(this).children('input[type=radio]').attr('value');
					} else {
						attrValue=$(this).children('label').text();
					}
					// verification de l'existance de "class" pour la garder
					var attrClass='';
					if ($(this).attr('class')) {
						attrClass=' '+$(this).attr('class');
					}

					// on conserve l'element selectionnÃ©
					var attrSelected='';
					if ($(this).children('input[type=radio]').attr('checked')) {
						attrSelected='checked="checked" ';
						$(this).parent().parent().children('.mSelected').html($(this).children('label').html());
					}

					// on ajoute l'option
					$(this).parent().parent().append('<div class="mOption'+attrClass+'"><input type="radio" '+attrSelected+'value="'+attrValue+'" class="mRadio" name="'+attrName+'" />'+$(this).children('label').html()+'</div>');
				});
			}
			// On cache le champ radio
			if (opts.radioHide) {
				$(this).parent().children('.mOption').children('.mRadio').hide();
			}
			// on passe en position 'absolute', on cache et on ajoute un ecouteur au click
			$(this).parent().children('.mOption').css({cursor:'pointer',position:'absolute'}).hide().click(function() {
				// on enleve tous les checkeds
				$(this).parent().children('.mOption').children('.mRadio').removeAttr('checked');
				// on passe celui en cours en checked
				$(this).children('.mRadio').attr('checked','checked');
				// on copie le contenu
				$(this).parent().children('.mSelected').html($(this).html());
				$(this).parent().children('.mSelected').children('.mRadio').remove();
				if (opts.eventClick) {
					opts.eventClick.apply(this,[$(this).children('.mRadio').val(),$(this).parent().children('.mSelected').html()]);
				}
			});
			// on ajoute un ecouteur d'evenement 'click' pour affichÃ© la liste
			$(this).parent().one('click',function() {
				$.fn.mSelect.clickOuvert(this,opts);
			});
			// on supprime l'ancien element
			$(this).remove();
		});

	};
	$.fn.mSelect.clickOuvert = function(obj,opts) {
		var info=$(obj).position();
		var x=info.left;
		var y=info.top+$(obj).outerHeight();
		var id='';

		$(obj).children('.mOption').each(function() {
			$(this).css({top:y,left:x}).fadeIn();
			y+=$(this).outerHeight();
			if ($(this).children('input')[0].checked) {
				id=$(this).children('input').val();
			}
		});

		if (opts.eventOpen) {
			opts.eventOpen.apply(obj,[id,$(obj).children('.mSelected').html()]);
		}

		$(document).delay(1).queue(function() {
			$(this).clearQueue();
			$(this).one('click',function() {
				var id='';
				$(obj).children('.mOption').each(function() {
					$(this).fadeOut();
					if ($(this).children('input')[0].checked) {
						id=$(this).children('input').val();
					}
				});
				if (opts.eventClose) {
					opts.eventClose.apply(obj,[id,$(obj).children('.mSelected').html()]);
				}
				$(obj).one('click',function() {
					$.fn.mSelect.clickOuvert(this,opts);
				});
			});
		});

	}
	$.fn.mSelect.debug = function(msg) {
		if (window.console && window.console.firebug) {
			console.error('mSelect : '+msg);
		} else {
			alert('mSelect : '+msg);
		}
	};
	$.fn.mSelect.defaults = {
		defaut:'',
		radioHide:true,
		eventClick:null,
		eventOpen:null,
		eventClose:null
	};
})(jQuery);
