//'use strict';

/*global window, document, console, jQuery, google, _gaq */

// private functions
function debug(o) {
	if(window.console && window.console.log) {
		window.console.log(o);
	}
}

if(typeof jQuery !== 'undefined') {
	jQuery.noConflict();
	(function($) {

		// app functions
		var App = {

			/**
			* Options
			* @desc General App related options
			*/
			options: {
				className:	{
					active:		'active',
					animating:	'animating',
					hover:		'hover',
					overlay:	'overlay',
					error:		'error'
					
				},
				slideView:	{
					duration:	1250,
					easing:		'easeInOutQuart', // easeInOutExpo
					delay:		10000
				},
				scroll:		{
					duration:	'slow',
					easing:		'easeInOutQuart' // easeInOutExpo
				},
				carousel:	{
					speed:		5000,
					easing:		'easeOutCirc',
					opacity:	0.4
				}
			},

			/**
			* Hover
			* @desc Fixing hover on navigation list items
			*/
			hover: function() {
				var sfEls, length, functions, i;

				sfEls		= $('#topNav').children('li');
				length		= sfEls.length;
				functions	= {
					mouseover: function() {
						this.className += ' ' + App.options.className.hover;
					},
					mouseout: function() {
						this.className = this.className.replace(App.options.className.hover, '');
					}
				};

				for(i=0; i<length; i++) {
					sfEls[i].onmouseover	= functions.mouseover;
					sfEls[i].onmouseout		= functions.mouseout;
				}
			},

			/**
			* Flash
			* @desc Flash embed
			*/
			flash: function() {
				if($.fn.flash && $.flash.available) {
					$('body').addClass('has-flash');

					$('#teamList li.flash-enabled').each(function(i, li){
						var $$, $div, id;

						$$		= $(li);
						$div	= $$.find('div[id]');
						id		= $div.attr('id');

						$('#' + id).flash({
							swf:	'/flash/team/' + id + '.swf',
							height:	172,
							width:	306,
							wmode: (i < 2) ? 'transparent' : 'opaque',
							hasVersion: 10,
							hasVersionFail: function(options) {
								return false;
							}

						});
					});
				}
			},

			/**
			* Slide View
			* @desc Homepage full-width sliding gallery
			*/
			slideView: function() {
				var $gallery, $galleryUl, $galleryLi,
					$galleryLiFirst, $galleryLiLast, $galleryLiActive, $galleryLiActiveA, $activeIcon,
					galleryLiActiveIndex, width, widthCounter, count, total,
					$wrapper, $ul, li = [], ii = 0,
					$shadow, $shadowA, slideshowMove, slideshowMoveTimeout;

				$('body').addClass('has-slideview');

				$gallery			= $('#headGallery');
				$galleryUl			= $gallery.find('ul');
				$galleryLi			= $galleryUl.children('li');
				$galleryLiFirst		= $galleryLi.filter(':first');
				$galleryLiActive	= $galleryLi.filter('.' + App.options.className.active);
				$galleryLiActive	= ($galleryLiActive.length === 1) ? $galleryLiActive : $galleryLiFirst.addClass('active');
				$galleryLiActiveA	= $galleryLiActive.find('a');
				galleryLiActiveIndex	= $galleryLiActive.index();

				width				= parseInt($galleryLi.filter(':first').outerWidth(true), 10);
				count = total		= $galleryLi.length;
				
				$wrapper			= $('<div />').addClass('ui-wrapper').addClass('section');
				$ul					= $('<ul />').addClass('ui-pagination').addClass('section');
				$shadow				= $('div.shadow');
				$shadowA			= $('<a />').appendTo($shadow).attr('href', $galleryLiActiveA.length ? $galleryLiActiveA.attr('href') : '#');

				$('<img />').attr('src', 'head-gallery-shadow.png');
		
				if(count > 1) {
					$galleryLi.each(function(i){
						var $$, $img,
							alt, className,
							position = i + 1;

						$$			= $(this);
						$img		= $$.find('img');
						alt			= $img.attr('alt');
						className	= $$.attr('class');

						li[ii++]	= '<li class="' + className + '">';
						li[ii++]	= '<a href="#' + position + '" title="' + alt + '" alt="' + alt + '">';
						li[ii++]	= position;
						li[ii++]	= '</a>';
						li[ii++]	= '</li>';
					});

					$shadowA.bind('click', function(event){
						var $$ = $(event.target).closest('a');

						$galleryLi.filter('.' + App.options.className.active).find('a').trigger('click');

						$$.blur();
						event.preventDefault();
					});

					// clone items to create seamless animation
					$galleryLi.filter(':gt(' + (total - 3) + ')').clone().removeClass().addClass('clone').prependTo($galleryUl);
					$galleryLi.filter(':lt(2)').clone().removeClass().addClass('clone').appendTo($galleryUl);
					count	  += 4;
					$galleryLi = $galleryUl.children('li');

					$galleryUl.wrap($wrapper);
					$galleryUl.css({'width': width * count, left: -(width * $galleryLiActive.index())});

					li[ii++] = '<li class="active-icon"></li>';

					$ul.append(li.join('')).appendTo($gallery).delegate('a', 'click', function(event){
						var $$, $li, $lis, $liActive, $target, $a,
							go, index, originalIndex, indexActive,
							fix = false;

						$$				= $(event.target);
						$li				= $$.closest('li');
						$lis			= $li.siblings();
						$liActive		= $lis.filter('.' + App.options.className.active);
						originalIndex	= $li.index();
						go = index		= originalIndex + 2;
						indexActive		= $liActive.index();

						if(indexActive === (total - 1) && originalIndex === 0) {
							fix		= true;
							go		= total + 2;
						}
						else if(indexActive === 0 && originalIndex === (total - 1)) {
							fix		= true;
							go		= 1;
						}

						$target = $galleryLi.eq(go);
						$a		= $target.find('a');
						$$.blur();
						event.preventDefault();

						if(!$li.is('.' + App.options.className.active) && !$ul.is('.' + App.options.className.animating)) {
							$lis.add($galleryLi).removeClass(App.options.className.active);
							//$galleryUl.add($ul).addClass(App.options.className.animating);

							// reset timeout
							window.clearTimeout(slideshowMoveTimeout);
							slideshowMoveTimeout = window.setInterval(slideshowMove, App.options.slideView.delay);

							$activeIcon.show().stop().animate({'left': (originalIndex * widthCounter)}, {
								duration:	App.options.slideView.duration,
								easing:		App.options.slideView.easing
							});
							$galleryUl.stop().animate({'left': -(go * width)}, {
								duration:	App.options.slideView.duration,
								easing:		App.options.slideView.easing,
								complete:	function(){
									//$galleryUl.add($ul).removeClass(App.options.className.animating);
									$activeIcon.hide();

									$lis.add($galleryLi).removeClass(App.options.className.active);
									$li.add($target).addClass(App.options.className.active);

									$shadowA.attr('href', $a.length ? $a.attr('href') : '#');
									
									if(fix === true) {
										$galleryUl.css('left', -(index * width));
										$target.removeClass(App.options.className.active);
										$galleryLi.eq(index).addClass(App.options.className.active);
									}
								}
							});
						}
					});
					/*
					$gallery.bind('mouseenter mouseleave', function(event){
						switch(event.type) {
							case 'mouseenter':
							case 'mouseover':
								window.clearTimeout(slideshowMoveTimeout);
								break;

							case 'mouseleave':
							case 'mouseout':
								slideshowMoveTimeout = window.setInterval(slideshowMove, App.options.slideView.delay);
								break;
						}
					});
					*/
					
					$activeIcon		= $('li.active-icon').hide();
					widthCounter	= parseInt($ul.find('li').eq(0).outerWidth(true), 10);
					$activeIcon.css('left', galleryLiActiveIndex * widthCounter);

					slideshowMove = function() {
						var $li, $next, $goTo;

						$li		= $ul.find('li');
						$next	= $li.filter('.' + App.options.className.active).next(':has(a)');
						$goTo	= $next.length ? $next : $li.filter(':first');

						$goTo.find('a').trigger('click');
					};
					window.clearTimeout(slideshowMoveTimeout);
					slideshowMoveTimeout = window.setInterval(slideshowMove, App.options.slideView.delay);
				}
			},

			scroll: function() {
				var $htmlBody = $('html, body'),
					$body = $htmlBody.filter('body'),
					$brief = $('#brief'),
					briefStart = parseInt($brief.css('top'), 10);

				$body.addClass('has-scroll');

				$('#grabs, a.more[href^=#workDetails], body.blog .arrows a').bind('click', function(event){
					var $$, $to,
						href;

					$$		= $(event.target).closest('a');
					href	= $$.attr('href');
					$to		= $(href);

					if($$.is('a') && $to.length) {
						$htmlBody.animate({
							scrollTop: $to.offset().top
						}, $.extend({}, App.options.scroll, {
							complete: function(){
								window.location.hash = href;
							}
						}));

						$$.blur();
						event.preventDefault();
					}
				});

				$(window).bind('scroll', function(event){
					$body.removeClass('fixed').removeClass('absolute').addClass(($htmlBody.scrollTop() > briefStart) ? 'fixed' : 'absolute');
				});
			},

			nav: function() {
				var $scroller, $scrollerUl, $scrollerItem,
					sliderWidth, itemWidth, totalContent;

				$('body').addClass('has-carousel');

				$scroller			= $('#miniGalleryWrapper');
				$scrollerUl			= $scroller.find('ul');
				$scrollerItem		= $scrollerUl.children('li');
				sliderWidth			= $scroller.width();
				itemWidth			= $scrollerItem.eq(0).outerWidth(true);

				$scrollerItem.each(function(i, element) {
					totalContent = i * itemWidth;
					$scrollerUl.css('width', totalContent + itemWidth);
				}).hover(function(event) {
					$(this).find('a').stop().fadeTo(300, 1);
				}, function(event) {
					$(this).find('a').stop().fadeTo(300, App.options.carousel.opacity);
				}).find('a').css('opacity', App.options.carousel.opacity);

				if($scrollerUl.width() > sliderWidth) {
					$scroller.mousemove(function(event) {
						var mouseCoords, mousePercentY,
							destY, thePosA, thePosB;

						mouseCoords		= parseInt(event.pageX - this.offsetLeft, 10);
						mousePercentY	= parseInt(mouseCoords / sliderWidth, 10);
						destY			= parseInt(-(((totalContent - (sliderWidth - itemWidth)) - sliderWidth) * (mousePercentY)), 10);
						thePosA			= parseInt(mouseCoords - destY, 10);
						thePosB			= parseInt(destY - mouseCoords, 10);

						if(mouseCoords === destY){
							$scrollerUl.stop();
						}
						if(mouseCoords > destY){
							$scrollerUl.stop().animate({left: -thePosA}, App.options.carousel.speed, App.options.carousel.easing);
						}
						if(mouseCoords < destY){
							$scrollerUl.stop().animate({left: thePosB}, App.options.carousel.speed, App.options.carousel.easing);
						}
					});
				}
			},

			portfolio: function() {
				var $body, $content, $section, $browse, $overlay,
					content, section;

				$body		= $('body');
				$content	= $('#content');
				$section	= $content.children('div.section');
				$browse		= $section.find('div.folioBrowse');
				$overlay	= $('<div />').addClass('folio-overlay').show();

				content		= {
					height:	parseInt($content.height(), 10),
					width:	parseInt($content.width(), 10)
				};
				section		= {
					height:	parseInt($section.height(), 10),
					width:	parseInt($section.width(), 10)
				};

				$overlay.css({
					height: section.height,
					width: content.width,
					left: -((content.width - section.width) / 2)
				}).hide();
								
				$overlay = $section.append($overlay).find('div.folio-overlay');

				$browse.add($browse.find('li')).bind('mouseover mouseleave click', function(event){
					var $$, $li, $latest, $h2, $a;

					$$		= $(event.target).closest('div.folioBrowse');
					$li		= $(event.target).closest('li');
					$latest	= $(event.target).closest('div.latest');

					switch(event.type) {
						case 'click':
							$a	= $(event.target).closest('a');
							$h2	= $a.closest('h2');
							if ($h2.length === 1) {
								$$.removeClass(App.options.className.hover);
								$body.removeClass('folio-hover');
								$overlay.hide();
								$a.blur();
								event.preventDefault();
							}
							else if ($a.length === 1) {
								window.location = $a.attr('href');
							}
							break;

						case 'mouseover':
						case 'mouseenter':
							$$.add($li).addClass(App.options.className.hover);
							$body.addClass('folio-hover');
							$overlay.show();
							break;

						case 'mouseleave':
						case 'mouseout':
							if($li.length === 1) {
								$li.removeClass(App.options.className.hover);
							}
							else {
								$$.removeClass(App.options.className.hover);
								$body.removeClass('folio-hover');
								$overlay.hide();
							}
							break;
					}
				});
				$overlay.bind('mouseenter mouseover', function(event){
					$browse.removeClass(App.options.className.hover);
					$body.removeClass('folio-hover');
					$overlay.hide();
				});
			},

			tabs: function() {
				// build the tab list, based on html
				$('div.tabs').each(function(i, tabs){
					var $$, $tabs, $list,
						list = [], li = 0;

					$$			= $(tabs);
					$tabs		= $$.find('div.tab');
					$list		= $('<ul />').addClass('tab-list');

					$tabs.each(function(ii, tab){
						var $tab, $heading,
							heading, attr = {};

						$tab		= $(tab);
						$heading	= $tab.children('h2.title');

						heading		 = $heading.text();
						attr.id		 = $tab.attr('id');
						attr.active	 = attr.id;
						attr.active	+= ($tab.is('.' + App.options.className.active)) ? ' ' + App.options.className.active : '';

						list[li++]	= '<li class="' + attr.active + '">';
						list[li++]	= '<a href="#' + attr.id + '">';
						list[li++]	= heading;
						list[li++]	= '</a>';
						list[li++]	= '</li>';
					});

					$list.append(list.join('')).insertBefore($tabs.filter(':first'));
				});

				// trigger the tab changes
				$('ul.tab-list > li > a, a.tab-trigger').live('click.tabs', function(event){
					var $$, $li,
						href, id, $div;

					$$ = $(event.target).closest('a');
					
					if($$.is('a')) {
						href		= $$.attr('href');
						id			= href.match(/#(.+)/)[1].replace('#', '');
						$div		= $('#' + id);
						$li			= $('a[href$=#' + id + ']').closest('li');

						if($div.length === 1 && $div.is(':not(.' + App.options.className.active + ')')) {
							$div.add($li).addClass(App.options.className.active)
								.siblings().removeClass(App.options.className.active);

							$$.addClass(App.options.className.active);
							$li.siblings().children('a').removeClass(App.options.className.active);
						}

						$$.blur();
						event.preventDefault();
					}
				});
				
				//Trigger URL anchors
				var anchorValue, anchor = document.location.hash, handlers = [];
				if(anchor) {
					anchorValue = anchor.match(/#(.+)/)[1].replace('#', '');
					$('ul.tab-list > li.'+ anchorValue +' > a').trigger('click');
				}
			
				
			},

			map: function() {
				$('div.contactBox').each(function(i, div){
					var $$, $map, $img, $vcard, $title,
						$getDirections, $directions, $form, $googleMap,
						id, height, width, src, query, center,
						latlng, options, map, marker, directions,
						formFields = [], f = 0;

					$$		= $(div);
					$map	= $$.find('div.map');
					$vcard	= $$.find('div.vcard');
					$title	= $$.find('h2');
					$img	= $map.find('img');
					id		= $$.attr('id');
					src		= $img.attr('src');
					height	= $img.attr('height');
					width	= $img.attr('width');
					query	= $.query(src);
					center	= query.center.split(',');

					if(typeof google !== 'undefined') {
						directions = {
							service: new google.maps.DirectionsService(),
							display: new google.maps.DirectionsRenderer(),
							current: null
						};

						// directions
						formFields[f++] = '<fieldset>';
						formFields[f++] = '<legend>Get directions</legend>';
						formFields[f++] = '<div>';
						formFields[f++] = '<label for="' + id + '-origin">From</label>';
						formFields[f++] = '<input name="origin" id="' + id + '-origin" type="text" />';
						formFields[f++] = '</div>';
						formFields[f++] = '<div>';
						formFields[f++] = '<label for="' + id + '-destination">To</label>';
						formFields[f++] = '<p class="destination">' + $title.text() + '</p>';
						formFields[f++] = '<input type="hidden" name="destination" value="' + query.center + '" />';
						formFields[f++] = '</div>';
						formFields[f++] = '<input type="submit" value="Calculate" class="submit" />';
						formFields[f++] = '</fieldset>';

						$form = $('<form />').attr({action: '#', method: 'post'}).append(formFields.join('')).hide();
						$directions = $('<div />').addClass('directions').hide().appendTo($map);
						$getDirections = $('<div />').addClass('get-directions').append(
							$('<h3 />').append(
								$('<a />').text('Get directions').attr('href', '#directions').append(
									$('<span />').text('Close').addClass('close')
								)
							)
						).append($form);

						$vcard.append($getDirections).delegate('a', 'click', function(event){
							var $$, $div, $form, $container;

							$$			= $(event.target).closest('a');
							$div		= $$.closest('div.get-directions');
							$form		= $div.find('form');
							$container	= $div.closest('div.contactBox');

							if($$.length) {
								if($form.is(':hidden')) {
									$div.add($container).addClass(App.options.className.active);
									$form.show();
								}
								else {
									$div.add($container).removeClass(App.options.className.active);
									$form.hide().trigger('reset');
								}

								$$.blur();
								event.preventDefault();
							}
						});

						// submit the form, calculate the directions
						$form.bind('submit reset', function(event){
							var $$, $origin, $destination, options;

							$$				= $(event.target).closest('form');
							$origin			= $$.find('input[name="origin"]');
							$destination	= $$.find('input[name="destination"]');

							options = $.extend({}, App.options.map.directions, {
								origin: $.trim($origin.val()),
								destination: $.trim($destination.val()),
								travelMode: google.maps.DirectionsTravelMode.DRIVING,
								unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL
							});

							if(event.type === 'reset') {
								directions.current = null;
								$directions.slideUp(App.options.map.speed);
								$origin.val('');
							}
							else {
								if(directions.current !== options.origin) {
									$directions.slideUp(App.options.map.speed);
								}
								if(options.origin.length > 0 && directions.current !== options.origin) {
									$origin.removeClass(App.options.className.error);
									directions.current = options.origin;
									directions.service.route(options, function(result, status) {
										if(status == google.maps.DirectionsStatus.OK) {
											directions.display.setDirections(result);
											$directions.slideDown(App.options.map.speed);
										}
										else {
											$origin.addClass(App.options.className.error);
										}
									});
								}
								else if(options.origin.length === 0) {
									$origin.addClass(App.options.className.error);
								}
							}

							$$.find('input:submit').blur();
							event.preventDefault();
						}).find('input[name="origin"]').bind('keypress', function(event){
							$(event.target).removeClass(App.options.className.error);
						});

						// map
						$googleMap	= $img.replaceWith('<div />').end().children().eq(0).css({height: height, width: width});
						latlng		= new google.maps.LatLng(parseFloat(center[0]), parseFloat(center[1]));
						options		= {
							zoom:		parseInt(query.zoom, 10),
							center:		new google.maps.LatLng(latlng.lat(), latlng.lng()),
							mapTypeId:	google.maps.MapTypeId.ROADMAP,
							mapTypeControl: false,
							navigationControlOptions: {
								style:	google.maps.NavigationControlStyle.SMALL
							},
							marker: {
								image: new google.maps.MarkerImage('/images/layout/contact/logo.png',
									new google.maps.Size(155, 85),
									new google.maps.Point(0,0),
									new google.maps.Point(50, 85)
								),
								shadow: new google.maps.MarkerImage('/images/layout/contact/shadow.png',
									new google.maps.Size(155, 85),
									new google.maps.Point(0,0),
									new google.maps.Point(50, 85)
								)
							}
						};
						
						map		= new google.maps.Map($googleMap.get(0), options);
						marker	= new google.maps.Marker({
							position:	latlng,
							map:		map,
							icon:		options.marker.image,
							shadow:		options.marker.shadow
						});
						directions.display.setMap(map);
						directions.display.setPanel($directions.get(0));
					}
				});
			},

			adRotate: function() {
				if($.fn.cycle) {
					$('ul.adverts').cycle();
				}
			},
			
			tracking: function() {
				var ids = ['#ourServices', '#recentWork', '#ourBlog', '#brief', '#workCon', '#headGallery'],
					selector = ids.join(','),
					isHome = $('body').is('.home');
					
				$(selector).bind('click', function(event){
					var $$, $parent, type;
						
					$$		= $(event.target).closest('a');
					$parent	= $$.closest(selector);
					type	= $parent.attr('id');

					//event.preventDefault();

					if($$.length) {
						if($$.is('a[rel^="external"]')) {
							return true; // stop these tracking, but continue to the other events
						}
						
						switch(type) {
							case 'ourServices':
								//debug('ourServices - ' + $$.attr('title'));
								_gaq.push(['_trackEvent', 'HomePage', $$.attr('title')]);
								break;

							case 'recentWork':
								//debug('recentWork - ' + ((isHome) ? 'HomePage' : 'Main categories') + ' - ' + $$.attr('title'));
								_gaq.push(['_trackEvent', (isHome) ? 'HomePage' : 'Main categories', 'Featured project', $$.attr('title')]);
								break;

							case 'ourBlog':
								//debug('blog - ' + $$.attr('title'));
								_gaq.push(['_trackEvent', 'HomePage', 'Blog post', $$.attr('title')]);
								break;

							case 'brief':
								//debug('Send us a brief');
								_gaq.push(['_trackEvent', 'Send us a brief']);
								break;

							case 'workCon':
								//debug('work - ' + $$.attr('title'));
								_gaq.push(['_trackEvent', 'Work', $$.attr('title')]);
								break;

							case 'headGallery':
								if($$.closest('#topPics').length) {
									//debug('banner - ' + $$.find('img').attr('alt'));
									// only track the actual banner click, not shadow or pagination
									_gaq.push(['_trackEvent', 'Banners', $$.find('img').attr('alt')]);
									window.location = $$.closest('a').attr('href');
								}
								break;
						}
					}
				});
			},

			liveChat: function () {
				if (!$.fn.multiswipe) {
					var html = '';
					html += '<div id="live-chat" class="fixed">';

					html += '<div id="lpButDivID-1292249597577"></div>';
					html += '<script src="https://server.iad.liveperson.net/hc/13183292/?cmd=mTagRepstate&site=13183292&buttonID=7&divID=lpButDivID-1292249597577&bt=3&c=1"></script>';

					//html += '<a href="https://livechat.boldchat.com/aid/5479115292886333021/bc.chat?cwdid=6876566096872413447" target="_blank" onclick="window.open((window.pageViewer && pageViewer.link || function(link){return link;})(this.href + (this.href.indexOf(\'?\')>=0 ? \'&amp;\' : \'?\') + \'url=\' + escape(document.location.href)), \'Chat1398299764716826458\', \'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=640,height=480\');return false;">Live Chat</a>';

					html += '</div>';

					$('#brief').after(html);
				}
			},

			mobile: function () {
				if ($.fn.multiswipe) {
					$('div.fixed').remove();
					$('body').addClass('mobile');
					$('#headGallery').multiswipe({
						threshold:	70,
						fingers:	2,
						swipeLeft:	function (event) {
							var $lis, $li, duration;
							duration	= App.options.slideView.duration;
							App.options.slideView.duration = parseInt(App.options.slideView.duration / 2, 10);
							$lis		= $('#headGallery').find('ul.ui-pagination li:not(.active-icon)');
							$li			= $lis.filter('li.active').next(':not(.active-icon)');
							$li			= ($li.length === 0) ? $lis.filter('li:first') : $li;
							$li.find('a').trigger('click');
							App.options.slideView.duration = duration; // reset the duration
						},
						swipeRight:	function (event) {
							var $lis, $li, duration;
							duration	= App.options.slideView.duration;
							App.options.slideView.duration = parseInt(App.options.slideView.duration / 2, 10);
							$lis		= $('#headGallery').find('ul.ui-pagination li:not(.active-icon)');
							$li			= $lis.filter('li.active').prev(':not(.active-icon)');
							$li			= ($li.length === 0) ? $lis.filter('li:last') : $li;
							$li.find('a').trigger('click');
							App.options.slideView.duration = duration; // reset the duration
						}
					});

				}
			}

		};

		/**
		* READY!
		* @desc Document ready, load all the app functions
		*/
		jQuery(document).ready(function($) {
			var $body = $('body').addClass('has-jquery');

			/**
			 * Overlay
			 */
			$('<div />').addClass(App.options.className.overlay).appendTo($body);

			App.flash();
			App.slideView();
			App.scroll();
			App.nav();
			App.portfolio();
			App.tabs();
			App.adRotate();
			App.tracking();
			App.mobile();
			App.liveChat();

			if($('body').is('.address')) {
				App.map();
			}

			$('a[rel^="external"]').live('click', function(event){
				var href = $(event.target).closest('a').attr('href');
				window.open(href);
				event.preventDefault();
			});
			
			/**
			 * Captcha Reload
			 */
			$('.verify span').append(
				$('<a />').attr('href', '#').html('Try another').bind('click', function(event){
					var $$, $img, $closest;

					event.preventDefault();

					$$			= $(this);
					$closest	= $$.closest('.verify');
					$img		= $('<img id="security-code" src="/captcha/verify.jpg?s=' + Math.random()  + '" alt="" title="" />');
					
					if($.browser.msie && $.browser.version == 6) {
						// IE6 fix
						if(window.confirm('Are you sure that you wish to generate a new verification image?')) {
							$closest.find('img').remove();
							$(this).parent('img', '.verify').remove();
							$closest.append($img);
						}
					}
					else {
						$closest.find('img').remove();
						$(this).parent('img', '.verify').remove();
						$closest.append($img);
					}
				})
			);
			
			$('.verify2 span').append(
				$('<a />').attr('href', '#').html('Try another').bind('click', function(event){
					var $$, $img, $closest;

					event.preventDefault();

					$$			= $(this);
					$closest	= $$.closest('.verify2');
					$img		= $('<img id="security-code" src="/captcha/verify.jpg?s=' + Math.random()  + '" alt="" title="" />');
					
					if($.browser.msie && $.browser.version == 6) {
						// IE6 fix
						if(window.confirm('Are you sure that you wish to generate a new verification image?')) {
							$closest.find('img').remove();
							$(this).parent('img', '.verify2').remove();
							$closest.append($img);
						}
					}
					else {
						$closest.find('img').remove();
						$(this).parent('img', '.verify2').remove();
						$closest.append($img);
					}
				})
			);

			if($.fn.validate) {
				//inline validation
				function isInteger(s) {
					for (var i = 0; i < s.length; i++) {
						// Check that current character is number.
						var c = s.charAt(i);
						if (((c < "0") || (c > "9"))) {
							return false;
						}
					}
					// All characters are numbers.
					return true;
				}
				
				function stripCharsInBag(s, bag) {
					var returnString = '';
					// Search through string's characters one by one.
					// If character is not in bag, append to returnString.
					for (var i = 0; i < s.length; i++) {
					// Check that current character isn't whitespace.
						var c = s.charAt(i);
						if (bag.indexOf(c) == -1) {
							returnString += c;
						}
					}
					return returnString;
				}			

				$.validator.addMethod('phone', function(phone_number, element) {
					var digits = "0123456789";
					var phoneNumberDelimiters = "()- ext.";
					var validWorldPhoneChars = phoneNumberDelimiters + "+";
					var minDigitsInIPhoneNumber = 10;
					s=stripCharsInBag(phone_number,validWorldPhoneChars);
					return this.optional(element) || isInteger(s) && s.length >= minDigitsInIPhoneNumber;
				}, jQuery.format("This field must contain a valid phone number"));

				$("#onlineform, #contactform, #contact-brief-quick form").validate($.extend({}, {
					submitHandler: function(form){
						form.submit();
					},
					highlight: function(element, errorClass, validClass) {
						$(element).closest('div').addClass(errorClass).removeClass(validClass);
					},
					unhighlight: function(element, errorClass, validClass) {
						$(element).closest('div').removeClass(errorClass).addClass(validClass);
					}
				}, App.options.validate));
			}
			//END inline validation
			
		});

		// IE 6 hover fix
		if(document.all && document.getElementById) {
			window.onload = App.hover;
		}

		// Flash External Interface
		$.fn.callFlash = function(callback, variables, prefix) {
			var $$, dom, data = false;
			$$ = $(this);
			if($$.length === 1) {
				dom = $$.get(0);
				if($$.attr('id').length > 0) {
					dom = document.getElementById($$.attr('id'));
				}
				if(typeof prefix === 'string') {
					callback = prefix + callback.charAt(0).toUpperCase() + callback.substr(1);
				}
				if(typeof dom !== 'undefined' && typeof dom[callback] === 'function') {
					data = dom[callback](variables);
				}
			}
			return data;
		};

		jQuery.query = function(s) {
			var r = {};
			if(s) {
				var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
				q = q.replace(/\&$/, ''); // remove the trailing &
				jQuery.each(q.split('&'), function() {
					var splitted = this.split('='),
						key = splitted[0],
						val = splitted[1];

					// convert booleans
					if(val == 'true') {val = true;}
					if(val == 'false') {val = false;}

					// ignore empty values
					if(typeof val !== 'undefined' && (typeof val === 'number' || typeof val === 'boolean' || val.length > 0)) {
						r[key] = val;
					}
				});
			}
			return r;
		};
		
		// slidyness for evolving web
		if($('body').hasClass('evolvingweb')) {
		
			var jumpPos, jumpText;
			
			$('.jumpbox ul').css('overflow', 'hidden'); // fixes jumping in slidetoggle
			
			$('.jumpbox').each(function() {
				if($('ul', this).size() > 0) {
				
					jumpText = $('p:first', this).text();
					jumpPos = jumpText.indexOf('.');
					jumpText = jumpText.slice(0,jumpPos+1) + '<span class="hide">' + jumpText.slice(jumpPos+1) + '</span>';
					$('p:first', this).html(jumpText);		
					
					$('ul, span.hide, p:not(:first)', this).hide();
					
					$(this).append('<p><a href="#" class="text readmore">Read more</a></p>');
					
					$(this).find('a.readmore').click(function() {
						$(this).parents('.jumpbox').find('ul, p:not(:first):not(:last)').toggle();
						
						if($(this).text() == 'Read more') {
							$(this).parents('.jumpbox').find('span.hide').css('display', 'inline');
							$(this).text('Hide content');
						} else {
							$(this).parents('.jumpbox').find('span.hide').css('display', 'none');
							$(this).text('Read more');
						}
						
						return false;
					});
				
				}
			});
			
		}
		
	// end of jQuery closure
	}(jQuery));
	
	
	jQuery(document).ready(function($) {
	
		var slider = $('#headLargeGallery ul#topPics').bxSlider({
			auto : false,
			pager : true,
			easing: 'easeInOutExpo',
			speed: 1000,
			onBeforeSlide: function(currentSlide, totalSlides, currentSlideHtmlObject){
				var link = $('#headLargeGallery .shadow a');
				if(currentSlide == 5){
					$('div.banner-phone').hide();
					setTimeout(function() {
						$('div.banner-phone').fadeIn();
					}, 1000);
				}else{
					$('div.banner-phone').fadeOut('fast');
				}
			},
			onAfterSlide: function(currentSlide, totalSlides, currentSlideHtmlObject){
				
				var bannerHref = currentSlideHtmlObject.find('a').attr('href');
				var link = $('#headLargeGallery .shadow a');
				
				if(bannerHref != '#'){
					link.attr('href',bannerHref);
					link.show();
					link.click(function(){
						document.location.href = bannerHref;
						return false;
					});
					
					link.unbind('click');
					
				}else{
					link.attr('href','#');
					link.click(function(){
						slider.goToNextSlide();
						return false;
					});
				}
			}
		});

	});

}
