/*

	@Class:	InputClearAndReplace
	@Author:	Brandon Gray for O3 World 2008
	@Brief:	Loops through all elements with a class name of 'clear_replace' and clears the default text when focused.
			When focus is lost it checks to see if the field is blank (no new data entered), if value is blank the default text is placed back in.
	@Example: <input type="text" name="firstname" id="firstname" value="" class="clear_replace" />

*/

var InputClearAndReplace = new Class ({
	
	options: {
		
		InputElement: '.clear_replace'
		
	},
	
	initialize: function()  {
		
		var inputElementList = $$( this.options.InputElement );
		var originalValue = new Array();
		
		inputElementList.each( function( element, i ) {
			
			originalValue.push( inputElementList[ i ].value );
			
			element.onfocus = function() {
				
				if( this.value == originalValue[ i ] ) this.value = '';
				
			},
			
			element.onblur = function() {
				
				if( this.value == '' ) this.value = originalValue[ i ];
				
			}
			
		});
		
	}

});

/*

	@Class:		ClientList
	@Author:		Brandon Gray for O3 World 2009 (http://www.o3world.com)
	@Brief:		Uses the HTML5 canvas element in order to manipulate pixel data to create a black and white image from a full color image.
				Sets up event handlers to display the black & white image by default and the full color image on mouseover.
	@Requirements:	Mootools 1.2
			
*/

var ClientList = new Class({

	initialize: function() {
		
		this.imgs	= $$( '#client_list img' );
		
		for ( var i = 0; i < this.imgs.length; i++ ) {
			
			this.setEvents( this.imgs[ i ] );
			
		}
		
	},
	
	setEvents: function( _instance ) {
		
		var colorImg 		= _instance.src;
		var greyscaleImg 	= this.greyscale( _instance );
		
		_instance.addEvent( 'mouseover', function() { this.src = colorImg; } );
		_instance.addEvent( 'mouseout', function() { this.src = greyscaleImg; } );
		
		_instance.src = greyscaleImg;
		
	},
	
	greyscale: function( _image ) {
		
		var canvas	= new Element( 'canvas' );
		canvas.width	= _image.width;
		canvas.height 	= _image.height;
		
		// Init IE fix for canvas object
		if ( typeof G_vmlCanvasManager != 'undefined' ) G_vmlCanvasManager.initElement( canvas ); 
		
		var canvasContext = canvas.getContext( '2d' );
		
		// Draw the image into the canvas in order to manipulate the pixel data.
		canvasContext.drawImage( _image, 0, 0 );

		// getImageData retrieves the ImageData object. The ImageData object gives access to the pixel data.
		// Security errors will be thrown if the image is not located on the same domain.
		var imageData = canvasContext.getImageData( 0, 0, _image.width, _image.height );
				
		// Change every pixel to a level of grey.  Averages the red, green, and blue of every pixel.
		// A pixel is represented by 4 numbers (red, green, blue, and alpha).  A color is a number between 0 to 255.
		for ( i = 0; i < imageData.height; i++ ) {
		
			for ( j = 0; j < imageData.width; j++ ) {
			
				var index = ( i * 4 ) * imageData.width + ( j * 4 );
				
				var red	= imageData.data[ index ];
				var green	= imageData.data[ index + 1 ];
				var blue	= imageData.data[ index + 2 ];
				
				var average = ( red + green + blue ) / 3;
				
				imageData.data[ index ]		= average;
				imageData.data[ index + 1 ]	= average;
				imageData.data[ index + 2 ]	= average;
			
			}
		
		}
		
		// Write the ImageData back to the canvas
		canvasContext.putImageData( imageData, 0, 0, 0, 0, imageData.width, imageData.height );
		
		// Return an image object
		return canvas.toDataURL();
		
	}

});

function initAboutTabs() {
	
	var menuAnchors = $( 'about_nav' ).getElements( 'a' );

	for ( var i = 0; i < menuAnchors.length; i++ ) {

		if ( menuAnchors[ i ].getAttribute( 'href' ) && menuAnchors[ i ].getAttribute( 'rel' ) == 'swap' ) {

			menuAnchors[ i ].addEvent( 'click', function( event ) {
				
				// Remove the active state from all links
				for ( var j = 0; j < menuAnchors.length; j++ ) {
					
					menuAnchors[ j ].removeClass( 'active' );
					
				}
				
				swapAboutContent( this.id );
				
				event.stop();

			});

		}

	}

}

function swapAboutContent( _id ) {
	
	// Set the active state on the selected link
	$( _id ).addClass( 'active' );

	var tabs = $$( '.tab_content' );
	
	for ( var i = 0; i < tabs.length; i++ ) {

		tabs[ i ].setStyle( 'display', 'none' );		

	}

	var newID 	= 'content_' + _id;
	var content 	= $( newID ).setStyle( 'display', 'block' );
	
	sifrRedraw(); 
	
}

function sifrRedraw() {
		
	var font 			= { src: 'flash/sifr/din.swf' };  
	var sIFRElement 	= {
		
		selector: 	'.gray_14px',
		css: [
			'.sIFR-root { font-size: 14px; color: #707070; leading: 0; text-transform:uppercase; }',
			'a { color: #707070; text-decoration: none; }',
			'a:hover { color: #ff0000; text-decoration: none; }'
		],
		ratios: 		[7, 1.47, 10, 1.43, 15, 1.36, 22, 1.34, 26, 1.32, 29, 1.31, 32, 1.32, 33, 1.3, 37, 1.31, 45, 1.3, 48, 1.29, 51, 1.3, 65, 1.29, 67, 1.28, 68, 1.29, 74, 1.28, 75, 1.29, 1.28],
		wmode:		'transparent',
		tuneHeight: 	-5
		
	};
	
	var font2 		= { src: 'flash/sifr/din.swf' };  
	var sIFRElement2 	= {
		
		selector: 	'.red_22px',
		css: [
			'.sIFR-root { font-size: 22px; color: #ff0000; leading: 0; text-transform:uppercase; }',
			'a { color: #ff0000; text-decoration: none; }',
			'a:hover { color: #ff0000; text-decoration: none; }'
		],
		ratios: 		[7, 1.47, 10, 1.43, 15, 1.36, 22, 1.34, 26, 1.32, 29, 1.31, 32, 1.32, 33, 1.3, 37, 1.31, 45, 1.3, 48, 1.29, 51, 1.3, 65, 1.29, 67, 1.28, 68, 1.29, 74, 1.28, 75, 1.29, 1.28],
		wmode:		'transparent',
		tuneHeight: 	-5
		
	};
	
	window.sIFR.replace( font, sIFRElement );
	window.sIFR.replace( font2, sIFRElement2 );
	
}

function embedCycle() {
	
	var flashvars = {};
	var params    = {};
	params.wmode = 'transparent';
	params.menu = 'false';
	params.allowscriptaccess = 'always';
	var attributes = {};
	swfobject.embedSWF( 'flash/about_cycle.swf', 'about_flash_slideshow', '937', '404', '9.0.0', flashvars, params, attributes );
	
}

function embedTeam() {
	
	var flashvars = {};
	var params    = {};
	params.wmode = 'transparent';
	params.menu = 'false';
	params.allowscriptaccess = 'always';
	var attributes = {};
	swfobject.embedSWF( 'flash/about_team.swf', 'about_flash_team', '937', '365', '9.0.0', flashvars, params, attributes );
	
}

function ie6NavFix() {
	
	var navLists = $( 'work_nav' ).getElements( 'li' );

	for ( i = 0; i < navLists.length; i++ ) {
	
		if ( navLists[ i ].getAttribute( 'title' ) == 'menu' ) {
			
			navLists[ i ].addEvent( 'mouseover', function() {
				
				this.getLast().setStyle( 'display', 'block' );
			
			});
			
			navLists[ i ].addEvent( 'mouseout', function() {
			
				this.getLast().setStyle( 'display', 'none' );
			
			});

		}

	}
	
}


function fixActions() {
	
	var actions = $$( 'ul.action' );
	
	for ( var i = 0; i < actions.length; i++ ) {
		
		actions[ i ].setStyle( 'position', 'absolute' );
		
	}
	
}

function fixServiceNav() {
	
	var navList = $( 'service_nav' ).getFirst( 'li' );
	
	navList.addEvent( 'mouseover', function() {
					
		this.getLast().setStyle( 'display', 'block' );
	
	});
	
	navList.addEvent( 'mouseout', function() {
	
		this.getLast().setStyle( 'display', 'none' );
	
	});
	
}

function ValidateBlogComment( ) {
	
	// Clear notifications
	$( 'Name_Hint' ).setStyle( 'display', 'none' );
	$( 'Email_Hint' ).setStyle( 'display', 'none' );
	$( 'Comments_Hint' ).setStyle( 'display', 'none' );

	// Validate input
	if( $( 'Name' ).value == "" ) {
		$( 'Name_Hint' ).setStyle( 'display', 'inline' );
		$( 'Name' ).focus();
		return false;
	} else if( !checkEmail( document.BlogCommentForm.Email ) ) {
		$( 'Email_Hint' ).setStyle( 'display', 'inline' );
		$( 'Email' ).focus();
		return false;
	} else if( $( 'Comments' ).value == "" ) {
		$( 'Comments_Hint' ).setStyle( 'display', 'inline' );
		$( 'Comments' ).focus();
		return false;
	} else if( $( 'Honeypot' ).value == "" ) {
		
		// Create new FX's
		var FormFx = new Fx.Tween( $( 'BlogCommentForm' ), { duration: '500', link: 'chain' } );
		if( $( 'comment_form' ) ) { FormFx.start( 'opacity', '1', '1' ); }
		
		var ProcessingFx = new Fx.Tween( $( 'comment_processing' ), { duration: '500', link: 'chain' } );
		if( $( 'comment_processing' ) ) { ProcessingFx.start( 'opacity', '0', '0' ); }
		
		var CompleteFx = new Fx.Tween( $( 'comment_complete' ), { duration: '500', link: 'chain' } );
		if( $( 'comment_complete' ) ) { CompleteFx.start( 'opacity', '0', '0' ); }
		
		// Begin responce
		new Request({
			method:		'post',
			url:			'AJAX_processing.cfm?AJAXRequest=blog_comment',
			link:		'cancel',
			onRequest:	function() {
							FormFx.start( 'opacity', '1', '0' );
							ProcessingFx.start( 'opacity', '0', '1' );
							//CompleteFx.start( 'opacity', '0', '0' );
						},
			onFailure:	function() {
							//FormFx.start( 'opacity', '0', '0' );
							ProcessingFx.start( 'opacity', '1', '0' );
							$( 'comment_complete' ).set( 'html', '<p>There was an error processing your comment.<br /><br />Please try again.</p>' );
							CompleteFx.start( 'opacity', '0', '1' );
						},
			onSuccess:	function() {
							//FormFx.start( 'opacity', '0', '0' );
							ProcessingFx.start( 'opacity', '1', '0' );
							$( 'comment_complete' ).set( 'html', '<p>Comment submitted successfully!<br /><br />Your comment will appear pending approval.</p>' );
							CompleteFx.start( 'opacity', '0', '1' );
						}
		}).send( $( 'BlogCommentForm' ) );
		
		return false;
		
	}
}

// Basic Regex validations (cross-form)
function checkEmail( formElement ) {
	//alert('run email check');
	if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/.test(formElement.value))){		
		return false;	
	} else {
		return true;
	}
}


function ValidateNewsletterSignup( ) {
	
	if( !checkEmail( $( 'NewsleterSignupInput' ) ) ){
		
		alert('Please enter your email address.');
		$( 'NewsleterSignupInput' ).focus();
		
	} else if( $( 'FormHP' ).value == '' ) {
		
		var myHTMLRequest	= new Request({
			url:			'AJAX_processing.cfm?AJAXRequest=newsletter_signup',
			method:		'post',
			link:		'cancel',
			onRequest:	 function(){ LoadingFx.start( 'opacity', '0', '1' ); },
			onComplete:	 function(){ LoadingFx.start( 'opacity', '1', '0' );  pageTracker._trackPageview('/newsletter_signup.cfm'); },
			onFailure:	 function(){},
			onSuccess:	 function(){ $( 'NewsleterSignupInput' ).value = "Thanks for signing up!"; }
		}).send( $( 'NewsletterInputWrap' ) );
		
	};
	
};


function ValidateFAQ() {
	
	if( $( 'Name' ).value == "" ){
		
		alert('Please enter your name.');
		$( 'Name' ).focus();
		
	} else if( !checkEmail( $( 'Email' ) ) ){
		
		alert('Please enter your valid email address.');
		$( 'Email' ).focus();
		
	} else if( $( 'Question' ).value == "" ){
		
		alert('Please enter your question.');
		$( 'Question' ).focus();
		
	} else {
		
		// Create new FX's
		var FormFx = new Fx.Tween( $( 'FAQForm' ), { duration: '500', link: 'chain' } );
		if( $( 'FAQForm' ) ) { FormFx.start( 'opacity', '1', '1' ); }
		
		var ProcessingFx = new Fx.Tween( $( 'FAQProcessing' ), { duration: '500', link: 'chain' } );
		if( $( 'FAQProcessing' ) ) {
			ProcessingFx.start( 'opacity', '0', '0' );
			$( 'FAQProcessing' ).setStyle( 'visibility', 'visible' );
		}
		
		var CompleteFx = new Fx.Tween( $( 'FAQResponce' ), { duration: '500', link: 'chain' } );
		if( $( 'FAQResponce' ) ) {
			CompleteFx.start( 'opacity', '0', '0' );
			$( 'FAQResponce' ).setStyle( 'visibility', 'visible' );
		}
		
		// Begin responce
		var myHTMLRequest = new Request({
			url:			'AJAX_processing.cfm?AJAXRequest=faq_form',
			method:		'post',
			link:		'cancel',
			onRequest:	 function(){
							FormFx.start( 'opacity', '1', '0' );
							ProcessingFx.start( 'opacity', '0', '1' );
						 },
			onComplete:	 function(){
							$( 'FAQForm' ).setStyle( 'display', 'none' );
							$( 'FAQResponce' ).setStyle( 'display', 'inline' );
							ProcessingFx.start( 'opacity', '1', '0' );
							CompleteFx.start( 'opacity', '0', '1' );
						 },
			onFailure:	 function(){ },
			onSuccess:	 function(){ }
		}).send( $( 'faq_form' ) );
		
	}
	
}

function descHandler( data ) {
	
	var desc = data.photo.description._content;
	
	var thumbs = $( 'flickr_thumbs' ).getElements( 'a' );
	
	for ( var i = 0; i < thumbs.length; i++ ) {
		
		thumbs[ i ].setProperty( 'title', desc );
				
	}
	
}

//FLICKR API CALLBACK HANDLER
function photosetHandler( data ) {
	
	var columns	= 2;
	var owner 	= data.photoset.owner;
	var photoSet 	= data.photoset.photo;
	
	photoSet.each( function( element, i ) {
		
		var thumbURL 		= 'http://farm' + element.farm + '.static.flickr.com/' + element.server + '/' + element.id + '_' + element.secret + '_s.jpg';
		var thumbList 		= new Element ( 'li' );
		var thumbAnchor 	= new Element( 'a', {
		
			'href':	'http://farm'  + element.farm + '.static.flickr.com/' + element.server + '/' + element.id + '_' + element.secret + '.jpg',
			'rel':	'lightbox[set1]',
			'id':	element.id
			
		});
		
		var thumbIMG 		= new Element( 'img', {
		
			'height': '75',
			'width':	'75',
			'alt': 	element.title,
			'src':	thumbURL
		
		});
		
		thumbIMG.inject( thumbAnchor );
		thumbAnchor.inject( thumbList );
		thumbList.inject( $( 'flickr_thumbs' ) );
		
		if ( !$( 'o3ms' ) ) { if ( ( i % 2 ) == 0 ) thumbList.addClass( 'mar_9_r' ); };
			
	});
	/*
	photoSet.each( function( element, i ) {
		
		var descRequest = new Request.JSONP({
			
			url: 'http://api.flickr.com/services/rest/',
			data: {
				method:			'flickr.photos.getInfo',
				api_key: 			'c3a51ed65f230e61e6a241217274d4d6',
				photo_id:			element.id,
				format: 			'json',
				nojsoncallback: 	'1'
			},
			noCache: true,
			onComplete: function( response ) {
				
				alert( 'i hope this works' );	
				
			}
				
		}).send();
		
	});
	*/
	
	window.Mediabox.scanPage();
	
}

// FLICKR API REQUEST
function flickrRequest( _setID ) {
	
	var setRequest = new Request.JSONP({
		
		url: 'http://api.flickr.com/services/rest/',
		data: {
			method:		'flickr.photosets.getPhotos',
			api_key: 		'c3a51ed65f230e61e6a241217274d4d6',
			photoset_id:	_setID,
			page:		'1',
			format: 		'json',
			jsoncallback: 	'photosetHandler'
		}
		
	}).send();
	
}

// Footer Twitter info
function twitterCallback2( twitters ) {
	
    var statusHTML = [];
    for (var i = 0; i < twitters.length; i++) {
        var username = twitters[i].user.screen_name;
        var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function (url) {
            return '<a href="' + url + '">' + url + '</a>';
        }).replace(/\B@([_a-z0-9]+)/ig, function (reply) {
            return reply.charAt(0) + '<a target="_blank" href="http://www.twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
        });
        statusHTML.push('<li><span>' + status + '</span><br /> <a target="_blank" href="http://twitter.com/' + username + '/status/' + twitters[i].id_str + '" class="time_stamp">' + relative_time(twitters[i].created_at) + '</a></li>');
    }
    document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
    
}



function relative_time(time_value) {
	
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);

    if (delta < 60) {
        return 'less than a minute ago';
    } else if (delta < 120) {
        return 'about a minute ago';
    } else if (delta < (60 * 60)) {
        return (parseInt(delta / 60)).toString() + ' minutes ago';
    } else if (delta < (120 * 60)) {
        return 'about an hour ago';
    } else if (delta < (24 * 60 * 60)) {
        return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
    } else if (delta < (48 * 60 * 60)) {
        return '1 day ago';
    } else {
        return (parseInt(delta / 86400)).toString() + ' days ago';
    }
    
}

// SLIDING FUNCTIONALITY FOR 'read more' & 'read less' button on home page
function homeMessage() {
	
	/* Read More slide functionality on home page */
	
	$( 'message' ).set({
		tween:  { 
			duration: 350
		}
	});
	
	$( 'message_wrap' ).set({
		tween:  { 
			duration: 350
		}
	});
	
	$( 'message_read_more' ).addEvent( 'click', function( event ) {
		
		$( 'message_wrap' ).tween( 'height', '335px' );
		$( 'message' ).tween( 'padding-bottom', '20px' );
		
		$( 'message_read_less' ).setStyle( 'display', 'block' );
		$( 'message_read_more' ).setStyle( 'display', 'none' );
		
		event.stop();
	
	});
	
	$( 'message_read_less' ).addEvent( 'click', function( event ) {
		
		$( 'message_wrap' ).tween( 'height', '0' );
		$( 'message' ).tween( 'padding-bottom', '0' );
		
		$( 'message_read_less' ).setStyle( 'display', 'none' );
		$( 'message_read_more' ).setStyle( 'display', 'block' );
		
		event.stop();
	
	});
	
}

//FOOTER FLICKR API CALLBACK HANDLER
function footPhotosHandler( data ) {
	
	var columns	= 4;
	var photo 	= data.photoset.photo;
	
	photo.each( function( element, i ) {
		
		var thumbURL 		= 'http://farm' + element.farm + '.static.flickr.com/' + element.server + '/' + element.id + '_' + element.secret + '_s.jpg';
		var thumbList 		= new Element ( 'li' );
		var thumbAnchor 	= new Element( 'a', {
		
			'href':	'http://farm'  + element.farm + '.static.flickr.com/' + element.server + '/' + element.id + '_' + element.secret + '.jpg',
			'rel':	'lightbox[footPhotos]',
			'id':	element.id
			
		});
		
		var thumbIMG 		= new Element( 'img', {
		
			'height': '75',
			'width':	'75',
			'alt': 	element.title,
			'src':	thumbURL
		
		});
		
		thumbIMG.inject( thumbAnchor );
		thumbAnchor.inject( thumbList );
		thumbList.inject( $( 'foot_thumbs' ) );
			
	});
	
	window.Mediabox.scanPage();
	
}

// FOOTER FLICKR API REQUEST
function footerFlickrRequest() {
	
	var setRequest = new Request.JSONP({
		
		url: 'http://api.flickr.com/services/rest/',
		data: {
			method:		'flickr.photosets.getPhotos',
			api_key: 		'c3a51ed65f230e61e6a241217274d4d6',
			photoset_id:	'72157623018510866',
			per_page:		8,
			format: 		'json',
			jsoncallback: 	'footPhotosHandler'
		}
		
	}).send();
	
}

/*

	@Class:		FeaturedProgram
	@Author:		Brandon Gray for O3 World 2010
	@Brief:		Controls the display of content in the "featured" section on the home page.
	@Requirements:	Mootools 1.2, Mootools "More" Asset class
			
*/
var FeaturedProgram = new Class ({
	
	initialize: function()  {
		
		this.menuLinks 	= $$( '#home_slides ul a' );
		this.contentDivs	= $$( '#home_slides div.feat' );
		this.pos			= 0;
		this.total		= this.menuLinks.length;
		this.fadeTimer;
		
		for ( var i = 0; i < this.menuLinks.length; i++ ) this.menuLinks[ i ].addEvent( 'click', this.setMenu.bindWithEvent( this, [ i ] ) );
				
	},
	
	setMenu: function( event, i ) {
		
		if( event ) event.stop();
		
		this.pos = i;
		
		for ( var j = 0; j < this.menuLinks.length; j++ ) {
			
			this.menuLinks[ j ].removeClass( 'active' );
			//this.menuLinks[ j ].getParent( 'li' ).addClass( 'rule' );
			
		}
		
		//this.menuLinks[ i ].getParent( 'li' ).removeClass( 'rule' );
		this.menuLinks[ i ].addClass( 'active' );
		
		this.setContent( i );
		
	},
	
	setContent: function( i ) {
		
		for ( var k = 0; k < this.contentDivs.length; k++ ) {
			
			this.contentDivs[ k ].setStyle( 'display', 'none' );
			this.contentDivs[ k ].setStyle( 'opacity', '0' );
			
		}
		
		this.contentDivs[ i ].setStyle( 'display', 'block' );
		this.contentDivs[ i ].fade( '1' );
		
	}
	
});

/*

	@Class:	CaseSlider
	@Author:	Brandon Gray for O3 World 2009
	@Brief:	Slider functionality

*/

var CaseSlider = new Class ({
	
	options: {
		
		// Passed into class upon instantiation
		totalWidth: Class.empty
		
	},
	
	initialize: function( options )  {
		
		this.setOptions( options );
		
		this.totalWidth 	= this.options.totalWidth;
		this.totalSections 	= this.totalWidth / 957;
		this.pos			= ( $( 'CurrentClient' ) && $( 'CurrentClient' ).value > 1 ) ? $( 'CurrentClient' ).value - 1 : 0;
		
		//alert( this.totalWidth + " " + this.totalSections );
		
		$( 'prev_case' ).addEvent( 'click', function( event ) {
		
			this.prevImage();
			event.stop();
			
		}.bind( this ) );
		
		$( 'next_case' ).addEvent( 'click', function( event ) {
				
			this.nextImage();
			event.stop();
			
		}.bind( this ) );
		
		// hide the previous case button on load because we're already at the first view, there are no previous views
		$( 'prev_case' ).fade( '0' );
		
		if( this.pos != 0) {
			this.nextImage();
		};
		
	},
	
	nextImage: function() {
		
		if ( this.pos < ( this.totalSections - 1 ) ) {
			
			this.pos++;
			
			var currentX 		= ( this.pos - 1 ) * -957;
			var newX 			= -957 * this.pos;
			var tweenElement 	= $( 'slide' );
			var newTween 		= new Fx.Tween( tweenElement, { 
										
				link: 'ignore',
				
				onStart: function() {
					
					$( 'prev_case' ).removeEvents( 'click' );
					$( 'next_case' ).removeEvents( 'click' );
					
				},
				
				onComplete: function() {
					
					$( 'prev_case' ).addEvent( 'click', function( event ) {
		
						this.prevImage();
						event.stop();
						
					}.bind( this ) );
					
					$( 'next_case' ).addEvent( 'click', function( event ) {
							
						this.nextImage();
						event.stop();
						
					}.bind( this ) );
					
				}.bind( this )
				
			});
			
			newTween.start( 'left', currentX, newX );
			
		}
		
		this.updateButtons();
		
	},
	
	prevImage: function() {
		
		if ( this.pos != 0 ) {
			
			this.pos--;
			
			var currentX 	= ( this.pos + 1 ) * -957;
			var newX 		= -957 * this.pos;
			var tweenElement 	= $( 'slide' );
			var newTween 		= new Fx.Tween( tweenElement, { 
										
				link: 'ignore',
				
				onStart: function() {
					
					$( 'prev_case' ).removeEvents( 'click' );
					$( 'next_case' ).removeEvents( 'click' );
					
				},
				
				onComplete: function() {
					
					$( 'prev_case' ).addEvent( 'click', function( event ) {
		
						this.prevImage();
						event.stop();
						
					}.bind( this ) );
					
					$( 'next_case' ).addEvent( 'click', function( event ) {
							
						this.nextImage();
						event.stop();
						
					}.bind( this ) );
					
				}.bind( this )
				
			});
			
			newTween.start( 'left', currentX, newX );
			
		}
		
		this.updateButtons();
		
	},
	
	updateButtons: function() {
		
		if ( this.pos == ( this.totalSections - 1 ) ) {
			
			$( 'next_case' ).fade( '0' );
			$( 'prev_case' ).fade( '1' );
			
		} else if ( this.pos == 0 ) {
			
			$( 'prev_case' ).fade( '0' );
			$( 'next_case' ).fade( '1' );
			
		} else {
			
			$( 'prev_case' ).fade( '1' );
			$( 'next_case' ).fade( '1' );
			
		}
		
	}
	
});

CaseSlider.implement( new Options );

/*
	@Class:		ScrollSpy
	@Author:		David Walsh (http://davidwalsh.name)
	@License:		MIT-style license
	@Brief:		ScrollSpy allows you to listen to scrolling within any DOM element and execute functions based upon the element's scroll position.
	@Example: 	var ss = new ScrollSpy({
					min: 300,
					onEnter: function() {
						$('gototop').fade('in'); //show the "Go To Top" link
					},
					onLeave: function() {
						$('gototop').fade('out'); //hide the "Go To Top" link
					},
					container: window
				});
	@Requirements:	Mootools 1.2.1
*/
var ScrollSpy = new Class({

	/* implements */
	Implements: [Options,Events],

	/* options */
	options: {
		container: window,
		max: 0,
		min: 0,
		mode: 'vertical'/*,
		onEnter: $empty,
		onLeave: $empty,
		onScroll: $empty,
		onTick: $empty
		*/
	},

	/* initialization */
	initialize: function(options) {
		/* set options */
		this.setOptions(options);
		this.container = document.id(this.options.container);
		this.enters = this.leaves = 0;
		this.max = this.options.max;
		this.inside = false;
		
		/* make it happen */
		this.addListener();
	},

	/* a method that does whatever you want */
	addListener: function() {
		/* state trackers */
		this.container.addEvent('scroll',function(e) {
			/* if it has reached the level */
			var position = this.container.getScroll(),
				xy = position[this.options.mode == 'vertical' ? 'y' : 'x'];
			/* if we reach the minimum and are still below the max... */
			if(xy >= this.options.min && (this.max == 0 || xy <= this.max)) {
					/* trigger Enter event if necessary */
					if(!this.inside) {
						/* record as inside */
						this.inside = true;
						this.enters++;
						/* fire enter event */
						this.fireEvent('enter',[position,this.enters,e]);
					}
					/* trigger the "tick", always */
					this.fireEvent('tick',[position,this.inside,this.enters,this.leaves,e]);
			}
			/* trigger leave */
			else if(this.inside){
				this.inside = false;
				this.leaves++;
				this.fireEvent('leave',[position,this.leaves,e]);
			}
			/* fire scroll event */
			this.fireEvent('scroll',[position,this.inside,this.enters,this.leaves,e]);
		}.bind(this));
	}
});

// Drop down display fix for IE
function ieWorkFix() {
	
	var clientLists = $$( '#clients li' );
	
	for ( var i = 0; i < clientLists.length; i++ ) {
	
		if ( clientLists[i].getChildren( 'div' ).length > 0 ) {
		
			clientLists[i].addEvent( 'mouseenter', function() {
				this.getChildren( 'div' )[ 0 ].setStyle( 'display', 'block' );
			});
			
			clientLists[i].addEvent( 'mouseleave', function() {
				this.getChildren( 'div' )[ 0 ].setStyle( 'display', 'none' );
			});
			
		};
		
	};
	
};

window.addEvent( 'domready', function() {
							  
	var InputList = new InputClearAndReplace();

	// Add newsletter signup event
	Element.Events.keyenter = {
		base:		'keyup',
		condition:	function( e ){ return e.key == 'enter'; }
	};
	
	if ( $( 'about_nav' ) ) {
		initAboutTabs();
		embedCycle();
		embedTeam();
	};
	
	if( $( 'NewsleterSignupBtn' ) && $( 'NewsleterSignupInput' ) && $( 'NewsletterLoadingIcon' ) ) {
		LoadingFx = new Fx.Tween( 'NewsletterLoadingIcon', { duration: '500', link: 'chain' } ).start( 'opacity', '0', '0' );
		$( 'NewsleterSignupBtn' ).addEvent( 'click', function() { ValidateNewsletterSignup( ) } );
		$( 'NewsleterSignupInput' ).addEvent( 'keyenter', function() { ValidateNewsletterSignup( ) } );
		$( 'NewsletterLoadingIcon' ).setStyle( 'visibility', 'visible' );
	};
	
	// Initiate drop down fix for IE6
	if ( $( 'blog_left' ) && document.all && !window.opera && !window.XMLHttpRequest ) { fixActions(); };
	if ( $( 'service_nav' ) && document.all && !window.opera && !window.XMLHttpRequest ) {  fixServiceNav(); };
	
	// IE6 sucks, we know this, fix the client hover state in this crap browser
	if ( $( 'clients' ) && Browser.Engine.trident4 ) var ieWork = new ieWorkFix();
	
	if ( $( 'more_work' ) ) {
		
		if ( !Browser.Engine.trident4 ) {
			
			// ScrollSpy functionality for control bar
			var ss = new ScrollSpy({
				min: $( 'work_wrap' ).getCoordinates().top,
				//max: $( 'work_wrap' ).getCoordinates().bottom - $( 'work_right' ).getCoordinates().height,
				onEnter: function() {
					//alert( $( 'work_wrap' ).getCoordinates().bottom - $( 'work_right' ).getCoordinates().height );
				},
				onTick: function() {
					if ( window.getScroll().y <= ( $( 'work_wrap' ).getCoordinates().bottom - $( 'work_right' ).getCoordinates().height ) ) {
						$( 'work_right' ).setStyles({
							'right': 		$( 'work_wrap' ).getCoordinates().right - $( 'work_wrap' ).getCoordinates().width,
							'top': 		15,
							'position': 	'fixed'
						});
					} else if ( window.getScroll().y >= window.getScroll().y - $( 'work_right' ).getCoordinates().height ) {
						$( 'work_right' ).setStyles({
							'right': 		0,
							'top': 		( $( 'work_wrap' ).getCoordinates().height - $( 'work_right' ).getCoordinates().height ),
							'position': 	'absolute'
						});
					}
				},
				onLeave: function() {
					$( 'work_right' ).setStyles({
						position: 'absolute' ,
						right: 0,
						top: 0
					});
				},
				container: window
			});
			
		};
		
		var totalSlides 	= $$( '#slide li' );
		var totalWidth 	= 319 * totalSlides.length;
		//alert( totalWidth );
		$( 'slide' ).setStyle( 'width', totalWidth );
		
		caseSlide = new CaseSlider({ 
							  
			totalWidth: $( 'slide' ).getStyle( 'width' ).toInt() 
			
		});
		
	};
	
	if ( $( 'message' ) ) {
		
		homeMessage();
		var featProg = new FeaturedProgram();
		
	}
	
	if( $( 'accordion' ) ) {
		
		var myAccordion = new Fx.Accordion( $$( 'div.toggler' ), $$( 'div.element' ), {
		   
			alwaysHide: true,
			onActive: function( toggler, element ){
				
				toggler.setStyle( 'background-position', '100% -72px' );
				
			},
			
			onBackground: function( toggler, element ){
				
				toggler.setStyle( 'background-position', '100% 0' );
				
			}
			
		});
		
	}
	
	footerFlickrRequest();
	
});
