/*
 * jQuery BTAjax plugin
 *
 * http://www.bt-struct.com
 *
 * Copyright (c) 2009 - 2009 Bruno Tiziano
 *
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */




(function($) {
    
    var $this;
    
    //
    // Proprietà di configurazione del plugin
    //
    $.requestajax = {
        defaults: {
	        params: '', 
	        async: true, 
	        viewLoading: true, 
	        fadeEffect: false, 
	        loadingWindow: false
        }
    };
    
    
    //
    // Definizione del plugin
    //
    $.fn.extend({
        // Costruttore
        requestajax: function(settings) {
	        //debug('Invio la richiesta');
	        
		    // Sovrascrivo i parametri di configurazione prima del ciclo
		    settings = $.extend({}, $.requestajax.defaults, settings);
		    
		    // Ciclo e invio la richiesta Ajax ad ogni elemento selezionato
		    return this.each(function() {
		        
		        $this = $(this);
                
		        debug("START");
		        debug("id element: "+$this.attr("id"));
		        $.data($this, "requestajax", settings);
		        
		        // Preparo i dati da spedire
                debug("params: " + settings.params);
                
                // La risposta via Ajax sarà nel formato JSON
                var options = {
                    url: 'ajax.php', 
                    data: settings.params, 
                    type: 'POST', 
                    async: settings.async, 
                    beforeSend: setLoading,
                    error: setError, 
                    success: responseJson, 
                    dataType: "json"
                }
		        
		        
		        // Invio la richiesta Ajax
	            $.ajax(options);
		    });
        }
    });
    
    
    //
    // Metodo privato per la visualizzazione di un errore Ajax
    //
    function setError(XMLHttpRequest, textStatus, errorThrown) {	        
        alert("Errore nella richiesta Ajax.\nL'errore è : "+XMLHttpRequest.responseText);
        $this.html('');
    }
    
    
    //
    // Metodo privato per il recupero di dati che ho storicizzato in $.data()
    //
    function settings(element) {
        return $.data(element, "requestajax");
    }
    
    
	//
	// Metodo privato per il debug
	//
    function debug(text) {
        if (window.console && window.console.log)
            window.console.log(text);
    };
    
    
    //
    // Metodo privato per la visualizzazione del loading
    //
    function setLoading(){
        // Visualizzo il loading solo se lo richiede l'utente
        if(settings($this).viewLoading){
	        var contentHeight = $this.height();
	        var contentWidth = $this.width();
	        var $contentLoading = $("#content-loading");
	        var $shadowLoading = $("#shadow-loading");
	        var $dialogLoading = $("#dialog-loading");
	        
	        if(settings($this).loadingWindow){
	            // Faccio il loading su tutta la pagina
	            var position = '';
	            contentHeight = $(window).height();
	            contentWidth = $(window).width();
	        } else {
	            // Faccio il loading solo sul contenitore che sto chiamando
	            var position = 'relative';
	        }
	                
	        // Setto una altezza di default qualora sia minore di 70px
	        if(contentHeight < 70)  contentHeight = 70;
	        
	        //debug("contentHeight: "+contentHeight+" contentWidth: "+contentWidth);
	        
	        // Setto la posizione centrale per il shadow
	        var widthShadow = 192/2;//262/2;
	        var leftShadow = Number(contentWidth/2)-Number(widthShadow);
	        $shadowLoading.css("left", leftShadow);
	        
	        var heightShadow = 32/2;//52/2;
	        var topShadow = Number(contentHeight/2)-Number(heightShadow);
	        $shadowLoading.css("top", topShadow);
	        
	        // Setto la posizione centrale per il dialog
	        var leftDialog = Number(contentWidth/2)-Number(widthShadow);
	        $dialogLoading.css("left", leftDialog);
	        
	        var topDialog = Number(contentHeight/2)-Number(heightShadow);
	        $dialogLoading.css("top", topDialog);
	        
	        
	        // Setto al contenitore del loading l'altezza uguale a quella dell'elemento da caricare via Ajax
	        $contentLoading.css({
	            'height' : contentHeight, 
	            'position' : position 
	        });
	        
	        // Prendo tutto l'html con lo stile corretto...
	        var loadingHTML = $("#loading").html();
	        // ... e lo setto all'html dell'elemento che sto per caricare tramite Ajax
	        $this.html(loadingHTML);
        }
    };
    
    
    //
    // Funzione privata che prende in gestione la risposta JSON tornata dalla richiesta Ajax
    //
    function responseJson(json, textStatus) {
        
        if(textStatus == "success"){
	        try {
	            if(json.append_filejs.length > 0){
	                var a_files = json.append_filejs;
	                
	                // remove
	                $("script[dynamic]").remove();
	                
	                var tagScript = '';
	                $.each( a_files, function(i, src){
	                    tagScript += '<script type="text/javascript" src="'+src+'" dynamic="yes"></script>';
	                });
	                
	                $("head").append(tagScript);
	            }
	            
	            if(json.error){
	                alert(json.error);
	                return false;
	            }
	            
	            if(json.message){
	                alert(json.message);
	            }
	            
	            if(json.js){
	                eval(json.js);
	            }
	            
	            if(json.xhtml){
	                var xhtml = json.xhtml;
	                
	                if(xhtml.exec_before){
	                    eval(xhtml.exec_before);
	                }
	                
	                // Decido se vedere l'effetto hide
	                if(settings($this).fadeEffect){
	                    $this.hide();
	                }
                    
	                $this.html(xhtml.content);
	                debug("ho settato il content");
	                
	                // Decido se vedere l'effetto fade
	                if(settings($this).fadeEffect){
	                    $this.fadeIn(1200);
	                }
	                
	                if(xhtml.exec_after){
	                    eval(xhtml.exec_after);
	                }
	            }
	            
                debug("END");
	        
	        } catch (exc) {
	            return false;
	        }
        }
        
        return true;
    };

})(jQuery);
