var enrizen = {

	// the width of each box
	itemWidth : 0,
	// the length of the animation
	effectDuration: 0.8,
	// enrizen address
	address : '275 Alfred St N, North Sydney NSW 2060, Australia',

	// Object constructor
	start : function () 
	{
		enrizen.createBox();
		enrizen.moveBox();
		enrizen.behaviour();
		enrizen.homepageTimer();
	},
	
	// Function to manipulate the page to make the widget work
	setup : function() 
	{
		// grab the elements of the widget
		var panel = $('scroll_box');
		var items = $$('div.page_text');
		var links = $$('#navbar li a');
		// determine the width of the boxes
		enrizen.itemWidth = items.first().getWidth();
		// loop through and make the scroll panel width match the total number of boxes
		var newWidth = 0;
		items.each(function(b){
			b.setStyle({ float : 'left' });
			newWidth += enrizen.itemWidth;
		});
		panel.setStyle({ width: newWidth + 'px' });
		$('page_box').setStyle({ 'overflow' : 'hidden' });
		// check the url and see if there is any defining fragments
		var fragment = window.location.toString().split('#').last();
		links.each(function(el, i){
			if(fragment == el.href.split('#').last()) {
				enrizen.doScroll(i);
				$('masthead').scrollTo(0);
			}
		});		
	},
	
	// Add page behaviours
	behaviour :  function() 
	{
		// add a click to the Enrizen logo
		$$('#masthead h1').each(function(el, i){
			el.setStyle({ 'cursor' : 'pointer' });
			el.observe('click', function(e){
				window.location = baseURL;				
			});
		});
		// add the click to the google map link
		$$('a#googleMapLink').each(function(el, i){
			el.observe('click', function(e){
				Event.stop(e);
				enrizen.googleMaps();
			});
		});
		// add some fancyness to the contact form
		$$('#auto_form input','#auto_form textarea').each(function(el, i){
			el.observe('focus', function(e){
				el.setStyle({ 'border' : '1px solid #333' });
				new Effect.Highlight(el, { startcolor: '#ffffff', endcolor: '#fefecf', restorecolor: '#fefecf' });
			});
			el.observe('blur', function(e){
				el.setStyle({ 'border' : '1px solid #999' });
				new Effect.Highlight(el, { startcolor: '#fefecf', endcolor: '#ffffff', restorecolor: '#ffffff' });
			});
		});
	},
	
	// Create the box to highlight the selected page
	createBox : function()
	{
		var html = '<div id="selected"></div>';
		$('masthead').insert({ 'top' : html });
		$('selected').hide();
	},
	
	// create timer for the homepage animation
	homepageTimer : function ()
	{	
		if ( !$('homePageGroups') ) return;
		
		new PeriodicalExecuter ( enrizen.animateHomePageBoxes, 6);		
	},
	
	// animate homepage boxes
	currAnimatedBox : 0,
	animateHomePageBoxes : function()
	{
		var boxes = $$('#homePageGroups div');
		
		boxes.each(function(el, i){			
			if( i == enrizen.currAnimatedBox)
				el.appear();
			else
				el.fade();
		});
		
		enrizen.currAnimatedBox = enrizen.currAnimatedBox == boxes.length - 1 ? 0 : enrizen.currAnimatedBox + 1;
	},
	
	// Move the highlight box used to designate the selected page 
	moveBox : function() 
	{
		var link;
		$$('#navbar a').each(function(el, i){
			if( el.href == window.location)
				link = el;
		});
		
		if (!link) return;
	
		var box = $('selected');
		var boxWidth = link.getWidth();
		var left = $('navbar').positionedOffset().left + link.positionedOffset().left;
		new Effect.Parallel([
				new Effect.Morph(box, { 
					sync: true, 
					style: { 
						'width' : boxWidth + 'px',
						'right' : ($('masthead').getWidth() - left - boxWidth).toString() + 'px' 
					} 
				}),
				new Effect.Appear(box, { sync: true }) 
			],
			enrizen.effectDuration
		);
	},
	
	googleMaps : function()
	{
		var html = '<div id="mapBox">';
		html += '<div id="gMapHeader">';
		html += '<input id="directions" type="text" value="... your address" style="color:#666;" onFocus="enrizen.wipeInputText()" />';
		html += '<input type="submit" id="getDirections" value="Get Directions" onClick="enrizen.getDirections();return false;" />';
		html += '<a href="#" onclick="enrizen.closeMap(); return false;">close</a>';
		html += '</div>';
		html += '<div id="gMapDirections" style="display:none;"></div>';
		html += '<div id="gMap" style="position:absolute;top:30px;left:10px;width:380px;height:380px;"></div>';
		html += '</div>';
		$('container').insert(html);
		
		var map = new GMap2(document.getElementById("gMap"));
  		map.setMapType(G_NORMAL_MAP);
  		
  		enrizen.gMap = map;
  		
  		enrizen.geoCode(enrizen.address, map);
		
		$('mapBox').appear({ duration:0.8 });
	},
	
	wipeInputText : function()
	{
		$('directions').setStyle({ 'color' : '#000' });
		$('directions').value = $F('directions') == '... your address' ? '' : $F('directions');
	},
	
	closeMap : function()
	{
		$('mapBox').fade({ 
			duration: 0.5, 
			afterFinish: function() {
				$('container').removeChild($('mapBox'));
			} 
		})
	
	},
	
	geoCode : function(address, map)
	{
		var geocoder = new GClientGeocoder();
		geocoder.getLatLng(
			address,
			function(point) {
				var icon = new GIcon();
        		icon.image = baseURL + "images/enrizen_map_marker2.png";
				icon.iconAnchor = new GPoint(16, 16);
				icon.infoWindowAnchor = new GPoint(16, 0);
				icon.iconSize = new GSize(21, 39);
				icon.shadow = baseURL + "images/enrizen_marker_shadow.png";
        		icon.shadowSize = new GSize(50, 39);

				map.setCenter(point, 15);
				var markerOptions = { icon:icon };
				var marker = new GMarker(point, markerOptions);
				map.addOverlay(marker);
			}
		);	
	},
	
	getDirections : function()
	{
		$('gMapDirections').innerHTML = '';
		enrizen.gdir = new GDirections(enrizen.gMap,$('gMapDirections'));
		GEvent.addListener(enrizen.gdir, "error", enrizen.handleErrors);
        GEvent.addListener(enrizen.gdir, "load", function(){
        	$('mapBox').morph('width:670px');
        	$('gMapDirections').appear({ duration:0.6 });
        });
        var locationString = 'from: ' + $F('directions') + ' to: ' + enrizen.address;
		enrizen.gdir.load(locationString, { 'locale' : 'en-US' });
	},
	
	handleErrors : function(){
		if (enrizen.gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS){
			alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + enrizen.gdir.getStatus().code);
		} else if (enrizen.gdir.getStatus().code == G_GEO_SERVER_ERROR) {
			alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + enrizen.gdir.getStatus().code);
		} else if (enrizen.gdir.getStatus().code == G_GEO_MISSING_QUERY) {
			alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + enrizen.gdir.getStatus().code);
		} else if (enrizen.gdir.getStatus().code == G_GEO_BAD_KEY) {
			alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + enrizen.gdir.getStatus().code);
		} else if (enrizen.gdir.getStatus().code == G_GEO_BAD_REQUEST) {
			alert("A directions request could not be successfully parsed.\n Error code: " + enrizen.gdir.getStatus().code);
		} else { 
			alert("An unknown error occurred."); 
		}
	}
	

};

document.observe('dom:loaded', enrizen.start);