/**
 * Global JS
 *
 * The custom JavaScript used for the added functionality.
 * Created for Backstop.org.uk
 *
 * @author Dan Hensby <dan@betterbrief.co.uk>
 * @version 0.1
 * @copyright Copyright (c) 2010, Better Brief LLP
 *
 */

//Load jQuery
google.load("jquery", "1.6.2");
//load maps

function loadMap(callback) {
	google.load("maps", "3", {
		callback: callback,
		"other_params" : "sensor=false"
	});
}

function initMap(){
	var mapElement = document.getElementById("MapCanvas");
	if (mapElement){
		var latlng = new google.maps.LatLng(51.46145, -0.21507),
			center = new google.maps.LatLng(51.46083, -0.21537),
			myOptions = {
				zoom: 15,
				center: center,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				navigationControl: true,
				mapTypeControl: false
			},
			map = new google.maps.Map(mapElement, myOptions),
			marker = new google.maps.Marker({
				position: latlng,
				map: map,
				title:"Backstop Support Ltd"
			});
	}
}

// effectively 'on document ready'
google.setOnLoadCallback(function() {

	(function($) {

		//Set variables for fade speeds of the hover background colours
		var fadeInSpeed = 250,
			fadeOutSpeed = 500;

		//add a class to body so we can disble standard css
		$('body').addClass('js');

		/**
		 * ALL PAGES
		 */
		//put the search label into the search box
		// get the search box
		var $searchBox = $('#SearchForm_SearchForm_Search');
		//get its label
		var $searchLabel = $('label[for=SearchForm_SearchForm_Search]');
		//get the label's value
		var defaultValue = $searchLabel.text();
		//hide the label
		$searchLabel.hide();
		//set the search box value to the label text
		if (!$searchBox.val()) {
			$searchBox.val(defaultValue);
		}

		$searchBox.focus(function() {
			//if it is the default value, remove it
			if (this.value == defaultValue) {
				this.value = '';
			}
		}).blur(function() {
			//if no value, add the default value back
			if (!this.value) {
				this.value = defaultValue;
			}
			//$(this).animate({backgroundColor: '#f5f5f5'});
		});

		//On all input boxes we will make the background colour fade in and out
		/*$('input').focus(function() {
			$(this).animate({backgroundColor: '#fff'});
		}).blur(function() {
			$(this).animate({backgroundColor: '#f5f5f5'});
		});*/

		//hover effect for icon lists
		var $icons = $('.icons li');
		//set the cursor to a pointer for the whole list item
		$icons.css('cursor','pointer').hover(function() {
			//underline the anchor text and animate the hover effect
			$('a',this).css('text-decoration','underline').parents('li').stop().animate({
				backgroundColor:"#f5f5f5"
			},fadeInSpeed);
		}, function() {
			//remove the underline on the anchor and fade out the hover effect
			$('a',this).css('text-decoration','none').parents('li').stop().animate({
				backgroundColor:"#fff"
			},fadeOutSpeed);
		}).click(function() {
			//navigate to the anchor location when clicking the list item
			window.location = $('a',this).attr('href');
		});

		//hover effect for lastest news items
		//AIM: The aim is to allow the user to click on the whole news item
		//	and go to the last mentioned link (read more...) or a bit.ly.
		//	this is because there could be more than one link in a tweet
		var $latestNews = $('.latestNews li');
		//set the cursor to a pointer for the whole list item
		$latestNews.css('cursor','pointer').hover(function() {
			//make the LAST anchor underline and animate hover effect
			$(this).children('a:last').css('text-decoration','underline').parent().not('#Footer li').stop().animate({
				backgroundColor:"#f5f5f5"
			},fadeInSpeed);
		}, function() {
			//remove underline and animated hover effect
			$(this).children('a:last').css('text-decoration','none').parent().not('#Footer li').stop().animate({
				backgroundColor:"#fff"
			},fadeOutSpeed);
		}).click(function() {
			//navigate to the last anchor's location
			window.location = $(this).children('a:last').attr('href');
		});

		//Search dropdowns, submit on change
		/*var $dropDowns = $('.search select');
		$dropDowns.change(function() {
			$(this).parents('form').submit();
		});*/


		var $subMenu = $('.subMenu');
		if ($subMenu.length) {
			var $mainMenu = $('ul',$subMenu);
			$mainMenu.children().each(function() {
				var $this = $(this);
				if ($this.hasClass('link')){
					var height = $this.children('a').outerHeight() -1; //-1 as it includes the border (i think)
					$this.height(height);
				}
			});
		}

		/*var $lis = $('#Content.typography ul:not(#SearchResults) li');
		if ($lis.length) {
			$lis.each(function(){
				if(this.childNodes[0] && this.childNodes[0].nodeType == 3){
					var data = $.trim(this.childNodes[0].data);
					if(data){
						this.childNodes[0].data = data;
						$(this.childNodes[0]).wrap("<span></span>");
					}
				}
			});
		}*/

		/**
		 * Home Page
		 */
		if ($('#SlideShow').length) {

			//SlideShow
			var $slideItems = $('#SlideShow li');
			var $currentItem = $slideItems.filter('.current');
			var $firstItem = $slideItems.first()

			//if no current item, then assume the first one
			if (!$currentItem.length) {
				$currentItem = $firstItem;
			}

			//get the current slide
			var $currentSlide = $currentItem.children('.slide');

			//hide all of the slides that arent the current one
			$slideItems.children('.slide').not($currentSlide).hide();

			//this function is called to start the automatic slide show
			function startRotator() {
				return setInterval(function() {
					var $next = $currentItem.next();
					if (!$next.length) {
						$next = $firstItem;
					}
					$next.click();
				},7000);
			}

			//start the slideshow and record it's ID so we can disable it later
			var intervalID = startRotator();

			//when we hover on a slide we want to stop the auto rotation
			$slideItems.hover(function() {
				//stop the auto rotation
				clearInterval(intervalID);
				//animate the hover effect
				$(this).stop().animate({
					backgroundColor: '#f5f5f5'
				},fadeInSpeed);
			}, function() {
				//start the auto animation
				intervalID = startRotator();
				var $this = $(this);
				//if we arent hovering off the current item, then fade out the
				//hover colour
				if (!$this.hasClass('current')) {
					$this.stop().animate({
						backgroundColor: '#fff'
					},fadeOutSpeed);
				}
			}).click(function(ev) {
				var $this = $(this);
				//dont do the click effect if we are in the current item
				if (!$this.hasClass('current')){
					//get this items slide
					var $thisSlide = $(this).children('.slide');
					//animate the 'current' effect (same as hover) and set it to
					//have the current class
					$this.stop().animate({
						backgroundColor: '#f5f5f5'
					},fadeInSpeed).addClass('current');
					//fade out the current slide
					$currentSlide.stop().fadeOut();
					//animate the current items 'current' effect (same as blur)
					//and remove the current class
					$currentItem.stop().animate({
						backgroundColor: '#fff'
					},fadeOutSpeed).removeClass('current');
					//fade in the new slide
					$thisSlide.stop().fadeIn();
					//set the new current slide and item
					$currentSlide = $thisSlide;
					$currentItem = $this;
				}
                //supress default action if not clicking on div.slide
                return ( !!$(ev.target).closest('div.slide', ev.currentTarget).length );
			});
		}

		if ($('#PrequalPage').length) {
			var $form = $('#Form_Form');
			var $steps = $('fieldset > .fieldgroup',$form);
			var $submit = $('input.action',$form);
			var $currentStep = $steps.first();

			//hide initial parts
			$steps.not(':first').hide();
			$submit.hide();

			//insert button html after the form
			var beforeHTML = '<div id="PleaseSelect" style="display:none">You must select an option to move on</div>';
			var buttonHTML = '<div id="Buttons"><a href="#" style="display:none" class="button prev"><span>Previous</span></a><a href="#" class="button next"><span>Next</span></a></div>';
			var crumbHTML = '<ol id="Crumbs" style="display:none"><li class="first experience">Experience</li><li class="knowledge">Knowledge</li><li class="qualification">Qualification</li><li class="workStatus">Work Status</li><li class="availibility">Availability</li><li class="last results">Results</li></ol>';
			$form.prepend(crumbHTML + beforeHTML).after(buttonHTML);


			$form.submit(function() {
				$warning.fadeOut();
				$.ajax({
					beforeSend: function() {
						$form.css('height',$form.height());
						$currentStep.fadeOut(null,function() {
							$('#Loading').fadeIn();
						}).after('<div id="Loading"></div>');
						$('#Buttons').fadeOut().remove();
						_gaq.push(['_trackEvent','Prequal','completed']);
					},
					cache: false,
					data: $form.serialize(),
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						var $crumbs = $('#Crumbs');
						$form.fadeOut(function() {
							var nextLink = $('link[rel=next]').attr('href');
							$form.replaceWith('<div id="Result"><h3>Sorry, there was an error</h3><p>Why not <a href="' + nextLink + '">apply to be a candidate anyway</a>?</p></div>');
							$('#Result').prepend($crumbs);
						});
						$crumbs.addClass('locked');
					},
					success: function(data) {
						var $crumbs = $('#Crumbs');
						$form.fadeOut(function() {
							$form.replaceWith(data);
							$('#Result').prepend($crumbs);
						});
						$crumbs.addClass('locked');
					},
					type: $form.attr('method'),
					url: $form.attr('action') + '?ajax'
				});
				$crumbItems.last().addClass('current');
				$nextButton.fadeOut();
				return false;
			});

			var $radios = $('input[type=radio]',$form);
			$radios.click(function() {
				setTimeout(function() {
					$nextButton.click();
				},250);
			});

			//set click actions
			var $nextButton = $('#Buttons .next');
			var $prevButton = $('#Buttons .prev');
			var $nextStep = $currentStep.next('.fieldgroup');
			var $prevStep = $currentStep.prev('.fieldgroup');
			var $warning = $('#PleaseSelect');
			var $crumbs = $('#Crumbs');
			var $crumbItems = $crumbs.children();

			$nextButton.click(function() {
				if (!$nextButton.hasClass('busy')){
					if ($nextStep.length) {
						if ($('input:checked',$currentStep).length){
							$nextButton.addClass('busy');
							$currentStep.fadeOut(null,function() {
								$prevStep = $currentStep;
								$currentStep = $nextStep.fadeIn();
								$nextStep = $nextStep.next('.fieldgroup');
								$($crumbItems.get($currentStep.index() - 1)).addClass('current');
								if (!$nextStep.length) {
									/*$nextButton.fadeOut(null,function() {
										$submit.fadeIn();
									});*/
									$nextButton.text('Submit');
								}
								$crumbs.fadeIn();
								$prevButton.fadeIn();
								$nextButton.removeClass('busy');
							});
							$warning.fadeOut();
						}
						else {
							$warning.slideDown();
						}
					}
					else {
						if ($('input:checked',$currentStep).length){
							$form.submit();
						}
						else {
							$warning.slideDown();
						}
					}
				}
				return false;
			});

			$prevButton.click(function() {
				if (!$prevButton.hasClass('busy')) {
					if ($prevStep.length) {
						$prevButton.addClass('busy');
						$currentStep.fadeOut(null,function() {
							$nextStep = $currentStep;
							$($crumbItems.get($currentStep.index() - 1)).removeClass('current');
							$currentStep = $prevStep.fadeIn();
							$prevStep = $prevStep.prev('.fieldgroup');
							if (!$prevStep.length) {
								$prevButton.fadeOut();
								$crumbs.slideUp();
							}
							$prevButton.removeClass('busy');
						});
						$nextButton.fadeIn(null,function() {
							$warning.fadeOut();
						});
						//$submit.fadeOut();
						$nextButton.fadeIn().text('Next');
					}
				}
				return false;
			});

		}

		var jobs = [], activeWindow, activeMarker;

		function switchMapJob(newMarker, newWindow) {
			if(activeWindow && activeMarker) {
				activeWindow.close();
				activeMarker.setAnimation(null);
			}
			if(newWindow && newMarker) {
				activeMarker = newMarker;
				activeWindow = newWindow;
			}
		}

		function updateJobCounter(counter) {
			var text = counter + ' job' + (counter != 1 ? 's' : '') + ' found';
			return $('#JobCounter').text(text);
		}

		function deviate(number, magnitude) {
			var random = Math.random(),
				deviation = random * magnitude,
				result;

			if(Math.random() > .5) {
				deviation = -deviation;
			}

			result = parseFloat(number) + parseFloat(deviation);

			return result;
		}

		function initSearchMap() {
			var mapElement = document.getElementById("MapCanvas"),
				$mapForm = $('#JobMapSearchForm_Form');
			if (mapElement) {
				var latlng = new google.maps.LatLng(51.46145, -0.21507),
					center = new google.maps.LatLng(51.46083, -0.21537),
					myOptions = {
						zoom: 8,
						minZoom: 6,
						maxZoom: 10,
						center: center,
						mapTypeId: google.maps.MapTypeId.ROADMAP,
						navigationControl: true,
						mapTypeControl: false
					},
					map = new google.maps.Map(mapElement, myOptions);
				//var clusterer = new MarkerClusterer(map, { maxZoom: 10 });

				//if(navigator.geolocation) {
				//	navigator.geolocation.getCurrentPosition(function(p) {
				//		center = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
				//		map.setCenter(center);
				//	},
				//	function() {
				//		// no geolocation API :(
				//	});
				//}

				if ($mapForm.length) {
					$.getJSON('/Jobs.json', function(data) {
						$.each(data, function(index, job) {
							var jobLocation = new google.maps.LatLng(deviate(job.Lat, .1), deviate(job.Lon, .1));

							// Create the markup
							job.Marker = new google.maps.Marker({
								position: jobLocation,
								map: map,
								icon: '/themes/backstop/images/map/' + job.JobCategoryIcon + '.png'
							});

							// Set title attribute
							job.Marker.setTitle(job.JobTitle);

							// Create an info window
							job.InfoWindow = new google.maps.InfoWindow();
							job.InfoWindow.setContent(job.InfoWindowContent);
							job.InfoWindow.setPosition(jobLocation);

							// When the marker is clicked, show the info window.
							google.maps.event.addListener(job.Marker, 'click', function() {
								switchMapJob(job.Marker, job.InfoWindow);
								job.InfoWindow.open(map, job.Marker);
							});

							// Handle the close button on the info window
							google.maps.event.addListener(job.InfoWindow, 'closeclick', function() {
								switchMapJob(null, null);
							});

							// Add to clusterer
							//clusterer.addMarker(job.Marker)
						});
						jobs = data;
						updateJobCounter(jobs.length);
					});
					var widget = $('div.MapKeyWidget');
					if(widget.length) {
						var categoryDropdown = $('#JobCategoryID select');
						widget.delegate('a', 'click', function() {
							var self = $(this),
								categoryID = self.attr('href').split('#Category_')[1];

							categoryDropdown[0].selectedIndex = categoryDropdown.find('option[value=' + categoryID + ']').index();

							categoryDropdown.trigger('change');

							return false;

						});
					}
				}

			}
		}

		if ($('#ContactPage').length) {
			loadMap(initMap);
		}
		else if ($('#MapSearchPage').length) {
			var $form = $('#JobMapSearchForm_Form');

			// Remove the search button
			$('div.Actions', $form).remove();

			// Update the map when the form changes
			$form.bind('change keyup', function() {
				var i,
					serialized = $form.serializeArray(),
					optionFields = [],
					flatOptionFields = {},
					jobCounter = 0;

				// Any fields that are arrays (i.e. checkboxsets)
				// have to be flattened to filter nicely.
				$.each(serialized, function(index, field) {
					if(field.name.indexOf('[') != -1) {
						// Add this to the special array and remove original
						optionFields.push(field);
						delete serialized[index];
					}
				});

				// Take each possible value and add it to an array of possible
				// values, where key is the name of the field.
				$.each(optionFields, function(index, field) {
					var lookup = field.name.replace(/\[\d+\]/, '');
					if(flatOptionFields[lookup]) {
						flatOptionFields[lookup].push(field.value.toString());
					}
					else {
						flatOptionFields[lookup] = [field.value.toString()];
					}
				});

				// Filter the jobs
				$.each(jobs, function(i, job) {

					var show = true;

					// Work our way through the serialized form's normal fields
					$.each(serialized, function(index, field) {
						if(show === false) {
							return false;
						}
						// Only filter if the field exists and it has a value
						if(field && field.value != '') {
							show = (field.value == job[field.name]);
						}
						// If show is false, this breaks the loop to save time.
						return show;
					});

					// Now through the checkboxes...
					if(optionFields.length) {
						var j;
						for(j in flatOptionFields) {
							var options = flatOptionFields[j];
							// If it's not in the array of possible values, stop
							if($.inArray(job[j].toString(), options) == -1) {
								show = false;
								break;
							}
						}
					}

					// If this job's info window is open and it doesn't match, close it.
					if(show == false && job.Marker === activeMarker) {
						switchMapJob(null, null);
					}

					if(show == true) ++jobCounter;

					job.Marker.setVisible(show);

				});

				updateJobCounter(jobCounter);

			});

			loadMap(initSearchMap);
		}

	})(jQuery);

});

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1211547-1']);
_gaq.push(['_trackPageview']);
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

