/* $Id$ */

$.fn.extend({
    /* Select the first option from a select */
    selectFirst: function() {
        var options = new Array();
        $(this).children().each(function() {
            options.push($(this).val());
        });

        var first = undefined;
        for (var k in options) {
            first = options[k];
            break;
        }

        if(first != undefined)
            $(this).selectOptions(first);

        return $(this);
    },

    /* Select the last option from a select */
    selectLast: function() {
        var options = new Array();
        $(this).children().each(function() {
            options.push($(this).val());
        });

        var last = undefined;
        for (var k in options) {
            last = options[k];
        }

        if(last != undefined)
            $(this).selectOptions(last);

        return $(this);
    },

    /* Return the tagname (ie: div, span, ...) */
    tagName: function() {
        return this.get(0).tagName.toLowerCase();
    },

    /* Find the 'id' from a className attribute (ie : class="box 12" => Return 12) */
    findId: function() {
        var regex = new RegExp(/[a-z_] ([0-9]{1,})/i);
        if(regex.exec($(this).attr('className'))[1])
            return regex.exec($(this).attr('className'))[1];
        return false;
    },

    /* Same than findId but like this : (ie : class="box 12-25" => Return 25) */
    findValue: function() {
        var regex = new RegExp(/[a-z_] [0-9]{1,}-([0-9]{1,})/i);
        if(regex.exec($(this).attr('className'))[1])
            return regex.exec($(this).attr('className'))[1];
        return false;
    },

    /* Show the message _html and autohide it after _time seconds */
    showAndHide: function(_html, _time) {
        var time = _time || 5000;
        var el = $(this);
        el.hide();
        el.html(_html).fadeIn();
        setTimeout("el.fadeOut().html(\"\")", time);
    }
});


/* Resizes boxes to the highest one */
(function($) {
    $.fn.alignBoxes = function(settings) {
        var options =  {
            'path': 'div.i3',         // selector per default for boxes
            'height': 0,             // height of boxes
            'height_offset': 0,        // height + offset = height of boxes
            'debug': 0                 // debug
        };
        options = $.extend(options, settings);

        /* Get max height */
        if(options.height == 0) {
            this.each(function() {
                $$ = options.path == '' ? $(this) : $(this).find(options.path);
                $$.each(function() {
                    var height = $(this).height();
                    if (height > options.height) {
                        options.height = height;
                    }
                });
            });
        }

        if(options.debug) {
            alert(options.height);
        }

        /* Set the same height for all box */
        return this.each(function() {
            $$ = options.path == '' ? $(this) : $(this).find(options.path);
            $$.each(function() {
                $(this).height(options.height + options.height_offset);
                return false;
            });
        });
    };
})(jQuery);


/* Highlight une ligne sur 2, ou 2 sur 4 si extraTrs */
(function($) {
    $.fn.highlightEvenTrs = function(settings) {
        var options =  {
            'extraTrs': false, // true if 2 adjacent TRs must be of the same color
            'visible' : false  // keep false if no hidden rows
        };
        options = $.extend(options, settings);

        var visible = options.visible ? ":visible" : "";

        return this.each (function () {
            var cpt = 0;
            $(this).find('tbody tr:not(.nohl)' + visible)
                .removeClass ('odd')
                .removeClass ('even')
                .each (function (i) {
                    cpt = i;
                    if (!options.extraTrs) {
                        if(cpt%2 == 0) {
                            $(this).removeClass('even').addClass('odd');
                        }
                        if(cpt%2 == 1) {
                            $(this).removeClass('odd').addClass('even');
                        }
                    } else {
                        if (cpt % 4 == 1 || cpt % 4 == 0) {
                            $(this).removeClass('even').addClass('odd');
                        }
                        if (cpt % 4 == 2 || cpt % 4 == 3) {
                            $(this).removeClass('odd').addClass('even');
                        }
                    }
                });
            if ($(this).find('tfoot').length) {
                if($(this).find('tbody tr' + visible + ':last').hasClass('even')) {
                    $('tfoot tr').removeClass('even').addClass('odd');
                } else {
                    $('tfoot tr').removeClass('odd').addClass('even');
                }
            }
        });
    }
})(jQuery);


/* Highlight une ligne sur 2, et met l'arrondi du bas de la bonne couleur */
(function($) {
    $.fn.stylise = function(settings) {
        var options =  {
            'extraTrs': false, // true if 2 adjacent TRs must be of the same color
            'visible' : false  // keep false if no hidden rows
        };
        options = $.extend(options, settings);

        var visible = options.visible ? ":visible" : "";

        return this.each (function () {
            $(this).highlightEvenTrs (options);
            $(this).removeClass ('odd').removeClass ('even');
            var classe;
            if ($(this).find('tfoot').length) {
                classe = $(this).find('tfoot tr' + visible + ':last').hasClass('even') ? 'even' : 'odd';
            } else {
                classe = $(this).find('tbody tr' + visible + ':last').hasClass('even') ? 'even' : 'odd';
            }
            $(this).addClass(classe);
        });
    }
})(jQuery);


/* Highlight une ligne sur 2, et met l'arrondi du bas de la bonne couleur */
(function($) {
    $.fn.styliseGTable = function(settings) {
        var options =  {
            'extraTrs': false // true if 2 adjacent TRs must be of the same color
        };
        options = $.extend(options, settings);

        return this.each (function () {
            var table = $(this).highlightEvenTrs(options);
            var div_header = $(this).prev();
            var div_footer = $(this).next();

            if (!table.find('thead').length) {
                div_header.addClass(table.find('tbody tr:first').hasClass('even') ? 'even' : 'odd');
            }

            if (!table.find('tfoot').length) {
                div_footer.addClass(table.find('tbody tr:last').hasClass('even') ? 'even' : 'odd');
            }
        });
    }
})(jQuery);


/* Check or uncheck checkboxes */
(function($) {
    $.fn.toggleCheckboxes = function(settings) {
        var options =  {
            'checked': true //check or uncheck checkboxes
        };
        options = $.extend(options, settings);

        return this.each (function () {
            $(this).attr('checked', options.checked);
        });
    }
})(jQuery);



(function($) {
    // Opera seem to dislike crlf with defaults
    var nocrlf = function(val) {
        return val.replace(/\r?\n/g, '');
    };

    $.fn.focusClearsDefault = function(settings) {
        var options = {
            'class_default' : null,
            'class_changed' : null
        };
        options = $.extend(options, settings);

        return this.each(function() {
            /* Values on load *may* be different from default (Firefox) */
            var val = nocrlf($(this).attr("value"));
            var dval = nocrlf($(this).attr("defaultValue"));

            if ( val == dval ) {
                $(this).removeClass(options.class_changed);
                $(this).addClass(options.class_default);
            } else {
                $(this).removeClass(options.class_default);
                $(this).addClass(options.class_changed);
            }

            // Remove default text on focus (+style)
            $(this).focus(function(ev) {
                // "this" is the event object here (the input)
                if ( nocrlf(this.value) == nocrlf(this.defaultValue) ) {
                    this.value = "";

                    $(this).removeClass(options.class_default);
                    $(this).addClass(options.class_changed);
                } else {
                    // Should already be "not default"
                }
            });

            // Put back default text on blur if empty (+style)
            $(this).blur( function(ev) {
                // "this" is the event object here (the input)
                if ( this.value == "" ) {
                    $(this).addClass(options.class_default);
                    $(this).removeClass(options.class_changed);

                    this.value = this.defaultValue;
                } else {
                    // should already be "not default"
                }
            });

        });
    };
})(jQuery);


/* Transforme un ensemble d'éléments ayant la même classe en reloaders de page */
(function($) {
    $.fn.activateReloaders = function() {
        return this.each (function () {
            $(this).click(function() {
                window.location = window.location;  //cause location.reload() re-submit potential post data
            });
        });
    }
})(jQuery);


/* Soumet le formulaire dans lequel se trouve l'element appelant cette fonction par evenement */
(function($) {
    $.fn.submitFormFromEl = function(e) {
        form = $(this).closest('form');
        if (form) {
            e.preventDefault();
            form.submit();
        }
    }
})(jQuery);


/* Demande une confirmation avant de submit */
(function($) {
    $.fn.setConfirmation = function(settings) {
        var options = {
            'mssg' : 'default_confirmation_mssg'
        };
        options = $.extend(options, settings);

        return this.each (function () {
            $(this).bind('submit', function(e, no_confirmation) {
                if(!no_confirmation) {
                    e.preventDefault();
                    if(confirm(options.mssg)) {
                        $(this).trigger('submit', 1)
                    }
                }
            });
        });
    }
})(jQuery);


/* Ouvre un popup avec le lien de l'élément */
/* Exemple : $('.popup').openPopup({'height' : 'height=640', 'width' : 'width=480'}); */
(function($) {
    $.fn.openPopup = function(settings) {
        var options =  {
            'title': 'Popup', //titre du popup
            'live': false,

            'height': 'height=500',
            'width': 'width=650',
            'top': 'top=100',
            'toolbar': 'toolbar=no',
            'menubar': 'menubar=no',
            'location': 'location=no',
            'resizable': 'resizable=yes',
            'scrollbars': 'scrollbars=yes',
            'status': 'status=no'
        };
        options = $.extend(options, settings);

        var options_list = new Array();
        $.each(options, function(k, v) {
            if(k != 'title' && k != 'live') {
                options_list.push(v);
            }
        });
        var selector = $(this).selector;

        return this.each (function () {
            function bindOpen (e, self) {
                e.preventDefault();
                var w = window.open($(self).attr('href'), options.title, options_list.join(', '));

                if($(self).hasClass('print')) {
                    window.setTimeout(function() {
                        w.print();
                    }, 1000);
                }
            }
            if (options.live) {
                $(selector).live('click', function(e) { bindOpen(e, this); });
            } else {
                $(this).bind('click', function(e) { bindOpen(e, this); });
            }
        });
    }
})(jQuery);


/* Rend cliquable une zone contenant un lien */
(function($) {
    $.fn.makeClickable = function(settings) {
        return this.each (function () {
            if ($(this).find('a').attr('href')) {
                $(this).addClass('clickable');
                $(this).click(function(e) {
                    window.location = $(this).find('a:first').attr('href');
                });
            }
        });
    }
})(jQuery);


/* Check la checkbox sur le onclick d'un tr de tableau */
(function($) {
    $.fn.clickCheckBox = function(settings) {
        var options =  {
            'cancel': ':input,option,a,.tooltipTextContent',//Ne pas cocher si on clique sur un de ces éléments
            'event': 'click',
            'checkbox_selector': 'input[type=checkbox]:enabled',
            'active_class': 'active'
        };
        options = $.extend(options, settings);

        function setHighlight (el) {
            var select = !!$(el).find(options.checkbox_selector).attr('checked');
            $(el).toggleClass(options.active_class, select);
        }

        //Init
        $(this).each(function(i) {
            setHighlight(this);
        });

        //Si clique sur checkbox (pas sur la ligne)
        $(this).find(options.checkbox_selector).live('change', function(e) {
            setHighlight($(this).parents('tr'));
        });

        return $(this).live(options.event, function(e) {
            var elIsCancel = $(e.target).parents().add(e.target).filter(options.cancel).length;
            if (e.button == 0 && !elIsCancel) {
                var checkbox = $(this).find(options.checkbox_selector);
                if(checkbox.length) {
                    if (checkbox.attr('checked')) {
                        checkbox.attr('checked', false);
                        $(this).removeClass(options.active_class);
                    } else {
                        checkbox.attr('checked', true);
                        $(this).addClass(options.active_class);
                    }
                }
            }
        });
    }
})(jQuery);


/* Toggle width fade effect
 *  $(".bio-toggler").click(function () {
 *      $("#bio-form").fadeToggle()
 *  });
 */
jQuery.fn.fadeToggle = function(speed, easing, callback) {
   return this.each (function () {
        $(this).animate({opacity: 'toggle'}, speed, easing, callback);
    });
};


/*
 * Uncomment un block HTML
 */
(function($) {
    $.fn.uncomment = function(recurse) {
        $(this).contents().each(function() {
            if ( recurse && this.hasChildNodes() ) {
                $(this).uncomment(recurse);
            } else if ( this.nodeType == 8 ) {
                // Need to "evaluate" the HTML content,
                // otherwise simple text won't replace
                var ev = $('<span>' + this.nodeValue + '</span>');
                $(this).replaceWith(ev.contents());
            }
        });
    };
})(jQuery);

/* @TODO */

/*
Object.extend( Element, {
    shorten: function(element, text, maximum_size) {
        if ( Element.getWidth(element) < maximum_size ) return;

        // Better be just text or it will mess up badly
        if ( !text ) text = element.innerHTML;

        var len = text.length / 2;
        var set_title = element.title == "";

        // Limit to 60 chars reduction
        for ( var i = 4; i < 60; i++ ) {
            var l = i/2;
            element.innerHTML = text.substr(0, len - l) + "&hellip;" + text.substr(len + l, 2*len);

            if ( Element.getWidth(element) < maximum_size ) {
                if ( set_title ) element.title = text;
                break;
            }
        }
    }
}

*/
