var efh = {

	maxCategoriesPerProfile : 3,
	sendToFriendPanel : null,
	introduceMePanel : null,
	messagesPanel : null,
	searchDefaultValue : 'Find quality companies by Name, Keyword, etc',
	categoriesJs : [], // Array of category names for use by autocomplete

	initCompanyListingsPage : function() {
		efh.sendToFriendPanel = new YAHOO.widget.Panel("sendToFriendDiv", {
			constraintoviewport : true,
			width : "500px",
			close : true,
			draggable : false,
			zindex : 7000,
			modal : true,
			visible : false,
			iframe : true,
			underlay : 'shadow'
		});
		efh.sendToFriendPanel.render();
		efh.sendToFriendPanel.subscribe('show', function() {
			YAHOO.util.Dom.setStyle('sendToFriendDiv', 'display', 'block');
		});

		efh.introduceMePanel = new YAHOO.widget.Panel("introduceMeDiv", {
			constraintoviewport : true,
			width : "500px",
			close : true,
			draggable : false,
			zindex : 7000,
			modal : true,
			visible : false,
			iframe : true,
			underlay : 'shadow'
		});
		efh.introduceMePanel.render();
		efh.introduceMePanel.subscribe('show', function() {
			YAHOO.util.Dom.setStyle('introduceMeDiv', 'display', 'block');
		});
	},

	sendToFriend : function(profileId) {
		YAHOO.util.Dom.get('sendToFriendProfileId').value = profileId;
		efh.sendToFriendPanel.show();
		efh.sendToFriendPanel.center();
	},

	introduceMe : function(profileId) {
		YAHOO.util.Dom.get('introduceMeProfileId').value = profileId;
		efh.introduceMePanel.show();
		efh.introduceMePanel.center();
	},

	descriptionCount : function() {
		return;

		var max = 250;
		var ta = YAHOO.util.Dom.get('company-description');
		var counter = YAHOO.util.Dom.get('description-counter');
		var remaining = max - ta.value.length;
		remaining = (remaining > 0) ? remaining : 0;

		counter.innerHTML = remaining + ' characters remaining.';

		if (ta.value.length > max) {
			ta.value = ta.value.substring(0, max);
		}
	},
	/*
	initSearch : function() {
		YAHOO.util.Dom.get('query').value = efh.searchDefaultValue;

		// Remove the default text onfocus
		YAHOO.util.Event.addListener('query', 'focus', function() {
			var input = YAHOO.util.Dom.get('query');
			if (input.value == efh.searchDefaultValue) {
				input.value = '';
				YAHOO.util.Dom.setStyle(input, 'color', '#000000');
			}
		});

		// Toggle advanced search
		YAHOO.util.Event.addListener('advanced-search-toggle', 'click',
				function(e) {
					var visible = (parseInt(YAHOO.util.Dom.getStyle(
							'advanced-search', 'height')) > 0);

					if (visible) {
						var attributes = {
							height : {
								to : 0
							}
						};
					} else {
						var attributes = {
							height : {
								to : 40
							}
						};
					}

					var anim = new YAHOO.util.Anim('advanced-search',
							attributes);
					anim.animate();

					YAHOO.util.Event.stopEvent(e);
				});

		// Remove the default text on submit
		YAHOO.util.Event.addListener('search-form', 'submit', function() {
			var input = YAHOO.util.Dom.get('query');

			if (input.value == efh.searchDefaultValue) {
				input.value = '';
			}
		});
	},
	*/
	initProfilesMap : function(companies, searchLocation) {
		var mapContainer = YAHOO.util.Dom.get('profiles-map');

		if (!mapContainer || !(companies instanceof Array)) {
			return;
		}

		var map = new GMap2(mapContainer);
		map.setUIToDefault();

		var numCompanies = companies.length;

		for ( var x = 0; x < numCompanies; x++) {
			var company = companies[x];

			var point = new GLatLng(company.addressLat, company.addressLong);

			// Center the map on the first result
			if (x == 0) {
				map.setCenter(point, 10);
			}

			if (point) {
				var label = company.resultPosition + ""; // var label = x +
															// 1; label = label
															// + "";
				var marker = efh.createMarker(point, company, label);
				map.addOverlay(marker);
			}
		}
	},

	createMarker : function(point, company, iconLabel) {
		var iconOptions = {
			label : iconLabel,
			primaryColor : "#f39328"
		};

		if (company.fid == 1) {
			iconOptions.addStar = 'true';
		}

		var newIcon = new MapIconMaker.createLabeledMarkerIcon(iconOptions);
		var marker = new GMarker(point, {
			icon : newIcon
		});

		GEvent.addListener(marker, 'click', function() {
			document.location = '#company-' + company.id;
		});

		return marker;
	},

	toggleProfileImage : function(profileId, logo) {
		switch (logo) {
		case 'secondary':
			YAHOO.util.Dom.setStyle('profile-' + profileId + '-primary-logo',
					'display', 'none');
			YAHOO.util.Dom.setStyle('profile-' + profileId + '-secondary-logo',
					'display', 'inline');

			YAHOO.util.Dom.setStyle('profile-' + profileId + '-primary-button',
					'color', '#378c63');
			YAHOO.util.Dom.setStyle(
					'profile-' + profileId + '-secondary-button', 'color',
					'#c1c1c1');
			break;
		default:
			YAHOO.util.Dom.setStyle('profile-' + profileId + '-secondary-logo',
					'display', 'none');
			YAHOO.util.Dom.setStyle('profile-' + profileId + '-primary-logo',
					'display', 'inline');

			YAHOO.util.Dom.setStyle('profile-' + profileId + '-primary-button',
					'color', '#c1c1c1');
			YAHOO.util.Dom.setStyle(
					'profile-' + profileId + '-secondary-button', 'color',
					'#378c63');
			break;
		}
	},

	initMessages : function() {
		efh.messagesPanel = new YAHOO.widget.Panel("messages-div", {
			constraintoviewport : true,
			fixedcenter : true,
			width : "500px",
			close : true,
			draggable : false,
			zindex : 7000,
			modal : true,
			visible : false,
			iframe : true,
			underlay : 'shadow'
		});
		efh.messagesPanel.render();
		efh.messagesPanel.show();
		YAHOO.util.Dom.setStyle('messages-div', 'display', 'block');
		efh.messagesPanel.center();
	},

	profileInit : function() {

		/**
		 * add action to add category link
		 */
		lf.event.addListener('add-category', 'click',
				this.profileCategorySelectShow, this);

		/**
		 * Load categories
		 */
		this.profileLoadSelectedCategories();

		/**
		 * Attach toggle actions to category lists and such
		 */
		lf
				.foreach(lf.element
						.query('#category-select .category-column h2 a'),
						function(link) {

							// determin if this a sub cat
						var distanceFromOuter = 0;
						YAHOO.util.Dom.getAncestorBy(link, function(element) {
							distanceFromOuter++;
							return (element.id == 'category-select');
						});

						// this is a main cat, just override the click and give
						// it a better class name
						if (distanceFromOuter <= 4) {

							lf.event.addListener(link, 'click', function(e) {
								YAHOO.util.Event.stopEvent(e);

								var target = lf.event.getTarget(e); // goes
																	// link->h2->container
									var subContainer = lf.element.query(
											'.category-column',
											target.parentNode.parentNode);

									// toggle the sub cat below this, is a div
									// with class category-column
									if (lf.element.isVisible(subContainer[0])) {
										lf.element.hide(subContainer);
									} else {
										lf.element.show(subContainer);
									}

								}, this);

							// add class to the h2 the link is in
							lf.element.addClass(link.parentNode,
									'main-category');

						}
						// this is a sub cat
						else {

							// see if there are sub categories beneath this link
							var subCats = lf.element.query('ul li',
									link.parentNode.parentNode);

							// if there are no sub cats, remove the link
							if (subCats.length == 0) {

								lf.element.addClass(link,
										'empty-parent-category');
								lf.event.addListener(link, 'click',
										YAHOO.util.Event.stopEvent,
										YAHOO.util.Event);

							} else {

								lf.event
										.addListener(
												link,
												'click',
												function(e) {

													YAHOO.util.Event
															.stopEvent(e);

													// get the link
													var link = lf.event
															.getTarget(e);
													var parent = link.parentNode.parentNode;

													// find UL inside here and
													// toggle it
													var ul = lf.element.query(
															'ul', parent, true);
													if (lf.element
															.isVisible(ul)) {
														lf.element.hide(ul);
													} else {
														lf.element.show(ul);
													}

												}, this);

							} // end if sub sub cats

							// drop in checkbox
							var categoryId = this
									.profileGetCategoryFromClassOfElement(link.parentNode);
							lf.element.insertAsFirst(link.parentNode, this
									.profileCreateCheckbox(categoryId));

						} // end if sub cat

					}, this);

		/**
		 * Drop in checkboxes instead of arrows for categories
		 */
		lf.foreach(lf.element.query('#category-select .category-group ul'),
				this.profileDropInCheckboxesForSubSubCategorys, this);

		/**
		 * Add close button to the cateogry select pane
		 */
		var close = document.createElement('a');
		close.innerHTML = "Close";
		close.id = "category-select-close";
		close.href = "#";

		var hd = document.createElement('div');
		hd.id = 'category-select-hd';

		hd.appendChild(close);

		lf.element.insertAsFirst('category-select', hd);
		lf.event.addListener(close, 'click', this.profileCategorySelectHide,
				this);

		// check the right boxes to start
		var categoryIds = lf.element.get('category-ids').value.split(",");
		lf.foreach(categoryIds, function(categoryId) {
			lf.element.query('.category-' + categoryId + '-checkbox', null,
					true).checked = true;
		});

		// add a suggest a category link as the last element in each sub cat
		// group
		var subCats = lf.element.query('.category-group');

		lf
				.foreach(
						subCats,
						function(container) {
							// onlly add suggest parent category columns
							if (container.parentNode.parentNode.id == 'category-select') {
								var suggest = document.createElement('div');
								lf.element.addClass(suggest, 'category-column');
								lf.element.addClass(suggest,
										'suggest-a-category');
								lf.element.hide(suggest);

								suggest.innerHTML = '<a href="#" onclick="efh.profileSuggestCategory(); return false;">Suggest A Category</a>';

								container.appendChild(suggest);
							}
						}, this);

		// highlight the proper checkboxes first thing
		this.profileCheckedSelectedCategoryCheckboxes();

		// exit confirmation
		var me = this;
		window.onbeforeunload = function(e) {
			return me.profileExit(e);
		}

		// make sure we don't throw an error on form submission
		lf.event.addListener('profile-form', 'submit', function() {
			this.profileFormSubmitting = true;
		}, this);

		// suggets panel
		this.profileSuggestPanel = new YAHOO.widget.Panel("suggest-a-category",
				{
					fixedcenter : true,
					draggable : true,
					zIndex : 100
				});

		this.profileSuggestPanel.render();
		this.profileSuggestPanel.hide();

		// submit category suggestion
		lf.event.addListener('suggest-form', 'submit',
				this.profileSuggestCategorySubmit, this);

		// save serialized form to compare against later to see if they are
		// leaving the page without saving
		setTimeout(function() {
			me.profileQueryString = YAHOO.util.Connect.setForm('profile-form');
		}, 500);
	},

	profileLoadSelectedCategories : function() {
		var postData = "category-ids=" + lf.element.get('category-ids').value;

		lf.asyncUpdate('selected-categories',
				'/member/update-profile-selected-categories/?' + postData, {
					success : function() {
					}
				}, postData, 'POST');
	},

	profileCategorySelectShow : function(e) {

		YAHOO.util.Event.stopEvent(e);

		/**
		 * Shrink all sub cats
		 */
		lf.element.hide(lf.element
				.query('#category-select .category-column .category-column'));

		/**
		 * Shrink up all subsubcats
		 */
		lf.element
				.hide(lf.element.query('#category-select .category-group ul'));

		/**
		 * Show the category select
		 */
		lf.element.show('category-select');
		this.profileModalShow();

		// check the right boxes
		this.profileCheckedSelectedCategoryCheckboxes();

		// highlight parent categories
		this.profileHighlighMainCategories();

	},

	profileCheckedSelectedCategoryCheckboxes : function() {
		/**
		 * Select the proper check boxes
		 */
		var categoryIds = lf.element.get('category-ids').value.split(",");
		lf.foreach(categoryIds, function(id) {
			if (id) {

				var checkbox = lf.element.query(
						'.category-' + id + '-checkbox', null, true);
				checkbox.checked = true;

				// check parent checkbox so it's checked if any child is checked
				this.profileCheckParentCategory(checkbox);

			}
		}, this);

		// lets show all sub sub cats from the start if their parent is checked
		var subCatCheckboxes = lf.element
				.query("#category-select input.skip:checkbox");
		lf.foreach(subCatCheckboxes, function(checkbox) {
			var subSubCategoryContainer = YAHOO.util.Dom
					.getNextSibling(checkbox.parentNode);
			lf.element.show(subSubCategoryContainer);
		}, this);

	},

	profileCheckParentCategory : function(checkbox, checked) {

		if (lf.isUndefined(checked)) {
			checked = true;
		}

		// make sure we're in a sub sub category
		if (checkbox.parentNode.nodeName == 'H2') {
			return;
		}

		// lets move up and find a parent if we can
		var parent = YAHOO.util.Dom.getAncestorByClassName(checkbox,
				'category-group');
		var parentCheckbox = lf.element.query("h2 input", parent, true);

		if (parentCheckbox) {

			// check a bit later if there are any sub cats checked
			setTimeout(function() {
				var checkedBoxes = lf.element.query(
						'ul input:checked:not(.skip)', parent);

				if (checkedBoxes.length > 0) {

					if (!YAHOO.util.Dom.hasClass(parentCheckbox, 'skip')) {
						lf.element.addClass(parentCheckbox, 'skip');
					}

					parentCheckbox.checked = true;

				} else {
					parentCheckbox.checked = false;
				}
			}, 0);

		}
	},

	profileCategorySelectHide : function(e) {

		YAHOO.util.Event.stopEvent(e);

		lf.element.hide('category-select');
		this.profileModalHide();
	},

	profileModalShow : function() {

		lf.element.show('modal-backdrop');
		lf.element.setStyle('modal-backdrop', 'opacity', .4);

		var height = lf.element.getDocumentHeight();
		lf.element.setStyle('modal-backdrop', 'height', height + 'px');
	},

	profileModalHide : function() {
		lf.element.hide('modal-backdrop');
	},

	/**
	 * Pass this a ul from the category select and it will drop in checkboxes
	 * and other actions
	 * 
	 * it does the checkbox for the categories that are nexted down a few levels
	 * deep, NOT in the H2 Tags
	 */
	profileDropInCheckboxesForSubSubCategorys : function(ul) {
		// loop through all LI's
		lf.foreach(lf.element.query('li', ul), function(li) {

			// if there is a link, remove it
				var link = lf.element.query('a', li, true);
				if (link) {
					var category = link.innerHTML;
					lf.element.deleteElement(link);
					li.innerHTML += category;
				}

				// get category id classname = array(category-343)
				var categoryId = this.profileGetCategoryFromClassOfElement(li);

				// insert checkbox

				var checkbox = this.profileCreateCheckbox(categoryId);
				checkbox = lf.element.insertAsFirst(li, checkbox);

				// remove an arrow if there is one
				var arrow = lf.element.query('span.arrows', li, true);
				lf.element.deleteElement(arrow);

			}, this);
	},

	profileCreateCheckbox : function(categoryId) {

		// drop in checkboxes
		var checkbox = document.createElement('input');
		checkbox.type = 'checkbox';
		checkbox.name = 'category[]';
		checkbox.value = categoryId;

		lf.element.addClass(checkbox, 'category-checkbox');
		lf.element.addClass(checkbox, 'category-' + categoryId + '-checkbox');
		lf.event.addListener(checkbox, 'mouseup',
				this.profileCategoryCheckboxClicked, this);

		return checkbox;
	},

	profileCategoryCheckboxClicked : function(e) {

		var target = lf.event.getTarget(e);
		var me = this;

		// check if this is a parent with the class if 'skip'
		// if not ,select the parent
		if (!YAHOO.util.Dom.hasClass(target, 'skip')) {

			// stop them if they have three selected already
			var selectedCheckBoxes = lf.element
					.query('#category-select input:checked:not(.skip)');
			if (!target.checked
					&& selectedCheckBoxes.length >= this.maxCategoriesPerProfile) {

				alert("You cannot have more than "
						+ this.maxCategoriesPerProfile
						+ " categories selected!");
				target.checked = true;

				YAHOO.util.Event.stopEvent(e);

				return;
			}

			// a checkbox that is not checked is going to be so we
			// !target.checked
			this.profileCheckParentCategory(target, !target.checked);
		}
		// if this is a parent click, we may want to de-select all children
		else {

			// get parent
			var container = YAHOO.util.Dom.getAncestorByClassName(target,
					'category-group');

			// de-select children inside it
			var checkboxes = lf.element.query('ul li input', container);

			lf.foreach(checkboxes, function(checkbox) {
				if (checkbox != target) {
					checkbox.checked = false;
				}
			}, this);

			// remove class and set as not checked
			lf.element.removeClass(target, 'skip');

		}

		setTimeout(function() {
			me.profileHighlighMainCategories();
			me.profileSetSelectedCategoryIds();
		}, 0);
	},

	profileSetSelectedCategoryIds : function() {

		// find all checked boxes
		var checkboxes = lf.element
				.query('#category-select input:checked:not(.skip)');
		if (checkboxes.length > this.maxCategoriesPerProfile) {
			alert("You can only select 3 categories, the rest are ignored.");
		}

		var categoryIds = [];
		for ( var index = 0; index < this.maxCategoriesPerProfile; index++) {
			if (checkboxes[index]) {
				categoryIds.push(checkboxes[index].value);
			}
		}

		categoryIds = categoryIds.toString();
		lf.element.get('category-ids').value = categoryIds;

		// refresh
		this.profileLoadSelectedCategories();
	},

	profileGetCategoryFromClassOfElement : function(element) {
		return lf.element.listClasses(element)[0].split('-')[1];
	},

	profileRemoveSelectedCategory : function(categoryId) {
		if (confirm("Are you sure you want to remove your profile from this category?")) {
			lf.element.query('.category-' + categoryId + '-checkbox', null,
					true).checked = false;
			this.profileSetSelectedCategoryIds();
			this.profileLoadSelectedCategories();
		}
	},

	profileSuggestCategory : function() {

		this.profileSuggestPanel.show();

	},

	profileSuggestCategorySubmit : function(e) {

		YAHOO.util.Event.stopEvent(e);
		var reply = lf.element.get('suggestions').value;

		lf.asyncRequest('/member/suggest-category', {},
				'suggestion=' + encodeURIComponent(reply));

		this.profileSuggestPanel.hide();

		alert("Thank you! We will review your suggestion and get back to you when we do.");

	},

	profileExit : function(e) {

		if (!this.profileFormSubmitting) {
			var queryString = YAHOO.util.Connect.setForm('profile-form');
			if (queryString != this.profileQueryString) {
				return 'You have made changes to you profile that you haven\'t saved yet!';
			}
		}
	},

	profileHighlighMainCategories : function() {

		lf.foreach(lf.element.query("#category-select .main-category"),
				function(mainCategory) {
					var container = mainCategory.parentNode;
					var checkboxes = lf.element.query(
							'input:type(checkbox):checked', container);
					if (checkboxes.length > 0) {
						lf.element.addClass(mainCategory, 'main-has-children');
					} else {
						lf.element.removeClass(mainCategory,
								'main-has-children');
					}
				}, this);
	},

	displayReviewFormHired : function() {
		YAHOO.util.Dom.setStyle('review-form-not-hired', 'display', 'none');
		YAHOO.util.Dom.setStyle('review-form-hired', 'display', 'block');
	},

	displayReviewFormNotHired : function() {
		YAHOO.util.Dom.setStyle('review-form-hired', 'display', 'none');
		YAHOO.util.Dom.setStyle('review-form-not-hired', 'display', 'block');
	},

	initSearch : function() {
		// Setup Category autocomplete
		var oDS = new YAHOO.util.FunctionDataSource(efh
				.getAutocompleteMatchFunction(efh.categoriesJs));
		oDS.responseSchema = {
			fields : [ "id", "name" ]
		};

		var categoryAutocomplete = new YAHOO.widget.AutoComplete(
				"search-query", "search-category-autocomplete", oDS);
		categoryAutocomplete.resultTypeList = false;
		categoryAutocomplete.formatResult = efh.getAutocompleteFormatFunction();

		var clickHandler = function(sType, aArgs) {
			var oData = aArgs[2]; // object literal of selected item's result
									// data

			YAHOO.util.Dom.get('search-query').value = oData.name;
			YAHOO.util.Dom.get('search-category-id').value = oData.id;
		};

		categoryAutocomplete.itemSelectEvent.subscribe(clickHandler);
	},

	getAutocompleteFormatFunction : function() {
		var formatFunction = function(oResultData, sQuery, sResultMatch) {
			return oResultData.name;
		};

		var formatFunction = function(oResultData, sQuery, sResultMatch) {
			var fullName = oResultData.name;
			var fullNameLower = oResultData.name.toLowerCase();
			var queryLower = sQuery.toLowerCase();
			var index = fullNameLower.indexOf(queryLower);
			var parts = [ fullName.substring(0, index), '<strong>',
					fullName.substring(index, index + queryLower.length),
					'</strong>', fullName.substring(index + queryLower.length) ];

			return parts.join('');
		};

		return formatFunction;
	},

	getAutocompleteMatchFunction : function(dataset) {
		var matchFunction = function(sQuery) {
			// Case insensitive matching
			var query = unescape(sQuery.toLowerCase()), contact, i = 0, l = dataset.length, matches = [];

			// Match against each name of each contact
			for (; i < l; i++) {
				contact = dataset[i];
				if ((contact.name.toLowerCase().indexOf(query) > -1)) {
					matches[matches.length] = contact;
				}
			}

			return matches;
		};

		return matchFunction;
	},

	initFilterDateRange : function() {
		cal1 = new YAHOO.widget.Calendar("cal1", "filter-date-range-1", {
			title : "Choose From date:",
			close : true
		});

		cal1.selectEvent.subscribe(function(type, args, obj) {
			var dates = args[0];
			var date = dates[0];
			var year = date[0], month = date[1], day = date[2];

			var txtDate1 = document.getElementById("from-date");
			txtDate1.value = month + "/" + day + "/" + year;
		}, cal1, true);

		cal1.render();
		YAHOO.util.Event.addListener('from-date', 'focus', cal1.show, cal1,true);
		cal1.hide();

		var cal2 = new YAHOO.widget.Calendar("cal2", "filter-date-range-2", {
			title : "Choose To date:",
			close : true
		});

		cal2.selectEvent.subscribe(function(type, args, obj) {
			var dates = args[0];
			var date = dates[0];
			var year = date[0], month = date[1], day = date[2];

			var txtDate1 = document.getElementById("to-date");
			txtDate1.value = month + "/" + day + "/" + year;
		}, cal2, true);

		cal2.render();
		YAHOO.util.Event.addListener('to-date', 'focus', cal2.show, cal2, true);
		cal2.hide();
	}

}

function menu_msover(obj) {
	var menu_name = "m_" + obj.id.substr(3);
	var menu_obj = document.getElementById(menu_name);
	if (!menu_obj)
		return;
	menu_obj.style.visibility = "visible";
}

function menu_msout(obj) {
	var menu_name = "m_" + obj.id.substr(3);
	var menu_obj = document.getElementById(menu_name);
	if (!menu_obj)
		return;
	menu_obj.style.visibility = "hidden";
}