/**
 * Primary Navigation
 */
$(document).ready(function() {
	var s = $("ul.sf-menu").size();
	if(s) {
		var fish = $("ul.sf-menu").supersubs({
			minWidth: 12,
			maxWidth: 27,
			extraWidth: 1
		}).superfish();
		if(fish.bgIframe) {
			fish.find('ul').bgIframe({opacity:false});
		}
	}
});
/**
 * Internet Explorer will crash if we don't remove flash
 * objects from the DOM on unload. Fuck me IE is shit.
 */
$(document).ready(function() {
	if($.browser.msie) {
		var setRemoveCallback = function() {
			__flash__removeCallback = function(instance, name) {
				if(instance) {
					instance[name] = null;
				}
			};
			window.setTimeout(setRemoveCallback, 10);
		};
		setRemoveCallback();
	}
});
/**
 * Impact Tabs
 */
$(function() {
	var s = $('ul.impactTabControl').size();
	if(s) {
		$("ul.impactTabControl").tabs("div.impactTabPane", {
			effect: 'fade',
			fadeOutSpeed: 'slow',
			rotate: true
		}).slideshow({
			autoplay: true,
			autopause: true,
			interval: 5000
		});
	}
});
/**
 * Scrollables
 */
$(function() {
	var s = $("#homeScroller").size();
	if(s) {
		$("#homeScroller").scrollable({
			size: 4,
			items: '.scrollable',
			clickable: false,
			keyboardSteps: 1
		}).circular();
	}
});
/**
 * Project Testimonials
 */
$(function() {
	var e = $('div.testimonials').size();
	if(e) {
		$('div.testimonials h3.testimonialHeader').click(function(evt) {
			$('div.testimonialWrapper').toggle('normal');
			$('p.testimonialTeaser').toggle('normal');
		});
		$('div.testimonials p.testimonialTeaser').click(function(evt) {
			$('div.testimonialWrapper').toggle('normal');
			$('p.testimonialTeaser').toggle('normal');
		});
	}
});
/**
 * Lightboxes
 */
$(function() {
	var e = $('.lbThumbnailContainer li').size();
	if(!e) {
		return;
	}
	var scroller = $('.lbThumbnailContainer').serialScroll({
		items: 'li',
		prev: 'div.lbPrev',
		next: 'div.lbNext',
		jump: false,
		step: 2, // Scroll two at a time
		cycle: false,
		exclude: 2, // Don't scroll to last two items
		onBefore: function(evt, target, scrolled, collection, pos) {
			if(pos == 0) {
				// Disable left button
				$("div.lbPrev").addClass('disabled');
			} else {
				$('div.lbPrev').removeClass('disabled');
			}
			if(pos == ( collection.size() - 3)) { // 3 = zero indexed array so -1 then -2 for 'exclude' option
				// Disable left button
				$("div.lbNext").addClass('disabled');
			} else {
				$('div.lbNext').removeClass('disabled');
			}
		}
	});
	$('.lbThumbnailContainer a[rel="lightbox"]').colorbox({
		inline: true,
		href: function() { return $(this).attr('href'); },
		innerWidth: 640
	});
	$('.lbContent .lbImage').each(function() {
		var me = $(this);
		$(this).qtip({
			content: me.parent().children('.lbInfo').html(),
			show: 'mouseover',
			hide: 'mouseout',
			position: {
				corner: {
					target: 'topMiddle',
					tooltip: 'topMiddle'
				}
			},
			style: {
				width: 640,
				background: "url('/images/colorbox/overlay.png') left top repeat",
				border: 'none',
				color: '#fff',
				opacity: 0.4
			}
		});
	});
	$('.lbContent .lbVideo').each(function() {
		$(this).qtip({
			content: $(this).parent().children('.lbInfo').html(),
			show: 'mouseover',
			hide: 'mouseout',
			position: {
				corner: {
					target: 'topMiddle',
					tooltip: 'topMiddle'
				}
			},
			style: {
				width: 640,
				background: "url('/images/colorbox/overlay.png') left top repeat",
				border: 'none',
				color: '#fff',
				opacity: 1
			}
		});
	});
});

/**
 * Contact Breakout Box
 */
$(function() {
	var e = $('div.contactBreakout').size();
	if(!e) {
		return;
	}
	$('div.contactBreakout span.phone').qtip({
		show: 'click',
		hide: 'unfocus',
		position: {
			target: $('body'),
			corner: {
				target: 'center',
				tooltip: 'center'
			}
		},
		style: {
			name: 'dark',
			border: {
				width: 2,
				radius: 15,
				color: '#000'
			},
			tip: {
				color: '#fff'
			},
			width: {
				max: 900
			},
			background: '#000',
			classes: {
				tooltip: 'qtipPhone'
			}
		}
	});
});
/**
 * Home Page Contact Box
 */
$(function() {
	var e = $('#homePageContact').size();
	if(!e) {
		return;
	}
	$('#homePageContact a').qtip({
		content: {
			text: false
		},
		position: { target: 'mouse' }
	});
});
/**
 * Colorbox Initialisation for Gallery/Tagged Photo Thumbnails
 */
$(function() {
	var e = $('.galleryThumbnail').size();
	if(e) {
		$('.galleryThumbnail a[rel="colorbox"]').colorbox({
			inline: true,
			href: function() { return $(this).attr('href'); },
			innerWidth: 640
		});
	}
	var e = $('.videoThumbnail').size();
	if(e) {
		$('.videoThumbnail a[rel="colorbox"]').colorbox({
			inline: true,
			href: function() { return $(this).attr('href'); },
			innerWidth: 640
		});
	}
	
});
/**
 * Tag cloud animation
 */
$(function() {
	var e = $('div.tagCloud ul li').size();
	if(!e) {
		return;
	}
	/**
	 * This is broken on IE at least up to v8 so far. Screw IE
	 */
	if($.browser.msie) return;
	
	$.each($('div.tagCloud ul li a'), function() {
		
		var color = $(this).css('color');
		var pr = parseFloat($(this).css('paddingRight'));
		var pt = parseFloat($(this).css('paddingTop'));
		var pl = parseFloat($(this).css('paddingLeft'));
		var pb = parseFloat($(this).css('paddingBottom'));
		var fs = parseFloat($(this).css('fontSize'));
		
		$(this).mouseenter(function() {
			var fi = fs + 10;
			$(this).animate({
				fontSize: fs * 1.1,
				color: '#000'
			}, 250);
		});
		$(this).mouseleave(function() {
			$(this).animate({
				fontSize : fs,
				color: color
			}, 250);
		});
	});
});
/**
 * Head Search Box cancel button
 */
$(function() {
	var len = $('a#headSearchCancel').size();
	if(!len) {
		return;
	}
	$('a#headSearchCancel').click(function(evt) {
		evt.preventDefault();
		$('input#headSearchField').val('');
	});
	
});
/**
 * Tertiary Project Navigation
 */
$(function() {
	
	if(!$('ul.tertiaryNav').size()) {
		return;
	}
	
	var topLevel = $('ul.tertiaryNav > li');
	
	jQuery.each(topLevel, function(objKey, listItem) {
		var li = $(listItem);
		var active = li.hasClass('active');
		var link = li.children('a'); // There can only be one because we are at the top level. All others will be inside another ul
		$kids = li.children('ul');
		/**
		 * Add the anchor class to the parent list item
		 * so we don't have to use adjacent sibling selectors in CSS
		 * therby making styles work for all browsers
		 */
		if(link.attr('class')) {
			li.addClass(link.attr('class'));
		}
		
		var isParent = $kids.size() >= 1; // only counts 1st level of child ul's not deeper nested ones
		// Disclose active branch
		if(active && isParent) {
			$kids.css('display', 'block');
		}
		if(isParent) {
			li.children('a').css('background-position', 'right top');
		}
		/**
		 * Add hover animation to all parents
		 */
		var intentConfig = {
			sensitivity: 5,
			interval: 100,
			over: function() { $(this).children('ul').slideToggle(500); },
			timeout: 1000,
			out: function() { $(this).children('ul').slideToggle(2000); }
		};
		if(isParent && !active) {
			li.hoverIntent(intentConfig);
		}
	});
});
/**
 * Tag Search Result Tabbed Interface
 */
$(function() {
	if(!$('#tagResultsNav').size()) {
		return;
	}
	$.localScroll.defaults.axis = 'x';
	$.localScroll.hash({
		target: '#tagResults', // Could be a selector or a jQuery object too.
		queue:true,
		duration:1500
	});
	$.localScroll({
		target: '#tagResults'
	});
	$('#tagResultsNav li a').eq(0).addClass('selected');
	$('#tagResultsNav a').click(function() {
		$('#tagResultsNav a').each(function() {
			if($(this).hasClass('selected')) {
				$(this).removeClass('selected');
			}
		});
		$(this).addClass('selected');
	});
});
/**
 * Mini Project Google Maps
 */
$(function() {
	if(!$('#miniProjectMap').size()) {
		return '';
	}
	var container = $('div.miniProjectMap');
	var lat = container.find('span.latitude').text();
	var lng = container.find('span.longitude').text();
	var projectId = container.find('span.projectId').text();
	var name = container.find('span.title').text();
	
	var initialLatLng = new google.maps.LatLng(lat, lng);
	var myOptions = {
		zoom: 6,
		center: initialLatLng,
		mapTypeId: google.maps.MapTypeId.HYBRID,
		disableDefaultUI: true, // Disable Default UI
		navigationControl: true, // The disc with compass click controls and Zoom Bar
		navigationControlOptions: {
			style: google.maps.NavigationControlStyle.SMALL, // Just zoom in/out buttons
			position: google.maps.ControlPosition.TOP_LEFT
		},
		mapTypeControl: false, // We'll add custom map type changers outside map viewport
		scaleControl: false // Shows a scale bar/ruler
	};
	var map = new google.maps.Map(document.getElementById('miniProjectMap'), myOptions);
	
	var markerImageUrl = "../images/maps/markers/" + projectId + ".png";
	var markerShadow = '../images/maps/shadow.png';
	
	var image = new google.maps.MarkerImage(
		markerImageUrl,
		new google.maps.Size(74, 83), // Size
		new google.maps.Point(0,0), // Origin
		new google.maps.Point(37, 83) // Anchor
	);
	
	var shadow = new google.maps.MarkerImage(
		markerShadow,
		new google.maps.Size(183, 83), // Size
		new google.maps.Point(0,0), // Origin
		new google.maps.Point(37, 83) // Anchor
	);
	
	var shape = {
		coord: [0,0, 0,53, 23,53, 37,83, 51,53, 74,53, 74,0, 0],
		type: 'poly'
	};
	
	var marker = new google.maps.Marker({
		map: map,
		shadow: shadow,
		icon: image,
		shape: shape
	});
	marker.setPosition(initialLatLng);
	marker.setTitle(name);
	
	map.panBy(0, -20); // Pan down slightly so marker is within the viewport
	
});
/**
 * FAQ List Sliders
 */
$(function() {
	if(!$('#faqList').size()) {
		return;
	}
	$('#faqList dt').each(function() {
		var dt = $(this);
		var dd = dt.next('dd');
		dt.click(function() {
			if(dt.hasClass('clicked')) {
				dd.hide();
				dt.removeClass('clicked');
			} else {
				dd.show();
				dt.addClass('clicked');
			}
		});
		dt.hoverIntent({
			over: function() {
				if(!dt.hasClass('clicked')) {
					if(dd.css('display') == 'none') {
						dd.slideDown();
					}
				}
			},
			out: function() {
				if(!dt.hasClass('clicked')) {
					if(dd.css('display') == 'block') {
						dd.slideUp();
					}
				}
			}
		});
	});
});
/**
 * Project Calculator
 */
$(function() {
	if(!$('#projectCalculator').size()) {
		return;
	}
	
	/**
	 * Add Click function for 'Add Project link' so
	 * we can add additional projects to the trip
	 */
	$('#pcAddProject a').click(function() {
		pcLoaderStart();
		addProjectToCalculator();
	});
	
	$('#doCalculate').click(function() {
		pcLoaderStart();
		updateCalculatorPrice();
	});
	
	addHandlersToPcControls();
	
	$('#pcLoading').bind('ajaxSend', function() {
		//pcLoaderStart();
	}).bind('ajaxComplete', function() {
		//$(this).fadeOut();
	});
	
});
function pcLoaderStart() {
	
	$('#pcErrors').empty().hide();
	$('#pcResult').empty().hide();
	
	var w = $('#projectCalculator').outerWidth();
	var h = $('#projectCalculator').outerHeight();
	var pos= $('#projectCalculator').position();
	return $('#pcLoading').css({
		width: w,
		height: h,
		top: pos.top,
		left: pos.left
	}).fadeIn();
}
function updateCalculatorPrice() {
	$updateDiv = $('#pcResult');
	$calcUrl = '/project/calculate-price?format=json';
	$.ajax({
		async: true,
		type: 'POST',
		data: $('#projectCalculatorForm').serializeArray(),
		dataType: 'json',
		url: $calcUrl,
		success: function(responseData, status, xhr) {
			$('#pcLoading').hide();
			var data = responseData.response;
			if( data.errors.length && data.errors.length > 0) {
				var html = '';
				for(error in data.errors) {
					var html = html + "\n" + '<p class="error">' + data.errors[error] + '</p>';
				}
				$('#pcErrors').html(html).fadeIn();
			} else {
				var html = $('<p class="price"><span>Estimate Total: </span><strong>' + data.price.toFixed(2) + '</strong> <em>' + data.currencyCode + '</em></p>');
				$('#pcResult').html(html).fadeIn();
				$('#pcResultText').fadeIn();
			}
		},
		error: function(xhr, status, error) {
			$('#pcLoading').hide();
			$('#pcErrors').html('<p class="error">Sorry, an error occurred. Please try reloading the page</p>').fadeIn();
		}
	});
}
function addHandlersToPcControls() {
	$("input[name*='pcData'][type='text']").each(function() {
		if( ! $(this).hasClass('gotHandler')) {
			$(this).blur(function() {
				var min = 1;
				var max = null;
				if($(this).attr('max') || $(this).attr('min')) {
					if($(this).attr('max')) {
						max = parseInt($(this).attr('max'));
					}
					if($(this).attr('min')) {
						min = parseInt($(this).attr('min'));
					}
				} else {
					var parts = $(this).attr('name').split('-');
					var index = parts[1];
					var selector = "select[name='pcData-" + index + "-project_id']";
					$select = $(selector);
					var $option = $select.children(':selected');
				
					if($option) {
						if($option.attr('min')) {
							min = parseInt($option.attr('min'));
						}
						if($option.attr('max')) {
							max = parseInt($option.attr('max'));
						}
					}
					
				}
				
				var value = $(this).val();
				
				if( value == '' || !value.match(/\d+/) ) {
					$(this).val(min);
				}
				
				value = parseInt(value);
				if(max && (value > max)) {
					$(this).val(max);
				}
				if(value < min) {
					$(this).val(min);
				}
			});
			$(this).addClass('gotHandler');
		}
	});
	
	
}
function addProjectToCalculator() {
	$.ajax({
		async: true,
		type: 'POST',
		data: $('#projectCalculatorForm').serializeArray(),
		dataType: 'html',
		url: '/project/project-select',
		success: function(respText, status, xhr) {
			$('#pcLoading').hide();
			if(respText) {
				var html = $(respText);
				html.insertBefore('#pcAddProject');
				html.fadeIn();
				addHandlersToPcControls();
				addHandlersForProjectRemove();
			}
		},
		error: function(xhr, textStatus, error) {
			$('#pcLoading').hide();
			$('#pcErrors').html('<p class="error">Sorry, an error occurred. Please try reloading the page</p>');
			resp = '';
		}
	});
}
function addHandlersForProjectRemove() {
	$('a.pcRemoveProject').each(function() {
		if( ! $(this).hasClass('gotHandler')) {
			$(this).click(function() {
				$(this).parent('div.projectCalculatorChoice').remove();
				pcLoaderStart();
				updateCalculatorPrice();
			});
			$(this).addClass('gotHandler');
		}
	});
}
/**
 * Application Form
 */
$(function() {
	if(!$('#appForm').size()) {
		return;
	}
	$form = $('#appForm');
	$('#appForm input[title], #appForm select[title], #appForm textarea[title]').qtip({
		content: {
			text: false
		},
		position: {
			corner: {
				target: 'rightMiddle',
				tooltip: 'leftMiddle'
			}
		},
		style: {
			name: 'dark',
			tip: 'leftMiddle'
		}
	});
});

/**
 * Footer Logos
 */
$(function() {
	if(!$('#footerLogos').size()) {
		return;
	}
	$('.footLogo').qtip({
		content: {
			text: false
		},
		position: {
			corner: {
				target: 'topMiddle',
				tooltip: 'bottomMiddle'
			}
		},
		style: {
			name: 'dark',
			tip: 'bottomMiddle'
		}
	});
});

