var xml;
var xsl;

var bgstyles = {};
bgstyles.bg_blue = 							"background: #0171bd url(/staticfiles/img/bg-blue.jpg) repeat-x top left;";
bgstyles.bg_home_how_we_deliver = 			"background: #0171bd url(/staticfiles/img/bg-blue.jpg) repeat-x top left;";
bgstyles.bg_home_talk = 					"background: #f15a25 url(/staticfiles/img/bg-orange.jpg) repeat-x top left;";
bgstyles.bg_home_products_and_services =	"background: #8cc63e url(/staticfiles/img/bg-green1.jpg) repeat-x top left;";
bgstyles.bg_home_our_clients = 				"background: #c2272d url(/staticfiles/img/bg-red.jpg) repeat-x top left;";
bgstyles.bg_home_contact = 					"background: #d3145a url(/staticfiles/img/bg-pink.jpg) repeat-x top left;";

bgcolors = {};
bgcolors.bg_blue = 							"#0171bd";
bgcolors.bg_home_how_we_deliver = 			"#0171bd";
bgcolors.bg_home_talk = 					"#f15a25";
bgcolors.bg_home_products_and_services =	"#8cc63e";
bgcolors.bg_home_our_clients = 				"#c2272d";
bgcolors.bg_home_contact = 					"#d3145a";

var current_style;
var current_color;

var animating = false;

var cookies = {};


function createCookie(name,value,days) {
	cookies[name] = value;
	
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	if(typeof(is_admin) != 'undefined' && is_admin) { return true; }
	
	return (typeof(cookies[name]) == 'undefined') ? '0' : cookies[name];
	
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// crossfade the background
var bgfade = function( cn )
{
	if($('bgs').childElements().length == 1)
	{
		if($('bgs').childElements().first().className != cn)
		{
			var style = bgstyles[cn.replace(/-/g, '_')];
			current_style = cn;
			current_color = bgcolors[cn.replace(/-/g, '_')];
			
			$('bgs').insert( new Element('div', { className: cn, 'style': style } ) );
			new Crossfader( 'bgs', { repeat: false, wait: 0.01, time: 1 } );
		}
	}
} 


var subnav = function( elem, link )
{
	if(animating) { return; }
	
	if($('welcomecopy'))
		$('welcomecopy').fade();
		
	$('logo').appear();
	var par = elem.up('div');
	var cn = 'bg-' + par.className;
	bgfade(cn);

	var co = par.up('li').positionedOffset();
	var carCo = $('carousel').down('ul').cumulativeOffset(); // $('carousel').cumulativeOffset();

	var tmp = par.cloneNode(true);

	var l = co.left + carCo.left;

	$('subnav').fade( { duration: 0.5, afterFinish: function() {
		
		$('subnav').descendants().invoke('stopObserving');
		$('subnav').update( tmp );
		
		tmp.setStyle( { position: 'absolute', top: 0, left: l+'px' } );

		tmp.down('h4').show();
		if(tmp.down('ul'))
		{
			tmp.down('ul').show();
		}

		$('carousel').up('div.plugHome-subbox').fade( { duration: 0.5 } );

		$('subnav').appear( { duration: 0.5, afterFinish: function() {
			new Effect.Move(tmp, { duration: 0.5, y: 0, x: -(l + 40), afterFinish: function() {

				pageloader( link );

			} }); return false;
		} } );

		tmp.childElements('a').each( function(el) {
			el.observe('click', link_observer, false );
		} );
	} } );
}

var filenameFromPath = function(path)
{
	var pathComponents = path.split('/');
	var fileComponets = pathComponents[pathComponents.length-1].split('.');
	var pageIdentifier = fileComponets[0];
	
	return pageIdentifier;
}

var nextPage = function()
{
	var currentPage = document.body.id;
	
	var links = ($$('div.subsubnav a[id="subsubnav-'+currentPage+'"]').length) ? 
					$$("div.subsubnav a") :
					$$("#subnav a:not(.menu-button)");
	
	
	if(links.length == 1)
		return;
	
	for(var i=0; i<links.length; i++)
	{
		var elem = links[i];
		var filename = filenameFromPath(elem.href);
		if(filename == currentPage)
		{
			var index = i+1;
			
			if(index > links.length-1)
				index = 0;
			
			pageloader(links[index].href);
			return;
		}
	}
}

var prevPage = function()
{
	var currentPage = document.body.id;
	
	var links = ($$('div.subsubnav a[id="subsubnav-'+currentPage+'"]').length) ? 
					$$("div.subsubnav a") :
					$$("#subnav a:not(.menu-button)");
	
	
	if(links.length == 1)
		return;
	
	for(var i=0; i<links.length; i++)
	{
		var elem = links[i];
		var filename = filenameFromPath(elem.href);
		if(filename == currentPage)
		{
			var index = i-1;
			
			if(index < 0)
				index = links.length-1;
			
			pageloader(links[index].href);
			return;
		}
	}
}

var pageupdate = function()
{
	if($('loading')) { $('loading').hide(); }
	
	if($('the-form-xcontact'))
	{
		$('the-form-xcontact').observe('submit', function(event) {
			$('ajax-content').down('div').hide();
			if($('loading')) { $('loading').show(); }
			
		    $('the-form-xcontact').request({
		        onFailure: function(t) {  },
		        onSuccess: function(t) {
					$('ajax-content').descendants().invoke('stopObserving');
					$('ajax-content').update(t.responseText);
					pageupdate();
		        }
		    });
		    Event.stop(event); // stop the form from submitting
		});
	}
	
	// $$('.footernav .nav li').each( function(el) { el.show(); } );
	// var hider = 'nav-' + $('bgs').childElements().last().className.replace('bg-home-', '');
	// $$('li.'+hider).each( function( el ) { el.hide(); } );

	$('flash-area').down('div').className = 'flash-' + current_style;
	Effect.BlindDown('ajax-content', { scaleContent: false, duration: 0.5, afterFinish: function() {
		if(current_style != "bg-home-contact")
		{
			$('flash-area').appear( { duration: 0.5 } );
			$('flash-toggle').observe('click', toggleFlashArea, false);	
			
			var cookie = current_style.replace(/-/, '') + '_flashplayed';
			var cookie2 = cookies.cookie;
			
			if(readCookie(cookie) != '1' && cookie2 != '1')
			{
				openFlashArea();
			}
		}
		
		$('footernav').appear( { duration: 0.5 } );
		$('footernav').observe('click', toggleFooterNav, false);
		
		animating = false;
	} } );
	
	observeNextPrevious();
	
	// Centralize the footer links
	var links = $$("#footernav2 li.level-1");
	var linkCount = 0;
	links.each(function(elem) {
		if(elem.visible())
			linkCount++;
	})
	
	// var padding = (linkCount == 3) ? '12.8' : '3.33';
	// 
	// $$('.footernav .container > ul.nav').each(function(elem)
	// {
	// 	elem.setStyle({paddingLeft: padding+'em'});
	// });
	
	$$('div.subsubnav li a').each( function(el) {
		el.observe('click', link_observer, false );
	} );
	
	$$('.breadcrumbs a.sublinks').each( function(el) { el.observe( 'click', link_observer, false); } );
	$$('a.reset').each( function(el) { el.observe('click', reset, false ); } );
	
	document.fire('page:updated');
}

var observeNextPrevious = function()
{
	// Ensure that the next/previous links are being observed
	$$('a.next').each(function(elem){
		// Only add the observer if it hasn't already been added else we'll get repeat ajax requests
		if(!elem.hasClassName('observed'))
		{
			elem.observe('click', this.nextPage.bindAsEventListener(this));
			elem.addClassName('observed');
		}
	});
	
	$$('a.prev').each(function(elem){
		// Only add the observer if it hasn't already been added else we'll get repeat ajax requests
		if(!elem.hasClassName('observed'))
		{
			elem.observe('click', this.prevPage.bindAsEventListener(this));
			elem.addClassName('observed');
		}
	});
}

var footerlinks = function( e )
{
	e.stop();
	var elem = e.findElement('a');
	
	toggleFooterNav();
	
	try{ $('subnav').down('div').fade(); }
	catch(e) { /* Might not exist yet */ }
	
	try
	{
		$('flash-toggle').stopObserving('click');
		$('flash-area').hide();
	}
	catch(e) { /* Might not exist yet */ }
	
	if($('ajax-content'))
	{
		Effect.BlindUp('ajax-content', { scaleContent: false, duration: 0.5, afterFinish: footerlinksLoadHrefFromElement.curry(elem).bind(this) } );
	}
	else
	{
		footerlinksLoadHrefFromElement(elem);
	}
}

var footerlinksLoadHrefFromElement = function(elem)
{
	var link = elem.href;

	var anch = elem.up('li').id.replace('nav-', 'home-');
	var anchs = $$( '#carousel ul.navi .'+anch );
	
	if(!anchs.length)
	{
		anch = elem.up('li.level-1').id.replace('nav-', 'home-');
		var anchs = $$( '#carousel ul.navi .'+anch );
	}
	var anchor = anchs.first().down('h4').down('a');
	subnav( anchor, link );
}

var toggleFooterNav = function()
{
	$('footernav').stopObserving('click');
	
	if( $('footernav').hasClassName('open') )
	{
		closeFooterNav();
	}
	else
	{
		openFooterNav();
	}
}

var closeFooterNav = function()
{
	$('footernav2').setStyle( { height: '0' } );
	
	$('footernav').morph( { height: '30px' }, { duration: 0.5, afterFinish: function() {
		$('footernav').removeClassName('open');
		$('footernav').observe('click', toggleFooterNav, false);

		$('footernav2').childElements('a').each( function(el) {
			el.stopObserving('click');
		} );
		
	} } );
}

var openFooterNav = function()
{
	try{
		animationComplete();
		
	} catch(e) { /* Might not exist yet */ }
	
	$('footernav').morph( { height: '248px' }, { duration: 0.5, afterFinish: function() {
		$('footernav').addClassName('open');
		$('footernav').observe('click', toggleFooterNav, false);
		
		$('footernav2').setStyle( { height: '600px' } );
		
		$('footernav2').childElements().each( function(el) {
			el.observe('click', footerlinks, false);
		} );
		
	} } );
}

var openFlashArea = function()
{
	closeFooterNav();
	
	$('flash-area').down('div').morph( { height: '182px' }, { duration: 0.5, afterFinish: function() {
		$('flash-toggle').observe('click', toggleFlashArea, false);
		$('flash-area').addClassName('open');
		$('flash-area-content').show();
		
		$('subnav').hide();
		$('logo').hide();
		
		var h = Math.max( document.documentElement.clientHeight, document.documentElement.scrollHeight ) + 'px';
		var w = Math.max( document.documentElement.clientWidth, document.documentElement.scrollWidth ) + 'px';

		var overlay = new Element('div', { id: 'overlay' } );
		overlay.setStyle( { position: 'absolute', top: 0, left: 0, height: h, width: w, backgroundColor: '#000', opacity: '0.8', 'z-index': 35 } );

		$$('.wrapper').first().insert( overlay );
		
		var flashvars = { };
		var params = { wmode: "transparent" };
		var attributes = {  };
		swfobject.embedSWF("./staticfiles/swf/"+current_style+".swf", "flash-area-content", "950", "182", "9.0.0", "/cache/swf/expressInstall.swf", flashvars, params, attributes);
		
		var cookie = current_style.replace(/-/, '') + '_flashplayed';
		createCookie(cookie,'1',365);
		cookies.cookie = '1';
	} } );
}

var closeFlashArea = function()
{
	$('flash-area-content').hide();
	$('flash-area-inner').update('<div id="flash-area-content"></div>');
	if($('overlay')) { $('overlay').remove(); }

	$('flash-area').down('div').morph( { height: '22px' }, { duration: 0.5, afterFinish: function() {
		$('flash-toggle').observe('click', toggleFlashArea, false);
		$('flash-area').removeClassName('open');
		
		$('subnav').show();
		$('logo').show();
	} } );
}

var toggleFlashArea = function()
{
	$('flash-toggle').stopObserving('click');
	
	if( $('flash-area').hasClassName('open') )
	{
		closeFlashArea();
	}
	else
	{
		openFlashArea();
	}
}

var set_flash_area = function()
{
	$('flash-area-content').hide();
	$('flash-area').down('div').addClassName( 'flash-' + current_style );

	if(current_style != "bg-home-contact" && document.body.id != 'home')
	{
		$('flash-area').show();
		$('flash-toggle').observe('click', toggleFlashArea, false);
		
		var cookie = current_style.replace(/-/, '') + '_flashplayed';
		var cookie2 = cookies.cookie;
		
		if(readCookie(cookie) != '1' && cookie2 != '1')
		{
			openFlashArea();
		}
	}
}

var appscripts = function()
{
	var bg = $('bgs').childElements().first().className;

	current_style = bg;
	current_color = bgcolors[bg.replace(/-/g, '_')];
	
	set_bg();
	set_flash_area();
	
	init();
}

var setup_nav = function()
{
	try
	{
		if(document.body.id == 'home')
		{
			$('flash-area').hide();
			$('logo').hide();
			
			showAnimation();
		}

		$('footernav').observe('click', toggleFooterNav, false);
		$('footernav2').observe('click', toggleFooterNav, false);
	}
	catch(e) { /* Might not exist yet */ }

	if( $('carousel') && $('carousel').down('ul'))
	{
		$('carousel').down('ul').childElements('a').each( function( el ) { el.observe( 'click', subnav_observer, false ); } );
	}
	
	// observe links if the page is not the homepage
	if($('subnav') && $('subnav').down('a'))
	{
		$('subnav').down(0).observe('click', link_observer, false);
		observeNextPrevious();
	}
	
	$$('.breadcrumbs a.sublinks').each( function(el) { el.observe( 'click', link_observer, false); } );
	$$('a.reset').each( function(el) { el.observe('click', reset, false ); } );
}

var subnav_observer = function( e )
{
	e.stop();
	
	closeFooterNav();
	var elem = e.findElement('a');
	if(elem)
	{
		subnav( elem, elem.href );
	}
} 

var link_observer = function( e )
{
	e.stop();
	
	closeFooterNav();
	var elem = e.findElement('a');
	if(elem)
	{
		pageloader(elem.href);
	}
}

var set_bg = function()
{
	$$('html').first().style.backgroundColor = current_color;
	document.body.style.backgroundColor = current_color;
}

var reset = function( e )
{
	e.stop();
	
	animationComplete();
	
	if(animating)
		return;
	
	animating = true;

	try
	{
		$('subnav').descendants().invoke('stopObserving');
		$('ajax-content').descendants().invoke('stopObserving');
		
		$('subnav').update('');
		$('ajax-content').update('');
		$('logo').hide();
		$('flash-area-content').hide();
		$('flash-area').hide();

		$('welcomecopy').appear();
		
		if($('bgs').childElements().length != 1)
		{
			$('bgs').update( new Element('div', { className: 'bg-blue', 'style': bgstyles.bg_blue } ) );
		}
		else
		{
			bgfade( 'bg-blue' );
		}
	}
	catch(e) { /* Might not exist yet */ }
	
	$('carousel').up('div.plugHome-subbox').appear( { duration: 0.5, afterFinish: function() { animating = false; } } );
	
	// $$('.footernav .nav li').each( function(el) { el.show(); } );
	// 
	// var padding = '3.33';
	// $$('.footernav .container > ul.nav').each(function(elem)
	// {
	// 	elem.setStyle({paddingLeft: padding+'em'});
	// });
} 

var cros = function( e )
{
	if(e.memo.value != 0 && $('bgs').childElements('div').length > 1)
	{
		set_bg();
		$('bgs').childElements('div').first().remove();
	}
}

var showAnimation = function()
{
	if(readCookie('home_flashplayed') != '1')
	{
		if($('plugHome2')) { $('plugHome2').style.visibility = 'hidden'; }
		if($('wrapper')) { $('wrapper').hide(); }

		var skip = new Element('a', { id: 'skipanim' } ).update('skip intro');
		skip.setStyle( { position: 'absolute', bottom: '20px', right: '20px', color: 'black', 'z-index': 100 } );
		skip.observe('click', animationComplete, false );
		
		$$('.wrapper').first().insert( { after: skip } );
		
		var flashintro_wrapper = new Element('div', { id: 'flashintro-wrapper'} ).update( new Element('div', { id: 'flashintro'} ) );
		flashintro_wrapper.setStyle( { 'z-index': 100, position: 'absolute', left: '50%', top: '50%', marginLeft: '-475px', marginTop: '-200px' } );

		$$('.wrapper').first().insert(flashintro_wrapper);
		
		var flashvars = { };
		var params = { wmode: "transparent" };
		var attributes = {  };
		swfobject.embedSWF("./staticfiles/swf/intro.swf", "flashintro", "950", "400", "9.0.0", "/cache/swf/expressInstall.swf", flashvars, params, attributes);
	}
}

var animationComplete = function()
{
	createCookie('home_flashplayed','1',365);
	
	if($('overlay')) { $('overlay').remove(); }
	
	if($('flashintro-wrapper')) { $('flashintro-wrapper').remove(); }
	if($('skipanim'))
	{ 
		$('skipanim').stopObserving();
		$('skipanim').remove();
	}

	if($('plugHome2')) { $('plugHome2').style.visibility = 'visible'; }
	if($('wrapper')) { $('wrapper').show(); }
	
	// $('overlay2').remove();
}

document.observe('crossfader:animating', cros );

function externalLinks() { $$('a').each( function(el) { if(el.getAttribute("href") && el.getAttribute("rel") == "external") { el.target="_blank"; } } ); }
function internalLinks() { $$('a').each( function(el) { if(el.getAttribute("href") && el.getAttribute("rel") == "internal") { el.target="_self"; } } ); }

document.observe('dom:loaded', appscripts, false);
document.observe('dom:loaded', externalLinks);
document.observe('dom:loaded', internalLinks);
