var lib =
{
    /**
     * Set border radius for IE only
     * Need DD_roundies_0.0.2a-min.js library
     *
     */
    setBorderRadiusIE :
    {
        init : function(elm, rad, noBackground)
        {
            if(true == $.browser.msie)
            {
                rad = 'undefined' == typeof(rad) ? '5px' : rad;

                if($(elm).size() != 0)
                {
                    DD_roundies.addRule(elm, rad);
                    
                    if(true == noBackground)
                    {
                        $(elm).css('background-color', 'none !important');
                    }
                }
            }
        }
    },
    
    /**
     * Set nice select button 
     * Need ui.selectmenu.js library
     * 
     */
    setNiceSelect : 
    {
        init : function()
        {
            $('select#tx_ttnews_scdcats').selectmenu({ style : 'dropdown' });
            $('select#tx_ttnews_scdmonth').selectmenu({ style : 'dropdown' });
            $('select#tx_ttnews_scdyear').selectmenu({ style : 'dropdown' });
        }
    },

     /**
      * Add page in favorites navigator
      */
     favorites : 
     {
        init : function()
        {
            $('#bt-favoris').click(function() 
            {
                var nomSite = window.document.title,
                    urlSite = 'http://'+window.location.hostname;

                if(window.sidebar) // FF
                {
                    window.sidebar.addPanel(nomSite,urlSite,"");
                }
                else if(navigator.userAgent.indexOf("Chrome",0)>0 || (window.opera && window.print)) //Chrome,Opera
                {
                    alert ("CTRL + D \n pour ajouter " + nomSite + " dans vos favoris !"); 
                }       
                else if (window.external) // IE
                {
                    window.external.AddFavorite(urlSite, nomSite);
                }
                else
                {
                    alert ("Cette fonction n'est pas disponible pour votre navigateur."); 
                }
            });
        }
     },

     /**
      * Beautiful scrollbar
      * Need library Scrollbar (jquery.scroll.js)
      */
     scroll :
     {
        init : function()
        {
            if($('.css-scrollbar').size() > 0)
            {
                $('.css-scrollbar').scrollbar();
            }
        }
     },

     /**
      * Show form login. 
      * Need plugin fancybox
      */
     connexion : 
     {
        _url : 'http://'+window.location.host+'?no_cache=1',

        init : function(elm)
        {
            if($(elm).size() > 0)
            {
                if($('div.changePassword').size() > 0)
                {
                    $.fancybox({
                        'scrolling'     : 'no',
                        'titleShow'     : false,
                        'content'       : $('#form_login').html(),
                        'onStart'       : function()
                        {
                            $('object').hide();
                        },
                        'onClosed'      : function()
                        {
                            $('object').show();
                            window.location.href = lib.connexion._url;
                        }
                    });

                    this._validFormChangePassword();
                }
                else
                {
                    $(elm).fancybox({
                        'scrolling'     : 'no',
                        'titleShow'     : false,
                        'content'       : $('#form_login').html(),
                        'onStart'       : function()
                        {
                            $('object').hide();
                        },
                        'onClosed'      : function()
                        {
                            $('object').show();
                        }
                    });
                }
                
                this._validFormConnexion();
                this._redirectToForm('p.forgot', '#form_forgot_password');
                this._redirectToForm('p.back', '#form_login');
                this._validFormForgotPassword();

                return false;
            }
        },

        /**
         * Action when form is validated
         */
        _validFormConnexion : function()
        {
            $("#fancybox-content #form_felogin").live("submit", function()
            {
                if((typeof($("#fancybox-content #user").val()) != 'undefined' && $("#fancybox-content #user").val().length < 1) 
                    || (typeof($("#fancybox-content #pass").val()) != 'undefined' && $("#fancybox-content #pass").val().length < 1))
                {
                    return false;
                }
                
                $.fancybox.showActivity();
                
                $.ajax({
                    type    : "POST",
                    cache   : false,
                    url     : lib.connexion._url+'&ajax=1',
                    data    : $(this).serializeArray(),
                    success : function(data)
                    {    
                        var reg = new RegExp('<p id="error_felogin">(.)+</p>', 'g');
                        
                        if(reg.test(data))
                        {
                            $.fancybox(data);
                        }
                        else
                        {
                            var regUid = new RegExp('<p id="uidExtranetHome" class="hide">([0-9]+)</p>', 'g'),
                                result = regUid.exec(data);
                  
                            window.location.href = (result != null && result[1] != null) ? 'index.php?id='+result[1]+'&no_cache=1' : lib.connexion._url;

                            data != '' ? $.fancybox(data) : '';
                            $.fancybox.close();
                        }
                    }
                });

                return false;
            });
        },

        /**
         * Link Back to connexion form
         */
        _redirectToForm : function(elm, form)
        {
            $('#fancybox-content '+elm+' a.connexionLink').live('click', function()
            {
                $.fancybox($(form).html());

                return false;
            });
        },

        /**
         * Validation form to get forgot password
         */
        _validFormForgotPassword : function()
        {
            $("#fancybox-content #form_forgot").live("submit", function()
            {
                if(typeof($("#fancybox-content #tx_felogin_pi1[forgot_email]").val()) != 'undefined' && $("#fancybox-content #tx_felogin_pi1[forgot_email]").val().length < 1) 
                {
                    return false;
                }

                $.fancybox.showActivity();
                
                $.ajax({
                    type    : "POST",
                    cache   : false,
                    url     : lib.connexion._url+'&tx_felogin_pi1[forgot]=1&ajax=1',
                    data    : $(this).serializeArray(),
                    success : function(data)
                    {    
                        data != '' ? $.fancybox(data) : '';
                    }
                });

                $('div.changePassword a.connexionLink').live('click', function()
                {
                    $.fancybox($('#form_login').html());
                });

                return false;
            });
        },

        /**
         * Form to change user password
         */
        _validFormChangePassword : function(url)
        {
            $("#fancybox-content #formChangePassword").live("submit", function()
            {
                $.fancybox.showActivity();
                
                var user = '',
                    hash = '',
                    get = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                
                for(var i = 0; i < get.length; i++)
                {
                    var data = get[i].split('=');
                    
                    if('tx_felogin_pi1[user]' == data[0])
                    {
                        user = data[1];
                    }
                    else if('tx_felogin_pi1[forgothash]' == data[0])
                    {
                        hash = data[1];
                    }
                }
                
                $.ajax({
                    type    : "POST",
                    cache   : false,
                    url     : lib.connexion._url+'&ajax=1&tx_felogin_pi1[user]='+user+'&tx_felogin_pi1[forgothash]='+hash,
                    data    : $(this).serializeArray(),
                    success : function(data)
                    {
                        var reg = new RegExp('<form', 'g');
                        
                        if(reg.test(data))
                        {
                            $.fancybox(data);
                        }
                        else
                        {
                            window.location.href = lib.connexion._url;

                            data != '' ? $.fancybox(data) : '';
                            $.fancybox.close();
                        }
                    }
                });

                return false;
            });
        }
    },

    /**
     * Set the same height to differents elements
     */
    setHeightElement : 
    {
        init : function()
        {  
            this._home();
            this._onglets('#navigation-page li');
            this._onglets('#link-portail li');
        },

        _home : function()
        {
            if($('#page-content').size() > 0 && $('#col-boite-outils').size() > 0)
            {
                var left = $('#page-content'),
                    right = $('#col-boite-outils'),
                    leftHeight = left.height(),
                    rightHeight = right.height();

                leftHeight > rightHeight ? right.height(leftHeight) : left.height(rightHeight);
            }
        },
        
        _onglets : function(elm)
        {
            if($(elm).size() > 0)
            {
                var menu = $(elm),
                    max = 0,
                    height = 0,
                    initPadding = $('.portail').size() > 0 ? 16 : 12;
                
                menu.each(function(i) // defined max height
                {
                    height = $(this).height();

                    if(height > max)
                    {
                        max = height;
                    }
                });

                menu.each(function(i) // applies max height for all elements   - old: if($(this).height() < max)
                { 
                        var padding = max-$(this).height()+initPadding-2;
                        
                        $(this).height(max-padding+initPadding).css('padding-top', padding+'px');
                    
                });
            }
        }
    },

    /**
     * Slide images - for tourisme only
     */
    showNextImage :
    {
        init : function(delay)
        {
            if($('#slideshow').size() > 0)
            {
                setInterval(function ()
                {
                    var active = $('#slideshow IMG.active');
                    
                    if ( active.length == 0 )
                    {
                        active = $('#slideshow IMG:last');
                    }

                    var next = active.next().length ? active.next() : $('#slideshow IMG:first');
                    active.addClass('last-active');

                    next.css({opacity: 0.0})
                        .addClass('active')
                        .animate({opacity: 1.0}, 1000, function() {
                            active.removeClass('active last-active');
                        });
                },delay);
            }
        }
    },

    /**
     * Print current page
     */
    print :
    {
        init : function()
        {
            if($('#bt-impression').size() > 0)
            {
                $('#bt-impression').click(function()
                {
                    window.print();
                });
            }
        }
    },

    /*
     * Add new fields when user upload file in extension 'airfilemanager'
     */
    airfilemanager : 
    {
        init : function()
        {
            if($('#tx_airfilemanager_addfields_btn').size() > 0)
            {
                var fieldcount = $('.fields').size() -1,
                    fields = $('#tx_airfilemanager_addfields_btn');
                    
                fields.show();

                fields.click(function()
                {
                    fieldcount++;

                    var clonedElement = $('.fields_template').clone();

                    clonedElement
                    .html(clonedElement.html().replace(/###FIELD_NO###/g, fieldcount))
                    .html(clonedElement.html().replace(/###FILE_NUMBER###/g, fieldcount+1))
                    .attr('class', 'fields')
                    .show()
                    .insertBefore($('#insert_new_fields_here'));

                    return false;
                });
            }
        }
    }
}

