// $cmignore
$(document).ready(function () {
	// Step 0: ie doesn't fire change events on dropdown, so we must use the
	// proprietary propertychange event instead.
	var eventType = $.browser.msie ? 'propertychange' : 'change';
	
	// Step 1: fetch the URL parameters on the current page and serialize them
	// into a hash/object, making sure to store multiple parameters with the 
	// same key into an array.
	$('.results-block .heading form select').bind(eventType, function () {
		var url = document.location.href.split('?')[1].split('#');
		var parameters = {};
		
		$.each(url[0].split('&'), function (i, n) {
			var pair = n.split('=');
			var key = decodeURIComponent(pair[0]);
			var value = decodeURIComponent(pair[1]);
			
			// jQuery's $.param function will encode + as %2D instead of a space
			// although, decodeURIComponent will keep a + as is. To prevent this
			// incorrect behavoir we must swap +s for spaces before parameterizing
			// them. (Note: the /g flad on the regex triggers a global search and
			// replace, i.e. *all* instances of + are replaced with a space,
			// instead of just the first.)
			value = value.replace(/\+/g, ' ');
			
			// If the key doesn't exist, insert it.
			if (typeof(parameters[key]) == 'undefined') {
				parameters[key] = value;
			}
			// Otherwise...
			else {
				// If the key already exists, and only has one value, make it an 
				// array containing the original value and the new value.
				if (typeof(parameters[key]) == 'string') {
					parameters[key] = [parameters[key], value];
				}	// Otherwise, assume we have an array and simply push the value
					// onto the array.
				else {
					parameters[key].push(value);
				}
			}
		});
		
		// Step 2: add the parameter for the dropdown to our hash. Since we 
		// always know we're dealing with scalar values, we can overwrite them
		// and not worry about switching over to an array as we do above.
		parameters[decodeURIComponent($(this).attr('name'))] = decodeURIComponent($(this).val());
		
		// Step 3: construc our new URL with the original parameters and our
		// new parameter combined.
		var newUrl = document.location.pathname + '?' + $.param(parameters) + (url.length > 1 ? '#' + url[1] : '');

		// Step 4: redirect to our new URL.
		window.location = newUrl;
	});
	
	$('.show a').click(function () {
		var form = $(this).closest('form');
		form.find('.check input[type=checkbox]')
			.attr('checked', 'checked');
		return false;
	});
	
	$('.choose-color-domain').hover(
		function () {
			$(this).find('.domain-chooser').show();
		},
		function () {
			$(this).find('.domain-chooser').hide();
		}
	);
	
	$('body').addClass('dynamic');
});
// $/cmignore
