/*

	Authors:
	
		Gesture Theory • gesturetheory.com
		Brian McAllister ⚡ brianmcallister.com

*/

// Format currency (for Highcharts)
// http://www.web-source.net/web_development/currency_formatting.htm
function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

$(function() {

	addthis_share = {
		templates: {
			twitter: 'check out {{title}} @ {{url}}'
		}
	}

	// Uniform for checkboxes and radio buttons
	// http://uniformjs.com/
	$('input:checkbox, input:radio').uniform();

	// Chosen for select boxes
	// http://harvesthq.github.com/chosen/
	$('select').chosen();

	/*
	
			Use ajax() to grab data from the AIGA database and use
			the results to populate the calculator results section.
			
	*/

	// Current location of the json response
	var url = document.location.href,
		title = document.title;


	var API = '/results-json.asp';


	var $form = $('form');

	// Ajax request settings
	$.ajaxSetup({
		dataType: 'json',
		type: 'POST',
		url: API,
		success: function(data) {
			formSuccess(data);
		}
	});

	// When a box or dropdown is selected, get the results
	$('#salary-calulator input, #salary-calulator select').change(function() {

		// If 'Include All' is checked, uncheck all other checkboxes.
		// If another checkbox is checked while 'Include All' is checked,
		// uncheck 'Include All'.
		var $parentList = $(this).parents('ul'),
			$el = $(this);

		if ($el.hasClass('all') && $el.attr('checked')) {
			$parentList.find('input').not($el).removeAttr('checked');
			$.uniform.update();
		};

		if (!$el.hasClass('all')) {
			$parentList.find('.all').removeAttr('checked');
			$.uniform.update();
		};

		// Only allow a city or a region
		var formData = $('#locations').val();

		if (formData.indexOf('region-') != -1) {
			var cities = 1,
				regions = formData.replace('region-', '');

		} else {
			var regions = 1,
				cities = formData;
		}

		// Make ajax request
		$.ajax({
			data: $form.serialize() + '&Q05=' + cities + '&Q06=' + regions
		});

		// Place charts in correct positions
		$('.finalresults').animate({
			'top': '0'
		});
	});

	// Set up the returned JSON object
	var formSuccess = function(response) {

		// console.log(response);
		var responseObject = {

			positionTitle: response.position.title,
			positionDescription: response.position.description,

			warning: response.warning,

			salaryYoursTwentyFive: response.salary.yourselections.twentyfive.replace(/^\$|,/g, ''),
			salaryYoursFifty: response.salary.yourselections.fifty.replace(/^\$|,/g, ''),
			salaryYoursSeventyFive: response.salary.yourselections.seventyfive.replace(/^\$|,/g, ''),
			salaryYoursResponses: response.salary.yourselections.responses,

			salaryNationalTwentyFive: response.salary.nationalaverage.twentyfive.replace(/^\$|,/g, ''),
			salaryNationalFifty: response.salary.nationalaverage.fifty.replace(/^\$|,/g, ''),
			salaryNationalSeventyFive: response.salary.nationalaverage.seventyfive.replace(/^\$|,/g, ''),
			salaryNationalResponses: response.salary.nationalaverage.responses,

			totalYoursTwentyFive: response.totalcompensation.yourselections.twentyfive.replace(/^\$|,/g, ''),
			totalYoursFifty: response.totalcompensation.yourselections.fifty.replace(/^\$|,/g, ''),
			totalYoursSeventyFive: response.totalcompensation.yourselections.seventyfive.replace(/^\$|,/g, ''),
			totalYoursResponses: response.totalcompensation.yourselections.responses,

			totalNationalTwentyFive: response.totalcompensation.nationalaverage.twentyfive.replace(/^\$|,/g, ''),
			totalNationalFifty: response.totalcompensation.nationalaverage.fifty.replace(/^\$|,/g, ''),
			totalNationalSeventyFive: response.totalcompensation.nationalaverage.seventyfive.replace(/^\$|,/g, ''),
			totalNationalResponses: response.totalcompensation.nationalaverage.responses,

			selType: response.summary.type,
			selSize: response.summary.size,
			selClients: response.summary.clients,
			selMetro: response.summary.metro,
			selRegion: response.summary.region

		};

		sendToPage(responseObject);

	};

	var $yourSelectionsContainer = $('#results-yourselections');

	// Send first data request on page load
	if ($yourSelectionsContainer.length) {
		$.ajax({
			data: 'Q01=23&Q05=1&Q02=1&Q03=1&Q04=1'
		});
	}

	var sendToPage = function(responseObject) {

		$('#selected-job-title').html(responseObject.positionTitle);
		$('#selected-job-description').html(responseObject.positionDescription);

		if (responseObject.warning == 'true') {

			$yourSelectionsContainer.animate({
				'top': '-=200px'
			});

		} else {

			$yourSelectionsContainer.animate({
				'top': '0'
			});

			yourSelectionsOptions.subtitle.text = responseObject.salaryYoursResponses + ' Responses';

			// Your selections base salary
			yourSelectionsOptions.series[1].data = [
			parseInt(responseObject.salaryYoursTwentyFive, 10), parseInt(responseObject.salaryYoursFifty, 10), parseInt(responseObject.salaryYoursSeventyFive, 10)];

			// Your selections bonus
			yourSelectionsOptions.series[0].data = [
			parseInt(responseObject.totalYoursTwentyFive - responseObject.salaryYoursTwentyFive, 10), parseInt(responseObject.totalYoursFifty - responseObject.salaryYoursFifty, 10), parseInt(responseObject.totalYoursSeventyFive - responseObject.salaryYoursSeventyFive, 10)];

		}; // end warning if statement
		nationalAverageOptions.subtitle.text = responseObject.totalNationalResponses + ' Responses';

		// National average base salary
		nationalAverageOptions.series[1].data = [
		parseInt(responseObject.salaryNationalTwentyFive, 10), parseInt(responseObject.salaryNationalFifty, 10), parseInt(responseObject.salaryNationalSeventyFive, 10)];

		// National average bonus
		nationalAverageOptions.series[0].data = [
		parseInt(responseObject.totalNationalTwentyFive - responseObject.salaryNationalTwentyFive, 10), parseInt(responseObject.totalNationalFifty - responseObject.salaryNationalFifty, 10), parseInt(responseObject.totalNationalSeventyFive - responseObject.salaryNationalSeventyFive, 10)];

		// Redraw the charts
		yourselections.destroy();
		yourselections = new Highcharts.Chart(yourSelectionsOptions);

		nationalaverage.destroy();
		nationalaverage = new Highcharts.Chart(nationalAverageOptions);
	};

	/*
	
			Tooltip mouseover effect
			
			http://jqueryfordesigners.com/coda-popup-bubbles/
			
	*/

	$('.data-row > h1').each(function() {

		var distance = 10,
			time = 250,
			hideDelay = 500,
			hideDelayTimer = null,
			beingShown = false,
			shown = false,
			trigger = $(this),
			popup = $(this).siblings('.popup').css('opacity', 0);

		// set the mouseover and mouseout on both element
		$([trigger[0], popup[0]]).mouseover(function() {

			var popupHeight = $(this).siblings('.popup').height();

			// stops the hide event if we move from the trigger to the popup element
			if (hideDelayTimer) clearTimeout(hideDelayTimer);

			// don't trigger the animation again if we're being shown, or already visible
			if (beingShown || shown) {
				return;
			} else {
				beingShown = true;

				// reset position of popup box
				popup.css({
					top: '-' + (popupHeight - 10) + 'px',
					left: '5px',
					display: 'block' // brings the popup back in to view
				})

				// (we're using chaining on the popup) now animate it's opacity and position
				.animate({
					top: '-=' + distance + 'px',
					opacity: 1
				},
				time, 'swing', function() {
					// once the animation is complete, set the tracker variables
					beingShown = false;
					shown = true;
				});
			}
		}).mouseout(function() {
			// reset the timer if we get fired again - avoids double animations
			if (hideDelayTimer) clearTimeout(hideDelayTimer);

			// store the timer so that it can be cleared in the mouseover if required
			hideDelayTimer = setTimeout(function() {
				hideDelayTimer = null;
				popup.animate({
					top: '-=' + distance + 'px',
					opacity: 0
				},
				time, 'swing', function() {
					// once the animate is complete, set the tracker variables
					shown = false;
					// hide the popup entirely after the effect (opacity alone doesn't do the job)
					popup.css('display', 'none');
				});
			},
			hideDelay);
		});

	});

	/*
	
		Highcharts
		
		highcharts.com
	
	*/

	// Overview page bar charts
	if ($('#overview-graph-1').length) {

		for (var i = 0; i < totalCompensationGraph.length; i++) {

			totalCompensationGraph[i] = new Highcharts.Chart({

				chart: {
					renderTo: 'overview-graph-' + (i + 1),
					defaultSeriesType: 'bar',
					backgroundColor: 'transparent',
					backgroundColor: 'rgba(255, 255, 255, 0.0)',
					borderRadius: 0,
					spacingTop: 0,
					spacingBottom: 0,
					spacingRight: 1,
					spacingLeft: 84,
					width: 528,
					height: 86
				},

				credits: {
					enabled: false
				},

				title: {
					text: null
				},

				tooltip: {
					enabled: true,
					backgroundColor: '#fff',
					borderColor: null,
					borderRadius: 4,
					borderWidth: 0,
					shadow: true,
					style: {
						font: '13px/20px Play, sans-serif',
						padding: '10px',
						color: '#69616c'
					},
					formatter: function() {
						if (this.series.name == 'Wages/Salary') {
							var hourlyRate = this.point.config / 2000;
							var dailyRate = (this.point.config / 2000) * 8;

							var daily = 'Implied hourly rate: <strong>$' + addCommas(hourlyRate) + '</strong><br />' + 'Implied daily rate: <strong>$' + addCommas(dailyRate) + '</strong>';

							return daily;
						} else {
							var compensation = 'Additional Compensation: <strong>$' + addCommas(this.point.config) + '</strong><br />' + 'Total Compensation: <strong>$' + addCommas(this.total) + '</strong>';

							return compensation;
						}
					}
				},

				xAxis: {
					categories: ['25% earn less', '50% earn less', '75% earn less'],
					reversed: true,
					lineColor: null,
					// '#83d0fb'
					tickLength: 0,
					labels: {
						enabled: false,
						y: 4,
						style: {
							font: '10px arial',
							width: 68
						}
					}
				},

				yAxis: {
					title: {
						text: null
					},
					labels: {
						enabled: false
					},
					gridLineColor: null,
					//'#83d0fb'
					tickPixelInterval: 86,
					max: 200000
				},

				legend: {
					enabled: false
				},

				plotOptions: {
					bar: {
						stacking: 'normal',
						borderColor: null,
						borderWidth: 0,
						shadow: false,
						pointWidth: 22,
						groupPadding: -22,
						states: {
							hover: {
								brightness: 0.15
							}
						}
					}
				},

				series: [{
					name: 'Additional Compensation',
					data: totalCompensationGraph[i].chart.bonus,
					color: '#8c1d09'
				},

				{
					name: 'Wages/Salary',
					data: totalCompensationGraph[i].chart.cash,
					color: '#dd3b21',
					dataLabels: {
						enabled: true,
						color: '#fff',
						y: 5,
						style: {
							font: '13px Play, sans-serif'
						},
						formatter: function() {

							return '$' + addCommas(this.y);

						}
					}
				}]

			}); // end options
		}; // end for loop - overview page bar charts
	}; // end if statement
	if ($('#median-graph-1').length) {

		for (var j = 0; j < medianTotalGraph.length; j++) {

			// console.log(medianTotalGraph[j]);
			medianTotalGraph[j] = new Highcharts.Chart({

				chart: {
					renderTo: 'median-graph-' + (j + 1),
					type: 'line',
					backgroundColor: 'transparent',
					backgroundColor: 'rgba(255, 255, 255, 0.0)',
					borderColor: null,
					marginLeft: 0,
					marginRight: 1
				},

				credits: {
					enabled: false
				},
				title: {
					text: null
				},
				legend: {
					enabled: false
				},

				xAxis: {
					title: {
						text: null
					},
					labels: {
						enabled: false
					},
					lineColor: '#83d0fb',
					lineWidth: 1,
					gridLineColor: '#83d0fb',
					gridLineWidth: 1,
					tickInterval: 1,
					tickLength: 0,
					tickWidth: 1,
					startOnTick: true,
					endOnTick: true
				},

				yAxis: {
					title: {
						text: null
					},
					labels: {
						enabled: false
					},
					max: 130000,
					min: 0,
					lineWidth: 0,
					gridLineColor: '#83d0fb',
					gridLineWidth: 1,
					tickInterval: 32500
				},

				plotOptions: {
					line: {
						lineWidth: 1,
						color: '#dd3b21',
						shadow: false,
						states: {
							hover: {
								enabled: false
							},
							marker: {
								fillColor: '#dd3b21',
								radius: 5,
								symbol: 'circle',
								states: {
									hover: {
										enabled: false
									}
								}
							}
						}

					}
				},

				tooltip: {
					enabled: true,
					backgroundColor: '#fff',
					borderColor: null,
					borderRadius: 4,
					borderWidth: 0,
					shadow: true,
					style: {
						font: '14px Play, sans-serif',
						padding: '5px',
						color: '#69616c',
						textAlign: 'center'
					},
					formatter: function() {

						var xValue = this.x + ''; // convert to string
						if (xValue.length == 1) {
							xValue = '200' + xValue;
						} else {
							xValue = '20' + xValue;
						}

						return xValue + ': <strong>$' + addCommas(this.y) + '</strong>';

					}
				},

				series: [{
					name: 'Median total cash compensation',
					data: medianTotalGraph[j].chart.salary
				}]

			}); // end options
		}; // end for loop
	}; // end if statement

	// Calculator page bar charts
	if ($('#results-yourselections').length) {

		var yourselections;
		yourSelectionsOptions = {

			chart: {
				renderTo: 'results-yourselections',
				defaultSeriesType: 'bar',
				backgroundColor: 'transparent',
				backgroundColor: 'rgba(255, 255, 255, 0.0)',
				borderRadius: 0,
				spacingTop: 0,
				spacingBottom: 0,
				spacingRight: 1,
				spacingLeft: 83,
				marginTop: 30,
				height: 114
			},

			credits: {
				enabled: false
			},

			title: {
				text: 'Your selections',
				floating: true,
				align: 'left',
				x: -75,
				y: 10,
				style: {
					font: '700 15px Play, sans-serif',
					color: '#666'
				}
			},

			subtitle: {
				text: '# Respondants',
				floating: true,
				align: 'right',
				y: 10,
				x: -10,
				style: {
					font: 'bold 12px Play, sans-serif',
					color: '#666'
				}
			},

			tooltip: {
				enabled: true,
				backgroundColor: '#fff',
				borderColor: null,
				borderRadius: 4,
				borderWidth: 0,
				shadow: true,
				style: {
					font: '13px/20px Play, sans-serif',
					padding: '5px',
					color: '#69616c'
				},
				formatter: function() {
					if (this.series.name == 'Wages/Salary') {
						var hourlyRate = this.point.config / 2000;
						var dailyRate = (this.point.config / 2000) * 8;

						var daily = 'Hourly rate: <strong>$' + addCommas(hourlyRate) + '</strong><br />' + 'Daily rate: <strong>$' + addCommas(dailyRate) + '</strong>';

						return daily;
					} else {
						var compensation = 'Additional Compensation: <strong>$' + addCommas(this.point.config) + '</strong><br />' + 'Total Compensation: <strong>$' + addCommas(this.total) + '</strong>';

						return compensation;
					}
				}
			},

			xAxis: {
				categories: ['25% earn less', '50% earn less', '75% earn less'],
				reversed: true,
				lineColor: null,
				//'#83d0fb'
				tickLength: 0,
				endOnTick: false,
				labels: {
					enabled: false,
					y: 4,
					style: {
						font: '10px sans-serif'
					}
				}
			},

			yAxis: {
				title: {
					text: null
				},
				labels: {
					enabled: false
				},
				gridLineColor: null,
				//'#83d0fb'
				tickPixelInterval: 85,
				endOnTick: false,
				max: 260000
			},

			legend: {
				enabled: false
			},

			plotOptions: {
				bar: {
					stacking: 'normal',
					borderColor: null,
					borderWidth: 0,
					shadow: false,
					pointWidth: 22
				}
			},

			series: [{
				name: 'Additional Compensation',
				data: [1, 2, 3],
				color: '#8c1d09'
			},

			{
				name: 'Wages/Salary',
				data: [4, 5, 6],
				color: '#dd3b21',
				dataLabels: {
					enabled: true,
					color: '#fff',
					y: 5,
					style: {
						font: '13px Play, sans-serif'
					},
					formatter: function() {

						return '$' + addCommas(this.y);

					}
				}
			}]

		}; // end options
		yourselections = new Highcharts.Chart(yourSelectionsOptions);

		var nationalaverage;
		nationalAverageOptions = {

			chart: {
				renderTo: 'results-nationalaverage',
				defaultSeriesType: 'bar',
				backgroundColor: 'transparent',
				backgroundColor: 'rgba(255, 255, 255, 0.0)',
				borderRadius: 0,
				spacingTop: 0,
				spacingBottom: 0,
				spacingRight: 1,
				spacingLeft: 83,
				marginTop: 30,
				height: 114
			},

			credits: {
				enabled: false
			},

			title: {
				text: 'National average',
				floating: true,
				align: 'left',
				y: 10,
				x: -75,
				style: {
					font: '700 15px Play, sans-serif',
					color: '#666'
				}
			},

			subtitle: {
				text: '# Respondants',
				floating: true,
				align: 'right',
				y: 10,
				x: -10,
				style: {
					font: 'bold 12px Play, sans-serif',
					color: '#666'
				}
			},

			tooltip: {
				enabled: true,
				backgroundColor: '#fff',
				borderColor: null,
				borderRadius: 4,
				borderWidth: 0,
				shadow: true,
				style: {
					font: '13px/20px Play, sans-serif',
					padding: '5px',
					color: '#69616c'
				},
				formatter: function() {
					if (this.series.name == 'Wages/Salary') {
						var hourlyRate = this.point.config / 2000;
						var dailyRate = (this.point.config / 2000) * 8;

						var daily = 'Implied hourly rate: <strong>$' + addCommas(hourlyRate) + '</strong><br />' + 'Implied daily rate: <strong>$' + addCommas(dailyRate) + '</strong>';

						return daily;
					} else {
						var compensation = 'Additional Compensation: <strong>$' + addCommas(this.point.config) + '</strong><br />' + 'Total Compensation: <strong>$' + addCommas(this.total) + '</strong>';

						return compensation;
					}
				}
			},

			xAxis: {
				categories: ['25% earn less', '50% earn less', '75% earn less'],
				reversed: true,
				lineColor: null,
				//'#83d0fb'
				tickLength: 0,
				endOnTick: false,
				labels: {
					enabled: false,
					y: 4,
					style: {
						font: '10px sans-serif'
					}
				}
			},

			yAxis: {
				title: {
					text: null
				},
				labels: {
					enabled: false
				},
				gridLineColor: null,
				//'#83d0fb'
				tickPixelInterval: 85,
				endOnTick: false,
				max: 260000
			},

			legend: {
				enabled: false
			},

			plotOptions: {
				bar: {
					stacking: 'normal',
					borderColor: null,
					borderWidth: 0,
					shadow: false,
					pointWidth: 22
				}
			},

			series: [{
				name: 'Additional Compensation',
				data: [1, 2, 3],
				color: '#8c1d09'
			},

			{
				name: 'Wages/Salary',
				data: [4, 5, 6],
				color: '#dd3b21',
				dataLabels: {
					enabled: true,
					color: '#fff',
					y: 5,
					style: {
						font: '13px Play, sans-serif'
					},
					formatter: function() {

						return '$' + addCommas(this.y);

					}
				}
			}]

		}; // end options
		nationalaverage = new Highcharts.Chart(nationalAverageOptions);

	}; // end if statement

});

