/* La calsse presence fornisce il collegamento con FMS per gestire le presenze sul sito,
 * l'invio e ricezione di eventi e messaggi, il trackID, l'ultima pagina navigata, l'ultima sessione
 *
 * PARAMETRI:
 * - flashContainer (contenitore dell'swf e target del bind per gli eventi)
 * - flashvars      (oggetto necessario per inizializzare correttamente l'swf e l'RTMP al FMS)
 *
 * METODI PUBBLICI:
 * - init(flashvars,flashContainer) (inizializza il componente swf)
 * - sendRTM(type,to,data)          (manda un messaggio a tutti i membri scatenando l'evento receiveRTM)
 *                                  usato per mandare gli eventi
 *                                  type:	String              -> msg, evt, act
                                    from:	Object              -> { id:xyz, name:pippo, ... }
                                    to:		Array of Objects    -> [ {id:xyz, name:pippo, ...}, {id:ert, name:maria, ...} ]
                                    data:	Object              -> { val:ciao, col:ff0000, brd:00ff00, size:10, weight:bold, style:italic } o { type:status, val:3 }
 * - updateUser(property,value)     (modifica una proprietà dello SharedObject dell'utente scatenando l'evento online_soSync)
 * - get_trackerLO()                (legge il LocalObject del trackID)
 * - set_lastpageLO(value)          (scrive nel LocalObject l'ultima pagina visitata)
 * - get_lastpageLO()               (legge nel LocalObject l'ultima pagina visitata)
 * - get_SO(SO,property)            (legge una data proprietà nello SO specificato)
 *
 * EVENTI:
 * - receiveRTM     (riceve i messaggi istantanei degli altri utenti online mandati da sendRTM)
 *                  usato per ricevere gli eventi: RTM_msg,RTM_evt,RTM_act
 *                  utilizzo: $(flashContainer).bind('nome evento', function(event){})
 * - online_soSync  (riceve la lista dei cambiamenti dello SO effettuati da updateUser)
 *                  usato per gestire le liste online
 *                  utilizzo: $(flashContainer).bind('onlineSync')
 * - NetStatusHandler (riceve i cambiamenti di stato alla connessione dell'utente)
 *                  utilizzo: $(flashContainer).bind('netStatusHandler')
 * - LOflushError   (evento scatenato dall'errore nel salvataggio dei LocalObject)
 *                  utilizzo: $(flashContainer).bind('LOflushError')
 **/
var presenceFlashInterface = {
    params : {
        flashContainer : '#presence',
        JSclass : 'presenceFlashInterface.',
        app     : 'boxpix_presence',
        room    : 'presence'
    },
    
    presence : undefined,

    init: function(_user,_trackID,_fms,_params)
    {
        if(!_user || !_fms) { // il trackID se manca forza l'inizializzazione sel SETTER nella classe LSO.as della presenza
            try{
                console.log('missing argument');
            }catch(e){};
            return;
        }
        
        this.params = $.extend(this.params, _params);

        var flashvars = $.toJSON({
            JSclass : this.params.JSclass,
            fms     : _fms,
            app     : this.params.app,
            room    : this.params.room,
            user    : _user,
            trackID : _trackID
        });
        
        /* eseguendo questa riga crea problemi con facebook */
        this.presence = flashembed(this.params.flashContainer,{
            id      : 'flashPresence',
            name    : 'flashPresence',
            src     : "/global/components/presence/presence.swf",
            wmode   : "opaque", //transparent,opaque,window
            width   : "1px",
            height  : "1px"
        },
        {
            vars : flashvars
        }).getApi();
        

    },
    // JS -> AS //////////////////////////////////
    sendRTM: function (rtm){
        this.presence.sendRTM(rtm);
    },
    updateUser: function (prop,val){
        //console.log('updatingSO: '+prop+' -> '+val);
        this.presence.updateUser(prop,val);
    },
    get_trackerLO: function (){
        //console.log('get trackID');
        return this.presence.get_tracker_lo();
    },
    set_trackerLO: function (val){
        //console.log('get trackID');
        this.presence.set_tracker_lo(val);
    },
    set_lastpageLO: function (val){
        this.presence.set_lastpage_lo(val);
    },
    get_lastpageLO: function (){
        return this.presence.get_lastpage_lo();
    },
    get_SO: function (SO,property){
        // if no property is defined the entire SO is returned
        return this.presence["get_"+SO](property);
    },
    // AS -> JS ////////////////////////////////////
    receiveRTM: function (type_from_to_data){
        // type:	String 			-> msg, evt, act
        // from:	Object 			-> { id:xyz, name:pippo, ... }
        // to:		Array of ID     	-> [ 'ID1', 'ID2', ... ]
        // data:	Object 			-> { val:ciao }
        var rtm =  $.evalJSON(type_from_to_data);
        //console.log(type_from_to_data);
        //console.log(rtm);

        // suddivido in diversi eventi così avrò diversi 'bind'
        var event   = jQuery.Event('RTM_'+rtm.type);
        event.rtm  = rtm;
        $(this.params.flashContainer).trigger(event);		
    },
    notification_soSync: function (changeList_json){
        // serve solo per identificare che lo SO è 'interrogabile'
        $(this.params.flashContainer).trigger('notificationSync');
    },
    online_soSync: function (changeList_json){
        var changeList = $.evalJSON(changeList_json);
        //console.log('online_soSync',changeList);
        var event = jQuery.Event('onlineSync');
        event.changeList = changeList;
        $(this.params.flashContainer).trigger(event);

    //        for (var el in changeList) {
    //            var elem = changeList[el];
    //            var id = elem.name;
    //            var action = elem.code;
    //            var oldVal = elem.oldValue;
    //            var newVal = elem.newVal;
    //            //console.log("elemento:",id,"azione:",action,"oldVal:",oldVal,"newVal:",newVal);
    //
    //
    //
    //            switch(action){
    //                case 'clear':
    //                    // mi sono connesso allo SO la prima volta oppure tutte le proprietà delle SO sono state cancellate
    //                    //console.log("mi sono connesso allo SO la prima volta oppure tutte le proprietà delle SO sono state cancellate");
    //                    break;
    //
    //                case 'delete':
    //                    // la proprietà col nome 'id' è stato rimossa dallo SO
    //                    //console.log(id +" - deleted");
    //                    //$.DOMCached.deleteKey(id, 'user');
    //                    break;
    //
    //                case 'change':
    //                    // qualcuno ha cambiato lo SO ed è arrivata la notifica
    //                    if(oldVal){
    //                        // l'elemento è stato modificato in una sua proprietà
    //
    //                        //console.log(id +" ("+oldVal.status+") - changed");
    //                        //console.log(id +" ("+newVal.status+") - changed");
    //                        //$.DOMCached.set(id, $.toJSON(newVal), false, 'user');
    //                        //$('#people_online').html(id +" ("+newVal.status+") - changed");
    //                    }else{
    //                        // l'elemento è stato aggiunto allo SO
    //                        //console.log(id +" ("+newVal.status+") - added");
    //                        //$.DOMCached.set(id, $.toJSON(newVal), false, 'user');
    //                        //$('#people_online').append("<li id='"+id+"'>"+ id +" ("+newVal.status+") - added</li>");
    //                    }
    //                    break;
    //
    //                case 'reject':
    //                    // non sono riuscito a cambiare lo SO, intanto un altro l'ha cambiato
    //                    //console.log('change status rejected');
    //                    break;
    //
    //                case 'success':
    //                    // ho modificato lo SO
    //                    //console.log('ho modificato lo SO');
    //                    break;
    //            }
    //        }
    },
    NetStatusHandler: function(code){
        //console.log("nc satus: ",code);
        $(this.params.flashContainer).trigger('NetStatusHandler',code);
    //        switch(code){
    //            case "NetConnection.Connect.Success":
    //                break;
    //
    //            case "NetConnection.Connect.Rejected":
    //                break;
    //
    //            case "NetConnection.Connect.Failed":
    //                break;
    //
    //            case "NetConnection.Connect.Closed":
    //                break;
    //        }
    },
    RSONetStatus : function(code){
        $(this.params.flashContainer).trigger('RSONetStatus',code);
    //        switch(code){
    //            case "SharedObject.BadPersistence":
    //                break;
    //            case "SharedObject.UriMismatch":
    //                break;
    //        }
    },
    LSOFlushStatus: function(code){
        $(this.params.flashContainer).trigger('LSOFlushStatus',code);
    //        switch(code){
    //            case "SharedObject.Flush.Failed":
    //                break;
    //            case "SharedObject.Flush.Success":
    //                break
    //        }
    }
// JS -> JS ///////////////////////////////////////////////
//    chkKey: function (e){
//        if(e.keyCode == 13){
//            e.preventDefault();
//
//            if ( $('#chat_input').val() == "") return false;
//
//            var tx = $('#chat_input').val();
//            presenceFlashInterface.sendRTM('msg',[],tx);
//            $('#chat_input').val('');
//        }
//    }
};

