// JavaScript Document

/*
* 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);
        var onchangeSelect = 1;     // 1 si attribut onchange existe
        var longueurTexte; 	        // permet de couper le texte affiché dans le select s'il est plus long que celui-ci
        var longueurTexteMax;       // longueur maximale autorisée

        $(this).each(function() {

            // Verification que l'ensemble du formulaire est correct
            if (!$(this).is('select') && !$(this).is('ul')) {
                $.fn.mSelect.debug('Seul les elements "select" et "ul" sont acceptes : ' + this);
                return;
            }

            // Recherche de l'attribut "name" des elements du formulaire 
            // 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') + '" ';
                if ($(this).attr('onchange')) {
                    var onchangeSelect = 1;
                }
            }
            // Creation du div conteneur general
            $(this).wrap('<div class="mSelect" ' + id + ' style="display:inline-block;" />');
            // Creation du div conteneur de l'option selectionne
            $(this).parent().append('<div class="mFleche"></div><div class="mSelected">' + opts.defaut + '</div><div class="mConteneur"></div>');

            // Creation des options
            if ($(this).is('select')) {

                $(this).children('option').each(function() {

                    // Creation 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 selectionne
                    var attrSelected = '';
                    if ($(this).attr('selected')) {
                        attrSelected = 'checked="checked" ';
                        // Calcul de la longueur du texte pour éventuellement le tronquer
                        longueurTexte = $(this).html().length;
                        longueurTexteMax = ($(this).parent().parent().children('.mSelected').width() - $('.mFleche').width()) / 5.8;
                        if (longueurTexte >= Math.floor(longueurTexteMax)) {
                            var texteSelected = $(this).html().substr(0, Math.floor(longueurTexteMax)) + '...';
                        }
                        else {
                            var texteSelected = $(this).html();
                        }
                        $(this).parent().parent().children('.mSelected').html(texteSelected);
                    }
                    // on ajoute l'option 
                    $(this).parent().parent().children('.mConteneur').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;
                    }
                    // Creation 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 selectionne
                    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().children('.mConteneur').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('.mConteneur').children('.mOption').children('.mRadio').hide();
                $(this).parent().children('.mConteneur').hide();
            }
            // on passe en position 'absolute', on cache et on ajoute un ecouteur au click
            $(this).parent().children('.mConteneur').children('.mOption').css({ cursor: 'pointer' }).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().parent().children('.mSelected').html($(this).html());
                $(this).parent().parent().children('.mSelected').children('.mRadio').remove();

                // on calcule le nombre de caractères pour couper le texte s'il est plus long que son contenu (mSelected)
                longueurTexte = $(this).parent().parent().children('.mSelected').html().length;
                longueurTexteMax = ($(this).parent().parent().children('.mSelected').width() - $('.mFleche').width()) / 5.8;
                if (longueurTexte >= Math.floor(longueurTexteMax)) {
                    texteTronque = $(this).parent().parent().children('.mSelected').html().substr(0, Math.floor(longueurTexteMax)) + '...';
                    $(this).parent().parent().children('.mSelected').html(texteTronque);
                }



                //setTimeout("__doPostBack('" + $(this).attr('id') + "','')", 0);
                if ($(this).parent().parent('div').attr('id') == 'ctl00_CarteRecherche_CarteRecherche1_ListeLieuMR') {
                    __doPostBack('ctl00$CarteRecherche$CarteRecherche1$ListeLieuMR', '');
                    //alert('1');
                }
                if ($(this).parent().parent('div').attr('id') == 'ctl00_CarteRecherche_CarteRecherche1_villeDDL') {
                    __doPostBack('ctl00$CarteRecherche$CarteRecherche1$villeDDL', '');
                    // alert('2');
                }


                if (opts.eventClick) {
                    opts.eventClick.apply(this, [$(this).children('.mRadio').val(), $(this).parent().parent().children('.mSelected').html()]);
                }
            });
            // on ajoute un ecouteur d'evenement 'click' pour afficher 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('.mConteneur').children('.mOption').each(function() {
            $(this).parent('.mConteneur').fadeIn();
            $(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('.mConteneur').children('.mOption').each(function() {
                    $(this).parent('.mConteneur').fadeOut();
                    $(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);
