/*!
* jQuery isAuth plugin
* Version 0.1 (14-APR-2011)
* @requires jQuery v1.5.x or later
*
* Copyright (c) 2011 M. Belluco
* Richiede il plugin jQuery blockUI plugin
* 
*/

(function($){

        var config = {
                _ssoUrl   : 'https://web.spaggiari.eu/home/app/default/login-sso.php',
                _ssoUtils : 'sso-utils.php',
                _page_success: 'area_riservata.html',
                _page_logout: 'home.html',
                _save_sessione: 'sso_auth.html'
            };
        
        var that = null;
        
        /* Public Method */
        
        /*
         * Funzione di autenticazione
         *
         * */
        $.fn.auth = function( settings ) {
            
                that = this;
                
                if ( typeof that[0] === 'undefined' ){
                    // throw new Error('Nessun oggetto associato');
                    return;
                }
                
                //Modifica le configurazioni di default scelte per il plugin
                if (settings) jQuery.extend( config, settings );
                
                
                /* Controllo che si tratta di una form */
                if(that[0].tagName.toLowerCase() === 'form') {
         
                    // Tolgo l'action della form
                    if ( typeof that.attr('action') != 'undefined') {
                        that.attr('action','javascript:;')
                    }
                    
                    // Assegno metodo on submit
                    that.bind( 'submit', _functionAction );
         
                }else if( that[0].tagName.toLowerCase() === 'a' ){
                    that.click( _functionAction );
                }else{
                    
                    throw new Error('Questo plugin funziona con i form o un link.');
         
                    return;
                    
                }
            
            
            
            
        };
        
        /*
         * Funzione di Keep Alive
         * 
         * */
        $.keepAlive = function( settings ) {
            
            //Modifica le configurazioni di default scelte per il plugin
            if (settings) jQuery.extend( config, settings );
            
            /* Eseguo una chiamata ajax ASICRONA al web server per mantenere viva la sessione*/
            _ticKeppAlive();
            
        };
    

        /* Private Method */
        
        _functionAction = function(){
                        
                        /* Controllo che all'attributo sia settato per capire che action si vule esegure */
                        if ( typeof that.attr('typeLogin') === 'undefined') {
                            
                        }else{
                            
                            _ticSso( that.attr('typeLogin') );
                            
                        }
                        return false;
                    
                    }

        
        _ticSso = function( action ){
                
                switch(action){
                        
                        // verifica se autenticato su TIC
                        case 'checkAuth':
                                _startQuery('Autenticazione in corso...');
                                $.post(
                                        config._ssoUrl,
                                        { a: 'checkAuth'},
                                        function(json){
                                                if(json && json.auth){
                                                        // qui posso fare una chiamata ajax ad uno script locale
                                                        // passando json...
                                                        $.post(
                                                                config._save_sessione,
                                                                {action: 'gotAccount', auth: json.auth },
                                                                function(data){
                                                                        _stopQuery();
                                                                }
                                                        );
                                                } else {
                                                        _stopQuery();
                                                }
                                        },
                                        'jsonp'
                                );
                                break;
                        
                        // effettua un logout da TIC (questa non dovrebbe essere mai usata)
                        case 'logout':
                                _startQuery('Logout in corso...');
                                $.post(
                                        config._ssoUrl,
                                        { a: 'logout'},
                                        function(json){
                                                if(json){
                                                        _stopQuery();
                                                } else {
                                                        // qui posso fare una chiamata ajax ad uno script locale passando json...
                                                        $.post(
                                                                config._save_sessione,
                                                                {action: 'loggedOut'},
                                                                function(data){
                                                                        _stopQuery();
                                                                         window.location = config._page_logout;
                                                                }
                                                        );
                                                        
                                                }
                                        },
                                        'jsonp'
                                );
                                break;			
                        
                        case 'stdLogin':
                            
                                _startQuery('Autenticazione in corso...');
                                
                                var custcode = that.find('input[name="custcode"]').val() ; //$('input[name="custcode"]').val();
                                var login    = that.find('input[name="login"]').val();
                                var password = that.find('input[name="password"]').val();
                                
                                $.post(
                                        config._ssoUrl,
                                        { a: 'stdLogin', c: custcode, u: login, p: password},
                                        function(json){
                                                
                                                if(json && json.auth){
                                                    
                                                        $.post(
                                                                config._save_sessione,
                                                                {action: 'gotAccount', auth: json.auth },
                                                                function(data){
                                                                        _stopQuery();
                                                                        window.location = config._page_success;
                                                                }
                                                        );
                                                } else {
                                                    alert( 'Attenzione!\nIl nome utente e/o password non corispondono!' );
                                                    _stopQuery();
                                                    
                                                }
                                        },
                                        'jsonp'
                                );
                                
                                break;
                        
                        case 'bdgLogin':
                            
                                _startQuery('Autenticazione in corso...');
                                var badge = $('input[name="badge"]').val();
                                //alert(action);
                                $.post(
                                        config._ssoUrl,
                                        { a: 'bdgLogin', b: badge},
                                        function(json){
                                                //alert('ok:' +json);
                                                if(json && json.auth){
                                                        // qui posso fare una chiamata ajax ad uno script locale passando json...
                                                        $.post(
                                                                config._save_sessione,
                                                                {action: 'gotAccount', auth: json.auth },
                                                                function(data){
                                                                        _stopQuery();
                                                                        window.location = config._page_success;
                                                                }
                                                        );
                                                } else {
                                                        alert( 'Attenzione!\nIl il badge non è corretto!' );
                                                        _stopQuery();
                                                }
                                        },
                                        'jsonp'
                                );				
                                break;
                        
                        default:
                        break;
                    
                }
        }
    
        /* funzione che esegue la chiamata ajax*/
        _ticKeppAlive = function (){
            
            $.ajax({
                    type: "POST",
                    dataType: "jsonp",
                    async: true,
                    url: config._ssoUrl,
                    data: {a: 'keepAlive' },
                    success: function( json ){
                        // json.ck
                        setTimeout( _ticKeppAlive, 500000); //  8 Minuti rieseguo la chiamata
                    }
                    
                });
            
        }
    
        /* Funzione che genera un pannello di blocco */
        _startQuery = function(msg){
                        
                        $.blockUI({
                            message: '<p>'+msg+'</p>',
                            css: { 
                                border: 'none', 
                                padding: '15px', 
                                backgroundColor: '#000', 
                                '-webkit-border-radius': '10px', 
                                '-moz-border-radius': '10px', 
                                opacity: .5, 
                                color: '#FFFFFF' 
                            }
                        });
                        
                    }
        
        /* Funzione che sblocca il pannello */
        _stopQuery = function(){
                        $.unblockUI();
                    }
    
    
})(jQuery);

