/**
 * @name NiceJForms
 * @description This a jQuery equivalent for Niceforms ( http://badboy.ro/articles/2007-01-30/niceforms/ ).  All the forms are styled with beautiful images as backgrounds and stuff. Enjoy them!
 * @param Hash hash A hash of parameters
 * @option integer selectRightSideWidth width of right side of the select
 * @option integer selectLeftSideWidth width of left side of the select 
 * @option integer selectAreaHeight
 * @option integer selectAreaOPtionsOverlap
 * @option imagesPath folder where custom form images are stored
 * @type jQuery
 * @cat Plugins/Interface/Forms
 * @author Lucian Lature ( lucian.lature@gmail.com ) 
 -------------------- modified by Yannick Lepetit
 * @credits goes to Lucian Slatineanu ( http://www.badboy.ro )
 * @version 0.1
 */

jQuery.NiceJForms = {
    options : {
        selectRightSideWidth     : 28,
        selectLeftSideWidth      : 5,
        selectAreaHeight         : 21,
        selectAreaOptionsOverlap : 2,
        imagesPath               : "/img/niceforms/"
        // other options here
        , buildThem              : true
        , where                    : ''
    },
    
    selectText     : 'please select',
    preloads       : new Array(),
    inputs         : new Array(),
    labels         : new Array(),
    textareas      : new Array(),
    selects        : new Array(),
    radios         : new Array(),
    checkboxes     : new Array(),
    texts          : new Array(),
    buttons        : new Array(),
    radioLabels    : new Array(),
    checkboxLabels : new Array(),
    hasImages      : true,
    /*ajout pour sauvegarder les anciens select -- MSA*/
    selectsOld     : new Array(),
    
    keyPressed : function(event)
    {
        var pressedKey = event.charCode || event.keyCode || -1;
        
        switch (pressedKey)
        {
            case 40: //down
            var fieldId = this.parentNode.parentNode.id.replace(/sarea/g, "");
            var linkNo = 0;
            for(var q = 0; q < selects[fieldId].options.length; q++) {if(selects[fieldId].options[q].selected) {linkNo = q;}}
            ++linkNo;
            if(linkNo >= selects[fieldId].options.length) {linkNo = 0;}
            selectMe(selects[fieldId].id, linkNo, fieldId, null);
            break;
        
        case 38: //up
            var fieldId = this.parentNode.parentNode.id.replace(/sarea/g, "");
            var linkNo = 0;
            for(var q = 0; q < selects[fieldId].options.length; q++) {if(selects[fieldId].options[q].selected) {linkNo = q;}}
            --linkNo;
            if(linkNo < 0) {linkNo = selects[fieldId].options.length - 1;}
            selectMe(selects[fieldId].id, linkNo, fieldId, null);
            break;
        default:
            break;
        }
    },
    
    build : function(options)
    {
        if (options)
            jQuery.extend(jQuery.NiceJForms.options, options);  
            
        if (window.event) {
            jQuery('body',document).bind('keyup', jQuery.NiceJForms.keyPressed);
        } else {
            jQuery(document).bind('keyup', jQuery.NiceJForms.keyPressed);
        }
        
        // test if images are disabled or not
        var testImg = document.createElement('img');
        $(testImg).attr("src", jQuery.NiceJForms.options.imagesPath + "blank.gif").attr("id", "imagineTest");
        jQuery('body').append(testImg);
        
        if(testImg.complete)
        {
            if(testImg.offsetWidth == '1') {jQuery.NiceJForms.hasImages = true;}
            else {jQuery.NiceJForms.hasImages = false;}
        }

        $(testImg).remove();
            
        if(jQuery.NiceJForms.hasImages)
        {
                    if(jQuery.NiceJForms.options.where != '')
                        el = jQuery.NiceJForms.options.where;
                    else
                        el              = jQuery();
                    
                    jQuery.NiceJForms.preloadImages();
                    jQuery.NiceJForms.getElements(el);
                    jQuery.NiceJForms.replaceSelects();
                    
        }   
    },
    
    preloadImages: function()
    {
        jQuery.NiceJForms.preloads = $.preloadImages(jQuery.NiceJForms.options.imagesPath + "input-login.gif", jQuery.NiceJForms.options.imagesPath + "input-ok.gif", 
        jQuery.NiceJForms.options.imagesPath + "input-ok.png", jQuery.NiceJForms.options.imagesPath + "input-search-grey.gif",
        jQuery.NiceJForms.options.imagesPath + "select-bg.gif", jQuery.NiceJForms.options.imagesPath + "select-left.gif", 
        jQuery.NiceJForms.options.imagesPath + "select-right.gif");
    },
    
    getElements: function(elm)
    {
        el = elm ? jQuery(elm) : jQuery(this);
      
        jQuery.NiceJForms.selects = $('select', el);
       
    },
    
    replaceRadios: function()
    {
        
    },
    
    changeRadios: function(who) {
    
    },
    
    rechangeRadios:function(e)  {
        
    },
    
    checkRadios: function(who) {
        
    },
    
    focusRadios: function(who) {
        
    },
    
    blurRadios:function(who) {
        
    },
    
    radioEvent: function(e) {
        
    },
    
    replaceCheckboxes: function () {
        
    },

    rechangeCheckboxes: function(e) {
        
    },

    checkCheckboxes: function(who, action) {
        
    },

    focusCheckboxes: function(who) {
        
    },

    changeCheckboxes: function(e) {
        
    },

    blurCheckboxes: function(who)  {
        
    },
    saveNiceSelects: function()
    {
    el =  jQuery();
    /*   sauvegarde des Anciens Select avant rebuild partiel -- MSA   */
        jQuery.NiceJForms.selectsOld = $('select', el);
    
    }, 
    
    replaceSelectsReload: function()
    {
    /*   dans ce cas on fait le menage sur les anciens select
         On supprime les div generes par nicejforms (le select et les option div) -- MSA  */
            jQuery.NiceJForms.selectsOld.each(function(q){
            $("#sarea" + q).remove(); 
            $("#optionsDiv" + q).remove();            
            });
            /*
            rebuild du form
            */
            jQuery.NiceJForms.build();
            
    },
    replaceSelects: function()
    {
        var self = this;
        
        jQuery.NiceJForms.selects.each(function(q){
            var selectTag = this;
            //create and build div structure
            var selectArea = document.createElement('div');
            var left = document.createElement('div');
            var right = document.createElement('div');
            var center = document.createElement('div');
            var button = document.createElement('a');
            var text = document.createTextNode(jQuery.NiceJForms.selectText);
            var selectWidth = parseInt(this.className.replace(/width_/g, ""));
            /* ajout yanlep - si oublie de la class width_... sur le select ==> bug IE */
            if(isNaN(selectWidth)) {
                selectWidth = 200;
            }
            
            jQuery(center)
                .attr({id:'mySelectText'+q})
                .css({width: selectWidth - 10 + 'px'});
            jQuery(selectArea)
                .attr({id:'sarea'+q})
                .css({
                    width: selectWidth + jQuery.NiceJForms.options.selectRightSideWidth + jQuery.NiceJForms.options.selectLeftSideWidth + 'px'
                })
                .addClass("selectArea");
                
            jQuery(button)
                .css({
                width      : selectWidth + jQuery.NiceJForms.options.selectRightSideWidth + jQuery.NiceJForms.options.selectLeftSideWidth + 'px',
                marginLeft : - selectWidth - jQuery.NiceJForms.options.selectLeftSideWidth + 'px',
                cursor: 'pointer'
                })
                .addClass("selectButton")
                .bind('click', {who:q}, function(e){
                    /* ajout yanlep */
                    if(jQuery(selectTag).attr('disabled')==false)
                        self.showOptions(e);
                    /* fin ajout yanlep */
                 })
                .keydown(jQuery.NiceJForms.keyPressed);
            
            jQuery(left).addClass("left");  
            jQuery(right).addClass("right").append(button); 
            jQuery(center).addClass("center").append(text); 
            
            jQuery(selectArea).append(left).append(right).append(center).insertBefore(this);
            //hide the select field
            $(this).hide();
            //insert select div
            //build & place options div
            var optionsDiv = document.createElement('div');
            selectAreaPos = jQuery.iUtil.getPosition(selectArea);
            
            jQuery(optionsDiv)
                .attr({id:"optionsDiv" + q})
                /* ajout yanlep */
                .attr({referto:this.id})
                /* fin ajout yanlep */
                .css({
                    width : selectWidth + 26 + 'px', 
                    left  : selectAreaPos.x + 'px', 
                    top   : selectAreaPos.y + jQuery.NiceJForms.options.selectAreaHeight - jQuery.NiceJForms.options.selectAreaOptionsOverlap + 'px'
                })
                .addClass("optionsDivInvisible");
                
            /* ajout yanlep pour IE6 qui ne connait pas maxHeight !! */
            if($(jQuery.NiceJForms.selects[q]).children().length > 8)
                jQuery(optionsDiv).css({height:140 + 'px'});
            /* fin ajout yanlep */
            
            var optgroupOption = 0;
            //get select's options and add to options div
            $(jQuery.NiceJForms.selects[q]).children().each(function(w){
            
                /* ajout yanlep lors de l'utilisation de balise optgroup */
                if(jQuery(this)[0].tagName == "OPTGROUP") {
                    var optgroupHolder = document.createElement('p');
                    var optgroupTitle = document.createElement('strong');
                    var optgroupTxt = document.createTextNode(jQuery(this).attr("label"));
                    
                    jQuery(optgroupTitle).append(optgroupTxt);
                    jQuery(optgroupHolder).append(optgroupTitle);
                    jQuery(optionsDiv).append(optgroupHolder);
                    
                    $(this).children().each(function(ww){
                        optgroupOption++;
                        var ogo = optgroupOption;
                        
                        var optionHolder = document.createElement('p');
                        var optionLink = document.createElement('a');
                        var optionTxt = document.createTextNode(jQuery.NiceJForms.selects[q].options[ogo].text);
                        
                        jQuery(optionLink)
                        .attr({href:'#'})
                        .css({cursor:'pointer'})
                        .append(optionTxt)
                        .bind('click', {who: q, id:jQuery.NiceJForms.selects[q].id, option:ww, select:q, group:w}, function(e){
                            self.showOptions(e);
                            self.selectMe(jQuery.NiceJForms.selects[q].id, ww, q, w, null); 
                            
                            // added by flobou to manage onchange event
                            if(jQuery.NiceJForms.selects[q].onchange) {
                                var changeEvent = setTimeout(function(){jQuery.NiceJForms.selects[q].onchange(); clearTimeout(changeEvent)}, 0);
                            }
                                
                            return false;
                        });
                        
                        jQuery(optionHolder).append(optionLink);
                        jQuery(optionsDiv).append(optionHolder);
                        
                        //check for pre-selected items
                        if(jQuery.NiceJForms
                           .selects[q].options[ogo].selected) {self.selectMe($(jQuery.NiceJForms.selects[q]).attr("id"), ww, q, w, null);}
                    });
                }
                else {
                /* fin d'ajout yanlep pour optgroup */
                    var optionHolder = document.createElement('p');
                    var optionLink = document.createElement('a');
                    var optionTxt = document.createTextNode(jQuery.NiceJForms.selects[q].options[w].text);
                    
                    jQuery(optionLink)
                        .attr({href:'#'})
                        .css({cursor:'pointer'})
                        .append(optionTxt)
                        .bind('click', {who: q, id:jQuery.NiceJForms.selects[q].id, option:w, select:q}, function(e){
                            self.showOptions(e);
                            self.selectMe(jQuery.NiceJForms.selects[q].id, w, q, null); 

                            // added by flobou to manage onchange event
                            if(jQuery.NiceJForms.selects[q].onchange) {
                                var changeEvent = setTimeout(function(){jQuery.NiceJForms.selects[q].onchange(); clearTimeout(changeEvent)}, 0);
                            }
                                
                            return false;
                        });
                    
                    jQuery(optionHolder).append(optionLink);
                    jQuery(optionsDiv).append(optionHolder);
                    
                    //check for pre-selected items
                    if(jQuery.NiceJForms
                       .selects[q].options[w].selected) {self.selectMe($(jQuery.NiceJForms.selects[q]).attr("id"), w, q, null);}
                }
            });
            
            jQuery('body').append(optionsDiv);
        });
    },

    selectMe: function(selectFieldId, linkNo, selectNo, groupNo) {
        // modif pour ID ayant un '.'
        //selectField = $('#' + selectFieldId);
        var selectField = null;
        if( selectFieldId.indexOf( "." ) != -1 )
            selectField = jQuery( document.getElementById( selectFieldId ) );
        else
            selectField = $('#' + selectFieldId);
        // fin modif
        
        sFoptions = selectField.children();
        /* ajout yanlep pour les optgroup */
        if(groupNo != null) {
            sFoptions = jQuery(sFoptions[groupNo]).children();
        }
        /* fin ajout yanlep */
        
        selectField.children().each(function(k){
        	//correction EHO : bug dans optgroup
		    if( !sFoptions[ k ] ){
		        return;
		    }
		    //fin correction EHO        
            if(k == linkNo) {sFoptions[k].selected="selected";}
            else {sFoptions[k].selected = "";}
        });
        
        textVar = $("#mySelectText" + selectNo);
        var newText = document.createTextNode($(sFoptions[linkNo]).text());
        textVar.empty().append(newText);
    }, 

    showOptions: function(e) {
        var self = this;
        /* ajout yanlep */
        jQuery('.optionsDivVisible').not("#optionsDiv"+e.data.who).toggleClass("optionsDivVisible").toggleClass("optionsDivInvisible");
        /* fin ajout yanlep */
        $("#optionsDiv"+e.data.who).toggleClass("optionsDivVisible").toggleClass("optionsDivInvisible").mouseout(function(e){self.hideOptions(e);});
    },
    
    hideOptions: function(e) {
        if (!e) var e = window.event;
        var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
        if(((reltg.nodeName != 'A') && (reltg.nodeName != 'DIV')) || ((reltg.nodeName == 'A') && (reltg.className=="selectButton") && (reltg.nodeName != 'DIV'))) {
            this.className = "optionsDivInvisible";
        };
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    },
    
    replaceTexts: function() {
        
    },
    
    replaceTextareas: function() {
        
    },
    
    buttonHovers: function() {
        
    }
}

jQuery.preloadImages = function()
{
    var imgs = new Array();
    for(var i = 0; i<arguments.length; i++)
    {
        imgs[i] = jQuery("<img>").attr("src", arguments[i]);
    }
    
    return imgs;
}

jQuery.iUtil = {
    getPosition : function(e)
    {
        var x = 0;
        var y = 0;
        var restoreStyle = false;
        var es = e.style;
        if (jQuery(e).css('display') == 'none') {
            oldVisibility = es.visibility;
            oldPosition = es.position;
            es.visibility = 'hidden';
            es.display = 'block';
            es.position = 'absolute';
            restoreStyle = true;
        }
        var el = e;
        while (el){
            x += el.offsetLeft + (el.currentStyle && !jQuery.browser.opera ?parseInt(el.currentStyle.borderLeftWidth)||0:0);
            y += el.offsetTop + (el.currentStyle && !jQuery.browser.opera ?parseInt(el.currentStyle.borderTopWidth)||0:0);
            el = el.offsetParent;
        }
        el = e;
        while (el && el.tagName  && el.tagName.toLowerCase() != 'body')
        {
            x -= el.scrollLeft||0;
            y -= el.scrollTop||0;
            el = el.parentNode;
        }
        if (restoreStyle) {
            es.display = 'none';
            es.position = oldPosition;
            es.visibility = oldVisibility;
        }
        return {x:x, y:y};
    },
    getPositionLite : function(el)
    {
        var x = 0, y = 0;
        while(el) {
            x += el.offsetLeft || 0;
            y += el.offsetTop || 0;
            el = el.offsetParent;
        }
        return {x:x, y:y};
    }
};