/**
 * Site.js
 * Copyright (c) Fluid Creativity, 2009
 *
 * Main site Javascript functionality. Dependent on Mootools 1.2.3
 */

Site = {

	init: function() {
		Site.setupRollOvers();
		Site.setupClearDefaults();
		Site.setupPopups();
		Site.setupExternalLinks();
		Site.setupFooterTools();
		Site.setupFooterLogos();
		Site.setupTextModes();
		//Site.setupClientLogin();
		Site.setupSearchPopup();
		Site.setupHeaderFont();
	},

	setupHeaderFont: function() {
		// Headings
		$$('h1, h2, .secondary h3, .subtitle').each(function(el) {
			el.set('html', el.get('html').replace(/^([^<]+)/, '<span>$1</span>'));
		});
		
		SiteUtils.applyTextReplacement('ul#serviceNav > li > a', 'navigation');
		SiteUtils.applyTextReplacement('h1 > span, h2 > span, .secondary h3 span, .subtitle span, ul#portfolioList h2', 'headings');
	},

	setupRollOvers: function() {
		$$('.rollOver').applyRollOver();
	},

	setupClearDefaults: function() {
		$$('.hasDefault').applyClearDefault('active');
	},

	setupPopups: function() {
		$$('a[rel~=popup]').addEvent('click', function(e) {
			e.stop();

			window.open(this.href, "poupWindow", "menubar=0,resizable=1,width=800,height=600");
		});
	},

	setupExternalLinks: function() {
		$$('a[href^=http://]', 'a[href$=.pdf]').each(function(el) {
			if (el.get('href').test(/\.pdf$/i) || !el.get('href').test(/fluidcreativity\.co\.uk/i)) {
				var title = el.set('target', '_blank').get('title');
				el.set('title', (title ? title + ' ' : '') + '[External link - opens in new window]');

				if (el.getChildren().length == 0) el.addClass('externalLink');
			}
		});
	},

	setupFooterTools: function() {
		var footerToggles = new Element('ul', { 'id': 'footerPanelToggle' }).inject($('pageWrapper').getElement('.wrapper'));
		var footerPanels = $('footerTools').getElements('div.footerPanel');

		footerPanels.each(function(el) {
			var title = el.getElement('h2').addClass('notVisible').get('text');

			el.store('origHeight', el.getSize().y).setStyle('height', 0);
			el.set('tween', { duration: 500 });

			footerToggles.adopt(new Element('li').adopt(
				new Element('a', { 'href': '#', 'text': title }).addEvent('click', function(e) {
					e.stop();

					footerToggles.getElements('li').removeClass('selected');

					if (this.getStyle('height').toInt() == 0) {
						var scroller = (function() { window.scrollBy(0, this.retrieve('origHeight') / 10) }.bind(this)).periodical(50);
						$clear.delay(550, null, scroller);
						$(e.target).getParent().addClass('selected');
					}

					footerPanels.tween('height', 0);
					this.tween('height', this.getStyle('height').toInt() > 0 ? 0 : this.retrieve('origHeight'));
				}.bind(el))
			));
		});
	},

	setupFooterLogos: function() {
		var accreditationBlock = $('accreditationBlock');

		if (accreditationBlock) {
			new Slidr(accreditationBlock.getElement('ul'), {
				slideWidth: 118,
				canPause: true
			}).start();
		}
	},

	setupTextModes: function() {
		var textModes = $('textSizeModes');

		if (textModes) {
			var textModeItems = textModes.getElements('li');

			textModeItems.each(function(el) {
				el.getFirst().addEvent('click', function(e) {
					e.stop();
					SiteUtils.switchTextSize(el.get('class').replace(/\s+.*/, ''));

					textModeItems.removeClass('selected');
					el.addClass('selected');
				});
			});
		}
	},

	setupClientLogin: function() {
		var loginPanel = new Element('div', { 'id': 'clientLoginPanel', 'class': 'headerPanel' }).setStyle('height', 0).inject($('pageWrapper'), 'before');

		new Request.HTML({
			url: '/login/panel',
			update: loginPanel,
			onComplete: function() {
				loginPanel.store('origHeight', loginPanel.getFullHeight());

				$('headerActions').getElement('a').addEvent('click', function(e) {
					e.stop();

					this.tween('height', this.getStyle('height').toInt() > 0 ? 0 : this.retrieve('origHeight'));
				}.bind(loginPanel));
			}
		}).get();
	},

	setupSearchPopup: function() {
		if (typeof LiveSearch != "undefined") {
			var searchPanel = new Element('div', { 'id': 'searchPanel', 'class': 'headerPanel' }).inject('pageWrapper', 'before');
	
			new LiveSearch($('headerActions').getElement('form'), {
				resultsPanel: searchPanel,
				url: '/search/panel'
			});
		}
	}
}

SiteUtils = {
	applyTextReplacement: function(selector, mode) {
		if (mode == 'navigation') {
			var options = { hover: true };
		} else {
			var options = {};
		}
		
		Cufon.replace(selector, options);
	},

	switchTextSize: function(mode) {
		$(document.body).erase('class').addClass(mode + 'Text');

		Cookie.write('textMode', mode, { path: '/', duration: 30 });
	}

}

Element.implement({
	applyRollOver: function() {
		if (this.src.test(/\.(gif|jpg|jpeg|png)$/i)) {
			// preload image
			var preload = new Image();
			preload.src = this.src.replace(/\.(gif|jpg|jpeg|png)/, '-over.$1');

			this.addEvents({
				mouseover: function() {
					this.src = this.src.replace(/\.(gif|jpg|jpeg|png)/, '-over.$1');
				},

				mouseout: function() {
					this.src = this.src.replace(/-over\.(gif|jpg|jpeg|png)/, '.$1');
				}
			});
		}

		return this;
	},

	applyClearDefault: function(className) {
		this.addClass(className).addEvents({
			'focus': function() {
				if (this.value == this.defaultValue && !this.retrieve('cleared')) {
					this.value = '';
					this.store('cleared', true);

					this.removeClass(className);
				}

			},
			'blur': function() {
				if (this.value == '' && this.retrieve('cleared')) {
					this.value = this.defaultValue;
					this.eliminate('cleared');

					this.addClass(className);
				}
			}
		});

		return this;
	},

	getFullHeight: function() {
		var origHeight = this.getStyle('height').toInt();
		var fullHeight = this.setStyle('height', 'auto').getSize().y;

		this.setStyle('height', origHeight);
		return fullHeight;
	}
});

String.prototype.truncate = function(length) {
	return (this.length > length ? this.substr(0, length) + '...' : this).replace(/^\s+|\s+$/g, '');
}

window.addEvent('domready', Site.init);
