/*!
 * Collapsible helper JS
 * Copyright (c) 2014 Intense Visions, Inc.
 */
/* global jQuery */

(function($) {
	'use strict';

	$(document).ready(function() {
		$('.intense.panel-title').parent().click(function(event) {
			event.preventDefault();

			var $el = $(this).children(".panel-title");
			var $panel = $el.parent().parent().find('.panel-collapse');
			var $collapseIcon = $(this).parent().find('.collapse-icon');
			var $expandIcon = $(this).parent().find('.expand-icon');
			var $panelGroup = $el.parents('.intense.panel-group');
			var $panelBody = $panel.find('.panel-body');
			var singleToggle = $panelGroup.data('single-toggle');

			$expandIcon.addClass('hide');
			$collapseIcon.addClass('hide');

			if ($panel.hasClass('in')) {
				$panel.removeClass('in');
				$expandIcon.removeClass('hide');

				$panelBody.slideUp("fast", function() {
					if ($.isFunction($.fn.isotope)) {
						$el.parents('.isotope').isotope();
					}
				});
			} else {
				if (singleToggle) {
					$panelGroup.find('.panel-collapse').removeClass('in');
					$panelGroup.find('.collapse-icon').addClass('hide');
					$panelGroup.find('.expand-icon').removeClass('hide');
					$panelGroup.find('.panel-body').hide();
				}

				$panelBody.show("fast", function() {
					if ($.isFunction($.fn.isotope)) {
						$el.parents('.isotope').isotope();
					}

					// trigger a resize so that maps will reload tiles					
					// this won't fix the center or zoom
					var evt = document.createEvent('UIEvents');
					evt.initUIEvent('resize', true, false, window, 0);
					window.dispatchEvent(evt);
				});

				// fix icon because when it is hidden at first
				// the size of the icon is wrong. This corrects the size
				intenseIconFix();

				$panel.addClass('in');
				$collapseIcon.removeClass('hide');
				$expandIcon.addClass('hide');
			}

			return false;
		});

		$( '.intense.panel' ).each( function( i, obj ) {
			var $collapsible = $(this).find( '.panel-collapse' );
			var $collapsible_body = $collapsible.find( '.panel-body' );

			if ( !$collapsible.hasClass( 'in' ) ) {
				$collapsible_body[0].style.display = 'none';
			}
		});
	});

	function intenseIconFix() {
		$('use.stack-base').each(function() {
			var $child = $(this).next();
			var parentWidth = $(this).parent().width();
			var parentHeight = $(this).parent().height();

			$child.attr('width', parentWidth * 0.5);
			$child.attr('height', parentHeight * 0.5);

			var childWidth = parentWidth * 0.5;
			var childHeight = parentHeight * 0.5;

			$child.attr('x', parentWidth / 2 - childWidth / 2);
			$child.attr('y', parentHeight / 2 - childHeight / 2);
			
			$(this).parent().css('visibility', 'visible');
		});
	}
})(jQuery);