(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery', 'jquery.mobile', 'moment'], factory);
    } else {
        factory(jQuery);
    }
}(function($){
	'use strict';
	$.widget('va.refresher', {
		_init: function(){
			if(!this.element.find(".refresh-container").length){
				this.refreshButtonOnly = ( /^false$/i.test(this.options.date) && /^false$/.test(this.options.time) ) || this.options.refreshButtonOnly;
				this.element.append(this._template());
				this.element.attr("data-refresher", true);
				this._refreshHandler();
			}
			this.updateTime();
		},
		_refreshHandler: function(){
			var that = this,
				refreshInterval;
			this.$container.on('click', '#refresh-btn', function(e){
				if(that.options.callback){
					if(that.options.context){
						that.options.callback.call(that.options.context);
					}
					else{
						that.options.callback.call();
					}
				}
				that.updateTime();
				that.$button.addClass('active');
				that.$container.off('click');
				refreshInterval = setInterval(function(){
					if(!$.active){
						that.$button.removeClass('active');
						clearInterval(refreshInterval);
						that._refreshHandler();
					}
				}, 500 );
			});
		},
		_template: function(){
			var icon 		= this.options.icon || 'icon-refresh';
			this.$container = $('<div class="refresh-container"></div>');
			this.$button 	= $('<div class="' + icon + '" id="refresh-btn"></div>');
			this.$subcontainer = $('<div></div>');
			this.$label 	= $('<span class="label">' + ( this.options.label || 'Updated' ) + ':</span>');
			this.$datetime 	= $('<span class="refresh-time"></span>');

			this.$container
				.append(this.$button)
				.append(this.$subcontainer);

			if(!this.refreshButtonOnly){
				this.$subcontainer
					.append(this.$label)
					.append(this.$datetime);
			}

			return this.$container;
		},
		updateTime: function(){
			this.$datetime.text(moment().format(this.getFormat.call(this)));
		},
		getFormat: function(){
			var format = '';
			if(this.options.customFormat){
				return this.options.customFormat;
			}
			if(!/^false$/i.test(this.options.date)){
				format = 'MM/DD/YYYY';
			}
			if(!/^false$/i.test(this.options.time)){
				format = format + ((format.length) ? ' ' : '' ) + 'hh:mm a';
			}
			return format;
		},
		_destroy: function(){
			// this.element.removeAttr("data-refresher");
			this.$container.detach();
			this.$container.off();
		}
	});
}));