var Analytics = Class.create({
    subscribers : {},
    listeners : {},
    fromConfigListeners : [],
    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.jsEvents = (typeof CONVERSION_EVENTS != "undefined" ) ? CONVERSION_EVENTS : [];
              self.jsEvents = self.jsEvents.concat( (typeof JS_EVENTS != "undefined" ) ? JS_EVENTS : [] );  
            if (typeof self.jsEvents != "undefined"){
                self.jsEventsWaited = [];

                self.jsEvents.each(function(CEVENT){
                    CEVENT.hookIds = [];  // allow for mapping one event to many elements
                    //console.log("event on ", CEVENT); 
                    //Check for events to wait on, loading iframes, bv etc to be custom handled in static listeners
                    //if the ele is expected to exist on load, then the event handlers can be set up right away in addFrontendEvent

                    if (CEVENT.after){
                        self.jsEventsWaited.push(CEVENT);
                    }else{                    
                        self._addFrontendEvent(CEVENT); 
                    } 
                    
                }); 
            }

        });
        //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"}]}});
        });

        // BV loaded and ready this is just a place to handle the event, tags come from the backend config. 
        document.observe("bv:loaded", function(){
              console.log("BV IS LOADED",self.jsEventsWaited);
            self.jsEventsWaited.each(function(EVENT){
               if (EVENT.after && EVENT.after == 'bv:loaded'){
                   self._addFrontendEvent(EVENT); 
               } 
            }); 

        });
        document.observe("bv:created", function(){
              console.log("BV IS LOADED",self.jsEventsWaited);
            self.jsEventsWaited.each(function(EVENT){
               if (EVENT.after && EVENT.after == 'bv:created'){
                   self._addFrontendEvent(EVENT);
               }
            });

        });

        // 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);
                                }
                            }
                        });
                    }
                }
            }
        });
    

        //Page data already exists hook
        document.observe('PAGEDATA:RESULT', function(obj){

            console.log("GOT PAGE DATA ",obj);
            if (typeof obj.memo != "undefined"){
                var catalog_path = obj.memo;
                if (typeof eval ('page_data.' + catalog_path) != "undefined"){
                    if (typeof eval ('page_data.' + catalog_path + '.rpcdata.result') != 'undefined'){
                        if (newTags = eval ('page_data.' + catalog_path + '.rpcdata.result.Analytics') ){ 
                            console.log("page data ",newTags);
                            self.addPendingTags(newTags);
                        }else{
                            console.log("NO TAG DATA FROM PAGE DATA - rpcdata.result.Analytics");
                        }
                    }else{
                        console.log("NO TAG DATA FROM PAGE DATA - rpcdata.result");
                    }  
                }else{
                    console.log("NO TAG DATA FROM PAGE DATA - catalog_path");
                } 
            }else{
                console.log("NO TAG DATA FROM PAGE DATA - obj.memo");
            }            
         
        }); 

    },

    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]);
                    
                    } 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);
            // removed by not deleted yet EF 
            //return;
        } 

        if (EVENT.event == "dom:loaded"){
            self.execTagsbyType(EVENT);
        }else{
            if (EVENT.domID || (EVENT.attachAttr && EVENT.attachValue) ){
               self._attachFrontendEvent(EVENT);  
            }
        }
    },

    _attachFrontendEvent: function(EVENT){
        var self = this; 
            // EVENT.attachAttr && EVENT.attachValue are required unless EVENT.domID is specified(for legacy cases with email signups)

            if (EVENT.domID){
                 EVENT.attachAttr = 'id';
                 EVENT.attachValue = EVENT.domID;
            }  
            if (typeof EVENT.attachTag == "undefined"){
                 EVENT.attachTag = '';
            }
            if (EVENT.attachAttr && EVENT.attachValue){
               console.log ( "got ",EVENT.attachTag,EVENT.attachAttr,EVENT.attachValue,EVENT.event);
               var theseListeners = [];
               $$(''+ EVENT.attachTag + '[' + EVENT.attachAttr + '=' + EVENT.attachValue + ']').each(function (ele){
                    EVENT.hookIds.push( $(ele).identify() ); // if id doesn't exist give it one to use for matching in event handlers  
                    self.fromConfigListeners.push(ele); // keep a full current list for ref
                    theseListeners.push(ele); // but don't dupilicate events
               });

                 theseListeners.each( function(ele){
                       //console.log("DOM ID IS ",EVENT.domID,EVENT,ele);
                     ele.observe(EVENT.event, function(evt){  
                        console.log("running event ",evt);
                    
                        // which events match in the current list?  
                        var cevents;
                        self.jsEvents.each(function(CEVENT){
                             unique_hooks = CEVENT.hookIds.uniq(); //super make sure that no dup ids exist 
                             unique_hooks.each(function(hooks){
                                var nodecheck = null;
                                if (hooks == evt.target.parentNode.id){
                                   nodecheck = evt.target.parentNode.id; 
                                }
                                if (hooks == evt.target.id){
                                   nodecheck = evt.target.id;
                                } 
                                if (nodecheck){
                                    cevents = CEVENT;
                                    console.log("HOOK MATCHED ",hooks,CEVENT);
                                    // now we know the event and have the data, exec the tag according to type
                                    self.execTagsbyType(CEVENT);
                                }
                             });
                        });
                        ele.stopObserving();
                     });
               });
            }
     },


    // tags specificly connected to user actions and tags more closely connected to frontend events vs backend data, like prodcat    
     /*
         cmCreatePageElementTag(elementID, elementCategory,attributes) 
         cmCreateManualPageviewTag(pageID, categoryID,DestinationURL,ReferringURL) 
         cmCreateManualLinkClickTag(href,name,pageID) 
         cmCreateManualImpressionTag(pageID, trackSP, trackRE) 
         cmCreateErrorTag(pageID, categoryID) 
     */
    execTagsbyType: function(CEVENT){
        if (CEVENT.type == 'conversion_event'){
            if (CEVENT.points < 1){
                CEVENT.points = '"0"';
            }

    
            this.addPendingTags({"CoreMetrics":{"dom:loaded":[{"params":[CEVENT.eventID, CEVENT.actionType, CEVENT.cat, CEVENT.points,CEVENT.attributes],"tag":"cmCreateConversionEventTag"}]}});
        }
        if (CEVENT.type == 'element'){
            this.addPendingTags({"CoreMetrics":{"dom:loaded":[{"params":[CEVENT.elementID,CEVENT.elementCategory,CEVENT.attributes],"tag":"cmCreatePageElementTag"}]}});
        }
        if (CEVENT.type == 'mpageview'){
            this.addPendingTags({"CoreMetrics":{"dom:loaded":[{"params":[CEVENT.pageID,CEVENT.categoryID,CEVENT.DestinationURL,CEVENT.ReferringURL],"tag":"cmCreateManualPageviewTag"}]}});
        }
        if (CEVENT.type == 'mlinkclick'){
            this.addPendingTags({"CoreMetrics":{"dom:loaded":[{"params":[CEVENT.href,CEVENT.name,CEVENT.pageID],"tag":"cmCreateManualLinkClickTag"}]}});
        }
        if (CEVENT.type == 'mimpression'){
            this.addPendingTags({"CoreMetrics":{"dom:loaded":[{"params":[CEVENT.pageID,CEVENT.trackSP,CEVENT.trackRE],"tag":"cmCreateManualImpressionTag"}]}});
        }
        if (CEVENT.type == 'error'){
            this.addPendingTags({"CoreMetrics":{"dom:loaded":[{"params":[CEVENT.pageID,CEVENT.categoryID],"tag":"cmCreateErrorTag"}]}});
        }

     

    },

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

