/**
 * Main script for 180byDesign site.
 *
 * @author		Michael Gilley
 * @version		$Id v4.0$
 * @copyright	180byDesign, June, 2011
 * @link		http://www.180bydesign.com
 * @package		180site
 **/

var OBD = (function($,undefined) {
	return {
		fire: function() {
			for (var i in OBD.init) OBD.init[i]();
		},
		init: {
			// preset any global settings
			presets: function() {
				$.address
					.crawlable(true)
					.internalChange( OBD.navControl.doHistory )
					.externalChange( OBD.navControl.reMix );
			},
			// Do navigation stuff
			nav: function() {
				var $nav = $('#menu a');
				if ( $nav.length ) OBD.navControl.init( $nav );
			},
			prePageRequests: function() {
				OBD.pagePresets();
			}
		},
		pagePresets: function($container) {
			$container = $container || $('#contents');
			
			// These are run everytime a new page is loaded in.
			OBD.roundAbout( $container );
			
			$('.address').address(function() {
				return $(this).attr('href').replace(window.path, '');
			});
			
			if ( $container.find('.project').length ) OBD.work.init( $container );
			
			if ( $('#freeform').length ) OBD.contact.init();
			
			if ( $('#commentform').length ) OBD.blog.init();
			
			if ( $('.blog').length ) OBD.blog.init();
			
			if ( $container.find('.dynamic_label').length ) OBD.formstart.init();
		},
		/**
		 * Handle Navigation internal requests
		 */
		navControl: {
			init: function($nav) {
				var navControl = this;
				
				// handle click events for navigation
				$nav.click(function(e) {
					var $t = $(this),
						addr = $t.attr('href');
					
					e.preventDefault();
					
					// if already active do nothing
					if ( $t.is('.active') ) {
						if ($t.is('.work') && $('#details').is(':visible')) $('a.grid').trigger('click');
						return;
					}
					
					// activate the item
					navControl.activateItem( $t );
					
					// navControl.dohistory( addr );
					$.address.value( addr );
				});
				
				// handle clicks for home page button
				$('#logo a').click(function(e) {
					var $t = $(this);
					
					e.preventDefault();
					
					$('#menu .active').removeClass('active');
					
					if ($.address.baseURL().replace( window.path.replace(/\/$/, ''), '') !== '') {
						return $.address.value('#home');
					}
					
					$.address.value('/');
				});
			},
			doHistory: function( e ) {
				var addr = e.path,
					navControl = this,
					work = addr.match(/^\/work\/?(.*)/),
					req, loader;
				
				// work interrupter
				if (work && (work[1] || $('#projects').length) && ! OBD.work.isFlat) {
					OBD.work.transition( work[1], e );
					return;
				}
				
				// do history for deep linking
				if (/^\//.test(addr) && window.path) addr = window.path.replace(/\/$/g, '') + addr;
				
				// make sure menu is pointing the right place
				if (e.type === "externalChange") OBD.navControl.activateItem( $('#menu a[href="'+e.path+'"]') );
				
				loader = setTimeout(function() { $('#loader').fadeIn(); }, 1000);
				
				$.when( $.get(addr), OBD.navControl.shiftLeft() )
					.always(function() {
						clearTimeout(loader);
						$('#loader').stop().fadeOut(50);
					})
					.done(function(obj) {
						// obj is the $.get() response parameters = responseText, textStatus, jqxhr object
						var res = obj[0].replace(/<script(.|\s)*?\/script>/g, ''),
							$c = $('<div/>').append(res),
							title = $c.find('title').text(),
							body = res.match(/<body\s+class=\"(.*)\">/);
						
						$c = $c.find('#contents').children();
						$.address.title(title);
						body = (body) ? body[1] : '';
						$('body').attr('class', body);
						$('#contents').html( $c ).css({left: 25, opacity: 0}).show().animate({left: 0, opacity: 1}, 450, 'easeOutExpo');
						
						// run any custom stuff that needs to happen per request
						OBD.pagePresets( $c );
					})
					.fail(function(obj) {
						OBD.setError( obj.status );
					});
			},
			reMix: function( e ) {
				// is this a fresh page?
				if (! OBD.navControl.loaded) return OBD.navControl.loaded = true;
				
				// fix issue with root address: /work on back btn will load /index
				if ( e.path === "/" && document.location.href.replace(window.path, '').length > 0 ) {
					e.path = '/' + document.location.href.replace(window.path, '');
				}
				
				// makes sure the error box goes away
				$('body').trigger('click.error');
				
				OBD.navControl.doHistory( e );
			},
			shiftLeft: function() {
				var df = $.Deferred();
				
				$('#contents').animate({left: -25, opacity: 0}, 450, 'easeOutExpo', df.resolve);
				
				return df.promise();
			},
			activateItem: function($item) {
				// remove previous active item
				$('#menu').find('.active').removeClass('active');
				
				// animate and activate the new item
				$item.css('bottom', 3).animate({bottom: 0}, 250, 'easeOutBounce', function() {
					$item.addClass('active');
				});
			}
		},
		roundAbout: function($obj) {
			var $roundies = ($obj) ? $obj.find('.roundabout') : $('.roundabout');
			
			$roundies.find('img').removeAttr('width').removeAttr('height');
			
			// make sure there's at least 3!
			if ($roundies.find('li').length < 3) {
				$roundies.find('li').clone().appendTo($roundies);
			}
			
			$roundies.roundabout({
				minOpacity: .6,
				minScale: .65,
				easing: 'easeInOutExpo',
				duration: 1000,
				tilt: .5,
				clickToFocus: false,
				//debug: true
			});
						
			var refreshId = setInterval(function()
			{
			    $roundies.roundabout_animateToPreviousChild(2000); 

			
			}, 6000);	
			
			$(".roundabout-holder").click(function() {
				$('.roundabout').roundabout_animateToPreviousChild(1000); 
			});		
			

			
		},
		work: {
			init: function($container) {
				// init category if already set
				this.setUpCategory( $container );
				
				// fix the grid
				this.alignGrid( $container );
				
				// project hovering
				this.projectHover();
				
				// filter bar
				this.filtering();
				
				// do flat nav
				this.handleFlatLoad();
			},
			setUpCategory: function($container) {
				var catid = $container.find('#projects').data('cat'),
					$catBtn;
				
				if ( catid && typeof catid === "number") {
					$catBtn = $('#filters').find('a[data-cat="'+catid+'"]');
					OBD.work.changeCategory( $catBtn );
				}
			},
			alignGrid: function($container) {
				$container = $container || $('#projects');
				
				$container.find('.project')
					.removeClass('last')
					.filter(':visible')
					.each(function(i) {
						if ((i+1)%4 == 0) $(this).addClass('last');
					});
			},
			projectHover: function() {
				$('.project').hover(function() {
					$(this).toggleClass('hover');
				});
			},
			filtering: function() {
				// controls the grid/details tabs
				$('#viewoptions .grid').click(function(e, keepUrl) {
					var $t = $(this);
					
					e.preventDefault();
					if ( $t.is('.selected') ) return;
					
					$('.detailed.selected').removeClass('selected');
					$t.addClass('selected');
					
					OBD.work.zoomOut( keepUrl );
				});
				
				$('#viewoptions .detailed').click(function(e) {
					var $t = $(this);
					
					e.preventDefault();
					if ( $t.is('.selected') ) return;
					
					$('.grid.selected').removeClass('selected');
					$t.addClass('selected');
					
					OBD.work.zoomIn();
				});
				
				// controls the filter tab and bar animation
				$('#viewoptions .filter').click(function(e, keepUrl) {
					var $t = $(this);
					
					e.preventDefault();
					
					// if details are showing we need to zoomout
					if ( $('#details').is(':visible') ) $('a.grid').trigger('click', [keepUrl]);
					
					if (! $t.hasClass('active')) {
						$t.addClass('active');
						$('#filters').slideDown(350, 'easeOutExpo');
					} else {
						$t.removeClass('active');
						$('#filters').slideUp(350, 'easeOutExpo');
					}
				});
				
				// controls the filters themselves
				$('#filters a').click(function(e) {
					var $t = $(this);
					
					e.preventDefault();
					
					if ( $t.hasClass('selected') ) return;
					
					$.address.value( $t.attr('href') );
					OBD.work.changeCategory( $t );
				});
				
				// controls each project thumbnail
					// instead of applying a costly click event to each individual project
				 	// we'll just apply one listener to the whole block and then bubble up the event
				$('#projects').click(function(e) {
					var $t = $(e.target),
						$p = $t.closest('.project');
					
					if ( $p.length ) {
						e.preventDefault();
						OBD.work.zoomIn( $p );
					}
				});
				
				// nav controls for projects
				$('#details-next').click(function(e) {
					e.preventDefault();
					OBD.work.switchOutProj('next');
				});
				
				$('#details-prev').click(function(e) {
					e.preventDefault();
					OBD.work.switchOutProj('prev');
				});
				
				// controls on details
					// again we're going to make use of bubbling so we don't have to spend costly
					// cycles on a bunch of large elements on the page
				$('#details').click(function(e) {
					var $t = $(e.target),
						kill = false;
					
					// if it's already active do nothing
					if ( !kill && $t.is('a.active') ) kill = true;
					
					if ( !kill && $t.is('a.tab') ) {
						kill = true;
						$t.parents('.panels').find('.active').removeClass('active').nextAll('div:first').slideUp(350, 'easeInOutExpo');
						$t.addClass('active').nextAll('div:first').slideDown(350, 'easeInOutExpo');
					}
					
					if ( !kill && $t.is('.simg') ) {
						kill = true;
						$t.parent('.window').cycle('next');
					}
					
					if (kill) e.preventDefault();
					return;
				});
			},
			changeCategory: function( $catBtn ) {
				var cat = $catBtn.data('cat'),
					show = (cat == 'showall') ? '*' : '.cat_'+cat;
				
				if (! $catBtn.hasClass('selected')) {
					$('#filters a.selected').removeClass('selected');
					$catBtn.addClass('selected');
					
					$('#projects .project').addClass('fhide').filter( show ).removeClass('fhide');
					
					OBD.work.alignGrid();
				}
			},
			transition: function(hash, event) {
				
				// is this a category shift?
				if ( hash.indexOf('category') >= 0 ) {
					
					if ( $('#details').is(':visible') ) {
						// we are going back to our grid view
						$('#viewoptions .filter').trigger('click', [true]);
						
					} else if ( $('#projects').length ) {
						
						// we just need to switch categories						
						var catid = hash.match(/[0-9]+/)[0],
							$catBtn = $('#filters').find('a[data-cat="'+catid+'"]');

						OBD.work.changeCategory( $catBtn );
					} else {
						
						// trying to go back to the work page from outside
						$.address.value('/work');
					}
					
				} else if ( hash === "" && event.type === "externalChange" ) {
					// we just hit the back button back to /work
					// we need to figure out what needs to happen
					
					if ( $('#projects').height() > 0 && ! $('.showall').is('.selected') ) {
						// reset filters
						OBD.work.changeCategory( $('.showall') );
						
					} else if ( $('#details').is(':visible') ) {
						// zoomOut
						$('.detailed.selected').removeClass('selected');
						$('.grid').addClass('selected');
						OBD.work.zoomOut();
					}
					
				} else if ( event.type === "externalChange" && $('#details').is(':hidden') ) {
					
					// we need to reopen the project details
					hash = hash.replace(/\/$/, '');
					OBD.work.zoomIn( $('.project a[href*="'+hash+'"]:first').closest('.project') );
					
				} else if ( event.type === "externalChange" && hash ) {
					
					// the project details have been requested outside of the work page
					$.address.value('/work');
					
				} else if ( event.type === "externalChange" ) {
					
					// if it's anything else it must be a project
					var $pid = $('.details[data-url="/work/'+hash+'"]');
					if ($pid.length) OBD.work.switchOutProj( $pid.data('pid') );
					
				}
				
			},
			zoomIn: function( $upFront ) {
				var $stack = $('.project:not(.fhide)'),
					eq = (! $upFront) ? 0 : null,
					$upFront = $upFront || $stack.eq( eq ),
					url = $upFront.find('a:first').attr('href'),
					pid = $upFront.data('pid');
				
				eq = (eq !== null) ? eq : $stack.index( $upFront );
				
				// make the present stack global
				OBD.work.stack = $stack;
				
				// switch to the display thumb above filters
				$('#viewoptions a').removeClass('selected').filter('.detailed').addClass('selected');
				
				// only when the first project has loaded and the work section has shifted down display that project
				$.when( OBD.work.loadProj( pid ), OBD.work.workSlideDown($stack, eq) )
					.then(function() {
						OBD.work.switchOutProj( pid );
					});
			},
			zoomOut: function( keepUrl ) {
				var $af = $('a.filter'),
					hH, pH;
				
				// fade out the projects
				$('#details').fadeOut(150, function() {
					// hide them
					$('.details').hide().remove();
					
					hH = $('.heading').data('origH');
					pH = $('#projects').data('origH');
					
					$('#projects').animate({height: pH}, 'slow', 'easeOutExpo');
					
					$('.heading').animate({height: hH}, 'slow', 'easeOutExpo', function() {
						$('#blinder').animate({opacity: 0}, 550, 'easeOutExpo');
						$('#bg').fadeIn();
						
						$('.project').show().animate({opacity: 1}, 350);
					});
				});
				
				if (! keepUrl) $.address.value('/work');
			},
			workSlideDown: function($stack, eq) {
				var dfd = $.Deferred();
				
				// take care of the filter tab if open
				if ( $('.filter').hasClass('active') ) {
					$('.filter').removeClass('active');
					$('#filters').slideUp(350, 'easeOutExpo');
				}
				
				// synchronized fadeout of project thumbnails
				var orig = $stack.eq( eq ).position(), a = [], d = 0;
				
				for (var i=0; i <= $stack.length-1; i++) {
					var $t = $stack.eq(i),
						pos = $t.position(),
						dis = Math.floor( Math.sqrt( Math.pow(orig.left - pos.left, 2) + Math.pow(orig.top - pos.top, 2) ) /2 );
						
					d = Math.max(d, dis);
					
					$t.delay(dis).animate({opacity: 0}, 350);
				}
				
				setTimeout(function() {
					var $projects = $('#projects'),
						ph = $projects.height(),
						$heading = $('.heading'),
						hh = $heading.height();
						
					$projects.data('origH', ph).height( ph );
					$('.project').hide();
					$('#bg').fadeOut('fast');
					$('#blinder')
						.css({opacity: 0, display: 'block'})
						.animate({opacity: 1}, 350, 'easeOutExpo', function() {
							$heading.data('origH', hh);
							$projects.animate({height: 0}, 'slow', 'easeOutExpo');
							$heading.animate({height: 504}, 'slow', 'easeOutExpo', function() {
								$('#details').fadeIn(150, dfd.resolve);
							});
						});
				}, d);
				
				return dfd.promise();
			},
			loadProj: function(pid, insert) {
				var insert = insert || 'after',
					$proj = $('#project-'+pid),
					req, url;
				
				// if the project doesn't exist or the details are already loaded send back a completed promise
				if (! $proj.length || $('#details-'+pid).length ) {
					console.debug('Already loaded: quiting loadProj');
					return $.Deferred().resolve().promise();
				}
				
				url = window.path + $proj.find('a:first').attr('href').substr(1);
				
				req = $.get(url)
					.done(function(res) {
						var proj = res.replace(/<script(.|\s)*?\/script>/g, ''),
							$p = $('<div/>').append(proj).find('.details');
						
						$p.hide();
						if (insert == 'after') {
							$('#details .details-wrap').append( $p );
						} else {
							$('#details .details-wrap').prepend( $p );
						}
						
						OBD.work.initCycle( $p.find('#pwindow-'+pid) );
					})
					.fail(function(obj) {
						OBD.setError( obj.status );
					});
				
				return req;
			},
			initCycle: function(obj) {
				var $obj = (obj.selector) ? obj : $( obj );
				
				$obj.cycle({
					fx: 'scrollHorz',
					speed: 350,
					timeout: 0,
					easing: 'easeInOutExpo',
					pager: $obj.prev()
				});
			},
			switchOutProj: function(param) {		// param can be either 'next' or 'prev' or a number for a specific id
				var $cur = $('.details:visible'),
					pid = (typeof param == 'number') ? param : null,
					dir = (typeof param == 'string') ? param : 'next',
					poss = (dir == 'next') ? [-25, 25] : [25, -25],
					$toShow, $nextLoad, $prevLoad;
				
				// animate only one at a time
				if ( $('.details:animated').length ) return;
				
				// find project to show
				if (! pid) {
					if (dir == "next") {
						if ( $cur.nextAll('.details:first').length ) {
							$toShow = $cur.nextAll('.details:first');
						} else if (! $('.details:first').is(':visible') ) {
							console.debug('going to first next');
							$toShow = $('.details:first');
						} else {
							// nothing else to show!
							console.debug('nothing to show next');
							return;
						}
					} else {
						if ( $cur.prevAll('.details:first').length ) {
							$toShow = $cur.prevAll('.details:first');
						} else if (! $('.details:last').is(':visible') ) {
							console.debug('going to last prev');
							$toShow = $('.details:last');
						} else {
							// nothing else to show!
							console.debug('nothing to show prev');
							return;
						}
					}
				} else {
					$toShow = (pid.length) ? pid : $('#details-'+pid);
				}
				
				// make sure it's actually here
				if (! $toShow.length) return false;
				
				// update the address
				$.address.value( $toShow.data('url') );
				
				// animate projects out and in
				$cur.animate({left: poss[0], opacity: 0}, 450, 'easeOutExpo', function() { $cur.hide(); });
				$toShow.css({left: poss[1], opacity: 0}).show().animate({left: 0, opacity: 1}, 450, 'easeOutExpo');
				
				// preload in projects on either side of current project
				$nextLoad = $('#project-'+$toShow.data('pid')).nextAll(':not(.fhide,.clear):first');
				$prevLoad = $('#project-'+$toShow.data('pid')).prevAll(':not(.fhide,.clear):first');
				
				if (! $nextLoad.length) $nextLoad = OBD.work.stack.first();
				if (! $prevLoad.length) $prevLoad = OBD.work.stack.last();
				
				// are these already loaded? if not load them in!
				if (! $('#details-'+$nextLoad.data('pid')).length ) 
					OBD.work.loadProj( $nextLoad.data('pid') );
				
				if (! $('#details-'+$prevLoad.data('pid')).length )
					OBD.work.loadProj( $prevLoad.data('pid'), 'before' );
			},
			handleFlatLoad: function() {
				OBD.work.isFlat = $('body').is('.flat');
				
				if ( OBD.work.isFlat ) {
					$('#details-next, #details-prev, #viewoptions a').unbind().bind('click', function(e) {
						e.preventDefault();
						$.address.value('/work');
					});
				}
			}
		},
		
		formstart: {
			init: function() {
				$(".dynamic_label label").inFieldLabels({ fadeOpacity:.4 });
				$(".logged_out_info, .submit_wrap").addClass("hide");
				$(".dynamic_label .basic_comment").click(function(){
					$(".logged_out_info, .submit_wrap").show('fast');
				});
			}
		},
		
		
		blog: {
			init: function() {
				$('.title a, a.more-link, h2 a, .widget a, .related a, a:has(.main_image)').click(function() {
					var href = $(this).attr('href').slice(window.path.length).replace(/\/$/g, '');
					$.address.value(href);
					return false;
				});
				/*$('.comments a:not(.single)').click(function() {
					var href = $(this).attr('href').slice(window.path.length).replace(/\/#(.+)$/, '');
					scroll = true;
					$.address.value(href);
					return false;
				});
				$('.comments a.single').click(function() {
					$.scrollTo('#respond', 450, {easing: 'easeOutExpo'});
					$('#commentform :input:first').focus().select();
					return false;
				});
				$('#commentform').submit(function(e) {
					var $t = $(this),
						send = true,
						req;
					
					e.preventDefault();
					
					$('#check').hide();
					send = $('#author').length == 0;
					if (!(/^[a-z]([0-9a-z_ ])+$/i.test($('#author').val())) || $('#author').val() == '') {
						$('#check').text('Field is required and may only use a-z, 0-9, underscores, and it must begin with a letter.').slideDown();
						$('#author').focus().select();
						send = false;
					} else if (! (OBD.blog.mailreg.test( $('#email').val() )) ) {
						$('#check').text('Field is required and must be in the form me@example.com').slideDown();
						$('#email').focus().select();
						send = false;
					} else if ($('#comment').val() == '') {
						$('#comment').focus();
						send = false;
					}
					
					if (send) {
						req = $.ajax({
							url: $t.attr('action'),
							type: 'POST',
							data: $t.serialize()
						})
						.complete(function(xhr, status) {
							var $list = $('.commentlist');
							var c = $('<div/>')
										.append( xhr.responseText.replace(/<script(.|\s)*?\/script>/g, "") )
										.find('.commentlist li:last')
										.hide();
							if ($list.length > 0) {
								$list.append(c);
								c.slideDown(450, 'easeOutExpo');
								$('#comments').html('Comments ('+$list.find('li').length+')');
								Cufon.refresh();
								$('#comment').val('');
							} else {
								var $h3 = $('<h3 id="comments" class="replace" />').text('Comments (1)').insertAfter('div.post');
								var $l = $('<ol class="commentlist" />').append(c).insertAfter($h3);
								Cufon.refresh();
								$l.find('li').slideDown(450, 'easeOutExpo');
								$('#comment').val('');
							}
						});
					}
				});
				
				$('.commentmetadata a').click(false);
				*/
				if (scroll) {
					setTimeout(function() {
						$.scrollTo('#respond', 450, {easing: 'easeOutExpo'});
						$('#commentform :input:first').focus().select();
					}, 500);
					scroll = false;
				}
			},
			mailreg: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i
		},
		contact: {
			init: function($contactForm) {
				var cont = this;
				
				$('.contact form').submit(function(e) {
					var valid = true,
						name = $('#name'),
						email = $('#email'),
						message = $('#message'),
						allFields = $([]).add(name).add(email).add(message);

					e.preventDefault();
					
					allFields.removeClass('error');
					valid = valid && cont.checkLength(name, 'Full Name', 3, 80);
					valid = valid && cont.checkLength(email, 'Email', 6, 80);
					valid = valid && cont.checkLength(message, 'Message', 1, 1000);
					// valid = valid && cont.checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Your Name may only use a-z, 0-9, underscores, and it must begin with a letter.");
					valid = valid && cont.checkRegexp(email, OBD.blog.mailreg,"eg. me@example.com");
					$('.error:first').focus().select();
					if (valid) {
						var self = $(this);
						$('#contents .form').height($('#contents .form').height()).wrapInner('<div class="fade"></div>').find('.fade').fadeOut(450, 'easeOutExpo');
						$.ajax({
							url: self.attr('action'),
							type: 'POST',
							data: self.serialize(),
							error: function(x,s,e) {
								var er = 'Sorry, there seems to be a problem with your internet connection. Please make sure that your computer is connected to the internet and then try again. Thank you.';
								OBD.setError(er);
								$('#contents .form .fade').fadeIn();
							},
							success: function(data, status) {
								$('.thanks').prependTo('#contents .form').fadeIn();
							}
						});
					}
				});
			},
			checkLength: function(o,n,min,max) {
				if ( o.val().length > max || o.val().length < min ) {
					o.addClass('error');
					$('#formcheck').text(n + " must be between "+min+" and "+max+" characters long.").slideDown(350, 'easeOutExpo');
					return false;
				} else {
					return true;
				}
			},
			checkRegexp: function(o,regexp,n) {
				if (!(regexp.test(o.val()))) {
					o.addClass('error');
					$('#formcheck').text(n).slideDown(350, 'easeOutExpo');
					return false;
				} else {
					return true;
				}
			}
		},
		/**
		 * Handle page errors.
		 * @param er 	A numerical page status (404) or a custom string to be used as the error.
		 */
		setError: function(er) {
			switch (er) {
				case 404:
					er = "Sorry, this page doesn't seem to exist. Please go back and try another option.";
					er += "We apologize for the inconvenience.";
					break;
			}
			
			$('<div id="error" />').text( er ).prepend('<button class="ex">x</button><h1>Oops!</h1>').appendTo('body');
			$('.ex', '#error').click(function(e) {
				e.preventDefault();
				$('#error').fadeOut(100, function() {
					$(this).remove();
				});
			});
			$('body').bind('click.error', function(e) {
				var $el = $(e.target);
				
				if ( $el.closest('#error').length == 0 ) {
					$('.ex', '#error').trigger('click');
					$('body').unbind('click.error');
				}
			});
		}
	};
})(jQuery);

jQuery( OBD.fire );

