var Analytics = Class.create({
    subscribers : {},
    listeners : {},
    seenMemoWithTag : {},
    isEnabled: false,
    enabledModules: new Array(),

    RPC_METHODS_ALLOWED: new Hash({
        "prodcat" : 1,
        "generic" : 1,
        "cart" : 1,
        "rpc.form" : 1,
        "search" : 1,
        "email.signup" : 1
    }),

    initialize: function(modules,enabled){
        this._addStaticListeners();
    },
    addPendingTags: function(newTags ){
        this.pendingTags = newTags;
        this.execTags();
        return this;
    },
    _addStaticListeners: function(){
        var self = this;
        document.observe("dom:loaded", function(){
            self.isEnabled = (typeof ANALYTICS_ENABLED != "undefined") ? ANALYTICS_ENABLED : false;
            self.enabledModules = (typeof ANALYTICS_MODULES != "undefined" ) ? ANALYTICS_MODULES : [];

            // CONVERSION EVENTS - If conversion events exist add handler as directed and form input for location 
            self.conversionEvents = (typeof CONVERSION_EVENTS != "undefined" ) ? CONVERSION_EVENTS : [];
            if (typeof self.conversionEvents != "undefined"){
                //console.log(self.conversionEvents);
                self.conversionEvents.each(function(CEVENT){
                    console.log("event on ", CEVENT); 
                    //_addFrontendEvent: function(myElement,myEvent,tagBlocks){  
                      self._addFrontendEvent(CEVENT); 
                    
                }); 

            }

            
            // console.log( "Analytics enabled: ", self.isEnabled );
            // console.log( "Analytics registered modules: ", self.enabledModules );
          // live chat and conversion events by name
          $$('a[livechat="1"]').invoke('observe', 'click', function(e) {
            liveperson_tag_cm();
          });
          $$('input[conversion_event="1"]').invoke('observe', 'focus', function(e) {
            conversion_event_footer();
          });

        });
        //Search hook for frontend and soon Endeca
        document.observe("search:results", function(event){
            var res = event.memo;
            self.addPendingTags({"CoreMetrics":{"dom:loaded":[{"params":[res.pageid,res.keywords,res.cat,'"' + res.count +'"',null],"tag":"cmCreatePageviewTag"}]}});
        });

        // our RPC hook
        document.observe('RPC:RESULT', function(obj){
            var rpcRequestArray, rpcResponseArray;
            var requestMethod, requestId;
            if (typeof obj.memo.request != "undefined") {
                rpcRequestArray = (obj.memo.request.parameters.JSONRPC != null) ?
                    obj.memo.request.parameters.JSONRPC.evalJSON() :
                    null;

                if (rpcRequestArray) {
                    rpcResponseArray = obj.memo.responseText.evalJSON();
                    if (rpcResponseArray) {
                        rpcRequestArray.each(function(rpcRequest){
                            requestMethod = rpcRequest.method;
                            requestId = rpcRequest.id;
                            // console.log("Analytics handling RPC request:  ", requestMethod, " with id: ", requestId);

                            // We can do special handlers for requests here or filter out non handled requests... 
                            if (!self.RPC_METHODS_ALLOWED.get(requestMethod)) {
                                // console.log("Analytics skipped ", requestMethod);
                            } else {
                                // Make sure we have the response for this request (id's must match).
                                var myRpcResponse = rpcResponseArray.find(function(rpcResponse){
                                    return rpcResponse.id == requestId
                                });
                                if (myRpcResponse && myRpcResponse.result != null) {
                                    //console.log("Analytics will handle ", myRpcResponse.result.data.Analytics);
                                    var newTags = myRpcResponse.result.data.Analytics;
                                    self.addPendingTags(newTags);
                                }
                            }
                        });
                    }
                }
            }
        });
    },
    addDynamicListener: function(taggingModule, myEvent, TagBlocks){
        var self = this;
        var id = "default";
        TagBlocks.each(function(tagBlock){
            if (typeof tagBlock.memo != "undefined") {
                id = tagBlock.memo;
            }
            if (!self.subscribers[id]) { self.subscribers[id] = {}; }
            if (!self.subscribers[id][taggingModule]) { self.subscribers[id][taggingModule] = {}; };
            if (!self.subscribers[id][taggingModule][myEvent]) {
                self.subscribers[id][taggingModule][myEvent] = new Array();
            } else {
                 //console.log( "Event is defined ", self.subscribers[id][taggingModule][myEvent] );
            }

            if (!self.seenMemoWithTag[id]) { self.seenMemoWithTag[id] = {}; }
            if (!self.seenMemoWithTag[id][tagBlock.tag]) {
                self.seenMemoWithTag[id][tagBlock.tag] = 1;
                self.subscribers[id][taggingModule][myEvent].push(tagBlock);
                //console.log( "pushed Event for: id: ", id, " taggingModule: ", taggingModule, " event: ", myEvent, " -> ", self.subscribers[id][taggingModule][myEvent] );
            }

        });

        // Attach the listener for this event type.
        if (!self.listeners[myEvent]) {
            self.listeners[myEvent] = 1;
            //Event.observe(window, myEvent, function(evt){
            document.observe(myEvent, function(evt){
                //console.log("running window event: ", myEvent, " with memo: ", evt.memo);

                var myId = evt.memo;
                self.enabledModules.each(function(taggingModule){
                     //console.log("for tagging module: ", taggingModule);
                    if (typeof self.subscribers[myId][taggingModule] != "undefined"){
                       if (self.subscribers[myId][taggingModule][myEvent]) {
                          self.execEventTagBlocks( self.subscribers[myId][taggingModule][myEvent] );
                       }
                    }
                });
            });
        }
    },
    execTags: function (){
        var self = this;
        if (typeof self.pendingTags == "object") {
            Object.keys(self.pendingTags).each(function(taggingModule){
                if (typeof taggingModule != "object" && self.pendingTags[taggingModule] == 'notag') {
                        return;
                }
                Object.keys(self.pendingTags[taggingModule]).each(function(myEvent){
                    // console.log("Analytics: module / event ", taggingModule, myEvent);
			        if (myEvent != 'dom:loaded'){
                        // register this event with our collection of listeners.
                        self.addDynamicListener(taggingModule, myEvent, self.pendingTags[taggingModule][myEvent]);
                        // and then execute it
                        //self.execEventTagBlocks( self.pendingTags[taggingModule][myEvent] );
                    } else {
                        // incoming tagging events under the 'dom:loaded' label can be executed straightaway.
                        self.execEventTagBlocks( self.pendingTags[taggingModule][myEvent] );
                    } 
                }); 
            });
        }
    },
    execEventTagBlocks: function(tagBlocks){
        tagBlocks.each(function(tagBlock){
            if (!tagBlock.params || !tagBlock.tag) { return; }
                 console.log( "Analytics.execEventTagBlocks about to execute tag: ", tagBlock.tag, " with params: ", tagBlock.params );
            if (typeof window[tagBlock.tag] == "undefined") {
                 //console.log( "The Tagging Module function is not found: ", tagBlock.tag );
                return;
            }
            window[tagBlock.tag].apply(this, tagBlock.params);
        });
    },

    _addFrontendEvent: function(EVENT){
        var self = this;

        if ( $(EVENT.domID) == null && EVENT.event != "dom:loaded" ){
            console.log("CM ELEMENT does not EXIST! ",EVENT.domID);
            return;
        } 
        if (EVENT.event == "dom:loaded"){
            if (EVENT.type == 'conversion_event'){
                 if (EVENT.points < 1){
                      EVENT.points = '"0"';
                 }
                 self.addPendingTags({"CoreMetrics":{"dom:loaded":[{"params":[EVENT.eventID, EVENT.actionType, EVENT.cat, EVENT.points,EVENT.attributes],"tag":"cmCreateConversionEventTag"}]}});
             }
           // other event types
        }else{

            Event.observe(EVENT.domID,EVENT.event, function(evt){
                var cevents;        
                console.log("CM Conv events ",evt.target.id);
                 self.conversionEvents.each(function(CEVENT){
                       if (CEVENT.domID == evt.target.id){
                           cevents = CEVENT;
                       }
                    });

                if (cevents.type == 'conversion_event'){
                     if (cevents.points < 1){
                          cevents.points = '"0"';  
                     }
                     self.addPendingTags({"CoreMetrics":{"dom:loaded":[{"params":[cevents.eventID, cevents.actionType, cevents.cat, cevents.points,cevents.attributes],"tag":"cmCreateConversionEventTag"}]}});
                     Event.stopObserving(cevents.domID,cevents.event);
               
                }
                
            });
        }
    },


    // Possible special funtions for front end (reserved for future use)
    onDivShow: function() {},
    onFrameUpdate: function() {},
    onJsRedirect: function() {}
});
Analytics = new Analytics();

