$(function() {

	var $accordion = $(".accordion"),
		$allItems,
		$allTabs,
		$allVideoContainers,
		$allVideos,
		$itemTemplate = $("#itemTemplate"),
		video_url_key = (window.screen.width >= 1024) ? 'ipad_video_url' : 'iphone_video_url',
		innerExpandedWidth = 544;

	// Grab XML data file with all content
	$.get("/includes/xml/careers-placeholder.xml", function(itemsXml) {
		var $itemsXml = $(itemsXml).find("tile");

		// Create DOM elements for each XML node
		$itemsXml.each(function(i, itemXml) {
			var $itemXml = $(itemXml);

			// Create item
			var $item = $itemTemplate.tmpl({
				title: $itemXml.find("main_title").text() || $itemXml.find("main_headline").text(),
				headline: $itemXml.find("main_headline").text(),
				copy: $itemXml.find("main_copy").text(),
				link1: $itemXml.find("link1_url").text(),
				link2: $itemXml.find("link2_url").text(),
				link3: $itemXml.find("link3_url").text(),
				video_url: $itemXml.find(video_url_key).text()
			});

			// Insert into accordion
			$accordion.append($item);
		
		});

		// Set up pointers to accordion elements
		$allItems = $accordion.find(".item");
		$allTabs = $allItems.find(".tab");
		$allVideoContainers = $allItems.find(".video");
		$allVideos = $allVideoContainers.children();

		// Disable the tabs while animating
		var disable = false;

		// Switch panels when a tab is clicked
		$allTabs.bind("click", function() {
			if (!disable && !$(this).parent().is(".active")) {
				disable = true;
				hideItem($allItems.filter(".active"));
				showItem($(this).parent(), function() {
					disable = false;
				});
			}
		});

		// Force videos to fill the entire panel
		$allVideos.width(innerExpandedWidth);

		// Initially show the item on the far left
		var $intialItem = $allItems.eq($allItems.length - 1);
		showItem($intialItem);

	});

	// Show a panel
	function showItem($item, callback) {

		var $tab = $item.children(".tab"),
			$videoContainer = $item.children(".video"),
			$video = $videoContainer.children(),
			$about = $item.children(".about");

		$item.addClass("active");
		$videoContainer.animate({ width: innerExpandedWidth }, 500, function() {

			$video.show();

			if ($video.is(":not([src])")) {
				$video.attr("src", $video.attr("data-lazyload-src"));
			}

			if (callback) callback();

		});
		$about.fadeIn();
	} 

	// Hide a panel
	function hideItem($item, callback) {

		var $tab = $item.children(".tab"),
			$videoContainer = $item.children(".video"),
			$video = $videoContainer.children(),
			$about = $item.children(".about");

		$item.removeClass("active");
		$videoContainer.animate({ width: 0 }, 500, callback);
		$video.hide()[0].pause();
		$about.fadeOut();
	}

});
