$(document).ready(function() {
	var expose = null;

	$('.contact-us').overlay({
		target: 'div.overlay',
		top: '5%',
		onBeforeClose: function() {
			if (expose) {
				expose.close();
			}
		}
	});

	$('.mc-link, #join-now a').overlay({
		target: '.mc-overlay',
		top: '32%',
		onBeforeClose: function() {
			if (expose) {
				expose.close();
			}
		}
	});

	$('#intro-movie').overlay({
		target: '#intro-movie-overlay',
		top: '22%',
		onBeforeClose: function() {
			if (expose) {
				expose.close();
			}
		}
	});
});

var Shopkick = Shopkick || {};

Shopkick.Jobs = function(jobs) {

	// Returns a comparator function to sort columns
	function buildCmp(getValueFunc) {
		return function(a, b) {
			var x = getValueFunc(a),
					y = getValueFunc(b);

			if (x < y) 
				return -1;
			if (x > y)
				return 1;
			return 0;
		};
	}

	function indicateSortedColumn(el) {
		$("th a").removeClass('active');
		$(el).addClass('active');			
	}

	function sortJobs(key) {

		jobs.sort(buildCmp(function(dict) { 
			return dict[key]; 
		}));

		var pressTable = $('table#press'),
				template = $('.job-template');

		pressTable
			.find('tr:not(.job-template)')
			.slice(1)
			.remove(); // Clear rows from table

		$.each(jobs, function(index, dict) {
			var newRow = template
					.clone()
					.removeClass('job-template');

			$.each(dict, function(key, value) {
				var cell = newRow.find('.'+key),
						cellLink = cell.find('a');

				if (cellLink.length > 0) {
					cellLink
						.attr('href', 'javascript:;')
						.click(function() {
							window.open(dict['link'], "jobWindow", "width=650,height=500,scrollbars=yes,location=no")
						})
						.text(value);
				} else {
					cell.text(value);
				}
			});

			pressTable.append(newRow);
		});

		indicateSortedColumn(this);
	}

	sortJobs.apply($('#position'), ['position']);

	var cols = "position department position-type".split(' ');
	// Add click handlers to each column
	$.each(cols, function(index, value) {
		$('#'+value).click(function() {
			sortJobs.apply(this, [value]); 
		});
	});

	
}

