/**
 * Namespace web application of the youbridge.com copyright : 2009-2011 (c)
 * Matwal, France.
 * 
 * important : 
 * use the librairie php.default.js (http://phpjs.org)
 */

var isset = function( pVariable )
{
    return ( typeof pVariable != 'undefined' );
};

var yb2ns = ( function()
{
    var nsPublic = {}; // public access of this namespace
    nsPublic.utils = {};
    nsPublic.utils.form = {};
    nsPublic.utils.bind = {};
    nsPublic.utils.msg = {};
    nsPublic.utils.view = {};
    
    var nsStateInitialized = false;
    var nsTimeoutAutoAction;
    
    var INFO = {
        VERSION: '2.2.0',
        AUTHOR: 'Frederic ISRAEL (Matwal), Francois HUCLIEZ (Matwal)',
        DATECREATION: '2011-04-28 10:00:00',
        DATEMODIFICATION: '2011-06-02 15:00:00',
        COPYRIGHT: '2011 (c) Matwal, France'
    };
    
    nsPublic.debug = false;
    
    /**
     * Internal log for this namespace
     * set $.fn.ajaxSubmit.debug to true to enable debug logging
     */
    var log = function()
    {
        if ( yb2ns.debug )
        {
            var msg = '[yb2ns] ' + Array.prototype.join.call( arguments, '' );
            if ( window.console && window.console.log )
                window.console.log( msg );
            else if ( window.opera && window.opera.postError ) window.opera.postError( msg );
        }
    };
    
    /**
     * External log for this namespace
     */
    nsPublic.log = function()
    {
        log( Array.prototype.join.call( arguments, '' ) );
    };
    
    /**
     * Initialize this name space
     */
    nsPublic.fInitialize = function( pOptions )
    {
        if ( !nsStateInitialized )
        {
            log( 'initialisation yb2ns : start' );
            
            nsStateInitialized = true;
            
            log( 'initialisation yb2ns : end' );
        }
    };
    
    var qtstyledefault = {
        classes: 'ui-tooltip-plain ui-tooltip-rounded ui-tooltip-shadow'
    };
    
    var qtpositiontop = {
        my: 'bottom center',
        at: 'top center'
    };
    
    var qtpositionleft = {
        my: 'right center',
        at: 'left center'
    };
    
    var qtpositionright = {
        my: 'left center',
        at: 'right center'
    };
    
    var qtpositiondefault = qtpositionleft;
    
    nsPublic.fQtipsStyleDefault = function()
    {
        return qtstyledefault;
    };
    
    nsPublic.fQtipsPositionDefault = function()
    {
        return qtpositiondefault;
    };
    
    nsPublic.fQtipsPositionLeft = function()
    {
        return qtpositionleft;
    };
    
    nsPublic.fQtipsPositionRight = function()
    {
        return qtpositionright;
    };
    
    nsPublic.fQtipsPositionTop = function()
    {
        return qtpositiontop;
    };
    
    /**
     * goto the URL
     */
    nsPublic.fGoUrl = function( pUrl )
    {
        window.location.replace( pUrl );
    };
    
    /**
     * Return the waiting template (html code)
     */
    nsPublic.fGetWaitViewPageHtml = function( pWaitMsg )
    {
        return '<p>&nbsp;</p><img src="/images/v3/_globals/gui-2.0.0/im_ajax_loader_32x32.gif" alt=""/><br/><p><br/>' + pWaitMsg + '.</p><br/><p>&nbsp;</p>';
        //return '<p>&nbsp;</p><img src="/images/v3/_globals/gui-2.0.0/im_ajax_loader_32x32.gif" alt=""/><br/><p><strong>' + pWaitMsg + '</strong></p><p style="font-size: 10px">Ne rechargez pas la page <br/>... à moins d\'un délai supérieur à 1 ou 2 minutes.</p>';
    };
    
    /**
     * Show the wait view, use for waiting the ajax loading view
     */
    nsPublic.fWaitViewPage = function( pTargetTag, pWaitMsg )
    {
        $( pTargetTag ).html( '<div style="text-align:center;"><p>&nbsp;</p><br/><img src="/images/v3/_globals/gui-2.0.0/im_ajax_loader_32x32.gif" alt=""/><br/><p><br/><br/>' + pWaitMsg + '.</p></div>' );
    };
    
    nsPublic.fDialogWaitView = function( pTargetTag, pWaitMsg, pWidth )
    {
        var waitMsg = pWaitMsg || 'Chargement en cours...';
        var widthMsg = pWidth || 300;
        
        return '<div id="' + pTargetTag + '" class="yb-wizard"><div style="width: ' + widthMsg + 'px; text-align:center;"><p>&nbsp;</p><br/><img src="/images/v3/_globals/gui-2.0.0/im_ajax_loader_32x32.gif" alt=""/><br/><p><br/><br/>' + waitMsg + '.<br/><br/></p></div></div>';
    };
    
    /**
     * Show the wait view, use for waiting the ajax loading view
     */
    nsPublic.fWaitViewBlock = function( pTargetTag, pWaitMsg, pEnableFlag, pWidthMessage )
    {
        if ( pEnableFlag )
        {
            pWidthMessage = pWidthMessage || '80%';
            var myWaitMsg = pWaitMsg || 'Veuillez patienter...';
            
            $( pTargetTag ).block( {
                fadeIn: 0,
                fadeOut: 0,
                css: {
                    top: '20%',
                    border: '0px',
                    backgroundColor: '#FFFFFFFF',
                    width: pWidthMessage
                },
                overlayCSS: {
                    backgroundColor: '#E1ECEF',
                    opacity: 0.8
                },
                message: nsPublic.fGetWaitViewPageHtml( pWaitMsg )
            } );
        }
        else
        {
            $( pTargetTag ).unblock();
        }
    };
    
    /**
     * Disable wait view block
     * 
     * @param pTargetTag
     * @param pWaitMsg
     */
    nsPublic.fWaitViewBlockEnable = function( pTargetTag, pWaitMsg )
    {
        nsPublic.fWaitViewBlock( pTargetTag, pWaitMsg, true );
    };
    
    /**
     * Enable wait view block
     * 
     * @param pTargetTag
     */
    nsPublic.fWaitViewBlockDisable = function( pTargetTag )
    {
        nsPublic.fWaitViewBlock( pTargetTag, '', false );
    };
    
    /** not used
     * Show the wait line, use for waiting the ajax submit by button.
     * 
     * @param pTargetTag
     * @param pWaitMsg
     */
    nsPublic.fWaitViewLine = function( pTargetTag, pWaitMsg )
    {
        if ( !isset( pWaitMsg ) ) pWaitMsg = '';
        $( pTargetTag ).html( '&nbsp;<img src="/images/v3/_globals/gui-2.0.0/im_ajax_loader_32x32.gif" alt=""/>&nbsp;&nbsp;&nbsp;&nbsp;' + pWaitMsg );
    };
    
    /**
     * Install a error message into the view
     * 
     * @param pTargetTag
     * @param pErrorMsg
     */
    nsPublic.fErrorViewPage = function( pTargetTag, pErrorMsg )
    {
        $( pTargetTag ).html( '<div class="ui-state-error ui-corner-all ui-yb-form-error-alert"><p><span><strong>ATTENTION</strong></span></p><p class="ui-yb-form-error-alert-message">' + pErrorMsg + '</p></div>' );
    };
    
    /**
     * Loading the ajax view with not waiting view
     * 
     * @param pTargetTag
     * @param pUrl
     */
    nsPublic.fLoadViewNoWaiting = function( pTargetTag, pUrl )
    {
        //this.fWaitViewPage( pTargetTag, 'Chargement en cours...' );
        $.ajax( {
            url: pUrl,
            type: 'GET',
            cache: false,
            error: function( pXMLHttpRequest, pTextStatus, pErrorThrown )
            {
                nsPublic.fErrorViewPage( pTargetTag, 'Erreur lors du chargement.' );
            }
        } );
    };
    
    /**
     * Loading the ajax view with a waiting view
     * 
     * @param pTargetTag
     * @param pUrl
     */
    nsPublic.fLoadView = function( pTargetTag, pUrl )
    {
        this.fWaitViewPage( pTargetTag, 'Chargement en cours...' );
        $.ajax( {
            url: pUrl,
            type: 'GET',
            cache: false,
            error: function( pXMLHttpRequest, pTextStatus, pErrorThrown )
            {
                nsPublic.fErrorViewPage( pTargetTag, 'Erreur lors du chargement.' );
            }
        } );
    };
    
    /**
     * Loading the ajax view with a waiting view
     * 
     * @param pTargetTag
     * @param pUrl
     */
    nsPublic.fLoadViewBlock = function( pTargetTag, pUrl )
    {
        this.fWaitViewBlockEnable( pTargetTag, 'Chargement en cours...' );
        $.ajax( {
            url: pUrl,
            type: 'GET',
            cache: false,
            error: function( pXMLHttpRequest, pTextStatus, pErrorThrown )
            {
                nsPublic.fErrorViewPage( pTargetTag, 'Erreur lors du chargement.' );
            },
            complete: function()
            {
                nsPublic.fWaitViewBlockDisable( pTargetTag );
            }
        } );
    };
    
    /**
     * Open a dialog with the loading
     * 
     * @param pTargetTag
     * @param pUrl
     */
    nsPublic.fOpenDialog = function( pTargetTag, pUrl )
    {
        // waiting message
        this.fWaitViewPage( pTargetTag, 'Chargement en cours...' );
        // show dialog
        $( pTargetTag ).dialog( 'open' );
        // load the form with the cache to false for IE
        $.ajax( {
            url: pUrl,
            type: 'GET',
            cache: false,
            error: function( pXMLHttpRequest, pTextStatus, pErrorThrown )
            {
                nsPublic.fErrorViewPage( pTargetTag, 'Erreur lors du chargement.' );
            }
        } );
    };
    
    // ************************
    // * Use into dialog form *
    // ************************
    
    nsPublic.fSetInstallFormField = function( pFormName )
    {
        $( pFormName + ' [help]' ).qtip( {
            content: {
                text: function( api )
                {
                    return $( this ).attr( 'help' );
                }
            },
            position: nsPublic.fQtipsPositionDefault(),
            style: nsPublic.fQtipsStyleDefault()
        } );
    };
    
    nsPublic.fSetErrorFormFieldAllReset = function( pFormName )
    {
        $( pFormName + ' .ui-widget-content' ).removeClass( 'ui-state-error' );
        
        // old class to remove after complete cleaning
        $( pFormName + ' .ui-yb-form-error' ).each( function()
        {
            $( this ).html( "" );
            $( this ).hide();
        } );
        
        // new class (for popins)
        $( pFormName + ' .yb-wizard-form-error' ).each( function()
        {
            $( this ).html( "" );
            $( this ).hide();
        } );
        
        // new class (for classic pages)
        $( pFormName + ' .form-field-error' ).each( function()
        {
            $( this ).html( "" );
            $( this ).hide();
        } );
    };
    
    nsPublic.fSetErrorFormField = function( pFieldName, pMessage )
    {
        var nameField = pFieldName;
        $( nameField + " .ui-widget-content" ).addClass( 'ui-state-error' );
        
        $( nameField + " .ui-yb-form-error" ).each( function()
        {
            $( this ).html( pMessage );
            $( this ).show();
        } );
        
        // new class (for popins)
        $( nameField + " .yb-wizard-form-error" ).each( function()
        {
            $( this ).html( pMessage );
            $( this ).show();
        } );
        
        // new class (for classic pages)
        $( nameField + " .form-field-error" ).each( function()
        {
            $( this ).html( pMessage );
            $( this ).show();
        } );
    };
    
    // **********************
    // * Use into page form *
    // **********************
    
    nsPublic.fSetFormFieldError = function( pFieldName, pMessage )
    {
        $( pFieldName + ' .ui-widget-content' ).addClass( 'ui-state-error' );
        
        var tmpObj = $( pFieldName );
        
        tmpObj.qtip( 'destroy' );
        tmpObj.qtip( {
            content: {
                text: pMessage
            },
            position: nsPublic.fQtipsPositionDefault(),
            style: yb2ns.fQtipsStyleDefault()
        } );
    };
    
    nsPublic.fSetFormFieldInstall = function( pFormName )
    {
        $( pFormName + ' *[id][help]' ).qtip( {
            content: {
                text: function( api )
                {
                    return $( this ).attr( 'help' );
                }
            },
            position: nsPublic.fQtipsPositionDefault(),
            style: yb2ns.fQtipsStyleDefault()
        } );
    };
    
    nsPublic.fSetFormFieldReset = function( pFormName )
    {
        $( pFormName + ' *[id][help]' ).qtip( 'destroy' );
        $( pFormName + ' *[id][help]' ).qtip( {
            content: {
                text: function( api )
                {
                    return $( this ).attr( 'help' );
                }
            },
            position: nsPublic.fQtipsPositionDefault(),
            style: yb2ns.fQtipsStyleDefault()
        } );
        
        $( '.ui-widget-content' ).removeClass( 'ui-state-error' );
    };
    
    /**
     * Install the qtips
     * 
     * @param pQtSelector
     * @param pQtFilter
     * @param pQtPosition
     * @param pQtStyle
     */
    nsPublic.fInstallQtips = function( pQtSelector, pQtFilter, pQtPosition, pQtStyle )
    {
        var qtFilter = pQtFilter || 'helpid';
        var qtPosition = pQtPosition || yb2ns.fQtipsPositionDefault();
        var qtStyle = pQtStyle || yb2ns.fQtipsStyleDefault();
        var jqSelector = pQtSelector + ' *[' + qtFilter + ']';
        
        $( jqSelector ).qtip( {
            content: {
                text: function( api )
                {
                    return $( this ).attr( qtFilter );
                }
            },
            position: qtPosition,
            style: qtStyle
        } );
    };
    
    nsPublic.fInstallQtipsWithTitle = function( pQtSelector, pQtFilter, pQtFilterTitle, pQtPosition, pQtStyle )
    {
        var qtFilter = pQtFilter || 'helpid';
        var qtFilterTitle = pQtFilterTitle || 'helptitle';
        var qtPosition = pQtPosition || yb2ns.fQtipsPositionDefault();
        var qtStyle = pQtStyle || yb2ns.fQtipsStyleDefault();
        var jqSelector = pQtSelector + ' *[' + qtFilter + ']';
        
        $( jqSelector ).qtip( {
            content: {
                text: function( api )
                {
                    return $( this ).attr( qtFilter );
                },
                title: function( api )
                {
                    return $( this ).attr( qtFilterTitle );
                }
            },
            position: qtPosition,
            style: qtStyle
        } );
    };
    
    /**
     * Uninstall qtips
     * 
     * @param pJqXpath
     */
    nsPublic.fUninstallTips = function( pJqXpath )
    {
        $( pJqXpath ).qtip( 'destroy' );
    };
    
    /**
     * BOXS
     */
    nsPublic.fBoxCreateDialog = function( pTargetTag, pTitle, pUrl )
    {
        return nsPublic.fBoxCreateDialogWithCloseHandler( pTargetTag, pTitle, pUrl );
    };
    
    nsPublic.fBoxCreateDialogWithCloseHandler = function( pTargetTag, pTitle, pUrl, pCloseHandler, pDefaultWidth )
    {
        var curX = null;
        var curY = 60;
        var curTitle = pTitle || 'www.organizeur.com';
        var curUrl = pUrl || null;
        var curCloseHandler = pCloseHandler || function()
        {
            //alert( 'Close' );
        };
        var curDefaultWidth = pDefaultWidth || 400;
        
        // create a dialog with the waiting content
        var newDialog = new Boxy( nsPublic.fDialogWaitView( pTargetTag, null, curDefaultWidth ), {
            x: curX,
            y: curY,
            draggable: true,
            title: curTitle,
            show: true,
            modal: true,
            unloadOnHide: true,
            hideFade: false,
            hideShrink: false,
            //afterHide: curCloseHandler
            beforeUnload: curCloseHandler
        } );
        
        // run the ajax request to loading the content of the dialog by taconite
        $.ajax( {
            url: pUrl,
            type: 'GET',
            cache: false,
            error: function( pXMLHttpRequest, pTextStatus, pErrorThrown )
            {
                nsPublic.fErrorViewPage( pTargetTag, 'Erreur lors du chargement.' );
            },
            complete: function( pXMLHttpRequest, pTextStatus )
            {
                newDialog.moveTo( curX, curY );
            }
        } );
        
        return newDialog;
    };
    
    // ***********************************
    // ***** SHOWING EMAIL FUNCTIONS *****
    // ***********************************
    
    /**
     * Get the id of the standard email showing dialog popin
     * 
     * @returns string
     */
    nsPublic.fBoxEmailShowingGetId = function()
    {
        return 'mail-showing-dialog';
    };
    
    nsPublic.fBoxEmailShowingGetState = function( pJqIdName )
    {
        var jq = pJqIdName || ( '#' + ( nsPublic.fBoxEmailShowingGetId() ) );
        
        //return $( jq ).attr( 'ybstate' );
        return nsPublic.fBoxGetState( jq );
    };
    
    /**
     * Create and showing the standard email showing dialog popin
     *  
     * @param pTitle
     * @param pUrl
     * @param pCloseHandler
     */
    nsPublic.fBoxEmailShowing = function( pUrl, pCloseHandler, pTitle )
    {
        var myTitle = pTitle || 'Confirmer l\'envoi du mail...';
        
        yb2ns.fBoxCreateDialogWithCloseHandler( nsPublic.fBoxEmailShowingGetId(), myTitle, pUrl, pCloseHandler );
    };
    
    nsPublic.fBoxGetState = function( pJqDialogName, pAttrName )
    {
        pAttrName = pAttrName || 'ybstate';
        
        return $( pJqDialogName ).attr( pAttrName );
    };
    nsPublic.fBoxSetState = function( pJqDialogName, pState, pAttrName )
    {
        pAttrName = pAttrName || 'ybstate';
        
        return $( pJqDialogName ).attr( pAttrName, pState );
    };
    
    // *****************************
    // ***** DIALOGS UTILITIES *****
    // *****************************
    /**
     * alert dialog with an optional callback for close
     * Note: this method is not intended to replace the native window.confirm() function provided by browsers
     *       as it does not have the capability to block program execution while the dialog is visible.
     * @param pMessage string
     * @param pTitle string
     * @param pOkHandler function
     */
    nsPublic.fAlertDialog = function( pMessage, pTitle, pOkHandler )
    {
        pTitle = pTitle || 'OrganiZeur';
        pOkHandler = pOkHandler || null;
        var buttons = {};
        buttons['Fermer'] = pOkHandler;
        nsPublic.fAskDialog( pMessage, buttons, pTitle );
    };
    /**
     * confirm dialog with a callback for second button
     *
     * @param pQuestion string
     * @param pOkHandler function
     * @param pTitle string
     * @param pAnswers array
     */
    nsPublic.fConfirmDialog = function( pQuestion, pOkHandler, pTitle, pAnswers )
    {
        pTitle = pTitle || 'Confirmation';
        pAnswers = pAnswers || [ 'Annuler', 'Confirmer' ];
        var buttons = {};
        buttons[pAnswers[0]] = null;
        buttons[pAnswers[1]] = pOkHandler;
        nsPublic.fAskDialog( pQuestion, buttons, pTitle );
    };
 
    /**
     * ask dialog with multi answer
     *
     * @param string pQuestion
     * @param object pButtons
     * @param string pTitle
     * @param function pCloseHandler
     * @param object pOptions
     */
    nsPublic.fAskDialog = function( pQuestion, pButtons, pTitle, pCloseHandler, pOptions )
    {
        pOptions = pOptions || {};
        if ( pTitle ) pOptions.title = pTitle;
        if ( pCloseHandler ) pOptions.beforeUnload = pCloseHandler;
        
        var options = jQuery.extend( {
            modal: true,
            closeable: false,
            draggable: true
        }, pOptions, {
            show: true,
            unloadOnHide: true,
            hideFade: true,
            hideShrink: ''
        } );
        
        var style = "";
        if ( typeof options.width != 'undefined' && options.width ) style = ' style="max-width:' + options.width + 'px"';
        
        var body = jQuery( '<div id="yb_ask_dialog"></div>' ).append( jQuery( '<div class="yb-dialog-question"' + style + '></div>' ).html( pQuestion ) );
        
        var buttons = jQuery( '<div class="yb-dialog-answers"><form class="answers"></form></div>' );
        
        var i = 0;
        
        var triggers = [];
        var btns = '';
        jQuery.each( pButtons, function( pText, pTrigger )
        {
            pTrigger = pTrigger || function()
            {
            };
            triggers[i] = pTrigger;
            if ( i > 0 ) btns = btns + "&nbsp;&nbsp;";
            btns = btns + '<input type="button" rank="' + i + '" class="ui-button ui-state-default ui-corner-all" value="' + pText + '" />';
            i = i + 1;
        } );
        buttons.html( btns );
        
        jQuery( 'input[type=button]', buttons ).click( function()
        {
            var callback = triggers[$( this ).attr( 'rank' )];
            Boxy.get( this ).hide( callback );
            return false;
        } );
        
        body.append( buttons );
        
        jQuery( document.body ).unbind( 'keypress.boxy' );
        
        new Boxy( body, options );
    };
    
    // *******************************
    // ***** CHECKBOCK UTILITIES *****
    // *******************************
    
    /**
     * Select or Unselect all checkbox
     * 
     * @param pJQSelector
     * @param pSelected
     */
    nsPublic.fFormCheckboxAllSelect = function( pSelector, pSelected )
    {
        var curSelector = pSelector || '.yb-checkbox';
        
        $( curSelector ).attr( 'checked', pSelected );
    };
    
    /**
     * get count the selected checkbox
     * 
     * @param pSelector
     * @returns
     */
    nsPublic.fFormCheckboxCountSelected = function( pSelector )
    {
        var curSelector = ( pSelector + ':checked' ) || '.yb-selector:checked';
        
        return $( curSelector ).size();
    };
    
    /**
     * Get the compute string to show the selection items.
     * 
     * @param pFormat
     * @param pCount
     * @param pMaximum
     * @param pStrItem
     * @param pStrItems
     * @returns
     */
    nsPublic.fCountString = function( pFormat, pCount, pMaximum, pStrItem, pStrItems, pStrNoneItem )
    {
        var curMaximum = pMaximum || 0;
        var curStrItem = pStrItem || '';
        var curStrItems = pStrItems || '';
        var curStrNoneItem = pStrNoneItem || '';
        var curResult = '';
        
        if ( curMaximum > 0 )
        {
            if ( pCount > 1 )
            {
                curResult = sprintf( pFormat, pCount, curMaximum, curStrItems );
            }
            else
            {
                curResult = sprintf( pFormat, pCount, curMaximum, curStrItem );
            }
        }
        else
        {
            curResult = curStrNoneItem
        }
        
        return curResult;
    };
    
    /**
     * Hide the info zone and show the input text with the focus
     * By example, used into the popin who show the mail for confirmation.
     * 
     * <code>
     *      yb2ns.fShowInputText("#mail-showing-wizard-infos","#mail-showing-wizard-input")
     * </code>
     */
    nsPublic.fShowInputText = function( pJqWizardInfo, pJqWizardInput )
    {
        var options = {
            'maxCharacterSize': 200,
            'originalStyle': 'originalTextareaInfo',
            'warningStyle': 'warningTextareaInfo',
            'warningNumber': 40,
            'displayFormat': '#input / #max '
        };
        // hide/show text input
        
        $( pJqWizardInfo ).hide();
        $( pJqWizardInput ).show();
        $( pJqWizardInput + ' textarea' ).textareaCount( options );
        $( pJqWizardInput + ' textarea' ).focus();
    };
    
    nsPublic.fTimoutClearZone = function( pSelector, pMilliseconds )
    {
        pSelector = pSelector || ".info-user";
        pMilliseconds = pMilliseconds || 5000;
        
        clearTimeout( nsTimeoutAutoAction );
        nsTimeoutAutoAction = setTimeout( function()
        {
            clearTimeout( nsTimeoutAutoAction );
            $( pSelector ).html( '' );
        }, pMilliseconds );
    };
    
    nsPublic.fTimoutClearAndHideZone = function( pSelector, pMilliseconds )
    {
        pSelector = pSelector || ".info-user";
        pMilliseconds = pMilliseconds || 5000;
        
        clearTimeout( nsTimeoutAutoAction );
        nsTimeoutAutoAction = setTimeout( function()
        {
            clearTimeout( nsTimeoutAutoAction );
            $( pSelector ).hide().html( '' );
        }, pMilliseconds );
    };
    
    // *******************************
    // ******* FORM UTILITIES *******
    // *******************************
    
    nsPublic.utils.form.fSetJqErrorFormFieldAllReset = function( pJqSelector )
    {
        $( pJqSelector ).each( function()
        {
            log( 'utils.form.fSetJqErrorFormFieldAllReset( "' + pJqSelector + '" )' );
            $( this ).html( '' );
            $( this ).hide();
        } );
    };
    
    nsPublic.utils.form.fSetJqErrorFormField = function( pJqSelector, pMessage )
    {
        $( pJqSelector ).each( function()
        {
            log( 'utils.form.fSetJqErrorFormField( "' + pJqSelector + '", "' + pMessage + '" )' );
            $( this ).html( pMessage );
            $( this ).show();
        } );
    };

    //compteur textarea
    nsPublic.utils.form.fTextareaLimiter = function(textarea_id, max) {
        var textarea = $("#" + textarea_id);

        var txt = textarea.val();
        var n = txt.length;

        if (n > max)
        {
            textarea.val(txt.substring( 0, max));
            n = max;
        }
    };
    // *******************************
    // ******* VIEWS UTILITIES *******
    // *******************************
    
    nsPublic.utils.view.fLoadViewBlock = function( pJqBlock, pUrl, pData, pType, pProcessName )
    {
        pData = pData || '';
        pType = pType || "GET";
        pProcessName = pProcessName || "Chargement";
        
        log( 'utils.view.fSubmitViewBlock( "' + pJqBlock + '", "' + pUrl + '", "' + pData + '", "' + pType + '", "' + pProcessName + '" )' );
        
        // waiting message
        nsPublic.fWaitViewBlockEnable( pJqBlock, pProcessName + ' en cours...' );
        
        // load the form with the cache to false for IE
        $.ajax( {
            url: pUrl,
            type: pType,
            cache: false,
            data: pData,
            error: function( pXMLHttpRequest, pTextStatus, pErrorThrown )
            {
                nsPublic.fErrorViewPage( pJqBlock, 'Erreur pendant ' + pProcessName + '.' );
            },
            complete: function( pXMLHttpRequest, pTextStatus, pErrorThrown )
            {
                nsPublic.fWaitViewBlockDisable( pJqBlock );
            }
        } );
    };
    
    nsPublic.utils.view.fSubmitViewBlock = function( pJqBlock, pUrl, pJqForm, pType, pProcessName )
    {
        pType = pType || 'POST';
        pProcessName = pProcessName || "Enregistrement";
        
        log( 'nsPublic.utils.view.fSubmitViewBlock( "' + pJqBlock + '", "' + pUrl + '", "' + pJqForm + '", "' + pType + '", "' + pProcessName + '" )' );
        
        // waiting message
        nsPublic.fWaitViewBlockEnable( pJqBlock, pProcessName + ' en cours...' );
        
        // serialize the datas form
        var dataForm = $( pJqForm ).serialize();
        
        // load the form with the cache to false for IE
        $.ajax( {
            url: pUrl,
            type: pType,
            cache: false,
            data: dataForm,
            error: function( pXMLHttpRequest, pTextStatus, pErrorThrown )
            {
                yb2ns.fErrorViewPage( pJqBlock, 'Erreur pendant ' + pProcessName + '.' );
            },
            complete: function( pXMLHttpRequest, pTextStatus, pErrorThrown )
            {
                yb2ns.fWaitViewBlockDisable( pJqBlock );
            }
        } );
    };

    nsPublic.utils.view.fEnsureVisible = function( pSelector , pTime, pDivSelector )
    {
        pTime =  pTime || 10;
        pDivSelector = pDivSelector || '';
        var docViewTop, docViewBottom;
        if (!pDivSelector)
        {
            docViewTop = $(window).scrollTop();
            docViewBottom = docViewTop + $(window).height();
            pDivSelector = 'html,body';
        } else {
            docViewTop = $(pDivSelector).scrollTop();
            docViewBottom = docViewTop + $(pDivSelector).height();
        }
        

        var elemTop = $(pSelector).offset().top;
        var elemBottom = elemTop + $(pSelector).height();

        if (elemTop <= docViewTop)
            $(pDivSelector).animate({scrollTop: elemTop - 5 }, pTime);
        else if (elemBottom >= docViewBottom)
            $(pDivSelector).animate({scrollTop: docViewTop+5+elemBottom-docViewBottom}, pTime);
    };
    //not exact
    nsPublic.utils.view.fEnsureVisibleHorizontal = function( pSelector , pTime, pDivSelector )
    {
        pTime =  pTime || 10;
        pDivSelector = pDivSelector || '';
        var docViewLeft, docViewRight, offset;
        if (!pDivSelector)
        {
            docViewLeft = $(window).scrollLeft();
            docViewRight = docViewLeft + $(window).width();
            offset = docViewRight;
            pDivSelector = 'html,body';
        } else {
            docViewLeft = $(pDivSelector).scrollLeft();
            docViewRight = docViewLeft + $(pDivSelector).width();
            offset = $(pDivSelector).width();
            offset = docViewRight;
        }
        
        var elemLeft = $(pSelector).offset().left;
        var elemRight = elemLeft + $(pSelector).width();
//$(pDivSelector).append("<div>"+docViewRight+" "+elemRight+"</div>");
//alert("DL "+docViewLeft+" w "+  $(pDivSelector).width() +" ER "+elemRight);
        if (elemLeft <= docViewLeft)
            $(pDivSelector).animate({scrollLeft: elemLeft - 5 }, pTime);
        else if (elemRight >= docViewRight)
            $(pDivSelector).animate({scrollLeft: docViewLeft+5+elemRight-offset}, pTime);
    };
    // *******************************
    // ******* BINDS UTILITIES *******
    // *******************************
    
    nsPublic.utils.bind.fInputFilterDigit = function( pInputSelector )
    {
        $( pInputSelector ).unbind( 'keypress' );
        $( pInputSelector ).bind( "keypress", function( pEvent )
        {
            var n = 0 + pEvent.which;
            if ( ( n < 48 || n > 57 ) && ( n != 0 && n != 8 && n != 13 ) )
            {
                pEvent.preventDefault();
            }
            // keep this for tests
            // par = $(inputSelector).parent();
            // par.append("<div>metaKey "+event.metaKey+" keyCode "+event.keyCode+" charCode "+event.charcode+" which"+event.which+"</div>");
        } );
    };
    
    // *******************************
    // ****** MESSAGE UTILITIES ******
    // *******************************
    
    nsPublic.utils.msg.nsTimeoutMesgShowing;
    nsPublic.utils.msg.fShowMessageWithTimeout = function( pJqSelector, pText, pMilliseconds )
    {
        pText = pText || '';
        pMilliseconds = pMilliseconds || 5000;
        
        var nodeJqSelector = $( pJqSelector );
//        if ( isset( nodeJqSelector ) )
        if ( nodeJqSelector.length )
        {
            if ( pText != '' )
            {
                nodeJqSelector.html( pText );
                nodeJqSelector.show(200);
                
                clearTimeout( nsPublic.utils.msg.nsTimeoutMesgShowing );
                nsPublic.utils.msg.nsTimeoutMesgShowing = setTimeout( function()
                {
                    clearTimeout( nsPublic.utils.msg.nsTimeoutMesgShowing );
                    nodeJqSelector.hide(600).html( '' );
                }, pMilliseconds );
            }
            else
            {
                nodeJqSelector.hide(200).html( '' );
            }
        }
        else
        {
            alert( 'ERROR fShowMessageWithTimeout : this selector "' + pJqSelector + '" is not found.' );
        }
    };
    
    return nsPublic;
    
}() );

// from old main.js, wich has been deleted (in case of ...)
//$( document ).ready( function()
//{
//    // -----
//    // preferences buttons
//    // -----
//    $( '.ui-button' ).hover( function()
//    {
//        $( this ).addClass( "ui-state-hover" );
//    }, function()
//    {
//        $( this ).removeClass( "ui-state-hover" );
//    } ).mousedown( function()
//    {
//        $( this ).addClass( "ui-state-active" );
//    } ).mouseup( function()
//    {
//        $( this ).removeClass( "ui-state-active" );
//    } );
//} )

