BLIP.Class.create('BLIP.Unit.DropDown.HoverDropDown.SubscriptionsDropDown', BLIP.Unit.DropDown.HoverDropDown,
	function(config) {
		BLIP.Unit.DropDown.HoverDropDown.call(this, config);
	},
	{
		selector : '.SubscriptionsDropDown',

		showTitleTrimSize : 26,

		init : function () {
			BLIP.Unit.DropDown.HoverDropDown.prototype.init.call(this);
			this.positionList();
			this.setupTracking();
		},

		setupTracking : function() {
			this.domRoot.find('.SubscriptionItem a').live('click', function(ev) {
				var name = $(this).find('span').html();
				_analytics.trackLinkClick(this, 'header-subscriptions-click', name);
			});
		},

		openDropDown : function() {
			var countElement = this.domRoot.find('.Count'),
				count = parseInt(countElement.html(), 10);

			if(!count) {
				return;
			}

			BLIP.Unit.DropDown.prototype.openDropDown.call(this);

			if(!this.hasLoadedItems) {
				this.loadItems();
			}
		},

		closeDropDown : function() {
			BLIP.Unit.DropDown.prototype.closeDropDown.call(this);
		},

		loadItems : function() {
			this.domRoot.addClass('Loading');
			$.getJSON('/subscriptions/masthead_list?no_wrap=1', this.delegate(this.onItemsLoaded));
		},

		positionList : function() {
			var offsetHeight = this.domRoot.height();
			this.domRoot.find('.SubscriptionsDropDownContent').css('top',offsetHeight+'px');
		},

		onItemsLoaded : function(data) {
			this.domRoot.removeClass('Loading');
			if(data.error) {
				this.onItemsLoadedError();
			}
			else {
				this.onItemsLoadedSuccess(data);
			}
		},

		onItemsLoadedError : function() {
		},

		onItemsLoadedSuccess : function(data) {
			var listFragment = document.createDocumentFragment(),
				template = this.domRoot.find('.SubscriptionItem.Template'),
				item = null,
				itemDOM = null,
				i = 0,
				len = data.length;

			for(; i < len; i++) {
				itemDOM = this.bindItemTemplate(template, data[i]).get(0);
				listFragment.appendChild(itemDOM);
			}


			this.domRoot.find('.SubscriptionsDropDownContent')
				.append(listFragment)
				.find('.Template')
					.remove();

			this.hasLoadedItems = true;
		},

		bindItemTemplate : function(template, data) {
			var name = data.display_name.length > this.showTitleTrimSize ?
				data.display_name.slice(0, this.showTitleTrimSize) :
				data.display_name;

			return template.clone()
				.removeClass('Template')
				.find('a')
					.attr('href', data.url)
					.end()
				.find('.SeriesTitle')
					.html(name)
					.end()
				.find('.SeriesEpisodeCount')
					.html(data.count)
					.end();
		}
	}
);

