$(window).load(function() {
	
	// toggle debugging
	//$('.secondary_content').data('log', 'true');
	
	
	
	/* ---------------------------------------------------------------------- */
	/* tooltips for each company
	/* ---------------------------------------------------------------------- */
	
	// png fix for company tooltips
	if ($.browser.msie && $.browser.version == '6.0') {
		DD_belatedPNG.fix('.portfolio .secondary_content ul.companies .tooltip');
	}
	
	// set up triggers
	$('.portfolio .secondary_content ul.companies li').live('mouseover', function() {
		$(this).parents('ul').find('.tooltip').hide();
		$(this).find('.tooltip').show();
	});
	$('.portfolio .secondary_content ul.companies li').live('mouseout', function() {
		$(this).find('.tooltip').hide();
	});
	$('.portfolio .secondary_content ul.companies li .tooltip').live('mouseover', function() {
		$('.portfolio .secondary_content ul.companies li .tooltip').hide();
	});	
	
	// dynamically position the tooltips
	$('.portfolio .secondary_content .tooltip').each(function() {
		$(this).css('top', $(this).parents('li').outerHeight() + 10);
	})
	
	
	
	/* ---------------------------------------------------------------------- */
	/* company filtering
	/* ---------------------------------------------------------------------- */

	// png fix for company logos in ie6
	if ($.browser.msie && $.browser.version == '6.0') {
		DD_belatedPNG.fix('.primary_content .companies img');
	}
	
	// hide submit button
	$('.secondary_content .company_browser input[type="submit"]').hide();
	
	// init tags array
	var tags = [];
	
	// loop through current tags and add them to array
	$('.secondary_content > .company_tags li').each(function() {
		tags.push({tag: $(this).find('a').html(), url: $(this).find('a').attr('href'), count: parseInt($(this).find('.tag_count').html())});
	});
	
	// run google tag cloud plugin
	$('.secondary_content > .company_tags').tagCloud(tags, {maxFontSizeEm: 2.5, sort: false });

	// The normal tag block
	var company_tags = $('.secondary_content > .company_tags');

	// Create a new block but add the selected class
	var selected_company_tags = company_tags.clone().empty().addClass('selected').addClass('group');
	
	// Place it before the regular tag list
	selected_company_tags.insertBefore(company_tags);
	
	// store an original version of the companies
	if ($('.primary_content .companies').size() > 0) {
		var sectors_select = $('.secondary_content select:last');
		sectors_select
			// set up original data for all primary_content companies
			.data('all_companies', $('.primary_content .all_companies:first').clone().addClass('companies').removeClass('all_companies'))
			// store current version of companies in case tag paring occurs
			.data('filtered_companies', $('.primary_content .companies:first').clone());
			
	}
	
	
	/**
	 * When category changed, trigger ajax
	 *
	 * @return void
	 **/
	$('.secondary_content .company_browser select').change(function() {
		log('function updateCompanies');
		$('.secondary_content > .selected.company_tags.group > li').click();
		$('.secondary_content form.company_browser')
			.ajaxSubmit({
				beforeSubmit: disableSelects,
				dataType:     'json',
				success:      processJson,
				url:          '/sup/ajax/company_browser'
			});
	});
	
	
	/**
	 * When tag clicked, trigger filtering
	 *
	 * @return false
	 **/
	company_tags.children('a').click(function(e){
		log('tag "' + $.trim($(this).contents().filter(function() { return this.nodeType == 3; }).text()) + '" clicked');
		
		if (!$(this)[0].user_selected) {
			// don't allow other actions while occurring
			disableSelects();
			
			// Make sure they can't click it again
			$(this)[0].user_selected = true;
			
			// Get some information
			var selector_tag      = $(this);
			var selected_tag      = $('<li>' + $.trim($(this).contents().filter(function() { return this.nodeType == 3; }).text()) + '</li>');
			
			// Add a remove click event to our newly generated child
			selected_tag.click(function(){
				selector_tag.fadeTo(500, 1);
				selector_tag[0].user_selected = false;
				
				// when clicked update the results
				$(this).fadeOut(750, function(){
					$(this).remove();

					// Redraw the lists
					var primary   = redrawPrimaryCompanies(true);
					var secondary = redrawSecondaryCompanies();

					if (!primary || !secondary) {
						displayError();
					}
				});
			});
			
			// Append the selected tag and fade the original
			selected_company_tags.append(selected_tag);
			selector_tag.fadeTo(750, .30);
			
			// Redraw the lists
			var primary   = redrawPrimaryCompanies(false);
			var secondary = redrawSecondaryCompanies();
			
			if (!primary || !secondary) {
				displayError();
			}
		}
		e.preventDefault();
	});
	
	
	/**
	 * While the ajax is being called, cover the current form and data to 
	 * prevent multiple submissions
	 *
	 * @return true
	 **/
	function disableSelects() {
		log('function disableSelects')
		
		// disabled selecting sectors until done
		$('.secondary_content select')
			.css('visiblity', 'hidden')
			.siblings('.select').css('opacity', 0.4);
		
		// here we could return false to prevent the form from being submitted; 
		// returning anything other than false will allow the form submit to continue 
	    return true; 
	}
	
	
	/**
	 * Display the error messaging, add back in the last image display
	 *
	 * @return void
	 **/
	function displayError() {
		log('function displayError');
		
		var content = '<div class="info"><strong>There are no search results with these filters.</strong>Please change your filters to see more results.</div>';
		$('.secondary_content .company_browser').after(content);
		
		if ($('.primary_content .companies').size() > 0) {
			$('.primary_content').append(content);
		}
		
		enableSelects();
	}
	
	
	/**
	 * Display the new search results
	 *
	 * @param  JSON  data  The new search results
	 * @return void
	 **/
	function displaySuccess(data) {
		log('function displaySuccess');
		
		// remove old results, messaging, set default styles
		$('.primary_content .info, .secondary_content .info, .secondary_content .companies, .secondary_content .sectors').remove();
		$('.primary_content .companies').show();
		
		// if there are no results, display error
		if (data.length == 0) {
			$('.primary_content .companies')
				.html('')
				.hide();
			displayError();
			return false;
		}
		
		// secondary_content update
		// ---------------------------------------------------------------------
		var companies = $('<ul class="companies"></ul>');
		
		// and loop through and append each company
		for (var key in data) {
			var company      = $('<li></li>');
			company.append('<a href="' + data[key].link + '">' + data[key].name + '</a><div class="tooltip"><img src="' + data[key].small_logo + '" alt="' + data[key].name + '" /><hr /><div class="sectors_text">' + data[key].sectors + '</div></div>');
			if (data[key].tags.length) {
				var company_tags = $('<ul></ul>').addClass('company_tags');
				for (var term_key in data[key].tags) {
					company_tags.append('<li>' + data[key].tags[term_key] + '</li>');
				}
				company.append(company_tags);
			}
			companies.append(company);
		}
		
		// insert new data
		companies.appendTo('.secondary_content .companies_sectors');
		
		
		// primary_content update
		// ---------------------------------------------------------------------
		if ($('.primary_content .companies').size() > 0) {
			var new_companies = sectors_select.data('all_companies').clone();

			// loop through each and determine if company is part of selected sector
			new_companies.find('> li').each(function() {
				var company_is_in_results = false;

				// iterate over each selected tag and see if it is within the company
				// specific tags.
				for (var key in data) {
					// iterate over company tags and if a match to the selected tag is
					// found set company_has_selected_tag to true.
					if ($(this).find('img:first').attr('alt') == data[key].name) {
						company_is_in_results = true;
					}
				}

				if (!company_is_in_results) {
					$(this).remove();
				}
			})

			// store current version of companies in case tag paring occurs
			sectors_select.data('filtered_companies', new_companies);

			// show the new companies
			runQuicksand(new_companies);
		} else {
			enableSelects();
		}
	}
	
	
	/**
	 * While the ajax is being called, cover the current form and data to 
	 * prevent multiple submissions
	 *
	 * @return true
	 **/
	function enableSelects() {
		log('function disableSelects')
		
		// disabled selecting sectors until done
		$('.secondary_content select')
			.css('visiblity', 'visible')
			.siblings('.select').css('opacity', 1);
	}
	
	
	/**
	 * Once the ajax has been returned, process the JSON results
	 *
	 * @param  JSON  data  The new search results
	 * @return void
	 **/
	function processJson(data) {
		log('function processJson')
		
		// remove cover
		$('.cover').remove();

		// show appropriate results
		if (data.error) {
			displayError();
		} else {
			displaySuccess(data);
		}
	}
	
	
	/**
	 * Quicksand sorting of companies by sector
	 *
	 * @return boolean
	 **/
	function redrawPrimaryCompanies(allCompanies) {
		log('redrawPrimaryCompanies');
		
		if ($('.primary_content .companies').size() > 0) {
			// remove old results, messaging, set default styles
			$('.primary_content .info').remove();
			$('.primary_content .companies').show();
			
			// create new dataset of companies
			if (allCompanies) {
				log(sectors_select);
				
				var new_companies = sectors_select.data('filtered_companies').clone();
			} else {
				var new_companies = $('.primary_content .companies:first').clone();
			}
		
			if (selected_company_tags.children().size() > 0) {
				// loop through each and determine if company is part of selected sector
				new_companies.find('> li').each(function() {
					var company_tags                  = $(this).find('.company_tags li');
					var company_has_all_selected_tags = true;
				
					// iterate over each selected tag and see if it is within the company
					// specific tags.
					selected_company_tags.children().each(function(){
						var selected_tag_text = $(this).text();
						var company_has_selected_tag = false;
					
						// iterate over company tags and if a match to the selected tag is
						// found set company_has_selected_tag to true.
						company_tags.each(function(){
							log($(this).text())
							if ($.trim($(this).text()) == selected_tag_text) {
								company_has_selected_tag = true;
							}
						});
					
						if (!company_has_selected_tag) {
							company_has_all_selected_tags = false;
						}
					
					});
				
					if (!company_has_all_selected_tags) {
						$(this).remove();
					}
				})
			}
			
			if (new_companies.find('> li').size() == 0) {
				log('no companies returned');
				
				$('.primary_content .companies')
					.html('')
					.hide();
				
				return false;
			}
		
			log(new_companies);
		
			runQuicksand(new_companies);
		} else {
			enableSelects();
		}
		
		return true;
	}
	
	
	/**
	 * Redraw the companies to have updated tags
	 *
	 * @return boolean
	 **/
	function redrawSecondaryCompanies(){
		log('redrawSecondaryCompanies');
		
		// remove old results, messaging, set default styles
		$('.secondary_content .info').remove();
		
		// var init
		var anyShowing = false;
		
		$('.secondary_content .companies li').each(function(){
	
			var company_tags                  = $(this).find('.company_tags li');
			var company_has_all_selected_tags = true;
			
			// iterate over each selected tag and see if it is within the company
			// specific tags.
			selected_company_tags.children().each(function(){
			
				var selected_tag_text = $(this).text();
				var company_has_selected_tag = false;
				
				// iterate over company tags and if a match to the selected tag is
				// found set company_has_selected_tag to true.
				company_tags.each(function(){
					if ($.trim($(this).text()) == selected_tag_text) {
						company_has_selected_tag = true;
					}
				});
				
				if (!company_has_selected_tag) {
					company_has_all_selected_tags = false;
				}
			});
		
			if (!company_has_all_selected_tags) {
				$(this).hide(300);
			} else {
				anyShowing = true;
				
				$(this).show(300);
			}

		});
		
		if (!anyShowing) {
			log('no companies returned');
			
			return false;
		}
		
		return true;
	};
	
	
	/**
	 * Run Quicksand on new companies list
	 *
	 * @return void
	 **/
	function runQuicksand(new_companies) {
		log('runQuicksand');
		
		// if IE6, simply switch out the old company set for the new
		if ($.browser.msie && $.browser.version == '6.0') {
			$('.primary_content .companies:first').remove();
			$('.primary_content').append(new_companies);
			
			enableSelects();
			
		// otherwise quicksand to the new set
		} else {
			// quicksand new data
			$('.primary_content .companies:first').quicksand(new_companies.find('> li'), {
				duration: 800,
				easing: 'easeInOutQuad',
				attribute: 
					function(v) {
						return $(v).find('a:first').attr('href');
					},
				enhancement:
					function() {
						// png fix for ie6
						if ($.browser.msie && $.browser.version == '6.0') {
							DD_belatedPNG.fix('.primary_content .companies img');
							DD_belatedPNG.fix('.portfolio .secondary_content ul.companies .tooltip');
						}
					}
				},
				// callback function
				enableSelects
			);
		}
	}
})


/**
 * Helper fn for console logging
 * Set $.fn.progressBar.debug to true to enable debug logging
 *
 * @return void
 **/
function log() {
	if ($('.secondary_content').data('log') == 'true' && window.console && window.console.log) {
		window.console.log(arguments);
	}
};

