/*
	flexible modal for universal usage on the pas website
	
	trigger and content must have:
	
		1) classes: modal-trigger and modal-content,
		2) as well as a matching data-modal attribute
	
	other params:
	
		data-modal-width : set interior width of content area
		data-modal-height : set interior height of content area
		data-modal-pad : add uniform padding to content area
		data-youtube : youtube video id, takes over all content
		data-vimeo : vimeo video id, takes over all content
	
	example pair:
	
		<a href="http://google.com" class="modal-trigger" data-modal="success">
			Trigger the success modal!
		</a>
		
		<div 
			class="modal-content" 
			data-modal="success" 
			title="Start planning for success today!" 
			style="display:none">
			<p>Content</p>
		</div>
	
	body appending html:
	
		<div id="modal-overlay" style="display:none" />
		<div id="modal-body" style="display:none">
			<div id="modal-header">
				<div id="modal-header-title" class="text-shadow af" />
				<a href="#" id="modal-close" class="pngBg" />
			</div>
			<div id="modal-content" />
		</div>
	
	event tracking:
	
		1) on click modal trigger (not just open, to avoid effecting bounce rate in GA)
		2) on close
*/
window.U = window.U || {};
U.tack_modal = {
	current_name: '',
	body_string: '<div id="modal-overlay" style="display:none" /><div id="modal-body" style="display:none"><div id="modal-header"><div id="modal-header-title" class="af text-shadow" /><a href="#" id="modal-close" class="pngBg" /></div><div id="modal-content" /></div>',
	$trigger: '.modal-trigger',
	$contents: '.modal-content',
	$overlay: '',
	$body: '',
	$header: '',
	$title: '',
	$close: '',
	$content: '',
	default_width: 700,
	default_height: 450,
	head_height: 0,
	use_position_absolute: false,
	
/*
	find all instances of trigger and content, only initiate if necessary
*/
	init: function() {
		// detect if ie 7 or less, use abs positioning instead
		if($.browser.msie && parseInt($.browser.version, 10) < 8) {
			U.tack_modal.use_position_absolute = true;
		}
		// initiate modal system if needed
		U.tack_modal.$trigger = $(U.tack_modal.$trigger);
		U.tack_modal.$contents = $(U.tack_modal.$contents);
		if (U.tack_modal.$contents.length > 0) {
			U.tack_modal.create_modal();
			U.tack_modal.test_hash();
			U.tack_modal.test_get();
		}
	},
	
/*
	adds necessary html to the page for modal
	store $content
	bind triggering
*/
	create_modal: function() {
		$('body').append(U.tack_modal.body_string); 
		
		//create the elements
		U.tack_modal.$overlay = $('#modal-overlay');
		U.tack_modal.$body = $('#modal-body');
		U.tack_modal.$header = $('#modal-header');
		U.tack_modal.$title = $('#modal-header-title');
		U.tack_modal.$close = $('#modal-close');
		U.tack_modal.$content = $('#modal-content'); 
		
		//jack the $content into an internal array
		//create trigger content pairs
		U.tack_modal.$trigger.live('click', U.tack_modal.click_trigger);
		
		//close modal on clicking close or overlay or pressing escape
		U.tack_modal.$close.click(U.tack_modal.close_modal);
		U.tack_modal.$overlay.click(U.tack_modal.close_modal);
		$(document).keypress(function(e) {
			if (e.which === 27) {
				U.tack_modal.close_modal();
			}
		}); 
		
		//move top of overlay and body to scrolltop of document
		
		if (U.tack_modal.use_position_absolute) {
			$(window).bind('scroll resize', function() {
				U.tack_modal.adjust_position();
			});
			U.tack_modal.$overlay.css('position', 'absolute');
			U.tack_modal.$body.css('position', 'absolute');
		}
		U.tack_modal.head_height = U.tack_modal.$header.outerHeight(true);
	},
	
/*
	based on data-modal attribute
	find the matching content
	change the content
	and display the modal if necessary
	or change its size
*/
	click_trigger: function() {
		U.tack_modal.current_name = $(this).data('modal');
		U.tack_modal.change_content();
		if(_gaq !== undefined) {
			_gaq.push(['_trackEvent', 'modal', 'click-trigger-open', U.tack_modal.current_name, 1]);
		}
		return false;
	},
	
/*
	DEPRECATED, do not use, use test_get or open_modal
*/
	test_hash: function() {
		var hash = window.location.hash.substring(1),
			$match = U.tack_modal.$contents.filter('[data-modal="' + hash + '"]');
		if ($match.length > 0) {
			U.tack_modal.current_name = hash;
			U.tack_modal.change_content();
			return false;
		}
	},

/*
	if the get data has
	?modal=data-modal-attr-name
	show the modal automatically
*/
	test_get: function() {
		var get = U.tack_modal.parseQueryString(),
			hash = get.modal,
			$match;
		if (hash !== undefined) {
			hash = hash[0];
		}
		if (hash !== undefined) {
			$match = U.tack_modal.$contents.filter('[data-modal="' + hash + '"]');
		}
		if ($match !== undefined && $match.length > 0) {
			U.tack_modal.current_name = hash;
			U.tack_modal.change_content();
			return false;
		}
	},

/*
	specific a modal to open via its data-modal attribute
*/
	open_modal: function(string) {
		var $match = U.tack_modal.$contents.filter('[data-modal="' + string + '"]');
		if ($match.length > 0) {
			U.tack_modal.current_name = string;
			U.tack_modal.change_content();
			return false;
		}
	},

/*
	find the content with the matching data-modal attr
	make sure there is exactly one match
	add in the content
	set the title
*/
	change_content: function() {
		U.tack_modal.$content.empty();
		U.tack_modal.$title.empty(); 
		//content to load in
		var $content_ref = U.tack_modal.$contents.filter('[data-modal="' + U.tack_modal.current_name + '"]'),
			$content = $content_ref.clone(); 
		U.tack_modal.check_and_add_video($content, $content_ref);
		U.tack_modal.check_matches_and_setup($content);
		U.tack_modal.adjust_size($content);
		if (U.tack_modal.use_position_absolute) {
			U.tack_modal.adjust_position();
		}
		U.tack_modal.show_modal();
		U.tack_modal.$content.trigger('ready');
	},

/*
	make sure there is one and exactly one matching content node
	add it, but hide it until after the
	size and position calculations are made
*/
	check_matches_and_setup:function($content) {
		//make sure there is exactly one match
		if ($content.length === 0) {
			U.tack_modal.$content.append('<p>No matching content.</p>');
		} else if ($content.length > 1) {
			U.tack_modal.$content.append('<p>More than one matching content element.</p>');
		} else { 
			//add in the content
			U.tack_modal.$content.append($content.html()); 
			//set the title
			U.tack_modal.$title.append($content.attr('title'));
		}
		U.tack_modal.$content.hide(); 
	},
	
/*
	if data-youtube or data-vimeo are set,
	add them to the modal
*/
	check_and_add_video: function($content, $content_ref) {
		//youtube/vimeo videos embed directly
		if ($content_ref.data('youtube') !== undefined || $content_ref.data('vimeo') !== undefined) {
			var vid = {}, vid_params, $vid;
			if($content_ref.data('vimeo') !== undefined) {
				vid.type = 'vimeo';
			} else {
				vid.type = 'youtube';
			}
			vid.data = $content_ref.data(vid.type);
			vid.data = vid.data.split(':');
			if(vid.type === 'vimeo') {
				vid.code = 'http://player.vimeo.com/video/' + vid.data[0];
				vid.code += '?title=0&byline=0&portrait=0&autoplay=1';
			} else {
				vid.code = 'http://www.youtube.com/embed/' + vid.data[0];
				vid.code +=  '?hd=1&rel=0&wmode=opaque&autoplay=1&html5=1';
			}
			vid_params = {
				width: vid.data[1],
				height: vid.data[2],
				frameborder: 0,
				src: vid.code
			};
			$vid = $('<iframe />', vid_params);
			$content.prepend($vid);
		}
	},
	
/*
	adjust size based on attrs
	data-modal-height and data-modal-width
*/
	adjust_size: function($content) {
		var h = $content.data('modal-height'),
			w = $content.data('modal-width'),
			p = $content.data('modal-pad'),
			total_height,
			total_width;
		w = parseInt(w, 10) || false;
		h = parseInt(h, 10) || false;
		p = parseInt(p, 10) || 0;
		if (h !== undefined && h) {
			total_height = h + p * 2 + U.tack_modal.head_height;
			U.tack_modal.$body.css({
				height: total_height,
				'margin-top': -(total_height / 2)
			});
			U.tack_modal.$content.css({
				height: h,
				padding: p
			});
		} else {
			U.tack_modal.$body.css({
				height: U.tack_modal.default_height,
				'margin-top': -(U.tack_modal.default_height / 2)
			});
			U.tack_modal.$content.css({
				height: U.tack_modal.default_height,
				padding: 0
			});
		}
		if (w !== undefined && w) {
			total_width = w + p * 2;
			U.tack_modal.$body.css({
				width: total_width,
				'margin-left': -(total_width / 2)
			});
		} else {
			U.tack_modal.$body.css({
				width: U.tack_modal.default_width,
				'margin-left': -(U.tack_modal.default_width / 2)
			});
		}		
	},
	
	
/*
	fixes the position of the modal and overlay
*/
	adjust_position: function() {
		U.tack_modal.$overlay.css({
			top: $(window).scrollTop()
		});
		U.tack_modal.$body.css({
			top: $(window).scrollTop() + $(window).height() / 2 - U.tack_modal.$body.outerHeight() / 2,
			'margin-top': 0
		});
	},
	
	
/*
	show the modal
*/
	show_modal: function() {
		U.tack_modal.$overlay.fadeIn(100, function() {
			U.tack_modal.$body.show(500, function() {
				U.tack_modal.$content.show();
			});
		});
	},
	
	
/*
	hides the modal
*/
	close_modal: function() {
		U.tack_modal.$content.trigger('close');
		if(_gaq !== undefined) {
			_gaq.push(['_trackEvent', 'modal', 'close-modal', U.tack_modal.current_name, 1]);		
		}
		U.tack_modal.$title.empty();
		U.tack_modal.$content.empty();
		U.tack_modal.$body.hide(500, function() {
			U.tack_modal.$overlay.fadeOut(100);
		});
		return false;
	}
}; 

//from http://safalra.com/web-design/javascript/parsing-query-strings/
U.tack_modal.parseQueryString = function(queryString) { 
	// define an object to contain the parsed query data
	var result = {}; 
	// if a query string wasn't specified, use the query string from the URI
	if (queryString === undefined) {
		queryString = location.search ? location.search : '';
	} 
	// remove the leading question mark from the query string if it is present
	if (queryString.charAt(0) == '?') queryString = queryString.substring(1); 
	// replace plus signs in the query string with spaces
	queryString = queryString.replace(/\+/g, ' '); 
	// split the query string around ampersands and semicolons
	var queryComponents = queryString.split(/[&;]/g); 
	// loop over the query string components
	for (var i = 0; i < queryComponents.length; i++) { 
	// extract this component's key-value pair
		var keyValuePair = queryComponents[i].split('=');
		var key = decodeURIComponent(keyValuePair[0]);
		var value = decodeURIComponent(keyValuePair[1]); 
		// update the parsed query data with this component's key-value pair
		if (!result[key]) result[key] = [];
		result[key].push((keyValuePair.length == 1) ? '' : value);
	} // return the parsed query data
	return result;
};
