IBSYS.using('widgets');
IBSYS.noLegacyTracking = false;

/**
 * The odd layout prevents multiple instantiations.
 */
IBSYS.widgets.DAPTracking=(IBSYS.widgets.DAPTracking || new function() {
    var widgets = [];

    /**
     * Called by XSLT: /iadyn/natlv2/xsl/browser4/sectionwidget.xsl
     */
    this.addWidget = function(id, kind, indexMap, xmlblockIDs) {
        if (xmlblockIDs === undefined || xmlblockIDs === null) { // XXX: Avoid js errors during deployment 
            xmlblockIDs = [];
        }
        if (widgets.length == 0) {
            initClickEvent();
        }
        widgets.push({id:id, kind:kind, indexMap:indexMap, xmlblockIDs:xmlblockIDs});
    };

    /**
     * Expensive if called more than once.
     */
    function initClickEvent() {
        IBSYS.tracking.trackingManager.setEventMapping('dapFWClicked', [{
            Strategy: {
                Name: 'WebTrends',
                Parameters: {
                         'WT.dl': '9',
                         'dcsID': 'dcsmprg6d00000sh88j0fli5q_8n3n',
                      'ib_event': 'click',                             /* Click tracking */
                       'ib_Wdgt': 'FW',                                /* Fixed Widgets */
                       'ib_ntwk': {propPath: 'siteinfo.distribution'}, /* core or extended net */
                    'ib_station': {application: 'station.identifier'},
                    'ib_partner': {application: 'station.ownergroup'},
                         'mtype': {meta: 'DCSext.mtype'},
                       'WT.cg_n': {meta: 'WT.cg_n'},
                       'FW_htln': {eventSource: '__coid' },   /* contentID */
                      'FW_icoid': {eventSource: '__icoid' },  /* index contentID */
                       'FW_kind': {eventSource: '__kind' },   /* client specific ID */
                        'FW_pos': {eventSource: '__pos' },    /* position (starts at 1) */
                         'FW_dm': {eventSource: '__dm' },     /* display method */
                   'mapReferrer': true
                }
            }
        }]);
    }

    function clickHook(e) {
        // The target should be stuffed full of our
        // own properties.  Sometimes we need to go up
        // a parent (for images inside <A> tags).
        var targetElement = YAHOO.util.Event.getTarget(e);
        if (!targetElement.__coid) {
            targetElement = targetElement.parentNode;
            if (!targetElement.__coid) {
                // assert fail!
                IBSYS.log("Error");
                IBSYS.log(targetElement);
            }
        }
        try {
            var myEvent = new IBSYS.event.GlobalEvent("dapFWClicked", targetElement);
            IBSYS.application.Application.announceEvent(myEvent);   
        } catch (x) {
            IBSYS.log(x);
        }
        return true;
    }
    
    /**
     * The argument looks like this:
     *      index = {
     *          id:12345,
     *          content:[{id:123, dm:'BL'}]
     *      }
     *
     * This should be refactored into getDisplayMethod()!
     */
    function registerIndexClicks(index, kind) {
        var parentIndexDOM = document.getElementById('index'+index.id);
        var bycn=YAHOO.util.Dom.getElementsByClassName;

        for (var j=0; j < index.content.length; ++j) {
            var scope = bycn('co'+index.content[j].id, '*', parentIndexDOM);
            if (scope.length == 0) continue;
            var el = scope[0];

            // Within the parent, look for Hyperlinkage-
            var nl=el.getElementsByTagName('a');
            for (var ii=0; ii<nl.length; ++ii) {
                YAHOO.util.Event.addListener(nl.item(ii),'click',clickHook,this,true);
                nl.item(ii).__coid = index.content[j].id;
                nl.item(ii).__icoid = index.id;
                nl.item(ii).__dm = index.content[j].dm;
                nl.item(ii).__pos = (j+1);
                nl.item(ii).__kind = kind;
            }
        }
    }
    
    /**
     * XMLBlock click elements include any anchor tag, and form ONSUBMIT
     * events.
     */
    function registerXMLBloxClicks(parentDOM, coid, kind) {
        // XXX: parentDOM refers to a sectionwidget.  Therefore it is possible to register
        // MORE elements than we intend to here.  In practice I have not seen this (all
        // xmlblox that come through here are in their own widget).
        // But this should still be fixed someday.
        var links = parentDOM.getElementsByTagName('a');
        for (var j=0; j < links.length; ++j) {
            YAHOO.util.Event.addListener(links.item(j),'click',clickHook,this,true);
            links.item(j).__coid = coid;
            links.item(j).__dm = 'xmlb';
            links.item(j).__pos = 1;
            links.item(j).__kind = kind;
        }
        var forms = parentDOM.getElementsByTagName('form');
        for (var j=0; j < forms.length; ++j) {
            YAHOO.util.Event.addListener(forms.item(j),'submit',clickHook,this,true);
            forms.item(j).__coid = coid;
            forms.item(j).__dm = 'xmlb';
            forms.item(j).__pos = 1;
            forms.item(j).__kind = kind;
        }
    }
    
    /* Match the class-name of headline elements. */
    var HEADLINE_RE = /(?:^|\s+)(?:item|bullet|inline|Headline(?:Wrap)?)(?:\s+|$)/;
    
    /**
     * Return an underscore-delimited list of 'display methods' as reflected
     * in webtrends.  
     * 
     * Note that this is not the same as CMS/XSL display method.
     */
    function getDisplayMethod(coid, parentIndexDOM) {
        var bycn=YAHOO.util.Dom.getElementsByClassName;
        var scope = bycn('co'+coid, '*', parentIndexDOM);
        if (scope.length == 0) {
            // XXX: This is an exceptional condition. 'co12345678' will show up in
            // DAP FW reports in webtrends, indicating that we failed to find
            // a displaymethod for 'coid'.  In that case, fix this function.
            return 'co'+coid; 
        }
        var hasImage=false, hasTeaser=false, hasHeadline=false;
        for (var j=0; j<scope.length; ++j) {
            if (String(scope[j].className).indexOf("coimage")!=-1) 
                hasImage=true;
            if (String(scope[j].className).indexOf("teaser")!=-1)
                hasTeaser=true;
            if (HEADLINE_RE.test(scope[j].className))
                hasHeadline=true;
            if (hasImage && hasTeaser && hasHeadline) {
                break; // Bail out if we know we have the full set.
            }
        }
        var sb = [];
        if (hasImage) { sb.push('img'); }
        if (hasTeaser) { sb.push('tsr'); }
        if (hasHeadline) { sb.push('hdln'); }
        return sb.join('_');
    }

    var dcsHook = function(e) {
        if (e.getName()!='beforeDcsTag') // bail out!
            return;
        if (widgets.length==0)  // bail out!
            return;
        
        var kinds=[], coids=[], dm=[], icoids=[], pos=[];
        do {
            var item=widgets.shift();
            var swElement=document.getElementById('sw'+item.id);
            
            if (item.xmlblockIDs.length > 0) {
                // XMLBlocks tracked with a special tag, written INSIDE 
                // the xmlblox:  <tracking/>
                for (var j=0; j < item.xmlblockIDs.length; ++j) {
                    dm.push('xmlb');
                    kinds.push(item.kind);
                    coids.push(item.xmlblockIDs[j]);
                    pos[pos.length]=1;
                    
                    registerXMLBloxClicks(swElement, item.xmlblockIDs[j], item.kind);
                }
            }
            
            // Double loopage: 
            // Indeces within the widget...
            for (var pp=0; pp<item.indexMap.length; ++pp) {
                var index = item.indexMap[pp];
                icoids.push(index.id);
                var parentIndexDOM = document.getElementById('index'+index.id);

                // ...And, content objects within the index.
                for (var xx=0; xx < index.content.length; ++xx) {
                    kinds.push(item.kind);
                    pos[pos.length] = (xx+1);
                    coids.push(index.content[xx].id);
                    dm.push(getDisplayMethod(index.content[xx].id, parentIndexDOM));
                }

                registerIndexClicks(index, item.kind);
            }
        } while (widgets.length > 0);

        var widgetParam = 'FW';

        DCSext.FW_icoid = icoids.join(';');
        DCSext.ib_Wdgt = (DCSext.ib_Wdgt===undefined ? widgetParam : DCSext.ib_Wdgt+';'+widgetParam);
        DCSext.FW_htln = coids.join(';');
        DCSext.FW_kind = kinds.join(';');
        DCSext.FW_dm = dm.join(';');
        DCSext.ib_event = "view";
        DCSext.FW_pos = pos.join(';');
    };
    IBSYS.application.Application.addEventListener(dcsHook, window);
});

