/* BLIP.Page
 * Responsible for:
 *   - Registering content containers
 *   - Modifying the page title
 *   - Handling history state changes
 *
 *  This is a singleton. on document.ready, it immediately searches for the #Content element, and tries to
 *  initialize BLIP.Unit.Content.TheContentElementClassName.
 *
 *  When a Unit fires its stateChanged event, it bubbles up to this class.
 *
 *  Page then queries the Content object for the new state's state object and URI, pushing it onto the history
 *  stack.
 *
 */


BLIP.Class.createSingleton("BLIP.Page", BLIP.Object,
	function() {
		/* all content master containers on the page.
		* Page needs to know these, so it can request and
		* set history state
		*/
		var thisContext = this;
		this.contentHolders = {};
		this.currentContent = {};
		this.originalState = {};

		$(document).ready(function() {
			if(window._gaq && _Analytics) {
				_Analytics.detectSubscriberStatus(function() {
					_gaq.push(['_trackPageview']);
				});
			}
			thisContext.initContent();
			thisContext.initHistory();
			thisContext.initImages();
			thisContext.initIeMessage();
			thisContext.initFacebookMouseTracking();
			if($.browser.mozilla && $.browser.version.indexOf('1.9') >= 0) {
				thisContext.initFirefoxScrollbarFix();
			}
		});
	},
	{

		// holds the x+y coords of the last click event
		lastClickPosition : [],


		/* Methods */

		/* Init functions */
		initContent : function() {
			// init the header

			if (BLIP.Unit.Header) {
				try {
					this.header = new BLIP.Unit.Header({
						domRoot : $("#Header")
					});
				} catch (e) {
					this.log(e);
				}
			}

			if (BLIP.Unit.Footer) {
				this.footer = new BLIP.Unit.Footer({
					domRoot : $("#Footer")
				});
			}

			if(BLIP.Unit.Modal && BLIP.Unit.Modal.FacebookConnect) {
				this.facebookConnectModal = new BLIP.Unit.Modal.FacebookConnect({
					domRoot : $('#SubscribeLoginModal')
				});
			}

			this.facebook = new BLIP.Facebook({
				appId : $('meta[property="fb:app_id"]').attr('content'),
				postsId : $('#PageInfo').attr('data-posts-id'),
				failureRedirect : '/subscriptions/start-subscribing'
			});

			this.addEventListener('FacebookReady', this.delegate(this.onFacebookReady));

			if(BLIP.Unit.Modal && BLIP.Unit.Modal.FacebookConnect) {
				this.addEventListener('SubscribeFacebookLogin', this.delegate(function() {
					this.facebookConnectModal.open();
				}));
				this.addEventListener('SubscribeFacebookLoginFinish', this.delegate(function() {
					this.facebookConnectModal.close();
				}));
			}
			this.registerDefaultContent();

		},

		queueFacebookLogin : function(callbacks) {
			this.facebookLoginQueued = callbacks;
		},

		onFacebookReady : function() {
			var thisContext = this;
			this.facebookReady = true;
			FB.Event.subscribe('edge.create', this.delegate(this.onFacebookLike_analytics));
			if(!this.hasFacebookCookie()) {
				this.facebook.authenticate();
			}
			if(this.facebookLoginQueued) {
				this.facebook.login(this.facebookLoginQueued);
			}

		},

		/* keeps track of the last known click event - useful for facebook event tracking */
		initFacebookMouseTracking : function() {
			var thisContext = this;
			$('div.FacebookLikeBox').live('mouseover', function(event) {
				$('.FacebookLikeBox').attr('data-active-like-box','');
				$(this).attr('data-active-like-box', '1');
			});
		},


		onFacebookLike_analytics : function() {
			var action = $('.FacebookLikeBox[data-active-like-box=1]').attr('data-action');
			_Analytics.trackEvent('facebook-like', action);
		},

		hasFacebookCookie : function() {
			return document.cookie.indexOf('v_session=') >= 0;
		},

		hasFacebookLoggedInCookie : function() {
			var myCookie = BLIP.Utils.getCookie('v_session');

			if (myCookie && myCookie !== null && myCookie !== "LOGGEDOUT") {
				return true;
			}

			return false;
		},

		hasFacebookLoggedOutCookie : function() {
			var myCookie = BLIP.Utils.getCookie('v_session');

			if (myCookie && myCookie !== null && myCookie === "LOGGEDOUT") {
				return true;
			}

			return false;
		},

		/* initFirefoxScrollbarFix
		 * fixes horizontal scrollbars caused by width 100% stuff for ads. This is kind of hacky ...
		 * there's probably a better solution, but no time.
		 */

		initFirefoxScrollbarFix : function() {
			$(document.body).css('overflow-x','hidden');
		},

		/**
		 * initImages() loads all images on the page that were supposed to be loaded later.
		 */
		initImages: function () {
			$('img[data-src]').each(function (index, element) {
				element.src = element.getAttribute('data-src');
				element.removeAttribute('data-src');
			});
		},

		/**
		 * initIeMessage() slides down our IE message if MSIE is detected.
		 */
		initIeMessage: function () {
			var msg;

			if ($.browser.msie) {
				msg = $('<div id="SwitchBrowsersMessage" style="display: none;"></div>');
				msg.html('For a superior experience, Blip recommends that you upgrade your browser to <a href="http://www.google.com/chrome/">Google Chrome</a> or install <a href="http://www.google.com/chromeframe">Chrome Frame</a>.');

				$('#Header').after(msg);
				$('#SwitchBrowserMessage').slideDown();
			}
		},

		initEventListeners : function() {
			this.currentContent.stateChanged.addListener(this.contentState_onChange, this);
		},



		initHistory : function() {
			this.history = BLIP.History.create(this.delegate(this.historyState_onChange));
		},


		registerFacebookLike : function(likeButton) {
			_Analytics.trackEvent('facebook-like', likeButton.action);
		},

		registerDefaultContent : function() {
			var contentToLoad = document.getElementById("Content") && document.getElementById("Content").className,
					thisContext = this,
					registerCallback;

			// this is a callback because eventually it will have to load
			// resources dynamically
			registerCallback = function() {
				var content = new BLIP.Unit.Content[contentToLoad]();
				thisContext.registerContent(content);
				thisContext.setCurrentContent(content);
				thisContext.defaultState = thisContext.currentContent.getState();

				if (BLIP.Unit.DeferredImage) {
					try {
						content.initSubUnit(BLIP.Unit.DeferredImage);
					}
					catch(e) {

					}
				}
			};

			if (BLIP.Unit.Content[contentToLoad]) {
				registerCallback();
			}
		},

		registerContent : function(content) {
			this.contentHolders[content.name] = content;
		},

		setCurrentContent : function(content) {
			this.currentContent = content;
			this.initEventListeners();
		},


		/* Event listeners */
		contentState_onChange : function() {
			if (this.currentContent) {
				var state = this.currentContent.getState();
				this.setHistoryState(state);
				this.setContentState(state);
			}
		},

		historyState_onChange : function(state) {
			if(state) {
				this.setContentState(state);
			}
			else {
				this.setContentState(this.defaultState);
			}
		},

		setHistoryState : function (state) {
			/*
			if (this.currentContent) {
//				this.history.pushState(state, null, this.currentContent.getStateURI(state));
			}
			*/
		},

		setContentState : function (state) {
			if(this.currentContent && this.currentContent.setState) {
				this.currentContent.setState(state);
			}
		},

		/* Getters */
		getScriptUri : function(scriptInfo) {
			// scriptInfo is an object literal with two optional members:
			// scriptInfo.contentName == "ContentControlName" or
			// scriptInfo.unitName == "UnitName"
			// this method returns /scripts/BLIP/Unit/UnitName.js
			// or /scripts/BLIP/Unit/Content/ContentName.js

		},

		setTitle : function(title) {
			window.title = title;
		},
		getTitle : function() {
			return window.title;
		}
	}
);

