// ***************************************************************
//  domReady handler
// ****************************************************************


window.addEvent ('domready', function(){	

	//blank the stage to conceal animation setup
	//(Don't do this in IE -- dunno why but it doesn't work
	if (!Browser.Engine.trident) { $('wrapper').setStyle('visibility','hidden'); }
	
	//Hide the default Hero image for later fade in
	if ($('defaultHero')) { $('defaultHero').setStyle('opacity',0); }


	//Hide any images tagged for fade in
	if (document.getElements('.fade')) 
	{
		var faders = $$('.fade');
		faders.each (function(element){ element.fade('hide'); });
	}


}); // end domReady handler










// ****************************************************************
// onload handler
// ****************************************************************


window.addEvent ('load', function(){


	//setup 'section' display area variables
	if ($('section'))
	{
		var sectionFx = new Fx.Morph($('section'), {duration:400, link:'cancel'})
		var sectionText = $('section').getElement('p').get('text');
		var sectionName = $('section').getElement('h2').get('text');	
		var sectionColor = $('section').getStyle('background-color');
		var pointerFx = new Fx.Morph($('section').getElement('.pointer'), {duration:300, link:'cancel'});
	} 
	
	
	//Record initial states and positions
	var tab = new Object;
		tab = document.getElement('li.nav');
		tab.restMargin 	 = 35;
		tab.restHeight 	 = 85;
		tab.extendHeight = $('main').getStyle('height');
		
	var tabText = new Object;
		tabText = tab.getFirst('a');
		tabText.restMargin = 60;
		tabText.extendHeight = tabText.getStyle('margin-top');


	//position home page animated elements offscreen
	
	if (currentSection() == 'home') 
	
	{
	
		elHeight = $('section').getSize().y.toInt()/10;
		$('section').setStyle('top',-(elHeight+3)+'em');
	
		elHeight = $('rightcol').getSize().y.toInt()/10;
		$('rightcol').setStyle('bottom',-(elHeight)+'em');

	}
		


	//Hide Services Teaser images
	if (document.getElement('.teaser'))
	{
		//set each teaser image to transparent and set default FX instance
		//so we can fade in each image independently later	
		$$('.teaser').each (function(element) {
			element.setStyle('opacity',0); 
			element.set('morph', {duration:400,  link:'cancel'});	
		});
		
		//show the image tag with 'active'
		document.getElement('.active').morph({'opacity':1});
	}





	//Setup the main navigation behaviors
	var navTabs = $$('li.nav');	
	
	navTabs.each (function(element){
	
			var tabFx = new Fx.Morph(element, {duration:200, link:'cancel'});
			var text = element.getFirst('a');
			var textFx = new Fx.Morph(text, {duration:300, transition:Fx.Transitions.Cubic.easeOut,link:'cancel'});

			//retract all nav tabs except current section
			
			if (element.id.split("_")[1] != currentSection()) 
			{
				element.setStyles({'margin-top':tab.restMargin, 'height':tab.restHeight});
				text.setStyle('margin-top',tabText.restMargin);
			}
	
			//Add mousevents
			element.addEvent('mouseenter', function(){
				if (element.id.split("_")[1] != currentSection()) 
				{
					tabFx.start({'margin-top':'0', 'height':tab.extendHeight});

					textFx.start({'margin-top':tabText.extendHeight});
					sectionFx.start({'background-color':getColor(element.id) });
					pointerFx.start({'background-position':'0 -28px'});
					setSectionInfo(text.get('text'), text.getProperty('title'));
					
				}		
			});
	
			element.addEvent('mouseleave', function(){
				if (element.id.split("_")[1] != currentSection()) 
				{
					tabFx.start({'margin-top':tab.restMargin, 'height':tab.restHeight});
					textFx.start({'margin-top':tabText.restMargin});	
					sectionFx.start({'background-color':sectionColor});			
					pointerFx.start({'background-position':'0 0'});
					setSectionInfo(sectionName, sectionText);
				} 
				
			});
	
	});
	
	
	
	// *** Services blocklist behaviors ***
	
	if (document.getElement('.services #blocklist')) 
	{

	
		if (currentSubSection()!='overview') {
			//set the initial pointer position based on the wrapper tag (current service)		
			currBlock = 'nav_'+currentSubSection();
			//grab the x position of the current block relative to the div container 'document'
			currBlockPos = ($(currBlock).getPosition($('document')).x);	
			//set the position of the pointer to that value	
			$('section').getElement('.pointer').setStyle('left',currBlockPos);
		} else {
				
			$('section').getElement('.pointer').setStyle('background-position','0 -28px');
		
		}
	
		//setup the mouse events for each block
		var items = $$('#blocklist dt');
		
		items.each (function(element){
		
		
			//we will need to address each element's FX independantly so rather than create 
			//a variable for each FX instance, we are setting the default FX instance
			//for each element.
			temp = element.getNext('dd');//need to do this because of stupid ie bug
			$(temp).set('morph', {duration:400, transition:Fx.Transitions.Cubic.easeOut, link:'cancel'});
			
			element.addEvent('mouseenter', function() { 
			
				if (currentSubSection()!='overview'){ 
					currTip = 'tip_'+currentSubSection();
					$(currTip).morph({'top': 0});
				}
				newPos = (element.getPosition($('document')).x);
				pointerFx.start({'left':newPos, 'background-position':'0 0'});
				var temp = element.getNext('dd');//need to do this becaus of stupid ie bug
				$(temp).morph({'top':65}); 
				//if we're on the overview page, fade in / out the pretty picture
				if (document.getElement('.overview')){
				$('hero_'+element.id.split("_")[1]).morph({'opacity':1});}
			});

			element.addEvent('mouseleave', function() {
					
				this.getNext('dd').morph({'top':0});
				if (currentSubSection()!='overview'){ 
					currTip = 'tip_'+currentSubSection();
					$(currTip).morph({'top': '65px'});
					pointerFx.start({'left':currBlockPos});					
				}	else {
				
					pointerFx.start({'background-position':'0 -28px'});
				
				}
				
				//if we're on the overview page, fade in / out the pretty picture
				if (document.getElement('.overview')){
				$('hero_'+element.id.split("_")[1]).morph({'opacity':0});}


			});
		
		});
	
	
	}
	

	//News blocklist behavior
	if (document.getElement('.news #blocklist')) 
	{
	
		var items = $$('#blocklist li');
		
		items.each (function(element){
		
			var itemFx = new Fx.Morph(element, {duration:100, transition:Fx.Transitions.Cubic.easeOut, link:'cancel'});
			
			element.addEvent('mouseenter', function() { 
			
				element.getFirst('a').setStyle('color','#ffffff');
				itemFx.start({'background-color':'#454748', 'margin-right':0 }); 
				
			});

			element.addEvent('mouseleave', function() {
			
				if (!element.hasClass('selected')) {	
			 		element.getFirst('a').setStyle('color','#454748');
			 		itemFx.start({'background-color':'#d1e0ef', 'margin-right':'10px' }); 
			 	}
			});
		
		});
	
	
	}




	// List ItemBlock striping
	if(document.getElement('.itemblock'))
	{

		var itemblocks = $$('.itemblock:odd');
		itemblocks.each (function(element){
			element.addClass('stripe');
		})

	}
	
	
	// List ItemBlock Slider behavior
	if(document.getElement('.expander'))
	{
	

	
		var sliders = $$('.expander');
		
		sliders.each (function(element){
			toggler = element.getNext('p').getFirst('a');
			//we are storing the FX object inside the toggler element so it can be directly addressed later
			toggler.store('slideFx', new Fx.Slide(element, {duration:400, fps:60, transition: Fx.Transitions.Quart.easeOut} ));
			toggler.retrieve('slideFx').hide();
			toggler.addEvent('click', function() {
				this.retrieve('slideFx').toggle();
				if (this.hasClass('deployed')) {
					this.removeClass('deployed');
					this.set('html', 'Read More &raquo;');
				} else {
					this.addClass('deployed');
					this.set('html', 'Close &laquo;');
				}
				return false;
				
			});

		});
		
	}








//ANIMATE IN PAGE elements

//setup animation objects
		var sectionFx = new Fx.Morph($('section'), {duration:400, unit:'em', transition:Fx.Transitions.Quart.easeOut, link:'cancel'})
		var rightcolFx = new Fx.Morph($('rightcol'), {duration:400, unit:'em',  transition:Fx.Transitions.Quart.easeOut, link:'cancel'})




//Show the stage now that all of the page elements have been setup

	$('wrapper').setStyle('visibility','visible');
	//alert('setting visibility');


//Expander first item of any collapsed lists

	if (document.getElement('.expander'))
	{
		//this is where the stored FX object comes into play.
		//since each slider object is stored inside the trigger element
		//we just send the click event to the first found trigger
		//and that triggers slider expands
		document.getElement('.more').fireEvent('click',document.getElement('.more'),200);
	}
	


	
	if (document.getElement('.fade')) 
	{
	
		var faders = $$('.fade');
		faders.each (function(element){ element.fade('in'); });	
		
	}


	if (currentSection() == 'home') 
	
	{
	
		sectionFx.start.delay(900, sectionFx, {top:'0'});
		rightcolFx.start.delay(1100, rightcolFx, {bottom:0});
	
		var defaultFx = new Fx.Morph($('defaultHero'), { 
			duration:900,
			onComplete: function()
					
					{
			
						var myRequest = new Request
					 	({
					 		method: 'get', 
					 		url: '_library/ajax.php',
					 		//url: 'http://10.0.1.200/stoutandteague.com/_library/ajax.php',
					 		onSuccess: function(responseText) { displayHomeImages(responseText); }, 
					 		onFailure: function(xhr) {alert(xhr);}						
					 	});
						myRequest.send('type=checkForImages&dir=home&ext=jpg');
			
					} 
			
			})

		defaultFx.start({opacity:1});
		

		

	}







	$('wrapper').setStyle('visibility','visible');



});  //End onLoad handler












// ****************************************************************
// global functions
// ****************************************************************


function currentSection() {

	//The class of the body tag is the current section
	return document.getElement('body').getProperty('class');
	
}

function currentSubSection() {
	//The class of div 'wrapper' is the current subsection
	return $('wrapper').getProperty('class');
}


function createRecordObject(response)

//Returns a JS object of the found record with
//table fields as properties of the object
//using = and | as delimeters

{

	var qResult = new Object;
	
	var records = response.split('|');
	
	for (var i = 0;i<records.length;i++)
	{
				
		var properties = records[i].split('=');		
		var key = properties[0];
		var val = properties[1];
		
		qResult[key] = val;
	}
	
	return qResult;
}
		
	

	
//Function to get the proper color of each nav item

function getColor(who) {
	var colors = new Array();
	colors.nav_company = '#116498'; 
	colors.nav_services = '#db9528'; 
	colors.nav_portfolio = '#8b9d20'; 
	return colors[who];
}
	
function setSectionInfo(name,description) {
	var sectionHead = $('section').getFirst('h2');
	var sectionText = $('section').getFirst('p');
	sectionHead.set('text', name);
	sectionText.set('text', description);
}



//Function to display rotating home images from ajax request
function displayHomeImages(responseText)
{
	var homeImages = responseText.split('|');
	var maxImages = homeImages.length;
	var count = 1;
	homeImages.each (function(image){
		var hero = new Element('img', {'class':'slideshow', 'src':'_media/_images/home/'+image});
		hero.inject($('leftcol'), 'bottom');
		hero.onload = function () {
		//	alert(maxImages);
			if (count == maxImages) {
				new viewer($$('.slideshow)'), {mode:'alpha',interval:5000}).play(true);
			} else {
				count++;
			}			
			//alert(image+' loaded');
			hero.setStyle('opacity',0);
		};
					
	});
	

}






