var FC = {};

Date.prototype.toRelativeTime = function(now_threshold) {
  var delta = new Date() - this;

  now_threshold = parseInt(now_threshold, 10);

  if (isNaN(now_threshold)) {
    now_threshold = 0;
  }

  if (delta <= now_threshold) {
    return 'Just now';
  }

  var units = null;
  var conversions = {
    millisecond: 1, // ms -> ms
    second: 1000, // ms -> sec
    minute: 60, // sec -> min
    hour: 60, // min -> hour
    day: 24, // hour -> day
    month: 30, // day -> month (roughly)
    year: 12 // month -> year
  };

  for (var key in conversions) {
    if (delta < conversions[key]) {
      break;
    } else {
      units = key; // keeps track of the selected key over the iteration
      delta = delta / conversions[key];
    }
  }

  // pluralize a unit when the difference is greater than 1.
  delta = Math.floor(delta);
  if (delta !== 1) { units += "s"; }
  return [delta, units, "ago"].join(" ");
};

/*
* Wraps up a common pattern used with this plugin whereby you take a String
* representation of a Date, and want back a date object.
*/
Date.fromString = function(str) {
  return new Date(Date.parse(str));
};

FC.navigationWithFlyouts = function() {
	var $navigationsWithFlyouts = $('.navigation:has(.flyout)');

	if($navigationsWithFlyouts.length == 0) {
		return;
	}

	function NavigationWithFlyouts(htmlRoot) {
		this.$htmlRoot = $(htmlRoot);
		this.fixIE7();

		this.navigationTabs = [];

		this.originalCurrentTab = null;

		var navigation = this;
		// Create a NavigationTab object for each tab
		this.$htmlRoot.find('>ul>li').each(function(tabIndex){
			var navigationTab = new NavigationTab(this, navigation, tabIndex);

			navigation.navigationTabs.push(navigationTab);
			// Figure out which tab is the current one when the page loads (so that we can reset it to this one, after changing the current tab on hover)
			if($(this).hasClass('current')){
				navigation.originalCurrentTab = navigationTab;
			}
		});

		this.currentTab = this.originalCurrentTab;
	}

	NavigationWithFlyouts.prototype.fixIE7 = function(){
		this.$htmlRoot.addClass('contains-flyout');
	}

	function NavigationTab(htmlRoot, navigation, tabIndex) {
		this.$htmlRoot = $(htmlRoot);
		this.navigation = navigation;

		this.flyout = new Flyout(this.$htmlRoot.find('.flyout'), this, navigation);
		this.tabIndex = tabIndex;

		this.isHovered = false;
		this.isFocused = false;

		var navigationTab = this;
		this.$htmlRoot.bind('mouseenter', function(){
			navigationTab.isHovered = true;
			window.setTimeout(function(){
				if(navigationTab.isHovered) {
					navigationTab.flyout.show();
				}
			}, 300);
		});
		this.$htmlRoot.bind('mouseleave', function(){
			navigationTab.isHovered = false;
			window.setTimeout(function(){navigationTab.flyout.hide()}, 1000);
		});
	}

	NavigationTab.prototype.makeCurrentTab = function(){
		this.$htmlRoot.addClass('current');
		this.navigation.currentTab = this;
	}

	NavigationTab.prototype.makeNotCurrentTab = function(){
		this.$htmlRoot.removeClass('current');
		if(this.navigation.originalCurrentTab != null) {
		this.navigation.originalCurrentTab.makeCurrentTab();
		}
	}



	function Flyout($htmlRoot, navigationTab, navigation) {
		this.$htmlRoot = $htmlRoot;
		this.navigationTab = navigationTab;
		this.navigation = navigation;

		this.isHovered = false;
		this.isFocused = false;

		var flyout = this;
		this.$htmlRoot.bind('mouseenter', function(){
			flyout.isHovered = true;
		});
		this.$htmlRoot.bind('mouseleave', function(){
			flyout.isHovered = false;
			window.setTimeout(function(){flyout.hide()}, 500);
		});
	}

	Flyout.prototype.show = function() {
		if(this.isVisible) {
			return;
		}

		if(this.navigation.currentTab != null) {
		this.navigation.currentTab.flyout.hide();
		}

		this.$htmlRoot.show();
		this.isVisible = true;
		this.navigationTab.makeCurrentTab();
	}

	Flyout.prototype.hide = function() {
		if(this.isHovered || this.isFocused || this.navigationTab.isHovered || this.navigationTab.isFocused){
			return;
		}

		this.$htmlRoot.hide();
		this.isVisible = false;
		this.navigationTab.makeNotCurrentTab();
	}


	$navigationsWithFlyouts.each(function(){
		new NavigationWithFlyouts(this);
	});
}

FC.commentsLoader = function()
{
	function commentsLoaderModule(root)
	{

		this.comments               = root;
		this.commentsCounter        = this.comments.children('.showing');
		this.commentsList           = this.comments.children('ol');
		this.totalComments          = this.commentsCounter.find('span.total-count');
		this.totalCommentsCount     = parseInt(this.totalComments.html());
		this.displayedComments      = this.commentsCounter.find('span.displayed-count');
		this.displayedCommentsCount = parseInt(this.displayedComments .html());
		this.moreCommmentsBtn       = this.comments.find('p.moar-comments a');
		this.measure                = $('<div class="measure"></div>');
		this.hide                   = $('<div class="hide"></div>');
		this.paginationCount        = 1;

		return this.init();
	}

	commentsLoaderModule.prototype =
	{
		prepareCounter: function()
		{
			this.measure.insertAfter(this.commentsList).wrap(this.hide);
		},
		setWaiAria: function()
		{
			this.commentsCounter.attr({'aria-atomic':'true', 'aria-live':'polite'});
			this.commentsList.attr({'aria-atomic':'false', 'aria-live':'polite'});
		},
		setCounter: function()
		{
			this.displayedCommentsCount = this.commentsList.children('li').length;
			this.displayedComments.html(this.displayedCommentsCount);
			if(this.displayedCommentsCount >= this.totalCommentsCount)
			{
				this.moreCommmentsBtn.remove();
			}
		},
		setMoreCommentsBtn: function()
		{
			that = this;
			this.moreCommmentsBtn.bind
			(
				"click",
				function(e)
				{
					that.commentsList.addClass('loading').css('background-position', 'center ' + that.commentsList.height() + 'px');
					that.paginationCount++;
					$.ajax
					(
						{
							url: this.href + "&" + "pagination=" + that.paginationCount,
							context: document.body,
							success: function(data)
							{
								$('<ol class="comments">' + data + '</ol>').appendTo(that.measure);
								that.commentsList.animate
								(
									{
    										height: '+=' + that.measure.height()
									},
									600,
									'swing',
									function()
									{
										that.commentsList.removeClass('loading');
										$(data).appendTo(that.commentsList);
										that.commentsList.css('height', 'auto');
										that.measure.empty();
										that.setCounter();
									}
								);
		      					},
		      					error: function()
								{
								that.commentsList.removeClass('loading');
		      					}
		      				}
		      			);
					return false;
				}
			)
		},
		init: function()
		{
			this.prepareCounter();
			this.setWaiAria();
			this.setMoreCommentsBtn();
			return true;
		}
	}

	$('div.comments').each
	(
		function()
		{
			new commentsLoaderModule($(this));
		}
	);
}

FC.setRelativeTime = function()
{
	$('p.datetime').each
	(
		function()
		{
			$(this).html(new Date($(this).html()).toRelativeTime());
		}
	)
}

FC.textSize = function(){

	//If there is an existing font size cookie, get that value and set as default
	var __userStored = FC.getCookie("fontSize");
	if(__userStored){
		$("body").css({"font-size":__userStored});
	}


	var __cont = $("div.text-size");

	var __header = "";
	var __controls = "";

	//Write in the header and controls HTML
	__cont.append(__header);
	__cont.append(__controls);

	//3 different text sizes
	var __smTxt = "71%";
	var __mdTxt = "75%";
	var __lgTxt = "95%";

	//Set cookie expiry in days
	var __cookieExp = 730

	//Find all 3 controls
	var __small = $("div.text-size li.small a");
	var __medium = $("div.text-size li.medium a");
	var __large = $("div.text-size li.large a");

	//Bind click event to "small" text size
	__small.bind("click", function(){
		$("body").css({"font-size":__smTxt});
		//Update/create cookie with this text size
		FC.writeCookie("fontSize",__smTxt,__cookieExp);
		return false;
	});

	//Bind click event to "medium" text size
	__medium.bind("click", function(){
		$("body").css({"font-size":__mdTxt});
		//Update/create cookie with this text size
		FC.writeCookie("fontSize",__mdTxt,__cookieExp);
		return false;
	});

	//Bind click event to "large" text size
	__large.bind("click", function(){
		$("body").css({"font-size":__lgTxt});
		//Update/create cookie with this text size
		FC.writeCookie("fontSize",__lgTxt,__cookieExp);
		return false;
	});


}

FC.writeCookie = function(name,value,days){
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

FC.getCookie = function(name){
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

FC.readersThoughts = function(){
	var $thoughts = $('.readers-thoughts');

	if ($thoughts.length == 0) {
		return;
	}

	function ReadersThoughts(root) {
		this.$root = $(root);

		this.$items = this.$root.find('.readers-thoughts-section');

		this.$links = this.$root.find('.side-tabs a');
		this.$links.eq(0).addClass('selected');

		var thoughts = this;
		this.$links.each(function(){
			this.onclick = function(){
				thoughts.showItem(this.hash, this);
				return false;
			}
		});
	}

	ReadersThoughts.prototype.showItem = function(item_hash, link){
		this.$items.hide();
		this.$items.filter(item_hash).show();
		this.$links.removeClass('selected');
		$(link).addClass('selected');
	}

	$thoughts.each(function(){
		new ReadersThoughts(this);
	});
}

FC.shareThis = function(){
	return;
	var $shares = $('.share');

	if ($shares.length == 0) {
		return;
	}

	var shared_object = SHARETHIS.addEntry({
		title: document.title,
		url: document.location.href
	});

	$(".ck_sharethis").each(function(){
		shared_object.attachButton(this);
	});
	$(".ck_email").each(function(){
		shared_object.attachChicklet("email", this);
	});
	$(".ck_facebook").each(function(){
		shared_object.attachChicklet("facebook", this);
	});
	$(".ck_twitter").each(function(){
		shared_object.attachChicklet("twitter", this);
	});
}

FC.mapShowHide = function(){
	var $maps = $('.theguide-page .map');

	if($maps.length == 0) {
		return;
	}

	function MapShowHide(root) {
		this.$root = $(root);
		this.shown = false;

		this.is_animating = false;

		this.control = new MapShowHideControl(this);

		this.$root.after(this.control.$html);

		this.setInitialState();
	}

	MapShowHide.prototype.setInitialState = function(){
		this.$root.css({'display': 'none', 'height': 'auto'});
	}

	MapShowHide.prototype.toggle = function(){
		if(this.is_animating){
			return;
		}
		else {
			if(this.shown) {
				this.hide();
			}
			else {
				this.show();
			}
		}
	}

	MapShowHide.prototype.show = function(){
		this.is_animating = true;

		var map = this;
		this.$root.slideDown(function(){
			map.shown = true;
			map.is_animating = false;
			map.control.hides();
		});
	}

	MapShowHide.prototype.hide = function(){
		this.is_animating = true;

		var map = this;
		this.$root.slideUp(function(){
			map.shown = false;
			map.is_animating = false;
			map.control.shows();
		});
	}


	function MapShowHideControl(map) {
		this.map = map;

		this.showText = 'Show map';
		this.hideText = 'Hide map';

		this.$html = $('<a href="#" class="map-control" title="'+this.showText+'">' + this.showText + '</a>');

		var map = this.map;
		this.$html.click(function(){
			map.toggle();
			return false
		});
	}

	MapShowHideControl.prototype.hides = function(){
		this.$html.text(this.hideText);
	}

	MapShowHideControl.prototype.shows = function(){
		this.$html.text(this.showText);
	}


	$maps.each(function(){
		new MapShowHide(this);
	});
}

FC.collapsible = function(){
	var $collapsibles = $('.collapsible');

	if($collapsibles.length == 0){
		return;
	}

	function Collapsible(root, i) {

		this.$root = $(root);

		this.$title = this.$root.find('.title');
		this.$content = this.$root.find('.content');
		this.$control = this.$root.find('.header');
		this.$arrow = $('<span>Hide</span>');

		this.collapsed = false;
		this.animating = false;

		var collapsible = this;
		this.$control.click(function(){
			collapsible.toggle();
			return false;
		});

		this.$control.append(this.$arrow);

		if(i !== 0) {
			this.collapse();
		}
		else{
			this.expand();
		}
	}

	Collapsible.prototype.toggle = function(){
		if(this.animating) {
			return;
		}
		else {
			if(this.collapsed) {
				this.expand();
			}
			else {
				this.collapse();
			}
		}
	}

	Collapsible.prototype.collapse = function(){
		this.$root.removeClass('.expanded');

		var collapsible = this;

		collapsible.$arrow.removeClass('collapsible_expanded_arrow');
		collapsible.$arrow.addClass('collapsible_expandible_arrow');

		this.animating = true;
		this.$content.slideUp(function(){
			collapsible.$root.addClass('.collapsed');
			collapsible.$arrow.text('Show');
			collapsible.collapsed = true;
			collapsible.animating = false;
		});
	}

	Collapsible.prototype.expand = function(){
		this.$root.removeClass('.collapsed');

		var collapsible = this;

		collapsible.$arrow.removeClass('collapsible_expandible_arrow');
		collapsible.$arrow.addClass('collapsible_expanded_arrow');

		this.animating = true;
		this.$content.slideDown(function(){
			collapsible.$root.addClass('.expanded');
			collapsible.$arrow.text('Hide');
			collapsible.collapsed = false;
			collapsible.animating = false;
		});
	}

	$collapsibles.each(function(i){
		new Collapsible(this, i);
	});
}

FC.placeholderText = function(){
	var $placeholderTexts = $('.placeholder-text');

	if($placeholderTexts.length == 0) {
		return;
	}

	function PlaceholderText(root) {
		this.defaultText = root.value;
		this.root = root;
		this.$root = $(root);

		this.$root.addClass('contains-default-text');

		var placeholderText = this;
		this.root.onfocus = function(){
			placeholderText.remove();
		}
		this.root.onblur = function(){
			placeholderText.replace();
		}
	}

	PlaceholderText.prototype.remove = function(){
		if(this.root.value == this.defaultText) {
			this.root.value = '';
			this.$root.removeClass('contains-default-text');
		}
	}

	PlaceholderText.prototype.replace = function(){
		if(this.root.value == '') {
			this.root.value = this.defaultText;
			this.$root.addClass('contains-default-text');
		}
	}

	$placeholderTexts.each(function(){
		new PlaceholderText(this);
	});
}

FC.theguideLocationFilter = function() {
	$('.theguide-region-select').each(function(){
		var $this = $(this);

		function followLink() {
			window.location = this.value;
		}

		$this.find('select').bind('change', followLink);

		$this.find('.submit-field').remove();
	});
}

FC.theguideNavigation = function() {
	var $theguideNavigation = $('.theguide-navigation');

	if($theguideNavigation.length == 0) {
		return;
	}

	function TheGuideNavigation(root) {
		this.$root = $(root)

		this.$topLevels = this.$root.find('> ul > li');

		var nav = this;
		this.$topLevels.each(function(){
			new TheGuideNavigationLevel1(this, nav);
		});
	}

	function TheGuideNavigationLevel1(root, nav) {
		this.nav = nav;

		this.$root = $(root);
		this.$title = this.$root.find('> h3');

		var object = this;

		this.$title.bind('mouseover', function(){
			object.mouseover();
			return true;
		});

		this.$title.bind('mouseout', function(){
			object.mouseout();
			return true;
		});

		this.$title.bind('click', function(){
			object.click();
			object.mouseout();
			return true;
		});
	}

	TheGuideNavigationLevel1.prototype.mouseover = function(){
		this.$title.addClass('hover');
	}

	TheGuideNavigationLevel1.prototype.mouseout = function(){
		this.$title.removeClass('hover');
	}

	TheGuideNavigationLevel1.prototype.click = function(){
		if(this.$root.hasClass('selected')){
			this.$root.removeClass('selected');
		}
		else {
			this.nav.$topLevels.removeClass('selected');
			this.$root.addClass('selected');
		}
	}

	$theguideNavigation.each(function(){
		new TheGuideNavigation(this);
	});
}

FC.scroller = function() {
	var $scrollers = $('.scroller');

	if($scrollers.length == 0) {
		return;
	}

	function Scroller(root) {
		this.$root = $(root);

		var itemContainerRoot = this.$root.find('.scroller-items').get(0);
		this.itemContainer = new ScrollerItemsContainer(itemContainerRoot, this);

		this.items = [];

		var scroller = this;

		this.itemContainer.$root.find('> li').each(
			function(){
				var item = new ScrollerItem(this, scroller);
				scroller.items.push(item);
			}
		);
		if(this.items[1] != null)
		{
		this.itemWidth = this.items[1].width;
		}
		this.currentItemIndex = 0;

		this.nextPreviousControls = {};
		this.addControls();
		this.isAnimating = false;

		this.switchTo(this.currentItemIndex);
	}

	Scroller.prototype.switchTo = function(newItemIndex) {
		if(this.isAnimating){
			return false;
		}
		else {
			this.isAnimating = true;

			var scroller = this;
			this.itemContainer.$root.animate(
				{marginLeft: -this.itemWidth*newItemIndex},
				'normal',
				'swing',
				function(){
					scroller.currentItemIndex = newItemIndex;
					scroller.updateNextPreviousControls();

					scroller.isAnimating = false;
				}
			);
		}
	}

	Scroller.prototype.next = function(){

		if(this.currentItemIndex + 4 > this.items.length - 4) {
			this.switchTo(this.items.length - 4);
		}
		else {
			this.switchTo(this.currentItemIndex + 4);
		}
	}

	Scroller.prototype.previous = function(){
		if(this.currentItemIndex - 4 < 0) {
			this.switchTo(0);
		}
		else {
			this.switchTo(this.currentItemIndex - 4);
		}
	}

	Scroller.prototype.addControls = function(){

		var $nextPreviousControls = $('<ul class="scroller-controls"></ul>');
		this.nextPreviousControls['next'] = new ScrollerNextPreviousControl('next', this);
		this.nextPreviousControls['previous'] = new ScrollerNextPreviousControl('previous', this);

		$nextPreviousControls.append($('<li class="next"></li>').append(this.nextPreviousControls['next'].$html));
		$nextPreviousControls.append($('<li class="previous"></li>').append(this.nextPreviousControls['previous'].$html));

		this.$root.append($nextPreviousControls);
	}

	Scroller.prototype.updateNextPreviousControls = function(){
		var previousControl = this.nextPreviousControls['previous'];
		var nextControl = this.nextPreviousControls['next'];

		if(this.currentItemIndex == 0){
			if(previousControl.isActive){
				previousControl.makeInactive();
			}
		}
		else {
			if(!previousControl.isActive){
				previousControl.makeActive();
			}
		}

		if(this.currentItemIndex == this.items.length - 4 || this.items.length < 4){
			if(nextControl.isActive){
				nextControl.makeInactive();
			}
		}
		else{
			if(!nextControl.isActive){
				nextControl.makeActive();
			}
		}
	}


	function ScrollerItemsContainer(root, scroller) {
		this.$root = $(root);
		this.scroller = scroller;
	}


	function ScrollerItem(root, scroller){
		this.$root = $(root);

		this.width = this.$root.width() + parseInt(this.$root.css('margin-left')) + parseInt(this.$root.css('margin-right'));

		this.scroller = scroller;

		this.$headline = this.$root.find('.headline');

		var scrollerItem = this;
        this.$root.bind('mouseenter', function() { scrollerItem.showHeadline(); });
        this.$root.bind('mouseleave', function() { scrollerItem.hideHeadline(); });
	}

	ScrollerItem.prototype.showHeadline = function() {
		this.$headline.animate(
			{ 'top': 112 - this.$headline.outerHeight() }
		);
	}

	ScrollerItem.prototype.hideHeadline = function() {
		this.$headline.animate(
			{ 'top': 112 }
		);
	}


	function ScrollerNextPreviousControl(text, scroller){
		this.scroller = scroller;
		this.text = text;
		this.isActive = true;

		this.$html = $('<a href="#' + text + '" class="active" title="'+text+' item"><span>' + text + ' item</span></a>');

		var control = this;

		this.clickNext = function(){
			control.scroller.next();
			return false;
		}
		this.clickPrevious = function(){
			control.scroller.previous();
			return false;
		}

		this.bindEvents();
	}

	ScrollerNextPreviousControl.prototype.bindEvents = function(){
		if(this.text == 'next') {
			this.$html.click(this.clickNext);
		}
		if(this.text == 'previous') {
			this.$html.click(this.clickPrevious);
		}
	}

	ScrollerNextPreviousControl.prototype.makeInactive = function(){
		if(this.isActive){
			this.hrefattr = this.$html.removeAttr('href');
			this.$html.addClass('inactive');
			this.$html.unbind('click');
			this.isActive = false;
		}
	}

	ScrollerNextPreviousControl.prototype.makeActive = function(){
		if(!this.isActive){
			this.$html.attr('href', '#' + this.text);
			this.$html.removeClass('inactive');
			this.bindEvents();
			this.isActive = true;
		}
	}

	$scrollers.each(function(){
		new Scroller(this);
	});
}

FC.photoFlipper = function() {
	var $photoFlippers = $('.multimedia-photos, .multimedia-teaser .multimedia-window');

	if($photoFlippers.length == 0) {
		return;
	}

	function PhotoFlipper(root) {
		this.$root = $(root);

		var itemContainerRoot = this.$root.find('.multimedia-items').get(0);
		this.itemContainer = new PhotoFlipperItemsContainer(itemContainerRoot, this);

		this.items = [];

		var photoFlipper = this;

		this.itemContainer.$root.find('.item').each(
			function(){
				var item = new PhotoFlipperItem(this, photoFlipper);
				photoFlipper.items.push(item);
			}
		);
		if(this.items[0] != null)
		{
		this.itemWidth = this.items[0].width;
		}

		this.currentItemIndex = 0;

		this.switchToControls = [];
		this.$switchToControls = null;
		this.nextPreviousControls = {};
		this.$nextPreviousControls = null;

		this.addControls();
		this.isAnimating = false;

		this.$root.mouseenter(function(){
			photoFlipper.showControlsAndMetadata();
		});

		this.$root.mouseleave(function(){
			photoFlipper.hideControlsAndMetadata();
		});

		this.switchTo(this.currentItemIndex);
	}

	PhotoFlipper.prototype.switchTo = function(newItemIndex) {
		if(this.isAnimating){
			return false;
		}
		else {
			this.isAnimating = true;

			var photoFlipper = this;
			this.itemContainer.$root.animate(
				{marginLeft: -this.itemWidth*newItemIndex},
				'normal',
				'swing',
				function(){
					photoFlipper.currentItemIndex = newItemIndex;
					photoFlipper.updateSwitchToControls();
					photoFlipper.updateNextPreviousControls();

					photoFlipper.isAnimating = false;
				}
			);
		}
	}

	PhotoFlipper.prototype.next = function(){
		this.switchTo(this.currentItemIndex + 1);
	}

	PhotoFlipper.prototype.previous = function(){
		this.switchTo(this.currentItemIndex - 1);
	}

	PhotoFlipper.prototype.addControls = function(){
		if(this.$root.hasClass('.multimedia-photos')) {
			var $switchToControls = $('<ul class="switch-to"></ul>');

			for(var i=0; i<this.items.length; i++) {
				var control = new PhotoFlipperSwitchToControl(i, this);
				this.switchToControls.push(control);
				$switchToControls.append($('<li>').append(control.$html));
			}

			this.$root.append($switchToControls);
			this.$switchToControls = $switchToControls;
		}
		else {
			this.switchToControls = null;
			this.$switchToControls = null;
		}

		var $nextPreviousControls = $('<ul class="next-previous"></ul>');
		this.nextPreviousControls['next'] = new PhotoFlipperNextPreviousControl('next', this);
		this.nextPreviousControls['previous'] = new PhotoFlipperNextPreviousControl('previous', this);

		$nextPreviousControls.append($('<li class="next"></li>').append(this.nextPreviousControls['next'].$html));
		$nextPreviousControls.append($('<li class="previous"></li>').append(this.nextPreviousControls['previous'].$html));

		this.$root.append($nextPreviousControls);
		this.$nextPreviousControls = $nextPreviousControls;
	}

	PhotoFlipper.prototype.updateSwitchToControls = function(){
		if(this.switchToControls) {
			for(var i=0; i < this.switchToControls.length; i++) {
				if(this.switchToControls[i].isSelected) {
					this.switchToControls[i].deselect();
				}
			}
			this.switchToControls[this.currentItemIndex].select();
		}
	}

	PhotoFlipper.prototype.updateNextPreviousControls = function(){
		var previousControl = this.nextPreviousControls['previous'];
		var nextControl = this.nextPreviousControls['next'];

		if(this.currentItemIndex == 0){
			if(previousControl.isActive){
				previousControl.makeInactive();
			}
		}
		else {
			if(!previousControl.isActive){
				previousControl.makeActive();
			}
		}

		if(this.currentItemIndex == this.items.length - 1){
			if(nextControl.isActive){
				nextControl.makeInactive();
			}
		}
		else{
			if(!nextControl.isActive){
				nextControl.makeActive();
			}
		}
	}

	PhotoFlipper.prototype.showControlsAndMetadata = function(){
		if(this.switchToControls) {
			this.$switchToControls.fadeIn();
		}
		this.nextPreviousControls['next'].$html.parent().fadeIn();
		this.nextPreviousControls['previous'].$html.parent().fadeIn();

		this.$root.find('.metadata').fadeIn();
	}

	PhotoFlipper.prototype.hideControlsAndMetadata = function(){
		if(this.switchToControls) {
			this.$switchToControls.fadeOut();
		}
		this.nextPreviousControls['next'].$html.parent().fadeOut();
		this.nextPreviousControls['previous'].$html.parent().fadeOut();

		this.$root.find('.metadata').fadeOut();
	}


	function PhotoFlipperItemsContainer(root, photoFlipper) {
		this.$root = $(root);
		this.photoFlipper = photoFlipper;
	}


	function PhotoFlipperItem(root, photoFlipper){
		this.$root = $(root);
		this.width = this.$root.width();
	}


	function PhotoFlipperSwitchToControl(itemIndex, photoFlipper) {
		this.photoFlipper = photoFlipper;
		this.isSelected = false;

		this.$html = $('<a href="#" title="Go to photo ' + itemIndex + '"><span>Go to photo ' + itemIndex + '</span></a>');

		var control = this;
		this.$html.click(
			function(){
				control.photoFlipper.switchTo(itemIndex);
				return false;
			}
		);
	}

	PhotoFlipperSwitchToControl.prototype.select = function() {
		this.$html.addClass('selected');
		this.isSelected = true;
	}

	PhotoFlipperSwitchToControl.prototype.deselect = function() {
		this.$html.removeClass('selected');
		this.isSelected = false;
	}


	function PhotoFlipperNextPreviousControl(text, photoFlipper){
		this.photoFlipper = photoFlipper;
		this.text = text;
		this.isActive = true;

		this.$html = $('<a href="#' + text + '" title="' + text + ' photo" class="active"><span>' + text + ' photo</span></a>');

		var control = this;
		this.clickNext = function(){
			control.photoFlipper.next();
			return false;
		}
		this.clickPrevious = function(){
			control.photoFlipper.previous();
			return false;
		}

		this.bindEvents();
	}

	PhotoFlipperNextPreviousControl.prototype.bindEvents = function(){
		if(this.text == 'next') {
			this.$html.click(this.clickNext);
		}
		if(this.text == 'previous') {
			this.$html.click(this.clickPrevious);
		}
	}

	PhotoFlipperNextPreviousControl.prototype.makeInactive = function(){
		if(this.isActive){
			this.hrefattr = this.$html.removeAttr('href');
			this.$html.addClass('inactive');
			this.$html.unbind('click');
			this.isActive = false;
		}
	}

	PhotoFlipperNextPreviousControl.prototype.makeActive = function(){
		if(!this.isActive){
			this.$html.attr('href', '#' + this.text);
			this.$html.removeClass('inactive');
			this.bindEvents();
			this.isActive = true;
		}
	}

	$photoFlippers.each(function(){
		new PhotoFlipper(this);
	});
}

FC.accordion = function() {
	var $accordions = $('.accordion');

	if($accordions.length == 0) {
		return;
	}

	function Accordion(root) {
		this.$items = $(root).find('> ul > li');
		this.selectedItem = null;

		var accordion = this;
		this.$items.each(
			function(itemIndex){
				var accordionItem = new AccordionItem(this, accordion);
				if($('body').hasClass(Accordion.CHANNEL_CLASSES[itemIndex])) {
					accordionItem.show();
				}
			}
		);
	}

	Accordion.CHANNEL_CLASSES = [
		'channel-1',
		'channel-2',
		'channel-3',
		'channel-4',
		'channel-5'
	];

	function AccordionItem(root, accordion) {
		this.accordion = accordion;

		this.$root = $(root);
		this.$control = this.$root.find('> h3 > a');
		this.$content = this.$root.find('.accordion-content');

		var accordionItem = this;
		this.$control.click(
			function(){
				accordionItem.toggle();
				return false;
			}
		);
	}

	AccordionItem.prototype.toggle = function() {
		if(this.$root.hasClass('shown')){
			this.hide();
		}
		else {
			this.show();
		}
	}

	AccordionItem.prototype.show = function() {
		var itemToBeShown = this;

		var callback = function(){
			itemToBeShown.$root.addClass('shown');
			itemToBeShown.$content.slideDown();
			itemToBeShown.accordion.selectedItem = itemToBeShown;
		}

		if(this.accordion.selectedItem){
			this.accordion.selectedItem.hide(callback);
		}
		else{
			callback();
		}
	}

	AccordionItem.prototype.hide = function(callback) {
		this.$root.removeClass('shown');
		this.$content.slideUp(callback);

		if(this.accordion.selectedItem == this) {
			this.accordion.selectedItem = null;
		}
	}

	$accordions.each(function(){
		new Accordion(this);
	});
}

FC.hideyShowyThingy = function(options) {
	var options = $.extend({
		          itemsSelector : '.journalist-directory .letter-group',
		navigationLinksSelector : '.journalist-directory .navigation a',
		         shownItemClass : 'hidey-showy-shown'
	}, options);

	var $items = $(options.itemsSelector)
	var $links = $(options.navigationLinksSelector)

	if($items.length) {
		var showThing = function(e) {
			if(e) { // If this function is being run from a click or similar
				var selectorToShow = this.hash;
				var $control = $(this);
				var hashesToSet = [selectorToShow + '_'];
			}
			else {
				if(location.hash && $items.filter(location.hash.replace(/_$/, '')).length) {// Someoneâ€™s linking to content in this component
					var selectorToShow = location.hash.replace(/_$/, '');
					var hashesToSet = [selectorToShow, selectorToShow + '_'];
				}
				else {// Someoneâ€™s just come to the page
					var selectorToShow = '#' + $items.get(0).id;
					var hashesToSet = [];
				}
				var $control = $links.filter('[href=' + selectorToShow + ']');
			}

			$thingToShow = $(selectorToShow);

			$items.removeClass(options.shownItemClass);
			$thingToShow.addClass(options.shownItemClass);

			$links.removeClass('selected');
			$control.addClass('selected');

			for(var i in hashesToSet) {
				location.hash = hashesToSet[i];
			}

			return false;
		}

		$links.bind('click', showThing);

		showThing();
	}
}

FC.topFive = function() {
	$('.top-writers h3').toggle(
		function(){
			$(this).siblings('.journo-list').addClass('journo-list-shown');
		},
		function(){
			$(this).siblings('.journo-list').removeClass('journo-list-shown');
		}
	).bind('mouseover', function(){
		$(this).addClass('hover');
	}).bind('mouseout', function(){
		$(this).removeClass('hover');
	});
}

FC.helpShowHide = function() {
	$('.help').each(function(){
		var $this = $(this);
		var $content = $this.find('.content');

		$this.find('.title').wrapInner('<a href="#"></a>');

		$this.find('a').toggle(
			function(){
				$content.show();
			},
			function(){
				$content.hide();
			}
		);
	});
}

FC.searchSuggestions = function() {

	var $inputsToAddSuggestionsTo = $('input.suggestions');

	function SearchSuggestions(input, url) {
		// Search field that wants suggestions
		this.root = input;

		// URL to request suggestions from
		this.url = url || 'super-special-search-suggestions';

		// HTML for suggestions
		this.$suggestionsContainer = $('<div class="search-suggestions"><h2 class="intro">These pages might be what youâ€™re looking for:</h2><ul class="suggestions"></ul><ul class="results-list"><li><input class="button" type="submit" value="View all results" /></li></ul></div>');
		this.$search = $('.search');

		this.queryTimeout = null;

		this.displayedSuggestions = [];
		this.selectedSuggestion = null;

		this.suggestionsAreAddedToPage = false;
		this.suggestionsAreVisible = false;

		this.hideSuggestionsIn321 = null;

		this.currentQuery = null;

		var searchSuggestions = this;

		// On keyup of the search field, if the user has typed 4 characters or more, set a timeout that will send a request for suggestions in half a second
		$(this.root).bind('keyup', function(){
			if(searchSuggestions.root.value.length >= 4 && searchSuggestions.root.value !== searchSuggestions.visibleQuery){
				searchSuggestions.queryTimeout = window.setTimeout(function(){searchSuggestions.sendQuery(searchSuggestions.root.value);}, 500);
			}
		});

		// On keydown of the search field, clear the timeout
		$(this.root).bind('keydown', function(e){
			if(searchSuggestions.queryTimeout) {
				window.clearTimeout(searchSuggestions.queryTimeout);
				searchSuggestions.queryTimeout = null;
			}
		});

		// When the search field is focused, show the current search suggestions.
		$(this.root).bind('focus', function(){
			searchSuggestions.cancelHideSuggestions();
			searchSuggestions.showSuggestions();
		});

		// When itâ€™s blurred, hide the current suggestions, but leave a delay in case weâ€™re about to focus on a suggestion
		$(this.root).bind('blur', function(){
			searchSuggestions.hideSuggestionsInABit();
		});

		// this.updateVisibleFocusHoverCount();
	}

	SearchSuggestions.prototype.sendQuery = function(query){
		var searchSuggestions = this;
		$.ajax({
			    'type' : 'GET',
			     'url' : searchSuggestions.url,
			    'data' : {
				          'query' : searchSuggestions.root.value
			             },
			'dataType' : 'json',
			 'success' : function(data){
				          searchSuggestions.addSuggestionsToPage(data, query);
				          searchSuggestions.showSuggestions();
			             },
			'complete' : function(){
			              window.clearTimeout(searchSuggestions.queryTimeout);
			              searchSuggestions.queryTimeout = null;
			             }
		});
	}

	SearchSuggestions.prototype.addSuggestionsToPage = function(suggestions, query){
		this.$suggestionsContainer.find('.suggestions').empty();
		this.$search.addClass('suggestions-open');

		this.selectedSuggestion = null;

		this.displayedSuggestions = [];

		for(suggestionType in suggestions) {
			var liClass = ''
			switch(suggestionType){
				case 'topics':
					liClass = ' class="topics-list"';
					break;
				case 'theNationalConversation':
					liClass = ' class="topics-list"';
					break;
				case 'articles':
					liClass = ' class="articles-list"';
					break;
				case 'blogs':
					liClass = ' class="blogs-list"';
					break;
			}

			var $suggestionGroup = $('<li' + liClass + '><h3>' + suggestionType + '</h3><ul></ul></li>');

			for(suggestion in suggestions[suggestionType]){
				var suggestion = suggestions[suggestionType][suggestion];

				var suggestionObject = new Suggestion(suggestion['url'], suggestion['description']);
				this.displayedSuggestions.push(suggestionObject);
				$suggestionGroup.find('ul').append(suggestionObject.$root);
			}

			this.$suggestionsContainer.find('.suggestions').append($suggestionGroup);

		}
		this.$suggestionsContainer.find('.suggestions > li:last-child').addClass("last");

		var searchSuggestions = this;

		this.$suggestionsContainer.find('a, input').bind('focus', function(){
			searchSuggestions.cancelHideSuggestions();
		});

		this.$suggestionsContainer.find('a, input').bind('blur', function(){
			searchSuggestions.hideSuggestionsInABit();
		});

		$(this.root).after(this.$suggestionsContainer);
		this.suggestionsAreAddedToPage = true;
		this.currentQuery = query;
	}

	SearchSuggestions.prototype.removeSuggestionsFromPage = function(){
		if(this.suggestionsAreAddedToPage) {
			this.$suggestionsContainer.remove();
			this.suggestionsAreAddedToPage = false;
			this.currentQuery = null;
		}
	}

	SearchSuggestions.prototype.showSuggestions = function(){
		this.$suggestionsContainer.show();
		this.suggestionsAreVisible = true;
	}

	SearchSuggestions.prototype.hideSuggestions = function(){
		this.$suggestionsContainer.hide();
		this.$search.removeClass('suggestions-open');
		this.suggestionsAreVisible = false;
		this.visibleQuery = null;

		if($(this.root).hasClass('contains-default-text')) {
			this.removeSuggestionsFromPage();
		}
	}

	SearchSuggestions.prototype.hideSuggestionsInABit = function(){
		var suggestions = this;
		this.hideSuggestionsIn321 = window.setTimeout(function(){
			suggestions.hideSuggestions();
		}, 50);
	}

	SearchSuggestions.prototype.cancelHideSuggestions = function(){
		if(!(this.hideSuggestionsIn321 === null)) {
			window.clearTimeout(this.hideSuggestionsIn321);
			this.hideSuggestionsIn321 = null;
		}
	}

	SearchSuggestions.prototype.followCurrentSuggestion = function(){
		if(this.selectedSuggestion !== null){
			window.location = this.displayedSuggestions[this.selectedSuggestion].url;
		}
	}


	function Suggestion(url, description) {
		this.url = url;
		this.description = description;

		this.$root = $('<li><a href="' + url + '">' + description + '</a></li>');
	}

	Suggestion.prototype.highlight = function(){
		this.$root.addClass('highlighted');
	}

	Suggestion.prototype.removeHighlight = function(){
		this.$root.removeClass('highlighted');
	}

/*
	$inputsToAddSuggestionsTo.each(function(){
		new SearchSuggestions(this);
	});*/
}

FC.imageTeaser = function() {
    var $imageTeasers = $('.article-teaser-with-image');

    if($imageTeasers.length == 0) {
        return;
    }

    function ImageTeaser(root){
        this.$root = $(root);

        this.width = this.$root.width() + parseInt(this.$root.css('margin-left')) + parseInt(this.$root.css('margin-right'));

        this.$headline = this.$root.find('.headline');

        var imageTeaserItem = this;

        this.$root.bind('mouseenter', function() { imageTeaserItem.showHeadline(); });
        this.$root.bind('mouseleave', function() { imageTeaserItem.hideHeadline(); });
    }

    ImageTeaser.prototype.showHeadline = function() {
        this.$headline.animate(
            { 'top': 112 - this.$headline.outerHeight() }
        );
    }

    ImageTeaser.prototype.hideHeadline = function() {
        this.$headline.animate(
            { 'top': 112 }
        );
    }

    $imageTeasers.each(function(){
        new ImageTeaser(this);
    });
}

$(function(){
	$('body').addClass('js');
	// $('body').get(0).onunload = GUnload;

	FC.textSize();
	FC.navigationWithFlyouts();
	FC.scroller();
	FC.photoFlipper();
	FC.accordion();
	FC.hideyShowyThingy();
	FC.hideyShowyThingy({
		itemsSelector : '.poll.tabs .tab-content',
		navigationLinksSelector : '.poll.tabs .tab-controls li a'});
	FC.hideyShowyThingy({
		itemsSelector : '.most.tabs .tab-content',
		navigationLinksSelector : '.most.tabs .tab-controls li a'});
	FC.topFive();
	FC.helpShowHide();
	FC.theguideNavigation();
	FC.theguideLocationFilter();
	FC.placeholderText();
	FC.collapsible();
	FC.mapShowHide();
	FC.readersThoughts();
	FC.commentsLoader();
	/*$(".datepicker").datepicker();*/
//	FC.shareThis();
	FC.searchSuggestions();
	FC.imageTeaser();
});
function more()
{
		FC.commentsLoader();
}

var http = createRequestObject();
function updateDB(id){
	 http.open('get', '/national/overrides/national_updateDB.jsp?cid=' + id);
     http.send(null);
}
function createRequestObject() {
    var tmpXmlHttpObject;
      //depending on what the browser supports, use the right way to create the XMLHttpRequest object
    if (window.XMLHttpRequest) {
        // Mozilla, Safari would use this method ...
        tmpXmlHttpObject = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        // IE would use this method ...
        tmpXmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return tmpXmlHttpObject;

}
