var Settings = {

	accordion: {
		content: 'div.acc_content',
		toggler: 'h3.acc_toggler',
		togglerActiveClass: 'acc_toggler_active'
	},
	
	fixedToc: {
		obj: 'fixedToc',
		heading: 'Document navigation',
		colour: 'green',
		topOffset: 15
	},

	kwiks: {
		obj: 'kwiks'
	},
	
	latestAdditions: {
		obj: 'latest_additions',
		noResults: 3
	},

	search: {
		obj: 'q',
		resultsObj: 'search-results',
		defaultText: 'Search...',
		content: 'div.acc_content',
		toggler: 'h2.acc_toggler'
	},
	
	testimonials: {
		obj: 'testimonial',
		heading: 'h3',
		text: 'p',
		delay: 7000,
		quotes: [
			{name: 'Site survey - Teacher comments: How has Crossref-it.info helped?', quote: 'Giving me ideas for introducing a topic'},
{name: 'Site survey - Student comments: How has Crossref-it.info helped?', quote: '[The Great Expectations guide] helped me very much, because it gave me a complete view of context, symbolism, themes and imagery'},
{name: 'Site survey - Parent comments', quote: 'This site is extremely helpful and well planned out!'},
{name: 'Andrew Motion, ex Poet Laureate', quote: 'How does a person expect to enjoy, to take an obvious example, Paradise Lost, or a picture by Poussin, unless they know some of this [contextual] stuff?'},
{name: 'Site survey - Teacher comments: What do you most appreciate about Crossref-it.info?', quote: 'Depth of information'},
{name: 'Site survey - Student comments: How have you used Crossref-it.info?', quote: 'For advice on how to revise and contextual information on texts.'},
{name: 'Site survey - Teacher comments: How have you used Crossref-it.info?', quote: 'I use the articles as part of my lesson plans'},
{name: 'Site survey - Student comments: What do you most appreciate about Crossref-it.info?', quote: 'The information is compact and easy to understand'},
{name: 'Site survey - Parent comments: What do you most appreciate about Crossref-it.info?', quote: 'Clearly thought out and articulated information and advice'},
{name: 'A Level teacher, Inner city London', quote: 'More and more students struggle with the cultural references in the texts they are studying. This limits their chances of exam success ...'},
{name: 'Site survey - Student comments', quote: 'This site is extremely helpful and well planned out!'},
{name: 'Site survey - Teacher comments', quote: 'Thanks for a great site!'}
		]
	},
	
	timeline: {
		obj: 'timeline',
		articleEntrySelector: '#timeline td.entry',
		timelineEntrySelector: '#timeline div.timeline_category',
		url: '/timeline/',
		sliderObj: 'timeline_slider',
		sliderInitObj: 'timeline_year',
		sliderStartObj: 'timeline_start_year',
		sliderEndObj: 'timeline_end_year',
		sliderBtnObj: 'timeline_btn'
	},
	
	tooltips: {
		elements: 'a.tooltip',
		scripture: 'a.scripture',
		textSection: 'a.text_section'
	}

};

var Xref = new Class({

	testimonialIndex: 0,
	fixedTocInitialTop: 0,
	
	initialize: function() {
		var kwiks;
		if ((kwiks = $(Settings.kwiks.obj))) this.addAccordion(kwiks.getElements(Settings.accordion.toggler), kwiks.getElements(Settings.accordion.content), kwiks);

		var searchResults;
		if ((searchResults = $(Settings.search.resultsObj))) this.addAccordion(searchResults.getElements(Settings.search.toggler), searchResults.getElements(Settings.search.content), kwiks);
		
		var testimonials;
		if ((testimonials = $(Settings.testimonials.obj))) this.initTestimonials(testimonials);
		
		var latestAdditions;
		if ((latestAdditions = $(Settings.latestAdditions.obj))) {
			var bloggerUrl = 'http://crossref-it.blogspot.com/feeds/posts/default?alt=json-in-script&callback=xref.setBloggerFeed';
			new Element('script', {'src': bloggerUrl}).inject($$('head')[0]);
		}
		
		var article = $$('div.article_body');
		if (article.length) this.initToc(article[0]);
		
		var gototop = $('gototop');
		gototop.set('opacity','0').setStyle('display','block');
		window.addEvent('scroll',function(e) {
			if(Browser.Engine.trident4) {
				gototop.setStyles({
					'position': 'absolute',
					'bottom': window.getPosition().y + 10,
					'width': 100
				});
			}
			gototop.fade((window.getScroll().y > 300) ? 'in' : 'out')
		});
		gototop.getElement('a').addEvent('click', function(e) {
			e.stop();
			new Fx.Scroll(window).toTop();
		});

		var gotohome = $('gotohome');
		gotohome.set('opacity','0').setStyle('display','block');
		window.addEvent('scroll',function(e) {
			if(Browser.Engine.trident4) {
				gotohome.setStyles({
					'position': 'absolute',
					'bottom': window.getPosition().y + 10,
					'width': 100
				});
			}
			gotohome.fade((window.getScroll().y > 300) ? 'in' : 'out')
		});
		gotohome.getElement('a').addEvent('click', function(e) {
			e.stop();
			document.location.href = '/';
		});
		
		var tooltips = $$(Settings.tooltips.elements);
		if (tooltips.length) this.initTooltips(tooltips);
				
		var sidenav = $$('div.subnav');
		if (sidenav.length) this.initSidenav(sidenav[0]);
		
		var timelineCategories = $$('div.timeline_category');
		if (timelineCategories.length) this.resizeTimeline(timelineCategories);
		
		var timelineEntries = $$(Settings.timeline.articleEntrySelector);
		if (!timelineEntries.length) timelineEntries = $$(Settings.timeline.timelineEntrySelector);
		if (timelineEntries.length) this.initTimelineEntries(timelineEntries);
		
		var timelineSlider = $(Settings.timeline.sliderObj);
		if (timelineSlider) this.initSlider(timelineSlider);
		
		if (pageTracker) {
			$$('a.download').addEvent('click',function() {  
				pageTracker._trackPageview('/download/'+this.get('href').replace('http://')); 
			});
		}
	},
	
	addAccordion: function(togglers, contents, container) {
		var acc = new Accordion(togglers, contents, {
			opacity: false,
			onActive: function(toggler, element) {
				toggler.addClass(Settings.accordion.togglerActiveClass);
			},
			onBackground: function(toggler, element) {
				toggler.removeClass(Settings.accordion.togglerActiveClass);
			}
		}, $(container));
	},
	
	initSearch: function(input) {
		if (input.get('value') == '') {
			input.set('value',Settings.search.defaultText);
		}
		input.addEvent('focus', function() {
			if (this.value == Settings.search.defaultText) this.value = '';
		});
		input.addEvent('blur', function() {
			if (this.value == '') this.value = Settings.search.defaultText;
		});
	},
	
	initSidenav: function(sidenav) {
		var items = sidenav.getElements('li');
		items.each(function(item) {
			item.addEvent('click', function(e) {
				e.stopPropagation();
				var ul = item.getElement('ul');
				if (ul) {
					if (item.hasClass('expander')) item.addClass('expanded').removeClass('expander');
					else item.addClass('expander').removeClass('expanded');
				}
			});
		});
		var links = sidenav.getElements('a');
		links.each(function(link) {
			link.addEvent('click', function(e) { e.stopPropagation(); });
		});
	},
	
	initSlider: function(slider) {
		var startYear = parseInt($(Settings.timeline.sliderStartObj).get('text'));
		var endYear = parseInt($(Settings.timeline.sliderEndObj).get('text'));
	
		var sliderRange = [startYear, endYear];
		
		var sliderSteps = endYear-startYear;
		
		var slider = new Slider(slider, slider.getElement('.knob'), {
			range: sliderRange,
			steps: sliderSteps,
			onChange: function(){
				$(Settings.timeline.sliderInitObj).set('text', this.step);
			}
		}).set($(Settings.timeline.sliderInitObj).get('text'));
		
		$(Settings.timeline.sliderBtnObj).addEvent('click', function() {
			document.location.href = Settings.timeline.url+$(Settings.timeline.sliderInitObj).get('text');
		});

	},
	
	initTestimonials: function(masterDiv) {
		var div = new Element('div').inject(masterDiv);
		new Element('h3').inject(div);
		new Element('p').inject(div);
		
		this.testimonialIndex = Math.floor(Math.random()*Settings.testimonials.quotes.length);
		
		this.rotateTestimonials();
		(function() { this.rotateTestimonials(); }.bind(this)).periodical(Settings.testimonials.delay);
	},
	
	initTimelineEntries: function(entries) {
		entries.each(function(entry) {
			if (!entry.hasClass('current')) {
				entry.addEvent('click', function() {
					document.location.href = Settings.timeline.url+this.get('rel');
				});
				entry.addEvent('mouseover', function() {
					this.addClass('hover');
				});
				entry.addEvent('mouseout', function() {
					this.removeClass('hover');
				});
			}
		});
	},
	
	initToc: function(articleBody) {
		var search = ['h2','h3','h4','h5','h6'];
		var matches = [];
		
		var els = articleBody.getElements('*');
		els.each(function(el) {
			if (search.contains(el.get('tag')) && (el.get('text').clean() != '') && (el.get('text') != 'Bookmark this page with:')) {
				var anchor = new Element('a', {'class': el.get('tag'), 'text': el.get('text'), 'href': '#'});
				anchor.addEvent('click', function(e) {
					new Event(e).stop();
					new Fx.Scroll(window).toElement(el);
				});
				matches.include(anchor);
			}
		});
		
		if (matches.length > 1) {
			var toc = new Element('div', {'id': 'toc'}).inject(articleBody.getElement('h1'),'after');
			matches.each(function(el) {
				el.inject(toc);
			});
			
			var relatedContent = $$('div.related_content');
			var sideSearch = $('inside_search');
			if (relatedContent.length && !new String(window.location).contains('repository')) {
				var fixedToc = new Element('div', {'id': Settings.fixedToc.obj, 'class': Settings.fixedToc.colour}).inject(relatedContent[0]);
				this.fixedTocInitialTop = parseInt(fixedToc.getTop());

				new Element('h3', {'html': Settings.fixedToc.heading}).inject(fixedToc);
				var list = new Element('ul').inject(fixedToc);
				matches.each(function(el) {
					el.clone().cloneEvents(el).inject(new Element('li').inject(list));
				});

				window.addEvent('scroll', function(){
					var scrollTop = Window.getScrollTop();
					if (scrollTop > this.fixedTocInitialTop) {
						fixedToc.setStyle('margin-top',parseInt(scrollTop-this.fixedTocInitialTop+Settings.fixedToc.topOffset)+'px');
					} else fixedToc.setStyle('margin-top','0px');
				}.bind(this));
			}
		}
	},
	
	initTooltips: function(tooltips) {
		var process = false;
	
		tooltips.each(function(tip) {
			var div = $(tip.get('rel'));
			if (div) {
				tip.store('tip:title', tip.get('title'));
				tip.store('tip:text', div.get('html'));
				process = true;
			}
		});
		
		if (process) var tips = new Tips(Settings.tooltips.elements, {className: 'tooltip'});
	},
	
	resizeTimeline: function(categories) {
		var parent = categories[0].getParent();
		var parentWidth = parseInt(parent.getStyle('width'));
		
		var yearDiv = parent.getElement('div.timeline_year');
		if (yearDiv) {
			var availableWidth = parentWidth-parseInt(yearDiv.getStyle('width'));
			categoryWidth = Math.floor(availableWidth/(categories.length/2))-1;
		} else {
			var breaks = parent.getElements('div.timeline_break');
			var division = Math.floor(categories.length/(breaks.length));
			var categoryWidth = Math.floor(parentWidth/division)-1;
		}

		categories.each(function(cat) {
			cat.setStyle('width',categoryWidth+'px');
		});
	},
	
	rotateTestimonials: function() {
		var div = $(Settings.testimonials.obj).getElement('div');
		var name = div.getElement('h3');
		var quote = div.getElement('p');
		
		div.fade('out').get('tween').chain(function() {
			name.set('html', Settings.testimonials.quotes[this.testimonialIndex].name);
			quote.set('html', Settings.testimonials.quotes[this.testimonialIndex].quote);
			div.fade('in');
		}.bind(this));

		if (this.testimonialIndex == Settings.testimonials.quotes.length-1) this.testimonialIndex = 0;
		else this.testimonialIndex++;
	},
	
	setBloggerFeed: function(json) {
		if (json.feed.entry.length > 0) {
			var div = $(Settings.latestAdditions.obj);
			div.empty().adopt(new Element('h3', {text: 'Latest Updates/Additions'}));
			
			var blogLink = new Element('a', {text: 'blog', href: 'http://crossref-it.blogspot.com'});
			
			var ul = new Element('ul').inject(div);
			for (var i = 0; i < Settings.latestAdditions.noResults; i++) {
				var entry = json.feed.entry[i];
				var date = json.feed.entry[i].published.$t.substr(0, 10).split('-');
				var li = new Element('li', {text: date[2]+'-'+date[1]+'-'+date[0]+' - New '}).adopt(blogLink.clone()).appendText(' post - ').adopt(new Element('a', {href: entry.link[4].href, text: entry.link[4].title})).inject(ul);
			}
		}
	}
	
});

var xref;
window.addEvent('domready', function() {
	xref = new Xref();
});