var Partizan = function() {
	var min_num_columns = 4;
	
	var mobile_devices = new Array(
		'iPad',
		'iPhone',
		'android',
		'Symbian',
		'BlackBerry',
		'palm',
		'Windows CE',
		'IEMobile',
		'Smartphone'
	);	
	
	var touch_devices = new Array(
		'iPad',
		'iPhone'
	);	
	
	var is_touch_device = isTouchDevice();
	
	var is_mobile_device = isMobileDevice();

	function init() {
		$(document.body).removeClass('nojs').addClass('js');
		
		pngFix();
		attachDynamicWidth();
		attachItemHovers();
		attachDarkHovers();
		attachFilterDropdown();
		attachRemoteHovers();
		attachGalleries();
		attachOverlays();
		attachOverlayClosers();
		attachOverlayDeeplinks();
		attachTabs();
		attachPlatformClass();
		attachPopups();
		attachExternalLinks();
		attachFullScreenVideo();
		attachVideoControls();
		attachPlayIcons();
		attachTouchHoverBypass();
		attachAjaxify();
		attachInfiniteScroll();
		attachScrollPane();
		attachDirectorDropdown();
		attachLocalScroll();
		attachOverlayTracking();		

		if (!is_mobile_device) {
			attachStickyNav();
		}
	}

	function loaded() {
		$('.equalheight .equalheight-item').equalHeights();
	}
	
	function pngFix() {
		if (typeof(jQuery.fn.pngFix) == 'function') {
			$(document).pngFix();
		}	
	}

	function attachDynamicWidth() {	
		$(window).resize(function() {
			var newColumnCount = Math.floor($(window).width()
							/ $('.col').width());
			if (newColumnCount >= min_num_columns) {
				var newWidth = (newColumnCount
							* $('.col').width()) + 1;
							
				$('.container').width(newWidth + 'px');

				$('.stretch').each(function() {
					var stretchWidth = ((newColumnCount-3) *
								$('.col').width())

					if ($(this).hasClass('col3')) {
						stretchWidth = ((newColumnCount-1) *
								$('.col').width());
					} else if ($(this).hasClass('col2')
						&& $(this).hasClass('half')) {
						stretchWidth = ((newColumnCount / 2) *
								$('.col').width());
					} else if ($(this).hasClass('col2')) {
						stretchWidth = ((newColumnCount-2) *
								$('.col').width());
					}
					
					// Substract padding and border from width
					stretchWidth = stretchWidth - ($(this).outerWidth() - $(this).width());
					
					$(this).width(stretchWidth + 'px');
					$('.equalheight .equalheight-item').equalHeights();
				});
			}
		}).resize();
	}
	
	function attachItemHovers() {
		$('.item').live('mouseover', function(event) {
			if (!$(this).data('original-color')) {
				$(this).data('original-color', $(this).find('.headline').css('color'));
			}		
	
			if ($(this).data('animating') == 'in') {
				return false;
			}
		
			if ($(this).find('.expander').length < 1) {
				$(this).prepend('<div class="expander"></div>');
			}
			
			$(this).data('animating', 'in').find('.expander').stop().animate({
				'top': $(this).height() -2000,
				'left': $(this).width() -2000
			}, 500);
			
			var thisRef = this;
			setTimeout(function() {
				if ($(thisRef).data('animating') != 'in') {
					return false;
				}
				
				$(thisRef).find('.bottom-icon').stop().animate({
					'bottom': -24,
					'right': -24
				}, 100);
			}, 400);
			
			$(this).find('.description:not(.no-animate), .cta:not(.no-animate), .headline:not(.no-animate)').stop().animate({
				'color': '#ffffff'
			}, 500);
		});
		
		$('.item').live('mouseout', function(event) {
			if (eventWithinElement(event, this)) {
				return false;
			}
				
			$(this).data('animating', 'out').find('.expander').stop().animate({
				'top': -2000,
				'left': -2000
			}, 500);
			
			$(this).find('.bottom-icon').stop().animate({
				'bottom': 0,
				'right': 0
			}, 100);
			
			$(this).find('.description:not(.no-animate), .cta:not(.no-animate), .headline:not(.no-animate)').stop().animate({
				'color': $(this).data('original-color')
			}, 300);
		});

		// Ensures if you press back button, mouse off state will be active
		$(window).unload(function() {
			$('.item').mouseout();
		});

		// For overlay links, switch to mouse off state as soon as link is clicked
		$('.item').click(function() {
			if ($(this).find('a').attr('rel') == 'overlay') {
				$('.item').mouseout();	
			}
		});
	}

	function attachDarkHovers() {
		$('#darken-hover').remove();

		$('.dark-hover').mouseover(function() {
			$(this).append('<div id="darken-hover"></div>');
			$('#darken-hover').css({
				'width': $(this).find('.darken-item').width(),
				'height': $(this).find('.darken-item').height()
			});

			$('#darken-hover, .dark-hover').mouseout(function(e) {
				var left = $(this).offset().left;
				var top = $(this).offset().top;
				var bottom = $(this).offset().top
							+ $(this).height();
				var right = $(this).offset().left
							+ $(this).width();

				if (e.pageX < left || e.pageX > right ||
					e.pageY < top || e.pageY > bottom) {
					$('#darken-hover').remove();
				}
			});
		});
	}

	function attachFilterDropdown() {
		// Set selected value
		$('#filter ul').before('<h3><a href="#" id="filter-selected" ' +
			'class="dB remote-hover" rel="filter-title ' +
			'filter-close"></a></h3>');
		$('#filter h3 a')
			.html($('#filter ul .active, #filter ul a:first')
			.last().html());
			
		var openFilter = function(e) {
			if ($('#filter-container').hasClass('open')) {
				return false;
			} else {
				e.stopImmediatePropagation();
			}

			e.preventDefault();

			// Set height of scrollbar to height of options
			$('#filter-container').addClass('open');
			$('#filter .filter').addClass('r');
			$('#filter-slider').height(
				$('#filter ul').height() - 3 + 'px'
			);
			$('#filter-slider-track').height(
				$('#filter ul').height() - 17 + 'px'
			);

			// Set scrollbar track position based on active
			// item
			var selected = $('#filter ul li').length;
			var options = $.makeArray($('#filter ul a')).reverse();
			for (var i = 0; i < options.length; i++) {
				if ($(options[i]).hasClass('active')) {
					selected = i+1;
				}
			}

			$('#filter-slider-track').slider({
				orientation: 'vertical',
				step: 1,
				min: 1,
				max: $('#filter ul li').length,
				value: selected,
				change: function(e, ui) {
					$('#filter .ui-slider-handle')
						.removeClass('mouseover');

					var options = 
						$.makeArray($('#filter ul a'))
						.reverse();
					window.location.href =
						$(options[ui.value-1])
						.attr('href');
				},
				slide: function(e, ui) {
					$('#filter ul a')
						.removeClass('active');

					var options =
						$.makeArray($('#filter ul a'))
						.reverse();

					$(options[ui.value-1]).addClass('active');
				}
			});

			// Ensure slider handle doesn't lose focus style while
			// dragging
			$('#filter .ui-slider-handle').mousedown(function() {
				$(this).addClass('mouseover');
			});
			$('#filter .ui-slider-handle').mouseup(function() {
				$(this).removeClass('mouseover');
			});

			addOverlayBacker();
			$('#overlay-backer, #filter-container.open .filter')
				.one('click', function() {
				$('#overlay-backer').remove();
				$('#filter-container').removeClass('open');
				$('#filter .filter').removeClass('r');
				$('#filter-slider-track').slider('destroy');
			});
		}

		$('#filter h3, #filter .filter').click(function(e) {
			return openFilter(e)
		});
		
		$('#filter').click(function(e) {
			if (!$('#filter-container').hasClass('open')) {
				return openFilter(e);
			}
			
			return true;
		});
	}

	function attachRemoteHovers() {
		$('.remote-hover').live('mouseover', function() {
			$($(this).attr('rel').split(' '))
				.each(function(item, value) {
				$('#'+value).addClass('mouseover');
			});
		});

		$('.remote-hover').live('mouseout', function() {
			$($(this).attr('rel').split(' '))
				.each(function(item, value) {
				$('#'+value).removeClass('mouseover');
			});
		});
	}

	function attachGalleries() {
		$('.gallery .pagination-controls a').click(function(e) {
			e.preventDefault();

			var target = $(this).attr('href').toString();
			scrollGallery($(this).parents('.gallery'), target);
		});

		$('.gallery').touchwipe({
			wipeLeft: function(e) {
				var target = $(e.currentTarget).find('a.active')
					.parent().next().find('a')
					.attr('href').toString();

				scrollGallery(e.currentTarget, target);
			},
			wipeRight: function(e) {
				var target = $(e.currentTarget).find('a.active')
					.parent().prev().find('a')
					.attr('href').toString();

				scrollGallery(e.currentTarget, target);
			},
			min_move_x: 20
		});
	}

	function scrollGallery(container, target) {
		if ($(target).length < 1) {
			return false;
		}

		var moveSpeed = 800;
		if ($(container).hasClass('narrow')) {
			moveSpeed = 400;
		}

		$(container).find('.gallery-contents')
						.scrollTo($(target), moveSpeed);
		$(container).find('.pagination-controls .active')
							.removeClass('active');
		$(container).find('a[href="'+target+'"]').addClass('active');
	}

	function attachOverlays() {
		$('a[rel~="overlay"]').live('click', function(e) {
			e.preventDefault();

			openOverlay($(this).attr('href'));
		});
	}
	
	function attachExternalLinks() {
		$('a[rel="external"]').attr('target', '_blank');
	}
	
	function openOverlay(url) {
		if ($('#overlay-bg').length < 1) {
			$(document.body).prepend('<div id="overlay-bg"' +
				' style="display: none;"' +
				' class="height-100"></div>');
		}

		$(window).resize(function() {
			$('#overlay-bg').height(getViewportSize().y);
		}).resize();	
			
		$('#overlay').remove();

		$('#overlay-bg').fadeIn(function() {
			$.ajax({
				url: url,
				success: function(response) {
					$(document.body).prepend(response);	
				
					attachTabs();
					
					$('#overlay .container').css({ 
						'padding-top': $(window).scrollTop() + 'px'
					});
					
					$(window).resize(function() {
						$('#overlay .container').height(
							getViewportSize().y - 
							parseInt(
								new String(
									$('#overlay .container')
										.css('padding-top')
									).replace('px', 0)
								)
						);
						
						
					}).resize();				
					
					$(window).resize(function() {
						$('#overlay-bg').height(getViewportSize().y)
					}).resize();

					window.location.hash = '!' + url;
				}
			});
		});	
	}

	function attachOverlayClosers() {
		$('.overlay-close').live('click', function(e) {
			e.preventDefault();

			$('.overlay-remove').css({
				'visibility': 'hidden'
			});
			$('#overlay, #overlay-bg').fadeOut(function() {
				$('#overlay, #overlay-bg').remove();
			});
			window.location.hash = '';
		});
	}
	
	function attachOverlayDeeplinks() {
		var hash = new String(window.location.hash);
		if (hash.length < 1 || hash.substring(0, 2) != '#!') {
			return false;
		}
		
		var url = hash.substring(2);
		openOverlay(url);
	}

	function attachTabs() {
		$('.tabs').tabs();
		
		// Trigger a window resize event when the tab links are clicked
		// in case the document size has changed.
		$(".tabs a[href^='#']").click(function() {
			$(window).resize();
		});
	}

	function attachPlatformClass() {
		// The platform detection is unfortunately needed to cater
		// for the different font rendering between Mac and Windows
		var ua = new String(navigator.userAgent).toLowerCase();
		var platform = 'windows';
		if (ua.indexOf('mac os') > 0) {
			platform = 'mac';
		}

		$(document.body).addClass(platform);
	}
	
	function attachStickyNav() {
		if ($('.utilities').length < 1) {
			return false;
		}
	
		var topOfNavigation = $('.utilities').offset().top;
	
		var moveMenu = function() {		
			if ($(window).scrollTop() > topOfNavigation) {
				// Insert placeholder to stop page from collapsing
				if ($('#utilities-holder').length < 1) {
					$('.utilities').before('<div id="utilities-holder"></div>');
				}
				
				$('#utilities-holder').css({
					'width': '1px',
					'height': $('.utilities').height() + 'px'
				});
			
				$('.utilities').addClass('scrolling').width($(window).width());
			} else {
				$('#utilities-holder').remove();
				$('.utilities').removeClass('scrolling').width('auto');
			}
		};

		$(window).scroll(moveMenu);
		$(window).resize(moveMenu);
	}
	
	function attachPopups() {	
		$("a[rel~='popup']").live('click', function(e) {
			e.preventDefault();

			var width, height = 500;
			var regex = /w([0-9]+)h([0-9]+)/;
			var dimensions = regex.exec($(this).attr('rel'));

			if (dimensions && dimensions.length > 2) {
				width = dimensions[1];
				height = dimensions[2];
			}
			
			if ($(this).hasClass('full-screen-button')) {
				width = screen.width;
				height = screen.height;
			}

			window.open(
				$(this).attr('href'),
				'partizan_popup',
				'status=1, height='+height+', width='+width+
				', resizable=1, scrollbars=1'
			);
		});

	}
	
	function attachFullScreenVideo() {
		if (!$('body').hasClass('full-screen')) {
			return false;
		}
		
		$(window).resize(function() {
			$('#video').height($(window).height() - 20);
		}).resize();
	}
	
	function attachVideoControls() {
		$('.stop').live('click', function() {
			document.video.Stop();
		});
	}
	
	function attachPlayIcons() {
		$('.video-play').append('' +
			'<span class="play"></span>' +
			'<img src="' + MEDIA_URL + 'img/icons/play.png" alt="Play"' +
				' class="play-icon">'
		);
		
		$('.video-play').live('hover', function() {
			$(this).children('.play').css({
				width: $(this).find('.video-thumb').width(),
				height: $(this).find('.video-thumb').height()
			});
			
			$(this).children('.play-icon').css({
				top: ($(this).find('.video-thumb').height() / 2) - 
							$(this).children('.play-icon').height() / 2,
				left: ($(this).find('.video-thumb').width() / 2) - 
							$(this).children('.play-icon').width() / 2
			});
		});
	}
	
	function attachTouchHoverBypass() {
		// For touch devices that emulate an onmouseover on first click, 
		// bypass and go straight to the click.
		$('.hover-bypass').live('mouseover', function() {
			if (is_touch_device) {
				$(this).click();
			}
		});
	}
	
	function attachAjaxify() {
		$('.ajaxify').live('submit', function(e) {
				e.preventDefault();
				
				$.ajax({
					url: $(this).attr('action'),
					type: 'post',
					data: $(this).serialize(),
					success: function(response, status, xhr) {
						$('#overlay').replaceWith(response);
					}
				});
		});
	}
	
	function attachInfiniteScroll() {
		if ($('#infinite-scroll').length < 1) {
			return false;
		}
		
		$('#infinite-scroll-pagination').hide();
		$('.inifinite-scoll-load').click(function() {
			$(document).trigger('retrieve.infscr');
		});
	
		$('#infinite-scroll').infinitescroll({
			navSelector: '#infinite-scroll-pagination',
			nextSelector: '#infinite-scroll-pagination .pagination-next',
			itemSelector: '#infinite-scroll .item',
			donetext: '',
			loadingImg: MEDIA_URL + 'img/trans.gif',
			loadingText: '',
			errorCallback: function() {
				$('.inifinite-scoll-load').hide();
			}
		}, function(elements) {
			$('.equalheight .equalheight-item').equalHeights();
		});
	}
	
	function attachScrollPane() {
		$('.scroll-pane').jScrollPane();	
		
		$('.scrollpane-navigation a').live('click', function() {
			var api = $('.scroll-pane').data('jsp');		
			api.scrollToElement($(this).attr('href'), true, true);
			
			return false;
		});
		
		$('.scrollpane-navigation-content a').live('click', function() {
			$(this).parents('ul').find('.active').removeClass('active');
			$(this).addClass('active');
		
			$.get($(this).attr('href') + '?pane=true', function(response) {
				var api = $('.scroll-pane').data('jsp');
			
				api.getContentPane().html(response);
				api.reinitialise();
			});

			return false;
		});
	}
	
	function attachDirectorDropdown() {
		var closeDropdown = function() {
			$('.director-dropdown').removeClass('active');
		
			$('.director-overlay-container').animate({
				height: 0
			}, 500, function() {
				$('.director-overlay-container').remove();
			});
		};
	
		$('.director-dropdown').click(function() {
			if ($('.director-overlay-container').length > 0) {
				closeDropdown();
				return false;
			}
						
			$('.director-dropdown').addClass('active');
			
			var link = $(this).attr('href');
		
			$('.utilities').before('<div class="director-overlay-container bGW bB"></div>');
			$('.director-overlay-container').animate({
					height: 500,
				}, 500, function() {				
					$('.director-overlay-container').prepend('<div '+
						'class="loading"></div>');
						
					$.get(link, function(response) {
						$('.director-overlay-container .loading').fadeOut(500, function() {
							$('.director-overlay-container').append(
								'<div class="director-overlay-container-inner">'+
									response+
								'</div>');
							$('.director-overlay-container-inner').fadeIn(500);
							
							attachScrollPane();
						});
					});
				}
			);
			
			return false;
		});
		
		$('.director-overlay-container .close').live('click', function() {
			closeDropdown();
			return false;
		});
	}

	function attachLocalScroll() {
		$('.local-scroll').click(function() {
			var selector = $(this).attr('href');

			$.scrollTo($(selector), 300, {offset: {top:-61}});

			return false;
		});
	}

	function attachOverlayTracking() {
		$('a[rel~="overlay"]').live('click', function() {
			if (typeof(_gaq) == 'undefined') {
				return false;
			}

			_gaq.push(['_trackPageview', $(this).attr('href')]);
		});
	}
	
	function isMobileDevice() {
		return matchDevice(mobile_devices);
	}
	
	function isTouchDevice() {	
		return matchDevice(touch_devices);
	}
	
	function matchDevice(devices) {
		for (i = 0; i < devices.length; i++) {
			var regex = new RegExp(devices[i], 'i');
			if (navigator.userAgent.match(regex)) {
				return true;
			}
		}

		return false;		
	}
	
	function getViewportSize() {
		var height = $(document).height();
		if ($(window).height() > height) {
			height = $(window).height();
		}	
	
		var width = $(document).width();
		if ($(window).width() > width) {
			width = $(window).width();
		}		
		
		return {
			'x': width,
			'y': height
		}
	}
	
	function eventWithinElement(event, element) {
		var eventX = event.pageX;
		var eventY = event.pageY;
		
		var elementLeft = $(element).offset().left;
		var elementRight = $(element).offset().left 
							+ $(element).outerWidth();
		var elementTop = $(element).offset().top;
		var elementBottom = $(element).offset().top 
							+ $(element).outerHeight();	
		
		if (eventX > elementLeft && eventX < elementRight && 
				eventY > elementTop && eventY < elementBottom) {
			// Event occurred inside element
			return true;
		}	
		
		return false;
	}
	
	function addOverlayBacker() {
		$(document.body).prepend(
				'<div id="overlay-backer"></div>'
		);	
		$('#overlay-backer').css({
			width: getViewportSize().x,
			height: getViewportSize().y
		});
	}

	return {
		init: init,
		loaded: loaded
	}
}();

$(document).ready(function() {
	Partizan.init();
});

$(window).load(function() {
	Partizan.loaded();
});

