var Site = {
	enlargeCookie: null,
	cookieDomain: '.titan.imagin8.com',		// TODO: Change before golive
	
	start: function(){
		MooTools.lang.setLanguage("en-US");

		// Launch-in-new-window links automagically created
		var extLinks = $$('a.external');
		if ( extLinks.length ) {
			extLinks.each(function(elem, idx) { 
				elem.setProperty('target', '_blank');
			});
		}
		
		
		// Safari Suckerfish 'fix'
		if ( navigator.appVersion.toLowerCase().indexOf('safari') != -1 ) {
			var navElems = $$('#navigation li a');
			navElems.each(function(elem, idx) {
				elem.set('title', '');
			});
		}
		
		
		// Form validation automagic
		var valForms = $$('form.validate-form');
		if ( valForms.length ) {
			valForms.each(function(elem, idx) { 
				new FormValidator.Inline(elem, {
					'onFormValidate': Site.formHandler,
					'errorPrefix': '',
					'useTitles': true
				});
			});
		}
		
		
		// Form overtext magic
		Site.attachOverTexts();
		
		
		// Submission link automagic
		Site.attachSubmitLinks();
		
		
		// Expandy image automagic
		Site.attachExpandLinks();
		
		
		Site.enlargeCookie = new Hash.Cookie('enlargeCookie', {	'duration': 	60,
																'domain': 		Site.cookieDomain,
																'path': 		'/'
															});
		
		if ( Site.enlargeCookie.get('enlarged') ) {
			Site.enlargeText('on');
		}
	},
	
	
	formHandler: function(pass, form, submitEvent) {
		// Do anything necessary here
	},
	
	
	attachOverTexts: function() {
		var overElems = $$('input.overtext');
		if ( overElems.length ) {
			overElems.each(function(elem, idx) {
				elem.setProperty('overType', elem.getProperty('type'));
				
				if ( elem.getProperty('alt') ) {
					// Focus state
					elem.addEvent('focus', function() {
						if ( this.value == this.getProperty('alt')) {
							if ( this.getProperty('overType') == 'password' ) {
								elem = Site.cloneAndChangeInputType(elem, 'password', true);
							} else {
								this.value = '';
							}
						}
					});
					
					// Blur state
					elem.addEvent('blur', function() {
						if ( this.value == '') {
							if ( this.getProperty('overType') == 'password' ) {
								elem = Site.cloneAndChangeInputType(elem, 'text');
								elem.value = elem.getProperty('alt');
							} else {
								this.value = this.getProperty('alt');
							}
						}
					});
					
					// Default state
					if ( elem.value == '') {
						if ( elem.getProperty('overType') == 'password' ) {
							elem = Site.cloneAndChangeInputType(elem, 'text');
						}
						
						elem.value = elem.getProperty('alt');
					}
				}
			});
		}
	},
	
	
	attachSubmitLinks: function() {
		// Submit link magic
		var submitLinks = $$('.submit-link');
		if ( submitLinks.length ) {
			submitLinks.each(function(elem, idx) {
				var props = elem.getProperty('class').split(' ');
				
				if ( props.length ) {
					props.each(function(propItem, pidx) {
						if ( propItem.indexOf(':') != -1 ) {
							var parsedProps = JSON.decode('{'+propItem+'}');
							elem.setProperties(parsedProps);
						}
					});
				}
				
				if ( elem.getProperty('submitTarget') ) {
					elem.addEvent('click', function(event) {
						if ( $(this.getProperty('submitTarget')).validate() ) {
							$(this.getProperty('submitTarget')).submit();
						}
					});
					
					// Inject a dummy submit button for form functionality to be maintained
					// I like hitting enter to submit
					elem.getParent().adopt(new Element('input', {	'type': 'submit',			'name': 'dummy-submit',
																	'class': 'dummy-submit'
																}));
				}
			});
		}
	},
	
	
	attachExpandLinks: function() {
		// Expand link magic
		var expandLinks = $$('.expand');
		if ( expandLinks.length ) {
			expandLinks.each(function(elem, idx) {
				var props = elem.getProperty('class').split(' ');
				
				if ( props.length ) {
					props.each(function(propItem, pidx) {
						if ( propItem.indexOf(':') != -1 ) {
							var parsedProps = JSON.decode('{'+propItem+'}');
							elem.setProperties(parsedProps);
						}
					});
				}
				
				if ( elem.getProperty('expandTarget') ) {
					elem.addEvent('mouseover', function(event) {
						Site.expandCartoon(this, this.getProperty('expandTarget'));
						elem.setProperty('imageExpanded', false);
					});
				}
			});
		}
	},
	
	
	enlargeText: function(toggleTo) {
		if ( !toggleTo ) {
			if ( document.body.className.indexOf('enlarge') !== -1 ) {
				document.body.className = document.body.className.replace('enlarge', '');
				Site.enlargeCookie.set('enlarged', false);
			} else {
				document.body.className += ' enlarge';
				Site.enlargeCookie.set('enlarged', true);
			}
		} else if ( toggleTo == 'on' ) {
			document.body.className += ' enlarge';
		} else {
			document.body.className = document.body.className.replace('enlarge', '');
		}
		
		Site.enlargeCookie.save();
	},
	
	
	expandCartoon: function(elem, imgPath) {
		if ( elem.getProperty('imageExpanded') != true ) {
			var windowScroll = window.getScroll();
			var windowSize = window.getSize();
			var elemCoords = elem.getCoordinates();
			var elemSize = elem.getSize();
			var mainBG = $('main-background').getSize();
			
			var triggerElem = elem;
			
//			alert(JSON.encode(windowSize));
			
			imgLoader = new Image();
			imgLoader.onload = function() {		
				imgLoader.onload = null;
				
				// Image dimension quick references
				var imageWidth = imgLoader.width;
				var imageHeight = imgLoader.height;
				
				var expandHalfWidth = Math.ceil((imageWidth - elemSize.x) / 2);
				var expandHalfHeight = Math.ceil((imageHeight - elemSize.y) / 2);
				
				// Create an enlarger box
				var enlargeBox = new Element('div', {	'class': 'enlarge-box'
													});
	
				enlargeBox.setStyle('backgroundImage', 'url('+imgPath+')');
				enlargeBox.setStyle('backgroundPosition', '-'+expandHalfWidth+'px -'+expandHalfHeight+'px')
				
				enlargeBox.setStyle('width', elemSize.x);
				enlargeBox.setStyle('height', elemSize.y);
				
				enlargeBox.setStyle('opacity', 0);
															
				$('main-background').adopt(enlargeBox);
				
				enlargeBox.fx = new Fx.Morph(enlargeBox, {	'duration': '200',	
															'transition': Fx.Transitions.Sine.easeInOut,
															'link': 'chain'
															});
				
				// Need to set the initial position to accomodate for padding/border/margin
				var enlargeBoxPadding = {	'top': (	parseInt(enlargeBox.getStyle('borderTopWidth')) +
														parseInt(enlargeBox.getStyle('marginTop')) +
														parseInt(enlargeBox.getStyle('paddingTop'))
													),
											'left': (	parseInt(enlargeBox.getStyle('borderLeftWidth')) +
														parseInt(enlargeBox.getStyle('marginLeft')) +
														parseInt(enlargeBox.getStyle('paddingLeft'))
													)};
				
				if ( navigator.appVersion.toLowerCase().indexOf('msie') != -1 ) {
					var fudgeFactor = 0;
				} else {
					var fudgeFactor = 1;
				}
													
				enlargeBox.setStyle('left', (elemCoords.left - enlargeBoxPadding.left + fudgeFactor)+'px');
				enlargeBox.setStyle('top', (elemCoords.top - enlargeBoxPadding.top)+'px');
				
				
				// Set up the hiding event
				enlargeBox.triggerElem = triggerElem;
							
				enlargeBox.addEvent('mouseout', function() {
					this.fx.cancel();
					this.fx.start({	'opacity': 0
							}).chain(function() {
								enlargeBox.dispose();
							});
				
							
					enlargeBox.triggerElem.setProperty('imageExpanded', false);
				});
				
				enlargeBox.addEvent('click', function() {
					window.location.href = '/page/Learning_Centre/Cartoons/';
				});
				
				// We're expanding in this order:
				//	1. Up (top / height / bgY transition)
				//	2. Left (left / width / bgX transition)
				//	3. Right + Down (width + height transition
				enlargeBox.fx.start({	'opacity': [0, 1]
				}).start({				'top': (elemCoords.top - expandHalfHeight - enlargeBoxPadding.top)+'px',
										'height': (elemSize.y + expandHalfHeight)+'px',
										'background-position': '-'+expandHalfWidth+'px 0px'
				}).start({				'left': (elemCoords.left - expandHalfWidth - enlargeBoxPadding.left + fudgeFactor)+'px',
										'width': (elemSize.x + expandHalfWidth)+'px',
										'background-position': '0px 0px'
				}).start({				'width': imageWidth+'px',
										'height': imageHeight+'px'
				});

			};
			
			
			imgLoader.src = imgPath;
			elem.setProperty('imageExpanded', true);
		}
	}
	
};


// Do stuff on load
window.addEvent('load', Site.start);