/*
*	Global Publicis Functions
*	
*
*/

Publicis.namespace('Publicis.Global', function ()
{
	var $self = $(this),
		configObj = {

			tile_selector: '.tile,.tweet-box', 								// sets the tile selector value
			$outerContainer: $('#tiles-container'), 						// outer tile container, includes current date and loader
			$container: $('#tiles'), 									// tiles container
			$content: $('#tile-content'), 							// content container
			$tiles: $('.tile', '#tiles'), 							// grabs all the tiles
			$tweets: $('.tweet-box', '#tiles'), 					// grabs all tweet boxes
			$filters: $('#global-nav a'),
			filterMap: {}, 											// filterMap
			contentMap: {}, 											// contentMap
			contentshowing: false, 										// boolean for content showing
			minPageWidth: 850, 											// min page width, background "hero" image uses this to not go behind header/nav text
			$background_pic: $('#background-hero'), 						// main background "hero" image
			$global_nav: $('#global-nav'), 								// global nav container
			contentLoading: false,
			imagesLoaded: false,
			backgroundScrollPercent: 3,
			deepLinking: false,
			overlayOpen: false
		},

	// updates the filtered content
	updateFilter = function (filter)
	{

		if (filter != configObj.filterMap[filter])
		{
			Publicis.Tiles.update(configObj.filterMap[filter]);
		}

		configObj.$filters.parent().removeClass('selected');
		configObj.$filters.each(function ()
		{
			var $this = $(this);

			if ($this.attr('data-filter') == configObj.filterMap[filter])
			{
				$this.parent().addClass('selected');
			}

		});
	},

	// sets content position offscreen right
	adjustContentPosition = function ()
	{
		if (!configObj.contentshowing)
			configObj.$content.css({ 'left': $(window).width() + 'px' }); // adjust $content position on window resize
	},

	// displays content container
	showContentContainer = function ()
	{
		var tilesLeft = -configObj.$container.width() + 'px'; 	// calculates how far to move the tiles left

		configObj.$outerContainer.animate({ 'left': tilesLeft }, 500, "easeOutCubic"); 	// animates tiles off screen left
		configObj.$content.show().animate({ 'left': '0px' }, 500, "easeInOutCubic", function ()
		{
			configObj.contentshowing = true;
			$('html, body').animate({ scrollTop: 300 }, 800, "easeInOutQuad");

		}); 	// animates content in from screen right

	},

	// shows the filter tiles
	showFilterTiles = function (filter)
	{
		if (configObj.$outerContainer.css('opacity') <= .1)
		{
			configObj.$outerContainer.css('visibility', 'visible').animate({ 'opacity': 1 }, 400);
		}

		updateFilter(filter);

	},

	removePopup = function ()
	{
		var $placeholder = $('div#placeholder');

		if ($placeholder.children().length > 0)
		{
			if ($('div#content-popup').length)
			{
				Publicis.NavScroll.UnRegisterScroller($('#overlay-nav'));
				Publicis.NavScroll.UnRegisterScroller($('#overlay-close'));

				$placeholder.empty();
				$('#content-popup').removeAttr('style');
				$('#inner-content').removeAttr('style');
				$('#overlay-container').css('height', 'auto');
			}

			$('#overlay-container').hide();

			if (configObj.deepLinking)
			{
				configObj.deepLinking = false;
			}

			configObj.$tiles.filter(':hidden').fadeIn(500);

			var $page_container = $('#page_container');
			var scrollTop = parseInt($page_container.css('top'), 10) * -1;

			$page_container.css({ position: '', width: '', top: '' });

			$(window).scrollTop(scrollTop);
			setTimeout(function ()
			{
				$(window).scrollTop(scrollTop);
			}, 0);

			configObj.overlayOpen = false;
		}
	},

	// loads content via ajax - populates content div, shows the container, adjusts filter
	loadContent = function (content, filter)
	{
		if (!configObj.contentLoading)
		{
			var $window = $(window);
			configObj.contentLoading = true;
			removePopup();

			configObj.overlayOpen = true;

			var curScrollTop = -$window.scrollTop();
			$('#page_container').css({ position: 'fixed', width: '100%', top: curScrollTop });

			if (configObj.contentMap[content])
			{
				var $this = configObj.contentMap[content].obj;
				var offset = $this.offset();
				var $face = $this.clone(false).addClass('face');
			}
			else
			{
				var $face = $('<div class="tile face" data-xhr="/index.php/xhr' + content + '" data-href="' + content + '"></div>');
				var offset = { left: ($window.width() - $face.width()) / 2, top: 300 };
			}

			var $content = $('#content-popup');
			var faceWidth = $face.width();
			if (faceWidth < 140)
			{
				faceWidth = 140;
			}


			$face.css({ 'left': offset.left + 1, 'top': offset.top, 'visibility': 'visible' });
			$content.css({ 'left': offset.left + 1, 'top': offset.top, width: faceWidth + 20, 'height': $face.height() + 20 });

			var $overlay_container = $('#overlay-container');
			$overlay_container.append($face);

			var win_width = $window.width();
			var left = (win_width < 840) ? '20px' : ($window.width() / 2) - 420 + $window.scrollLeft() + 'px';

			$.ajax({

				url: $face.data('xhr'),
				success: [function (data, status, xhr)
				{
					$innerContent = $('#inner-content');
					var $placeholder = $('#placeholder');
					$placeholder.html(innerShiv(data, false));

					Publicis.ContentOverlay.loaded($placeholder);

					var save_file = $placeholder.find('#save_file_path').val();
					if (save_file && save_file.length > 0)
					{
						$('#overlay-save').attr('href', save_file);
						$('li:has(#overlay-save)').show();
					}
					else
					{
						$('li:has(#overlay-save)').hide();
					}

					var $addthis_button = $('.addthis_button');
					var addthis_title = $('h1', $placeholder).text();
					$addthis_button.attr('addthis:title', addthis_title.length > 0 ? 'Publicis West: ' + addthis_title : 'Publicis West');
					$addthis_button.attr('addthis:url', base_share_url + $face.data('url-title'));

					// Reset addthis so it grabs the updated title and url
					window.addthis.ost = 0;
					window.addthis.ready();

					if ($this)
					{
						$overlay_container.show();
					}
					else
					{
						$overlay_container.fadeIn(1000);
					}

					$overlay_container.css({ height: $innerContent.outerHeight() + 150 });

					$face.delay(150).fadeOut(250, function ()
					{
						if ($this)
						{
							$this.hide();
						}

						$face.detach();
						$.scrollTo(0, 500);

						$content.animate({ boxShadow: '0px 0px 30px rbga(0, 0, 0, 0.5)' }, { duration: 500, queue: false });
						$content.animate({ left: left, top: '100px', width: '840px', height: $innerContent.outerHeight() }, 500, "easeInOutExpo", function ()
						{
							setTimeout(function ()
							{
								var $overlay_nav = $('#overlay-nav');
								var $overlay_close = $('#overlay-close');
								var $ribbon = $('#ribbon');

								Publicis.NavScroll.RegisterScroller($ribbon, { left: $ribbon.offset().left }, undefined, true);
								Publicis.NavScroll.RegisterScroller($overlay_close, { left: $overlay_close.offset().left }, undefined, true);
								Publicis.NavScroll.RegisterScroller(
									$overlay_nav,
									{
										left: $overlay_nav.offset().left
									},
									{
										docked: function ()
										{
											$('#at20mc').addClass('docked');
										},
										undocked: function (reset)
										{
											$('#at20mc').removeClass('docked');
										}
									},
									true
								);
							}, 0);
						});
						$innerContent.delay(350).fadeIn(250);
					});
				},

				function ()
				{
					// applies the chosen filter after content is shown
					updateFilter(filter)
					configObj.contentLoading = false;
				} ]
			});
		}
	},

	// Occurs when a filter is clicked
	filterClick = function ()
	{
		var $this = $(this),
			href = $this.attr('href').split('#')[1];

		if ($this.parent().hasClass('selected'))
		{
			$.address.value(''); // sets the address value to none
			$.address.parameter('filter', 'all').update(); // updates the address with the filter
		}
		else
		{
			$.address.value(''); // sets the address value to none
			$.address.parameter('filter', href).update(); // updates the address with the filter
		}

		return false;
	},

	// Occurs when a tile is clicked.

	tileClick = function ()
	{
		var $this = $(this),
			hash = $this.attr('data-href'),
			filter = "";


		if ($.address.parameter('filter'))	// if it has a parameter, store it.
		{
			filter = $.address.parameter('filter');

			$.address.value(hash).parameter('filter', filter).update(); //update the value with the link and add the filter parameter
		}
		else
		{
			$.address.value(hash).update(); // if there is no filter, don't worry about it and just update the content
		}

		return false;
	},

	addressChange = function (event)
	{
		if (configObj.imagesLoaded)
		{
			var value = event.value,
				filter = event.parameters.filter === '/' ? '' : event.parameters.filter;
			content = event.path === '/' ? '' : event.path;

			removePopup();

			if (configObj.contentMap[content]) 		// if there is valid content url in the map
			{
				loadContent(content, filter);
			}
			else if (configObj.filterMap[filter])	// else if there is a valid filter in the url
			{
				showFilterTiles(filter);
			}
			else if (content.length > 1)
			{
				loadContent(content, filter);
			}
			else	// otherwise just show all the tiles with no filter
			{
				Publicis.Tiles.update('*');
				showFilterTiles();
			}
		}
	},

	mergeTweetsIntoTiles = function ()
	{
		var numTiles = configObj.$tiles.length;
		var numTweets = configObj.$tweets.length;
		var numTotal = numTiles + numTweets;
		var tilesPerTweet = Math.floor(numTiles / numTweets);
		var start = 0;

		tilesPerTweet = Math.max(tilesPerTweet, 1);
		start = Math.min(tilesPerTweet - 1, 2);

		var cnt = start;
		configObj.$tweets.each(function ()
		{
			if (cnt >= numTotal)
			{
				configObj.$container.append($(this));
			}
			else
			{
				$(this).insertAfter(configObj.$tiles.eq(cnt));
			}

			cnt += tilesPerTweet;
		});
	},

	init = function ()
	{
		if (/WebKit/.test(navigator.userAgent))
		{
			$('html').addClass('webkit');
		}

		if (/Macintosh/.test(navigator.userAgent))
		{
			$('html').addClass('mac');
		}

		configObj.deepLinking = $.address.path().length > 1;

		mergeTweetsIntoTiles();

		// adjust the $content window position just in case
		adjustContentPosition();

		//adjustContentPosition on window resize
		$self.resize(adjustContentPosition);

		// create a filter map based on global filter navigation
		configObj.$filters.each(function (i)
		{

			var $this = $(this),
				href = $this.attr('href').split('#')[1],
				filter = $this.attr('data-filter'),
				path = href.substring(href.indexOf('#') + 1);

			configObj.filterMap[path] = filter;
		});

		// creates a content map out of the items loaded on the page.
		configObj.$tiles.each(function (i)
		{

			var $this = $(this),
				xhr = $this.attr('data-xhr');
			key = $this.attr('data-href');
			obj = { xhr: xhr, obj: $this };

			configObj.contentMap[key] = obj;

		});

		// sets up the initial click events with $.address initializes
		$.address.init(function (event)
		{
			// adds filter click handler from Publicis.Tiles
			configObj.$filters.bind('click', filterClick);

			// sets tile click function
			configObj.$tiles.bind('click', tileClick);

			// adds back button click
			configObj.$content.delegate('a.tile-return', 'click', function () { history.go('-1'); return false });
			configObj.$content.delegate('a.no-func', 'click', function () { return false; });

			this.change(addressChange);

		});

		// Register for overlay close
		$('#overlay-close').click(function ()
		{
			if (configObj.deepLinking)
			{
				$.address.path('/');
				$.address.update();
			}
			else
			{
				history.go(-1);
			}
			return false;
		});

		//Images Loaded

		Publicis.Global.config.$container.imagesLoaded(function ()
		{
			configObj.imagesLoaded = true;

			Publicis.Tiles.initialize();
		});
	};

	return {
		initialize: init,
		config: configObj
	};
}, 'initialize');


