function sortNumber(num1, num2) {
	return num1 - num2;
}

var manageMobileMenuOpen = function () {
	
	var element = document.querySelector('#menu-collapse-mobile');

	var observer = new MutationObserver(function (mutations) {
		handleMobleMenuMutations(mutations);
	});
	
	observer.observe(element, {
		attributes: true //configure it to listen to attribute changes
	});
};

var handleMobleMenuMutations = function (mutations) {
	mutations.forEach(function (mutation) {
		if (mutation.type == "attributes") {
			if (mutation.attributeName == "aria-expanded") {
					document.body.dataset.mobileMenuOpen = mutation.target.ariaExpanded;
				if (mutation.target.ariaExpanded) {
					 window.scrollTo(0, 0);
				 }
			
			}
		}
	});	
};

jQuery(document).ready(function($){
	function highlightDistrict() {

		var mousePos = { x: -1, y: -1 };
		$(document).mousemove(function(e) {
			mousePos.x = +e.pageX;
			mousePos.y = +e.pageY;
		});

		$('dd[class^="district-"]').hover(
			function (e) {
				var district = $(this).attr('class');
				$('.council-districts-map.'+district).addClass(district+'-hover');
			},
			function (e) {
				var district = $(this).attr('class');
				$('.council-districts-map.'+district).removeClass(district+'-hover');
			}
		);
		$('#city-council-map path.district').hover(
			function (e) {
				var district = $(this).attr('id');
				/*
				var district_pos = $(this).offset();
				var district_w = $(this)[0].getBoundingClientRect().width;
				var district_label = '.council-districts-map .reveal-title.' + district;
				var district_label_w = $(district_label).outerWidth();
				var district_label_h = $(district_label).outerHeight();
				var district_label_top = mousePos.y - district_label_h - 20;
				var district_label_left = mousePos.x - district_label_w/2;
				$(district_label).offset({'top': district_label_top, 'left': district_label_left});
				*/
				$('.council-districts-map .reveal-title.' + district).addClass('title-reveal');
				if( $('.council-districts-map').hasClass(district) ) {
					$('dd[class^="district-"]').addClass('district-fade');
					$('dd.' + district).addClass('district-hover');
				}
			},
			function (e) {
				var district = $(this).attr('id');
				$('.council-districts-map .reveal-title.' + district).removeClass('title-reveal');
				$('dd[class^="district-"]').removeClass('district-fade');
				$('dd.'+district).removeClass('district-hover');
			}
		);
		$('#city-council-map path.district').mousemove(
			function (e) {
				var district = $(this).attr('id');
				var district_label = '.council-districts-map .reveal-title.' + district;
				var district_label_w = $(district_label).outerWidth();
				var district_label_h = $(district_label).outerHeight();
				var district_label_top = mousePos.y - district_label_h - 15;
				var district_label_left = mousePos.x - district_label_w/2;
				$(district_label).offset({'top': district_label_top, 'left': district_label_left});
			}
		);
	}
	highlightDistrict();

	manageMobileMenuOpen();
	
	/*
	$(".side-slide").css("display", "block");
	$('.side-slide').after('<div id="nav-slide" class="feature-nav">').cycle({ 
		fx:     'scrollLeft', 
		timeout: 6000, 
		delay:  4000,
		random: 0,
		pager: '#nav-slide',
		// callback fn that creates a thumbnail to use as pager anchor 
		pagerAnchorBuilder: function(idx, slide) { 
			return '<a href="#">&bull;</a>'; 
		}
	});
	
	$(".side-slide2").css("display", "block");
	$('.side-slide2').after('<div id="nav-slide2" class="feature-nav">').cycle({ 
		fx:     'fade', 
		timeout: 6000, 
		delay:  4000,
		random: 0,
		pager: '#nav-slide2',
		// callback fn that creates a thumbnail to use as pager anchor 
		pagerAnchorBuilder: function(idx, slide) { 
			return '<a href="#">&bull;</a>'; 
		}
	});
	*/
	
	questionNext = function (current, next) {
		checkAnswer = $(
			'#' + current + ' input[name=' + current + ']:checked'
			).val();
			if (current !== 'intro' && checkAnswer === null) {
				alert('Please select one of the choices.');
			} else if (current === 'city') {
				var answers = [];
				var mirror = $('input[name=mirror]:checked').val();
				var animal = $('input[name=animal]:checked').val();
				var city = $('input[name=city]:checked').val();
				mirrorArray = mirror.split(',');
				animalArray = animal.split(',');
				cityArray = city.split(',');
				arrayMerge1 = $.merge(animalArray, mirrorArray);
				arrayMerge2 = $.merge(cityArray, arrayMerge1);
				
				answersSorted = arrayMerge2.sort(sortNumber);
				
				var freqs = {};
				var max_index;
				var max_value = -1 / 0; // Negative infinity.
				$.each(answersSorted, function (i, v) {
					if (freqs[v] !== undefined) {
						freqs[v]++;
					} else {
						freqs[v] = 1;
					}
				});
				$.each(freqs, function (num, freq) {
					if (freq > max_value) {
						max_value = freq;
						max_index = num;
					}
				});
				if (max_index !== undefined) {
					// alert("Most common element is " + max_index + " with " + max_value + " repetition(s).");
					if (max_value == 1) {
						$(answersSorted).each(function (index) {
							if (index > 4) {
								return false;
							}
							$('#color ul').append(
								'<li><label for="radio' +
								this +
								'" class="label_radio label_color_' +
								this +
								'"><input type="radio" class="radio" name="color" value="' +
								this +
								'" id="radio' +
								this +
								"\" onclick=\"questionNext('color', 'results')\" /></label></li>"
								);
							});
							$('#' + current).fadeOut(500);
							$('#' + current).hide();
							$('#color').fadeIn(500);
						} else {
							email = $('#intro input[name=email]').val();
							color_name = getColorName(max_index);
							// submitMailChimp(email, color_name, max_index);
							$('#results div.question').append(
								'<div style="float: left; margin: 0 50px 0 0;"><img src="http://www.sa2020.org/wp-content/themes/sa2020/images/quiz-color-' +
								max_index +
								'.png" /></div><h1>' +
								color_name +
								'</h1><p style="clear: none;">Find out what your color means <a href="http://www.sa2020.org/about/">now</a>! <br />&nbsp;</p>'
								);
								$('#social').append(
									'<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url="http://www.sa2020.org/quiz/?color=' +
									max_index +
									'&color_name=' +
									color_name +
									'"><a class="addthis_button_facebook"></a><a class="addthis_button_twitter" addthis:title="My #SA2020 color is ' +
									color_name +
									'. Take the quiz to find Your Passion. Get Involved. Be a part of SA2020."></a><a class="addthis_button_google"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4f9062624afca058"></script>'
									);
									// addthis.update('share', 'url', 'http://www.sa2020.org/quiz.php?color='+max_index+'&color_name='+color_name);
									// addthis.update('share', 'description', 'My SA2020 Color is '+color_name+'! Go find what your color is and know what it means on May 19th!');
									$('#' + current).fadeOut(500);
									$('#' + current).hide();
									$('#results').fadeIn(500);
								}
							}
						} else if (current === 'color') {
							color_id = $('input[name=color]:checked').val();
							color_name = getColorName(color_id);
							email = $('#intro input[name=email]').val();
							// submitMailChimp(email, color_name, color_id);
							$('#results div.question').append(
								'<div style="float: left; margin: 0 50px 0 0;"><img src="http://www.sa2020.org/wp-content/themes/sa2020/images/quiz-color-' +
								color_id +
								'.png" width="200" /></div><h1>' +
								color_name +
								'</h1><p style="clear: none;">Find out what your color means <a href="http://www.sa2020.org/about/">now</a>!'
								);
								$('#social').append(
									'<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url="http://www.sa2020.org/quiz/?color=' +
									color_id +
									'&color_name=' +
									color_name +
									'"><a class="addthis_button_facebook"></a><a class="addthis_button_twitter" addthis:title="My #SA2020 color is ' +
									color_name +
									'. Take the quiz to find Your Passion. Get Involved. Be a part of SA2020."></a><a class="addthis_button_google"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4f9062624afca058"></script>'
									);
									$('#' + current).fadeOut(500);
									$('#' + current).hide();
									$('#results').fadeIn(500);
								} else {
									$('#' + current).fadeOut(500);
									$('#' + current).hide();
									$('#' + next).fadeIn(500);
								}
								return false;
							};
							
							submitMailChimp = function (email, color_name, color_id) {
								merges = {};
								merges['MMERGE1'] = color_name;
								merges['MMERGE2'] = color_id;
								data = {
									apikey: '4658c63ed7f43703382f132410bc3c6f-us2',
									id: '2cadc48efc',
									email_address: email,
									output: 'json',
									send_welcome: true,
									double_optin: false,
									merge_vars: merges,
								};
								$.ajax({
									type: 'POST',
									url: 'http://us2.api.mailchimp.com/1.3/?method=listSubscribe', //replace us4 with yours
									data: data,
									dataType: 'jsonp',
									success: function (data) {
										//
									},
									error: function () {
										//
									},
								});
							};
							
							getColorName = function (color_id) {
								if (color_id == 1) {
									color_name = 'Arts & Culture';
								} else if (color_id == 2) {
									color_name = 'Community Safety';
								} else if (color_id == 3) {
									color_name = 'Downtown Development';
								} else if (color_id == 4) {
									color_name = 'Economic Competitiveness';
								} else if (color_id == 5) {
									color_name = 'Education';
								} else if (color_id == 6) {
									color_name = 'Family Well-Being';
								} else if (color_id == 7) {
									color_name = 'Government Accountability & Civic Engagement';
								} else if (color_id == 8) {
									color_name = 'Health & Fitness';
								} else if (color_id == 9) {
									color_name = 'Natural Resources and Environment Sustainability';
								} else if (color_id == 10) {
									color_name = 'Neighborhoods and Growth Management';
								} else if (color_id == 11) {
									color_name = 'Transportation';
								}
								return color_name;
							};
						});
						