﻿/*! 
* jsHub open source tagging
*
* Custom plugin for Read It Swap It
* Prepared by Causata consulting
*/

// JSLint options
/*global jsHub, diPageData */
/*jslint white: true, browser: true, laxbreak: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, strict: true, newcap: true, immed: true, maxerr: 50, indent: 2 */
"use strict";

(function() {

    /*
    * Metadata about this plug-in for use by UI tools and the Hub
    */
    var metadata = {
        name: 'Read It Swap It custom page data plugin',
        id: 'risi-custom',
        version: 1.0,
        vendor: 'Causata consulting',
        type: 'data-capture'
    };

    /*
    * First trigger an event to show that the plugin is being registered
    */
    jsHub.trigger("plugin-initialization-start", metadata);

    /**
    * Capture page data from the pagedata object in the page
    * @method capture
    * @param event {Object} Config object for the plugin, containing data found by other plugins, and
    * the context (DOM node) to start parsing from.
    * @property metadata
    */
    metadata.eventHandler = function capture(event) {

        // Notify start lifecycle event
        jsHub.trigger("RISI-parse-start", event);

        if (!window.pagedata) {
            jsHub.trigger("RISI-parse-failed");
            return;
        }

        var name, data = event.data, pagedata = window.pagedata;

        for (name in pagedata) {
            if (pagedata.hasOwnProperty(name)) {

                if (name === "page-view") {
                    var attr, pageViewData = pagedata["page-view"];
                    for (attr in pageViewData) {
                        if (pageViewData.hasOwnProperty(attr)) {
                            data[attr] = pageViewData[attr];
                        }
                    }

                } else {
                    // otherwise trigger an event with that name
                    jsHub.trigger(name, pagedata[name], event.timestamp);
                }

            }
        }

        // and send to output plugins
        return data;
    };

    /*
    * Bind the plugin to the Hub to look for data to add to page view events
    */
    jsHub.bind("page-view", metadata);

    /*
    * Last trigger an event to show that the plugin has bene registered
    */
    jsHub.trigger("plugin-initialization-complete", metadata);
} ());
