'use strict';

// constructor
function BackToTop(options) {
    options = (options === undefined) ? {} : options;
    this.scroll_context  = options.scroll_context   || 'window'
    this.scroll_boundary = options.scroll_boundary || 50;
    this.opacity_offset  = options.opacity_offset  || 1200;
    this.scroll_duration = options.scroll_duration || 700;
    this.id              = options.id              || "#back-to-top";
    this.append_to       = options.append_to       || 'body';

    this.create();
    this.addScrollListener();
    this.addClickListener();
}

// prototype overriding
// apply constructor and functions
(function() {

    this.constructor = BackToTop;

    this.create = function() {
        $(this.append_to).append('<a href="#" id=' + this.id.substring(1) + '></a>');
    };

    this.addScrollListener = function() {
        var data = {
            id: this.id,
            sB: this.scroll_boundary,
            oF: this.opacity_offset
        };


        $(this.scroll_context).on('scroll', data, function(e) {
            ($(this).scrollTop() >= e.data.sB) ? $(e.data.id).addClass('is-visible'): $(e.data.id).removeClass('is-visible reduce_opacity');
            if ($(this).scrollTop() > e.data.oF) {
                $(e.data.id).addClass('reduce_opacity');
            }
        });
    };

    this.addClickListener = function() {
        $(this.id).on('click', {
            sD: this.scroll_duration,
            sC: this.scroll_context
        }, function(e) {
            e.preventDefault();
            $(e.data.sC).animate({
                scrollTop: 0
            }, e.data.sD);
        });
    };

}).call(BackToTop.prototype);

//
// add the back-to-top button
//
$(document).ready(function() {
  var options = {
    'scroll_context': '#main_content',
    'scroll_boundary': 100,
    'opacity_offset': 600
  }
  new BackToTop(options);
});
