/**
 * fusionLib JavaScript library to implement height matching of elements.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * Copyright (c) 2014 fusionLib. All rights reserved.
 */

(function() {

	// Match the height of items
	var _lastW = 0,
		elements = [],
		isLoaded = false;

	/**
	 * Match the height of all elements in a group.
	 *
	 * @param Array elements The elements to match the height of.
	 */
	function updateElementGroup(elements) {
		var maxHeight = 0;

		// Find the max height
		for(var i = 0; i < elements.length; i++) {
			var e = fusionLib(elements[i]);
			e.css('height', 'inherit');
			maxHeight = Math.max(maxHeight, parseInt(e.css('height')));
		}

		// Set the heights of elements
		for(var i = 0; i < elements.length; i++) {
			fusionLib(elements[i]).css('height', maxHeight + 'px');
		}
	}

	/**
	 * Run through the list of element groups and match their heights.
	 */
	function updateMatchHeights() {
		if(isLoaded) {
			if(fusionLib(window).width() != _lastW) {
				_lastW = fusionLib(window).width();

				for(var n = 0; n < elements.length; n++) {
					updateElementGroup(elements[n]);
				}
			}
		}
	}

	/**
	 * Track window resize events.
	 */
	fusionLib(window).bind('resize', function() {
		updateMatchHeights();
	}).bind('orientationchange', function() {
		updateMatchHeights();
	}).bind('load', function() {
		isLoaded = true;
		updateMatchHeights();
	});

	fusionLib.fn.extend({
		/**
		 * Match the heights of the selected elements
		 *
		 * @return fusionLib This object.
		 */
		matchHeights: function() {
			if(isLoaded)
				updateElementGroup(this);
			elements.push(this);
			return this;
		}
	});

})();