var layout;
window.addEvent('domready', function() {
	new RedpinRegion();
	makeRounded();
	layout = new panels({
		rotatorEnabled: false
	});
});

function setTheme(theme) {
	var currentTheme = document.getElement('body').get('class');
	$('page').getElements('img.' + currentTheme).each(function(el) {
		el.set('src', el.get('src').replace(currentTheme, theme));
		el.removeClass(currentTheme);
		el.addClass(theme);
	});
	document.getElement('body').set('class', theme);
}

/**
 * Controls all items pertaining to panels and home page cusomisation
 */
var panels = new Class ({
	Implements: Options,
	placeHolder: null,
	drag: null,
	Rotator: null,
	Rotate : null,
	options: {
		elements: null,
		rotatorSpeed: 9000,
		rotatorEnabled: true,
		eventScroll: false,
		featuredSpeed: 7000,
		eventSpeed: 7000
	},

	initialize: function(options) {
		this.setOptions(options);

		/*
		 * Load all of the relevant cookie items
		 */
		if (Cookie.read('L4-EVENTS-SCROLL'))
			this.options.eventScroll = Cookie.read('L4-EVENTS-SCROLL');
		if (Cookie.read('L4-ROTATOR-ON'))
			this.options.rotatorEnabled = Cookie.read('L4-ROTATOR-ON');

		$$('input.fh.disable_form_history').set('autocomplete','off');

		if ($('contentContainer').hasClass('home')) {
			this.drag = new Sortables($('contentContainer').getElements('div.contentColumn'), {
				clone: true,
				handle: 'h2',
				revert: true,
				snap: 0,
				onStart: function(el, cl) {
					cl.removeClass('hover');
					el.removeClass('hover');
					el.addClass('dragging');
					cl.setStyle('z-index',100);
				},
				onComplete: function(el) {
					el.removeClass('dragging');
					this.handleResize();
					var order = {
						1: this.drag.serialize(0),
						2: this.drag.serialize(1)
					}

					//this.fireCustomise('column', )
					this.fireCustomise('/customise?action=columns',this.drag.serialize(0).join('|') + ';' + this.drag.serialize(1).join('|'))
				}.bind(this)
			});

			$('contentContainer').getElements('div.panel').each(function(el) {
				if (el.get('id') != 'featured') {
					/*
					 * Add the hover rounded corners
					 */
					new Element('div', {'class': 'hoverCorner tl'}).inject(el, 'top')
					new Element('div', {'class': 'hoverCorner tr'}).inject(el, 'top')
					new Element('div', {'class': 'hoverCorner bl'}).inject(el, 'top')
					new Element('div', {'class': 'hoverCorner br'}).inject(el, 'top')

					/*
					 * Make the panel draggable
					 */
					this.drag.addItems(el)

					/*
					 * If a container is pre-closed then configure the sliding
					 * animation at load and hide it.
					 */
					if (el.hasClass('closed')) {
						var container = el.getElement('div.container')
						new Fx.Slide(container).slideIn();
						container.setStyle('display','block')
					} else if (el.hasClass('open')) {
						el.getElement('div.container').setStyle('display','block')
					}

					/*
					 * Make all of the tools work
					 */
					if (el.getElement('.tools')) {
						el.getElements('.tools a').addEvent('click', function(event) { event.preventDefault(); });
						if (el.getElement('.tools .fold')) {
							el.store('slide', new Fx.Slide(el.getElement('div.container')));
							el.getElement('.tools .fold').addEvent('click', this.foldPanel.pass(el, this));
						}

						if (el.getElement('.tools .remove'))
							el.getElement('.tools .remove').addEvent('click', this.removePanel.pass(el.getElement('.tools .remove'), this));
					}

					/*
					 * Make the header highlight the box on hover and fold/unfold
					 * when clicked
					 */
					if (el.getElement('h2')) {
						el.getElement('h2').addEvents({
							'mouseover': function() { el.addClass('hover'); },
							'mouseout': function() { el.removeClass('hover'); },
							'click': function() {
								el.removeClass('hover');
							}.bind(this)
						}).setStyle('cursor','move');
					}
				}
			}.bind(this));

			this.handleResize();
			this.createEdits();
			if (this.options.eventScroll == true)
				this.scrollEvents();
			else
				$('events').getElement('div.container').setStyles({
					'max-height': '100%',
					'overflow': 'visible'
				});
			this.scrollFeatured();

			if ($('rotator'))
				this.makeRotator();
		}
	},

	/**
	 * Collapses and expands a panel
	 */
	foldPanel: function(el) {
		if (el.hasClass('open')) {
			el.retrieve('slide').slideOut().chain(function() {
				el.removeClass('open');
				el.addClass('closed');
			});
			var aText = el.getElement('p.fold a').get('title').replace('Minimise','Maximise');
			el.getElement('p.fold a').set('title', aText);
			el.getElement('p.fold a img').set('alt', aText);
			this.fireCustomise(el.getElement('p.fold a').get('href'), 'closed');
		} else if(el.hasClass('closed')) {
			el.retrieve('slide').slideIn().chain(function() {
				el.addClass('open');
				el.removeClass('closed');
			});
			var aText = el.getElement('p.fold a').get('title').replace('Maximise','Minimise');
			el.getElement('p.fold a').set('title', aText);
			el.getElement('p.fold a img').set('alt', aText);
			this.fireCustomise(el.getElement('p.fold a').get('href'), 'open');
		}
	},

	removePanel: function(el) {
		this.fireCustomise(el.getElement('a').get('href'));
		el.getParent('div.panel').dispose();
	},

	/**
	 * Shoots off a JSON query that saves some personalisaion of the home page
	 */
	fireCustomise: function(action, value) {
		var url = action;
		if (value)
			url += '&value=' + value;

		new Request.JSON({
			'url': url,
			'onSuccess': function(result) {
				if (result) {
					if (result.reload) {
						location.reload();
					}
				}
			}
		}).get();
	},

	/*
	 * Create all of the edit buttons and add click events
	 */
	createEdits: function() {
		/*var localNewsEdit = new Element('p', {'text':'Edit','class':'edit'}).inject($('news').getElement('div.localNews h3'), 'after');
		localNewsEdit.addEvent('click', function() {
			// Popup the customise region box
		}).setStyle('cursor','pointer')*/
	},

	/*
	 * In order to make it easier to move items to the bottom of columns, make
	 * the columns always fill the available height
	 */
	handleResize: function() {
		var container = $('contentContainer').getElement('div.mainContainer').getSize();
		var topPanel = $('contentContainer').getElement('div.topPanel').getSize();
		$('contentContainer').getElements('.contentColumn').setStyle('min-height', container.y - topPanel.y - 7);
	},

	/*
	 * Makes the featured horses panel scroll
	 */
	scrollFeatured: function() {
		var featuredList = $('featured').getElement('.inner');
		var featuredContainer = $('featured').getElement('.container');

		var listSize = featuredList.getSize();
		var containerSize = featuredContainer.getCoordinates();
		var featuredScroller = new Fx.Tween(featuredList, {duration: 1000});
		var scrollSpeed = this.options.featuredSpeed;
		
		if (!$('featured').getElement('.featuredHorse'))
			return;

		var lineHeight = $('featured').getElement('.featuredHorse').getStyle('height').toInt() + 9;

		if (listSize.y > containerSize.height) {
			var scrollBy = function(to) {
				featuredScroller.start('top', (to * -1));
				// The 3 caters for the 3px margin
				if (to >= listSize.y - 3) {
					resetScrollBy.delay(scrollSpeed / 4.5);
				} else {
					scrollBy.delay(scrollSpeed, null, to + lineHeight /*93*/);
				}
			}

			var resetScrollBy = function() {
				featuredList.setStyle('top', 186);
				scrollBy(0);
			}

			scrollBy.delay(scrollSpeed / 2, null, lineHeight);
		}
	},

	/*
	 * Makes the events panel automatically scroll
	 */
	scrollEvents: function() {
		var eventsList = $('events').getElement('table');
		var eventsContainer = $('events').getElement('.container');

		var listSize = eventsList.getSize();
		var containerSize = eventsContainer.getCoordinates();
		var offset = containerSize.top;

		var totalLines = $('events').getElements('tr').length;
		var eventScroller = new Fx.Morph(eventsList, {duration: 1000});
		var scrollSpeed = this.options.eventSpeed;

		/*
		 * Only scroll if there are bits not visible.  This function will scroll
		 * the panel by a certain number of lines within the table and then
		 * fade out and reset once it gets to the bottom of the list.
		 */
		if (listSize.y > containerSize.height) {
			eventsContainer.setStyle('height', containerSize.height);
			eventsList.setStyles({
				'position': 'absolute',
				'top': 0
			});
			var scrollBy = function(line) {
				if (line >= totalLines) {
					resetScrollBy();
				} else {
					var theLine = $('events').getElement('tr:nth-child(' + line + 'n)').getCoordinates();
					eventScroller.start({'top': (theLine.top - eventsList.getStyle('top').toInt() - offset) * -1});
					scrollBy.delay(scrollSpeed, null, line + 5);
				}
			}
			var resetScrollBy = function() {
				eventsList.fade('out');
				(function() {
					eventsList.setStyle('top',0);
					eventsList.fade('in');
					scrollBy.delay(scrollSpeed/2.8, null, 5)
				}).delay(1000);
			}

			scrollBy.delay(scrollSpeed/2.8, null, 5);
		}
	},

	/**
	 * Makes the rotator actually rotate :)
	 */
	makeRotator: function() {
		$('rotator').getElement('div.article').getAllNext('div.article').setStyle('opacity',0);
		$('rotator').getElements('div.article').setStyles({
			'position': 'absolute',
			'top': 0
		});
		this.Rotator = $('rotator').getElement('div.article');
		if (this.options.rotatorEnabled === true)
			this.Rotate = this.rotateArticle.delay(this.options.rotatorSpeed, this);

		var me = this;

		$('newsRotator').getElements('ul li').addEvents({
			mouseenter: function() {
				clearTimeout(me.Rotate);
				me.rotateArticle($('rotator').getElement('.' + this.get('class')));
			}
		})
	},

	/**
	 * Fades one panel out and the next in.  If passed a specific article then
	 * does this, else it will do the next one in order
	 */
	rotateArticle: function(article) {
		this.Rotator.tween('opacity', '0');

		$('newsRotator').getElement('.' + this.Rotator.get('class').split(' ')[1]).removeClass('current');
		if (article) {
			this.Rotator = article;
		} else {
			this.Rotator  = this.Rotator.getNext('div.article');
			if (!this.Rotator)
				this.Rotator = $('rotator').getElement('div.article');
		}

		this.Rotator.tween('opacity', '1');
		$('newsRotator').getElement('.' + this.Rotator.get('class').split(' ')[1]).addClass('current');
		if (this.options.rotatorEnabled === true)
			this.Rotate = this.rotateArticle.delay(this.options.rotatorSpeed, this);
	}
});

var RedpinRegion = new Class ({
	cookie: null,
	Overlay: null,

	initialize: function() {
		this.cookie = Cookie.read('L4-LOCALISATION');
		
		if (typeOf(this.cookie) !== 'null')
			this.cookie = JSON.decode(this.cookie);
		this.Overlay = new Overlay();

		// If we are accessing a magazine via a forced region, don't press for
		// the county
		var thisURL = new URI()

		if (!this.getRegion() && !thisURL.get('data').region)
			this.pickCounty()

		$('personalise').addEvent('click', function(e) {
			e.preventDefault();
			this.pickCounty()
		}.bind(this))
	},

	pickCounty: function() {
		this.Overlay.show($('personalise').get('href'));
	},

	getRegion: function() {
		if (!this.cookie || !this.cookie.region)
			return false;

		return this.cookie.region;
	},
	getCounty: function() {
		if (!this.cookie || !this.cookie.county)
			return false;

		return this.cookie.county;
	}
});

var Overlay = new Class({
	Overlay: null,
	OverlayContent: null,
	OverlayFX: null,
	options: {
		hideOnClick: true
	},

	initialize: function() {
		if ($('Overlay')) {
			this.Overlay = $('Overlay');
		} else {
			this.Overlay = new Element('div', {
				styles: {
					position: 'absolute',
					width: '100%',
					height: '100%',
					top: 0,
					left: 0,
					background: 'rgb(0,0,0)',
					opacity: 0,
					visibility: 'hidden',
					'z-index': 1000
				},
				id: 'Overlay'
			}).inject(document.body);
			this.OverlayContent = new Element('div', {
				styles: {
					position: 'absolute',
					top: '50%',
					left: '50%',
					'z-index': 1001
				},
				id: 'OverlayContent'
			}).inject(this.Overlay,'after');
		}

		this.OverlayFX = new Fx.Tween(this.Overlay);

		if (this.options.hideOnClick) {
			var hideOverlay = this.hide.bind(this);
			this.Overlay.addEvent('click', hideOverlay)
		}
		document.getElement('body').setStyle('height','100%')
	},

	/**
	 * Destroys the content of the overlay and fades the overlay out
	 */
	hide: function() {
		var OverlayContent = this.OverlayContent;
		document.getElement('body').setStyle('overflow', 'visible');
		this.OverlayFX.start('opacity',0).chain(
			function() {OverlayContent.empty(); this.callChain()}
		);
	},
	show: function(url, closeHandle) {
		this.OverlayFX.start('opacity',0.8);
		document.getElement('body').setStyle('overflow','hidden');
		this.Overlay.setStyle('top', window.getScroll().y);
		if (url)
			this.load(url, closeHandle);
	},
	Element: function() {
		return this.OverlayContent;
	},
	load: function(url, closeHandle) {
		var hideOverlay = this.hide.bind(this);
		var OverlayContent = this.OverlayContent;
		new Request.HTML({
			url: url,
			update: this.OverlayContent,
			onSuccess: function(result) {
				var ContentSize = OverlayContent.getSize();
				OverlayContent.setStyles({
					'margin-left': (ContentSize.x / 2) * -1,
					'margin-top': ((ContentSize.y /2) * -1) + window.getScroll().y
				});
				if (closeHandle && $(closeHandle)) {
					$(closeHandle).addEvent('click', hideOverlay);
				}
			}
		}).get();
	}
})

/*
 * Simple function that locates all a.rButton tags and gives them rounded
 * corners
 */
function makeRounded() {
	if (Browser.ie) {
		var cornerHTML = '<span class="topleft corner_mask"><span class="corner"></span></span><span class="topright corner_mask"><span class="corner"></span></span><span class="bottomright corner_mask"><span class="corner"></span></span><span class="bottomleft corner_mask"><span class="corner"></span></span><span class="horizontal piece"></span><span class="vertical piece"></span>';
		$('contentContainer').getElements('a.rButton').each(function(el) {
			var buttonText = el.get('text');
			var href = el.get('href');

			var newButton = new Element('a', {'html':cornerHTML, 'class':'roundedButton', 'href': href});
			new Element('span', {'text':buttonText, 'class':'text'}).inject(newButton.getElement('.vertical'));

			Function.attempt(function() {
				if (xLinks)
					xLinks.processLink(newButton);
			});

			newButton.inject(el, 'after');

			el.dispose();
		});
	}
}
