if (typeof Mekin == 'undefined') {
	throw('Mekin library is required for ComfortStation to work.\nPlease include Mekin.js first');
}

// Requires resource and effects
Mekin.checkObject( 'Mekin.Resource', Mekin.Resource );
Mekin.checkObject( 'Mekin.Effects',  Mekin.Effects  );

var ComfortStation = {
	
	copyrightHeight: 0,
	
	Scriptname: 'ComfortStation.js',
	
	divLoadingBar: null,
	
	divLoader: null,
	
	divContent: null,
	
	isLoaded: false,
	
	options: {},
	
	pageToLoad: null,
	
	rolloverLinks: [ 'shop-online', 'news', 'about', 'london-store', 'press', 'stockists', 'contact' ],

	onResourceLoadUpdate: function(pc) {
	
		log('Loading...' + Math.floor(pc*100) + '%' );

		if (this.divLoadingText) {
			this.divLoadingText.innerHTML = Math.floor(pc*100) + '%';
		}
	
		/*
		if (this.divLoadingBar) {
			this.divLoadingBar.setStyle({
				width: pc*100 + '%'
			});
		}
		*/
	},
	
	placeCopyright: function() {
		//return;
		
		var divCopyright = $('copyright');
		if (!divCopyright) {
			// Couldn't find; early out
			return;
		}
		divCopyright.hide();
		
		pageSize = Mekin.getPageSize();

		divCopyright.show();
		
		if (this.copyrightHeight == 0) {
			// For some reason the reported height changes on subsequent calls so only get it once
			this.copyrightHeight = divCopyright.getHeight();
		}
		
		var top = (Math.max( pageSize[1], pageSize[3] ) - this.copyrightHeight);
		top = Math.max( top, 600 );
		
		divCopyright.setStyle({
			position: 'absolute',
			top: top + 'px',
			bottom: ''
		});
	},
	
	loadLoadingMsg: function() {
		// We need to begin loading the, um, loading message
		// early on in case we need it later.
		
		// Begin loading
		var imgLoadingMsg = Mekin.Resource.createImageRel( 'patience.gif', {position:'absolute'}, {
			onLoad: function() {
				log( 'Patience is a Virtue image has loaded' );				
			}
		});
		
		// Set alt text in case image hasn't loaded yet
		imgLoadingMsg.alt = 'Patience is a virtue...';
	
		// Create a container div for the image and some text underneath
		this.divLoader = $(document.createElement('div'));
		this.divLoader.setStyle({
			position: 'absolute',
			top: (465 - 91)/2 + 'px',
			width: '251px',
			height: (91 + 16) + 'px',
			left: '40%',
			margin: '0 auto'
		});
		
		// Create a div for the percent complete text
		this.divLoadingText = $(document.createElement('div'));
		this.divLoadingText.setStyle({
			position: 'absolute',
			width: '100%',
			opacity: '0.8',
			top: (91 + 8) + 'px',
			textAlign: 'center',
			color: 'white',
			fontSize: '10pt'
		});
		
		// Initialize to zero
		this.divLoadingText.innerHTML = '0%';
		
		// Add percent complete to container
		this.divLoader.appendChild( this.divLoadingText );
		
		// Add image to the conatiner
		this.divLoader.appendChild( imgLoadingMsg );
	},
	
	showLoadingMsg: function() {
	
		log('show loading msg');
		
		// Show the loading message (add it to the content div)
		var divContainer = $('container');
		if (divContainer)
		{
			divContainer.appendChild( this.divLoader );
		}
		
	},
	
	load: function( page ) {
	
		this.pageToLoad = page;
	},
	
	addOnLeaveEventsByTagName: function( tagName ) {
	
		tags = document.getElementsByTagName(tagName);
		//if (tagName == 'area')
		//	alert(tags.length);
			
		for (var i=0; i<tags.length; ++i) {
			tag = $(tags[i]);

			if (tag.href.indexOf('#') == -1 && tag.href.indexOf('javascript:') == -1 && tag.href.indexOf('mailto:') == -1 && tag.href != '') {
				tag.onclick = function() {
					return ComfortStation.onLeave(this);
				}
			}
		}

	},
	
	createSolid: function( bgColor, innerStyle ) {
	
		// Hide everything
		$('content').setStyle({
			opacity: '0',
			display: 'block',
			backgroundColor: bgColor
		});
		
		// Inner cell may have background style
		if (innerStyle) {
			$('innerContent').setStyle(innerStyle);
		}
	
	},
	
	// Page creation function common to most pages
	create: function( bgMain, bgTile ) {
			
		// Hide everything
		$('content').hide();
		
		// Preload bg image
		Mekin.Resource.createImage( bgMain );
		
		// Set background image of main content cell
		$('content-cell').setStyle({
			background: "url('" + bgMain + "')",
			position: 'relative'
		});
		
		//
		// Set background of left and right tiled panels
		//
		// Provide a default
		if (typeof bgTile == 'undefined') {
			bgTile = 'images/bg-texture-left.jpg';
		}
		
		Mekin.Resource.createImage(bgTile);
				
		$('left-panel').setStyle({
			background: "url('" + bgTile + "') repeat-x top right"
		});
		$('right-panel').setStyle({
			background: "url('" + bgTile + "') repeat-x top left"
		});
		
	},
	
	defaultLeave: function(dest) {
		
		Mekin.Effects.disappear('content', {
			duration:.3,
			afterFinish: function(){
				window.location = dest;
			}
		});
		
		return false;
	},
	
	onLeave: function(a) {
		var page = this.pageToLoad;
		
		if (page && page.leave) {
			return page.leave.call( page, a.href );
		} else {
			return this.defaultLeave(a.href);
		}
		
		return true;
	},
	
	onPageLoad: function() {
	
		var that = this;
	
		this.installLinks();
	
		// Position copyright correctly at bottom of page
		this.placeCopyright();
				
		// Get the content div
		this.divContent = $('content');
		
		// Load the page
		var page = this.pageToLoad;
		if (!page) {
			Mekin.error('You must supply a page to load in ComfortStation.load');
			return;
		}
		
		// Begin loading the loading message if
		// we might need it later
		if (page.showLoadingMsg)
		{
			this.loadLoadingMsg();
		}
		
		// Show loading message if necessary
		setTimeout( function() {
			if (page.showLoadingMsg == true && !that.isLoaded) {
				that.showLoadingMsg();
			}		
		}, 500 );
	
		//this.options = Object.extend( this.options, options );
		
		if (!page.create) {
			Mekin.error('You must supply a \'create\' method for the page in ComfortStation.load');
			return;
		}
		
		// Create the page
		page.create.call( page );

		// Add 'on leave' event listener to all links
		this.addOnLeaveEventsByTagName( 'a' );
		this.addOnLeaveEventsByTagName( 'area' );
				
		if (!page.run) {
			Mekin.error('You must supply a \'run\' method for the page in ComfortStation.load');
			return;
		}
		
		Mekin.Resource.load( {
//	Don't use loading bar -- doesn't jive with the site layout
			onUpdate: function(pc) {
				that.onResourceLoadUpdate.call( that, pc );
			},
			
			afterFinish: function() {
			
				that.isLoaded = true;
			
				// Fade out the loader
				if (that.divLoader) {
					Mekin.Effects.disappear( that.divLoader );
				}

				// Start the page
				page.run.call( page );
			}
		});
		
	},
	
	installLinks: function() {
		map = $('navMap');
		theTop = $('top');
		
		if (!map || !theTop) {
			Mekin.warning('No navigation map found.');
			return;
		}
		
		theTop.setStyle({position:'relative'});
		
		areas = map.getElementsByTagName('area');
		
		/*
		var addCallback = function( area, img ) {
			area.observe( 'mouseover', function(){
				Mekin.Effects.appear( img );
			});
			img.observe( 'mouseout', function() {
				Mekin.Effects.disappear( img );
			});
		}
		*/
		c = Math.min(areas.length, this.rolloverLinks.length+1);
		for (var i = 1; i < c; ++i) {
			area = $(areas[i]);
			l = this.rolloverLinks[i-1];
			new RolloverLink( area, 'nav-' + l + '-on.gif' );
		}
	}
}

var RolloverLink = new Class.create({

	img: null,
	a:   null,

	initialize: function( area, src ) {
	
		var that = this;
		
		if (typeof Collection != 'undefined') {
			src = "collections/" + src;
		}

		this.img = Mekin.Resource.createImageRel( src, {}, {preload: false, hide:true} );
		this.a   = $(document.createElement('a'));
		
		// Extract coordinates (right,top,left,bottom)
		var rect = area.coords.match(/[0-9]+/g);
		var pLeft   = Math.min(rect[0], rect[2]);
		var pTop    = Math.min(rect[1], rect[3]);
		var pWidth  = Math.abs(rect[0] - rect[2]);
		var pHeight = Math.abs(rect[3] - rect[1]);
		this.a.setStyle({
			position: 'absolute',
			left:     pLeft   + 'px',
			top:      pTop    + 'px',
			width:	  pWidth  + 'px',
			height:   pHeight + 'px'
		});

		this.a.href = area.href;
		this.a.appendChild(this.img);
	
		// Install callbacks
		this.a.observe( 'mouseover', function() {
			Mekin.Effects.appear( that.img );
		});
		this.a.observe( 'mouseout',  function() {
			Mekin.Effects.disappear( that.img );
		});
		
		area.parentNode.parentNode.appendChild(this.a);
	}

});

Event.observe( window, 'resize', function(){
	//ComfortStation.placeCopyright();
});
Event.observe( window, 'load', function(){
	ComfortStation.onPageLoad();
});