﻿/* globals
    jQuery, CsLogger
 */
/* exported
 */
"use strict";
(function ($, window, document, undefined) {

    // default settings.
    var _pluginName = "document";
    var _defaultsOptions = {
        debug: false,
    };
    var _logger = new CsLogger(_pluginName);

    var _downloadUrlLink;

    // constructor.
    function Document(element, options) {
        this._element = element;

        // $.extend to store user provided options.
        this._options = $.extend({}, _defaultsOptions, options);
        this._defaultOptions = _defaultsOptions;
        this._name = _pluginName;
        this.init();

        _downloadUrlLink = options.downloadUrlLink;
    }

    // (void) ensure the selected element is valid.
    function validateElement(element) {
        _logger.log("validateElement()");
        if (element == undefined || $(element).length == 0) {
            _logger.error("selected element is not valid.");
            return;
        }
    }

    // (void) validate the options passed into the plugin.
    function validateOptions(options) {
        if (typeof (options.debug) == "boolean" && options.debug == true) {
            _logger.enable();
        }
        _logger.obj("validateOptions() | opts:", options);
    }

    // prototype extensions.
    Document.prototype = {

        // (void) initialise.
        init: function () {
            validateOptions(this._options);
            validateElement(this._element);
            _logger.log("init()");

            bindControls(this._element);
        }
    };

    function bindControls(element) {
        var $element = $(element);

        var downloadClick = $element.find('.download-document-click');

        downloadClick.off('click');
        downloadClick.on('click', function () {
            var documentId = this.attributes.getNamedItem("data-documentId").value;
            var folderId = this.attributes.getNamedItem("data-folderId").value;

            var url = _downloadUrlLink
                .replace('{folderId}', folderId)
                .replace('{documentId}', documentId);

            window.open(url);
        });
    }

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[_pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + _pluginName)) {
                $.data(this, "plugin_" + _pluginName,
                    new Document(this, options));
            }
        });
    };
})(jQuery, window, document);