

/*	GLOBALS
------------------------------------------------------*/
var Blinds,
	img_load,
	pages,
	mobile_pages,
	minimized = (document.body.offsetWidth <= 1280) ? true : false,
	navholding = false;
if (minimized) { document.body.className = 'minimized'; }
var gutter = (minimized) ? 697 : 747;

/*	AJAX REQUESTS
	- The sections to load
------------------------------------------------------*/
var Req = {
	main: new Request.HTML({
		method: 'get',
		onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
			var weLike = ["panel_1", "panel_2", "panel_3", "panel_4", "panel_5"];
			var panels = {};
			$$(responseElements).filter(function(el) {
				if ($(el) && el.get && weLike.contains(el.get("id"))) {
					panels[el.get("id")] = el;
				}
				return false;
			});
			if (Object.keys(panels).length) {
				Blinds.updatePanel('panel_1', panels.panel_1.getFirst('.panel').getChildren());
				Blinds.updatePanel('panel_2', panels.panel_2.getFirst('.panel').getChildren());
				Blinds.updatePanel('panel_3', panels.panel_3.getFirst('.panel').getChildren());
				Blinds.updatePanel('panel_4', panels.panel_4.getFirst('.panel').getChildren());
				Blinds.updatePanel('panel_5', panels.panel_5.getFirst('.panel').getChildren());
			}
	    }
	})
//	}).setHeader('If-Modified-Since','0')
};

/*	REQUEST QUEUE
------------------------------------------------------*/
var request_queue = new Request.Queue({

	requests: Req,

	onRequest: function(){
		// add loading graphic to main content area
		if (!Blinds.firstrun) { $('panel_1').addClass('loading'); }
	},

	onSuccess: function(name, instance, text, xml){

		var images = $(document.body).getElements('img'),
			img_count = images.length;

		if (Blinds.firstrun) {
			Blinds.firstrun = false;
			if (img_count > 0) {
				for (i = 0; i < img_count; i++) { images[i] = images[i].src; }
				var firstrun_img_assets = new Asset.images(images, {
					onComplete: function() {
						var cover_fx = new Fx.Morph('cover', {
							duration: 400,
							transition: Fx.Transitions.Cubic.easeOut,
							onComplete: function(){
								// initiate
								Blinds.setupPage();
								// animate the panels into place
								(function(){
									Blinds.animate_in();
								}).delay(100);
//								$('cover').destroy();
								$('cover').setStyles({
									height: 0,
									width: 0
								});
							}
						}).set({'opacity' : 0.5}).start({'opacity' : 0});
					}
				});
			}
			else {
				var cover_fx = new Fx.Morph('cover', {
					duration: 400,
					transition: Fx.Transitions.Cubic.easeOut,
					onComplete: function(){
						// initiate
						Blinds.setupPage();
						// animate the panels into place
						(function(){
							Blinds.animate_in();
						}).delay(100);
//						$('cover').destroy();
						$('cover').setStyles({
							height: 0,
							width: 0
						});
					}
				}).set({'opacity' : 0.5}).start({'opacity' : 0});
			}
		}
		else {

			if (img_count > 0) {
				for (i = 0; i < img_count; i++) { images[i] = images[i].src; }
				var img_assets = new Asset.images(images, {
					onComplete: function() {
						$('panel_1').removeClass('loading');		// remove loading graphic to main content area
						Blinds.setupPage();							// initiate page
						if (!Blinds.open) { Blinds.animate_in(); }	// animate the panels into place
					}
				});
			}
			else {
				$('panel_1').removeClass('loading');		// remove loading graphic to main content area
				Blinds.setupPage();							// initiate page
				if (!Blinds.open) { Blinds.animate_in(); }	// animate the panels into place
 			}
		}
	}

});

/*	BLINDS
------------------------------------------------------*/
Blinds = {

	firstrun: true,				// first run?
	running: true,				// are we between sections?
	page: 'default',			// current selected page
	chained: null,				// animation chain
	doubleup: false,			// are we animating two panels at once?
	direction: undefined,		// are we animating in or out?
	open: false,				// are the blinds currently open or closed?
	page_parameters: null,		// parameters for the page we're loading

	init: function(){

		Blinds.chained = new Chain();

		// set up main nav detail morph
		$('section-tagline').getFirst().set('morph', {
			duration: 800,
			transition: 'cubic:in:out'
		});

		// set up each panel's morph
		$$('.panel').each(function(panel){
			panel.set('morph', {
				duration: 500,
				transition: 'cubic:in:out',
				onStart: function(){
					panel.getParent().addClass('animating');
				},
				onComplete: function(){
					if (Blinds.direction === 'in') {
						panel.getParent().removeClass('animating');
						panel.erase('style');
					}
					if (!Blinds.doubleup) { Blinds.chained.callChain(); }
					else { Blinds.doubleup = false; }
				}
			});
		});

	},

	animate_out: function(sectionname, newpage){

		Blinds.direction = 'out';

		// stop if we're trying to load the current page
//		if (sectionname === Blinds.page) return false;

		// dim the previous nav item
		this.lowlightNav();

		// get queue of panels to collapse based on body ID
		if (!DetectSmartphone()) {
			var queue = pages.get($(document.body).getProperty('id')).get('out').getKeys();
		}
		else {
			var queue = mobile_pages.get($(document.body).getProperty('id')).get('out').getKeys();
		}

		// build queue of panels to animate
		queue.each(function(panel, i){

			// get the property to animate
			if (!DetectSmartphone()) { var anim_property = pages.get($(document.body).getProperty('id')).get('out').get(panel); }
			else { var anim_property = mobile_pages.get($(document.body).getProperty('id')).get('out').get(panel); }

			// if we're animating only one panel at a time
			if (panel.indexOf("|") === -1) {
				Blinds.chained.chain(
					function(){
						$(panel).getFirst('.panel').morph(anim_property);
					}
				);
			}
			// if we're animating more than one panel at a time
			else {
				var simultaneous = panel.split('|');
				Blinds.chained.chain(
					function(){
						simultaneous.each(function(sim, i){
							if (i === 0) { Blinds.doubleup = true; }
							$(sim).getFirst('.panel').morph(anim_property);
						});
					}
				);
			}
		});

		// add the final function to be called
		Blinds.chained.chain(
			function(){

				Blinds.open = false;
				Blinds.page = sectionname;

				// update body id with new section
				$(document.body).setProperty('id', sectionname);

				// select which pages to load
//				alert('Requesting new page...');
				Req.main.send({
					url: newpage,
					data: Blinds.page_parameters
				});
			}
		);

		Blinds.chained.callChain();

	},

	animate_in: function(){

		Blinds.direction = 'in';

		if ($('panel_2').hasClass('collapsed')) $('panel_2').removeClass('collapsed');

		// highlight the previous nav item
		this.highlightNav();

		// get queue of panels to collapse based on body ID
		if (!DetectSmartphone()) {
			var queue = pages.get(Blinds.page).get('in').getKeys();
		}
		else {
			var queue = mobile_pages.get(Blinds.page).get('in').getKeys();
		}

		// build queue of panels to animate
		queue.each(function(panel){

			// get the property to animate
			if (!DetectSmartphone()) { var anim_property = pages.get($(document.body).getProperty('id')).get('in').get(panel); }
			else { var anim_property = mobile_pages.get($(document.body).getProperty('id')).get('in').get(panel); }

			// if we're animating only one panel at a time
			if (panel.indexOf("|") === -1) {
				Blinds.chained.chain(
					function(){
						var anim_item = $(panel).getFirst('.panel');
						anim_item.morph(anim_property);
					}
				);
			}
			// if we're animating more than one panel at a time
			else {
				var simultaneous = panel.split('|');
				Blinds.chained.chain(
					function(){
						simultaneous.each(function(sim, i){
							if (i === 0) { Blinds.doubleup = true; }
							$(sim).getFirst('.panel').morph(anim_property);
						});
					}
				);
			}
		});

		// add the final function to be called
		Blinds.chained.chain(
			function(){
				Blinds.open = true;
				// google map
				Blinds.grid();

				if ($('map-canvas') && Blinds.page !== 'contact' && typeof GoogleMap !== 'undefined') { setTimeout(function(){ GoogleMap.init(0); }, 500); }
				else if ($('map-canvas') && Blinds.page === 'contact' && typeof GoogleMap !== 'undefined') { setTimeout(function(){ GoogleMap.init(3); }, 500); }

				Cufon.refresh();
				setTimeout(function(){
					Blinds.running = false;
				}, 1000);
			}
		);
		Blinds.chained.callChain();
	},

	hardStart: function(path){
		Blinds.closePanels();
		Req.main.send({
			url: path,
			data: Blinds.page_parameters
		});
	},

	closePanels: function(){
		// get queue of panels to collapse based on body ID
		if (!DetectSmartphone()) { var queue = pages.get($(document.body).getProperty('id')).get('out').getKeys(); }
		else { var queue = mobile_pages.get($(document.body).getProperty('id')).get('out').getKeys(); }
		queue.each(function(panel){

			// get the property to animate
			if (!DetectSmartphone()) { var anim_property = pages.get($(document.body).getProperty('id')).get('out').get(panel); }
			else { var anim_property = mobile_pages.get($(document.body).getProperty('id')).get('out').get(panel); }

			// if we're animating only one panel at a time
			if (panel.indexOf("|") === -1) {
				$(panel).addClass('animating');
				$(panel).getFirst('.panel').setStyles(anim_property);
			}
			// if we're animating more than one panel at a time
			else {
				var simultaneous = panel.split('|');
				simultaneous.each(function(sim, i){
					$(sim).addClass('animating');
					$(sim).getFirst('.panel').setStyles(anim_property);
				});
			}
		});
	},

	lowlightNav: function(){
		$('section-tagline').getFirst().morph({ 'width': 0 });
		// lowlight the appropriate tab
		var nav = $('nav-' + Blinds.page);
		nav.removeClass('here');
		nav.morph({ 'background-position': '0 0' });
		if (Browser.ie) { nav.setStyle('background-color','rgb(34,34,33)'); }
		Cufon.refresh();
	},

	highlightNav: function(){

		// slide in tagline
		$('section-tagline').getFirst().set('text', Blinds.getTagline());
		$('section-tagline').getFirst().morph({ 'width': 510 });

		// highlight the appropriate tab
		var nav = $('nav-' + Blinds.page);
		nav.addClass('here');
		nav.morph({ 'background-position': '0 -50px' });
		if (Browser.ie) { nav.setStyle('background-color','rgb(242,0,13)'); }
		Cufon.refresh();
	},

	updatePanel: function(panel, content){
		// insert new content into panel
		$(panel).getFirst('.panel').empty().adopt(content);
	},

	setupPage: function(){

		this.setupVideo();
		this.updateImages();			// lazyload
		this.updateLinks();				// update all internal links
		this.doodle();					// random doodle hover
		this.clientHover();				// client logo hovers
		this.updateNews();				// update the news feed
		Subnav.init();					// init subnav
		Contact.init();
		Cufon.refresh();				// refresh cufon
		Shadowbox.setup("a.fullscreen, a.slide-image");
		this.updateScrolls();			// set up scrollers
		//access.init();

	},

	updateVideos: function(){


	},

	// update sizing of all scrollbars
	updateScrolls: function(){

		if (scrollpane[1] !== undefined) {
			scrollpane[1].update();
			scrollpane[1].scrollTo(0);
		}
		if (scrollpane[2] !== undefined) {
			scrollpane[2].update();
			scrollpane[2].scrollTo(0);
		}
		if (scrollpane[3] !== undefined) {
			scrollpane[3].update();
			scrollpane[3].scrollTo(0);
		}
		if (scrollpane[4] !== undefined) {
			scrollpane[4].update();
			scrollpane[4].scrollTo(0);
		}
		if (scrollpane[5] !== undefined) {
			scrollpane[5].update();
			scrollpane[5].scrollTo(0);
		}

		if (DetectIpad()) {
			iScrollers.each(function(panel,i){
				iScrollers[i].refresh();
			});
		}
		// Make all columns equal height on smartphones
		if (DetectSmartphone()) {
			var m_bottom = Blinds.getMaxHeight();
			$$('#panel_1, #panel_2, #panel_4').each(function(panel){
				if (panel.getStyle('display') === 'block') {
					panel.setStyle('height', m_bottom - panel.getTop());
				}
			});
		}

	},

	getMaxHeight: function(){
		var panels = $$('#panel_1, #panel_2, #panel_4'),
			m_bottom = 0;
		panels.each(function(panel){
			if (panel.getStyle('display') === 'block') {
				var panel_height = panel.getCoordinates().bottom;
				if (panel_height > m_bottom) { m_bottom = panel_height; }
			}
		});
		return m_bottom;
	},

	// update all internal links
	updateLinks: function(){
		var domains = "preview.gsdm.com|www.gsdm.com|dev2.gsdm.com";
		var ishttp = /(http(.)*:\/\/)/;
		var filetypes = "pdf|doc|docx";
		$$('a').each(function(a, i){
			if ((a.href != null) && (a.href.match(domains) == null) && (a.href.match(ishttp)!=null)) {
				a.setProperty('target','_blank');
			}
			if (!a.hasClass('nofollow') && !a.hasClass('fullscreen') && (a.href !== null) && (a.href.match(domains) !== null) && (a.href.match(filetypes) === null)) {
				a.addEvent('click', function(event){
					event.preventDefault();
					if (!Blinds.running && !Subnav.running) {
						if (DetectSmartphone()) setTimeout(function(){ window.scrollTo(0,0); }, 500);
						SWFAddress.setValue(SEO.getRelURL(this.getProperty('href')));
					}
				});
			}
		});
	},

	// image lazy load
	visibleImages: function(){
		if (DetectIpad()) {
			var value = parseInt($('panel_3').getElement('.panel').getStyle('-webkit-transform').split(', ')[1], 10);
			var y = (isNaN(value)) ? 0 : value * -1;
		}
		else { var y = $('panel_3').getFirst().scrollTop; }
		var h = $('panel_3').getHeight();
		var img_h = (minimized || DetectIpad()) ? 157 : 222;
		return {
			"top" : Math.floor(y / img_h),
			"bottom" : Math.ceil((y + h) / img_h)
		}
	},

	updateImages: function(){
		var image_cells = $$('.staff-list li img'),
			visible_imgs = Blinds.visibleImages();
		for (var i = visible_imgs.top; i < visible_imgs.bottom; i++) {
			if (image_cells[i].src.indexOf("shim") !== -1) new img_load(image_cells[i]);
		}
	},

	// initiate the client logo hovers
	clientHover: function(){
		if ($('clients')) {
			$$('.subsection-image-nav li').each(function(li, i){
				var a = li.getFirst('a');
				a.set('morph', {
					duration: 400,
					transition: 'cubic:out'
				});
				if (!DetectSmartphone() && !DetectIpad()) {
					a.set({ 'opacity' : 0 });
				}
				li.addEvents({
					'mouseenter': function(){
						if (!this.getFirst('a').hasClass('here')) {
							this.getFirst('a').get('morph').cancel();
							this.getFirst('a').morph({
								'opacity': 1
							});
						}
					},
					'mouseleave': function(){
						if (!this.getFirst('a').hasClass('here')) {
							this.getFirst('a').get('morph').cancel();
							this.getFirst('a').morph({
								'opacity': 0
							});
						}
					},
					'click': function(){
						if (!this.getFirst('a').hasClass('here')) {
							this.getFirst('a').get('morph').cancel();
							this.getFirst('a').morph({
								'opacity': 0
							});
						}
					}
				});
			});
		}
	},

	doodle: function(){
		if ($('doodle-info')) {
			var doodle_info = $('doodle-info');
			doodle_info.set('morph', {
				duration: 600,
				transition: 'Circ:in:out'
			});
			$('random-doodle').addEvent('mouseenter', function(){
				doodle_info.get('morph').cancel();
				doodle_info.morph({
					'bottom': 0
				});
			});
			$('random-doodle').addEvent('mouseleave', function(){
				doodle_info.get('morph').cancel();
				doodle_info.morph({
					'bottom': -60
				});
			});
		}
	},

	grid: function(){
		var page = $(document.body).getProperty('id');
		switch (page) {
			case 'home':
			case 'default':
				if (!DetectSmartphone() || !DetectIpad()) {
					// RESIZE THE FEATURE VIDEO
					var max_w = 800,
						max_h = 450,
						par_w = $('feature-column').getWidth(),
						ratio = max_h/max_w,
						new_h = Math.floor(par_w * ratio);
					var video = $$('#feature-column .video');
					video.setStyles({
						width: par_w,
						height: new_h
					});
				}
				if ($('map-canvas')) { $('map-canvas').setStyle('height', Blinds.setHeight($('map-canvas'))); }
			break;
		}
	},

	setHeight: function(el){
		return $(document.body).getHeight() - el.getTop();
	},

	gutter: function(){
		var gutter = $(document.body).getWidth() - $('panel_4').getFirst().getCoordinates().left;
		return gutter;
	},

	getTagline: function(){
		var section = $(document.body).getProperty('id');
		switch(section) {
			case "home":
			case "default":
				var today = new Date();
				var dayNames = ['Sunday',"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
				return "Welcome to GSD&M. It's a fine " + dayNames[today.getDay()] + " here in Austin, Texas.";
			case "work":
				return "This is why we get up in the morning. Well, this and breakfast tacos.";
			case "about":
				return "Check out what we're all about while we play ping-pong.";
			case "newsroom":
				return "We're not the bragging type, but we will when we have to.";
			case "contact":
				return "Looking for something or someone or an enchilada?";
		}
	},

	updateNews: function(){
		if ($(document.body).getProperty('id') === 'default') {
			checkFeed();
		}
	},

	setupVideo: function(){

		$$('.video').each(function(video){

			if (video.get('data-width')) {

				var w = video.get('data-width'),
					h = video.get('data-height'),
					path = video.get('data-vidpath'),
					poster = video.get('data-posterpath'),
					credits = video.get('data-videocredits'),
					linkpath = video.get('data-linkpath');

				if (DetectBlackBerryWebKit()) {
					video.empty();
					var img = new Element('img', {
						'src': poster,
						'alt': credits
					}).inject(video);
				}
				// show video tag
				else if (DetectSmartphone() || DetectIpad()) {
					video.empty();
					var vid = new Element('video', {
						'class': 'html5-video',
						'controls': 'controls',
						'poster': poster,
						'src': path,
						events: {
							touchstart: function(){
								alert(this);
								this.play();
							}
						}
					}).inject(video);
				}
				else {
					video.empty();
					var swf = new Swiff('/swf/videoPlayer.swf', {
						container: video,
						width: w,
						height: h,
						params: {
							wMode: 'transparent',
							allowfullscreen: 'true',
							allowScriptAccess: 'sameDomain'
						},
						vars: {
							vidPath: path,
							posterPath: poster,
							videoCredits: credits,
							linkPath: linkpath
						}
					});
				}
			}

		});

		// Using an iPhone, iPod or iPad?
/*		if ((DetectSmartphone()) || DetectIpad()) {
			$$('div.video').each(function(video){
				var swf = video.getFirst('.flash-video');
				if (swf) { swf.destroy(); }
			});
		}
		else {
			$$('div.video').each(function(video){
				var vid = video.getFirst('.html5-video');
				if (vid) { vid.destroy(); }
			});
		}*/
	}

};

/*	PAGES
	- Defines order of panel animation for the
	  different "pages" of the site
	- If two panels need to be animated at the
	  same time, split with "|".
------------------------------------------------------*/
pages = new Hash ({
	'default' : new Hash ({
		'friendlyname': 'Home',
		'in' : new Hash ({
			'panel_1|panel_2' : { opacity: 1 },
			'panel_3' : { width: (document.body.className === 'minimized' || DetectIpad()) ? 120 : 170 },
			'panel_4' : { width: Blinds.gutter() }
		}),
		'out' : new Hash ({
			'panel_5' : { opacity: 0 },
			'panel_4' : { width: 0 },
			'panel_3' : { width: 0 },
			'panel_1|panel_2' : { opacity: 0 }
		})
	}),
	'work' : new Hash ({
		'friendlyname': 'Work',
		'in' : new Hash ({
			'panel_1' : { opacity: 1 },
			'panel_5|panel_2' : { opacity: 1 },
			'panel_4' : { width: 251 },
			'panel_3' : { width: ($(document.body).hasClass('minimized') || DetectIpad()) ? 120 : 170 }
		}),
		'out' : new Hash ({
			'panel_3' : { width: 0 },
			'panel_4' : { width: 0 },
			'panel_5|panel_2' : { opacity: 0 },
			'panel_1' : { opacity: 0 }
		})
	}),
	'about' : new Hash ({
		'friendlyname': 'About',
		'in' : new Hash ({
			'panel_1' : { opacity: 1 },
			'panel_5|panel_2' : { opacity: 1 },
			'panel_4' : { width: 251 },
			'panel_3' : { width: ($(document.body).hasClass('minimized') || DetectIpad()) ? 120 : 170 }
		}),
		'out' : new Hash ({
			'panel_3' : { width: 0 },
			'panel_4' : { width: 0 },
			'panel_5|panel_2' : { opacity: 0 },
			'panel_1' : { opacity: 0 }
		})
	}),
	'newsroom' : new Hash ({
		'friendlyname': 'News Room',
		'in' : new Hash ({
			'panel_1' : { opacity: 1 },
			'panel_5|panel_2' : { opacity: 1 },
			'panel_4' : { width: 251 },
			'panel_3' : { width: ($(document.body).hasClass('minimized') || DetectIpad()) ? 120 : 170 }
		}),
		'out' : new Hash ({
			'panel_3' : { width: 0 },
			'panel_4' : { width: 0 },
			'panel_5|panel_2' : { opacity: 0 },
			'panel_1' : { opacity: 0 }
		})
	}),
	'contact' : new Hash ({
		'friendlyname': 'Contact',
		'in' : new Hash ({
			'panel_5' : { opacity: 1 },
			'panel_1' : { opacity: 1 },
			'panel_2' : { opacity: 1 }
		}),
		'out' : new Hash ({
			'panel_2' : { opacity: 0 },
			'panel_1' : { opacity: 0 },
			'panel_5' : { opacity: 0 },
			'panel_3|panel_4' : { width: 0 }
		})
	})
});
mobile_pages = new Hash ({
	'default' : new Hash ({
		'friendlyname': 'Home',
		'in' : new Hash ({
			'panel_1|panel_2' : { opacity: 1 }
		}),
		'out' : new Hash ({
			'panel_1|panel_2' : { opacity: 0 }
		})
	}),
	'work' : new Hash ({
		'friendlyname': 'Work',
		'in' : new Hash ({
			'panel_1|panel_2' : { opacity: 1 }
		}),
		'out' : new Hash ({
			'panel_1|panel_2' : { opacity: 0 }
		})
	}),
	'about' : new Hash ({
		'friendlyname': 'About',
		'in' : new Hash ({
			'panel_1|panel_2' : { opacity: 1 }
		}),
		'out' : new Hash ({
			'panel_1|panel_2' : { opacity: 0 }
		})
	}),
	'newsroom' : new Hash ({
		'friendlyname': 'News Room',
		'in' : new Hash ({
			'panel_1|panel_2' : { opacity: 1 }
		}),
		'out' : new Hash ({
			'panel_1|panel_2' : { opacity: 0 }
		})
	}),
	'contact' : new Hash ({
		'friendlyname': 'Contact',
		'in' : new Hash ({
			'panel_5' : { opacity: 1 },
			'panel_1' : { opacity: 1 },
			'panel_2' : { opacity: 1 }
		}),
		'out' : new Hash ({
			'panel_2' : { opacity: 0 },
			'panel_1' : { opacity: 0 },
			'panel_5' : { opacity: 0 },
			'panel_3|panel_4' : { width: 0 }
		})
	})
});

/*	STAFF IMAGES
------------------------------------------------------*/
var img_load = new Class({

	Implements: Options,

	initialize: function(element, options){
		this.setOptions(options);
		this.element = element;
		this.stat_source = this.element.get('data-static');
		this.anim_source = this.element.get('data-animated');
		this.show_image();
	},

	show_image: function(){
		this.element.addClass('loading');
		var me = this,
			shim = this.element;
		(function(){
			var imgs = Asset.images([me.stat_source, me.anim_source], {
			    onComplete: function(){
					shim.fade('hide').set('src', me.stat_source).removeClass('loading').fade('in');
					shim.addEvent('touchstart',function(e) {
						if (this.get('src') === me.anim_source) {
							this.set('src', me.stat_source);
						}
						else {
							this.set('src', me.anim_source);
						}
					});
					shim.addEvent('mouseenter', function(){
						this.set('src', me.anim_source);
					});
					shim.addEvent('mouseleave', function(){
						this.set('src', me.stat_source);
					});
			    }
			});
		}).delay(100);
	}
});

