/**
 * Header.js
 *
 * Takes care of the header expandomenu
 */
BLIP.Class.create("BLIP.Unit.Header", BLIP.Unit,
	function(config) {
		BLIP.Unit.call(this, config);
	},
	{
		selector : "#Header",

		init : function() {
			var thisContext = this;

			this.splitChannelList();

			// This code is for the elements in the header that "open" when they
			// are hovered over. We need to make sure and close each one before
			// we allow the one we want to open. That way, a user can't have
			// more than one dropdown in the header open at the same time.
			this.captions = this.initSubUnit(BLIP.Unit.DropDown.HoverDropDown, {
				captionSelector: ".HeaderCaption",
				onOver: function () {
					try {
						thisContext.captions.each(thisContext.closeUnitDropDown);
						thisContext.facebookSubscriptions.each(thisContext.closeUnitDropDown);
						thisContext.searchField.close();
					} catch (x) {
						// if it gets here, it's probably IE8 complaining about the search
						// field not being initialized.
					}
					finally {
						this.openDropDown();
					}
				}
			});

			this.searchField = this.initSubUnit(BLIP.Unit.SearchField, {
				onOpened: function () {
					try {
						thisContext.captions.each(thisContext.closeUnitDropDown);
						thisContext.facebookSubscriptions.each(thisContext.closeUnitDropDown);
					} catch (x) {
					}
				}
			}).single();

			this.initFacebook();
			this.domRoot.find(".ChannelList").attr('style',"");
			this.domRoot.find("#SwitchUsersLink").hover(
				this.delegate(this.onMouseOverSwitchUsersLink),
				this.delegate(this.onMouseOutSwitchUsersLink)
			);

			this.suColumn = this.domRoot.find("#FastUserSwitchingColumn");

			this.suColumn.hover(
				this.delegate(this.onMouseOverSwitchUsersColumn),
				this.delegate(this.onMouseOutSwitchUsersColumn)
			);
			this.addEventListener('FacebookLogin', this.delegate(this.onFacebookLogin));
			this.addEventListener('SubscribedToShow', this.delegate(this.onSubscribedToShow));
			this.addEventListener('UnsubscribeFromShow', this.delegate(this.onUnsubscribeFromShow));
			this.addEventListener('subscriptionsUpdated', this.delegate(this.refreshSubscriptions));

			/* set up tracking */

			this.suColumn.find('.User a').live('click', function(ev) {
				_Analytics.trackLinkClick(this, 'header', 'header-producer-username-click');
				ev.preventDefault();
				return false;
			});
			this.domRoot.find('.AccountMenuContents a').live('click', function(ev) {
				_Analytics.trackLinkClick(this, 'header', 'header-producer-tools-click');
				ev.preventDefault();
				return false;
			});
		},

		initFacebook : function() {
			var thisContext = this;
			thisContext.captions.push(new BLIP.Unit.DropDown.HoverDropDown({
				domRoot : $('.FacebookWelcomeLoggedIn .FacebookHoverDropDown'),
				captionSelector : '.HeaderCaption',
				onOver: function () {
					try {
						thisContext.captions.each(thisContext.closeUnitDropDown);
						thisContext.facebookSubscriptions.each(thisContext.closeUnitDropDown);
						thisContext.searchField.close();
					} catch (x) {
						// if it gets here, it's probably IE8 complaining about the search
						// field not being initialized.
					}
					finally {
						this.openDropDown();
					}
				}
			}));

			this.facebookSubscriptions = this.initSubUnit(BLIP.Unit.DropDown.HoverDropDown.SubscriptionsDropDown, {
				captionSelector : '.SubscriptionsDropDownCaption',
				onOver : function () {
					try {
						thisContext.captions.each(thisContext.closeUnitDropDown);
						thisContext.searchField.close();
					} catch (x) {

					}
					finally {
						this.openDropDown();
					}
				}
			});
			$('#FacebookLoginButton').click(this.delegate(this.facebookLoginClicked));
			$('#FacebookUserContents .Logout').live('click', function(ev) {
				BLIP.Page.facebook.logout();
				ev.preventDefault();
			});
		},

		facebookLoginClicked : function() {
			var thisContext = this;

			if(this.facebookLoginHasClicked) {
				return;
			}

			this.facebookLoginHasClicked = true;
			this.domRoot.addClass('Loading');


			function facebookLoginContinue () {
				this.facebookLoginHasClicked = false;
				this.domRoot.removeClass('Loading');
				BLIP.Page.facebook.login();
			}

			if(BLIP.Page.facebookReady) {
				facebookLoginContinue.call(this);
			}
			else {
				this.addEventListener('FacebookReady', this.delegate(facebookLoginContinue));
			}
		},

		onFacebookLogin : function() {
			this.refreshSubscriptions();
		},

		onSubscribedToShow : function() {
			this.refreshSubscriptions();
		},

		onUnsubscribeFromShow : function() {
			this.refreshSubscriptions();
		},

		refreshSubscriptions : function() {
			var thisContext = this;
			$.get('/subscriptions/get_heading?no_wrap=1&no-cache=1', function(response) {
				thisContext.domRoot.find('.Subscriptions').html($(response).html());
				thisContext.initFacebook();
			});
		},

		closeUnitDropDown : function(unit, idx) {
			unit.closeDropDown();
		},

		onMouseOverSwitchUsersLink: function (event) {
			this.overSULink = true;
			this.suColumn.show();
		},

		onMouseOutSwitchUsersLink: function (event) {
			this.overSULink = false;

			if (!this.overSUColumn) {
				this.hideSUColumnSoon();
			}
		},

		onMouseOverSwitchUsersColumn: function (event) {
			this.overSUColumn = true;
		},

		onMouseOutSwitchUsersColumn: function (event) {
			this.overSUColumn = false;

			if (!this.overSULink) {
				this.hideSUColumnSoon();
			}
		},

		/**
		 * hideSUColumSoon() will hide our fancypants switch user column
		 * on a timeout to make sure the interaction is comfortable and fluid.
		 */
		hideSUColumnSoon: function () {
			var thisContext = this;

			clearTimeout(this.hideSuTimeout);

			this.hideSuTimeout = setTimeout(function () {
				if (!thisContext.overSULink && !thisContext.overSUColumn) {
					thisContext.suColumn.hide();
				}
			}, 1000);
		},

		/**
		 * splitChannelList() splits the channel li's into two
		 * columns.
		 */
		splitChannelList : function() {
			var list = this.domRoot.find(".ChannelList .List li"),
					listLength = list.length,
					columnLength = Math.floor(listLength / 2) + listLength % 2,
					fragment = document.createDocumentFragment(),
					i = 0,
					currentColumn = null;

			list.each(function (n, el) {
				if (n % columnLength === 0) {
					if (currentColumn) {
						fragment.appendChild(currentColumn[0]);
					}
					currentColumn = $("<ul class='Column'>");
				}
				currentColumn.append(el);
			});

			if(currentColumn.find("li").length) {
				fragment.appendChild(currentColumn[0]);
			}

			this.domRoot.find(".ChannelList .List").remove();
			this.domRoot.find(".ChannelList").append(fragment);
		}
	}
);

