var captchaLoaded = false;

var DOMUtilities = {
	// XHTML 1.0 Strict work around for external links
	// ========================================================
	// locality [string] CSS path for the locality of the function
	// to be applied. Defaults to document.body
	targetBlank : function(locality) {
		$$m(locality + ' a[rel*="external"]').each( function(e) {
			e.writeAttribute("target", "_blank");
		});
	},

	// Automatic text clear for input fields
	// ========================================================
	// locality [string] CSS path for the locality of the function
	// to be applied. Defaults to document.body
	inputAutoClear : function(locality) {
		$$m(locality + ' input.clearField').each( function(e) {
			e.observe('focus', function() {
				if (this.value == this.defaultValue) {
					this.value = "";
				}
			}).observe('blur', function() {
				if (this.value == "") {
					this.value = this.defaultValue;
				}
			});
		});
	},

	// Image roll-over setup
	// ========================================================
	// locality [string] CSS path for the locality of the function
	// to be applied. Defaults to document.body
	imgRollover : function(locality) {
		$$m(
				locality + ' img.rollOver, ' + locality
						+ ' input[type="image"].rollOver').each( function(e) {
			e.observe('mouseover', function() {
				if (this.src.indexOf("_i.") != -1) {
					this.src = this.src.replace("_i.", "_o.");
				}
			}).observe('mouseout', function() {
				if (this.src.indexOf("_o.") != -1) {
					this.src = this.src.replace("_o.", "_i.");
				}
				if (this.src.indexOf("_a.")) {
					this.src = this.src.replace("_a.", "_i.");
				}
			})
			if (e.match("input")) {
				e.observe('mousedown', function() {
					this.src = this.src.replace("_o.", "_a.");
				}).observe('mouseup', function() {
					this.src = this.src.replace("_a.", "_i.");
				});
			}
		});
	},

	// Initialize all DOM utilities on the body. Run onDOMReady
	init : function(locality) {
		if (locality == null) {
			locality = "body";
		}
		this.targetBlank(locality);
		this.inputAutoClear(locality);
		this.imgRollover(locality);
	}
}

var refineSearch = {
	animating : false,
	opened : false,
	effects : [],
	init : function() {
		$$m('#refine_tab, #btn_collapse_refine')
				.each(
						function(e) {
							e
									.observe(
											'click',
											function() {
												if (refineSearch.animating == false) {
													refineSearch.animating = true;

													if (refineSearch.opened == false) {
														refineSearch.opened = true;
														$m('refine_tab')
																.addClassName(
																		'opened');

														if (document.viewport
																.getDimensions().width
																- $m('content')
																		.cumulativeOffset().left < $m(
																'refine_wrapper')
																.getDimensions().width
																+ $m('content')
																		.getDimensions().width) {
															refineSearch.effects
																	.push(new Effect.Morph(
																			'refine_wrapper',
																			{
																				style : 'margin-left: -491px;',
																				sync : true
																			}));
															refineSearch.effects
																	.push(new Effect.Morph(
																			'header',
																			{
																				style : 'left: 100px;',
																				sync : true
																			}));
															refineSearch.effects
																	.push(new Effect.Morph(
																			'header_back',
																			{
																				style : 'padding-left: 200px;',
																				sync : true
																			}));
															refineSearch.effects
																	.push(new Effect.Morph(
																			'footer_wrapper',
																			{
																				style : 'padding-left: 100px;',
																				sync : true
																			}));
															refineSearch.effects
																	.push(new Effect.Morph(
																			'footer',
																			{
																				style : 'padding-left: 200px; left: -100px;',
																				sync : true
																			}));
															refineSearch.effects
																	.push(new Effect.Morph(
																			'footer_inner',
																			{
																				style : 'left: -100px;',
																				sync : true
																			}));
															refineSearch.effects
																	.push(new Effect.Morph(
																			'content',
																			{
																				style : 'left: 100px;',
																				sync : true
																			}));
															if ($m('results_map')
																	.getStyle(
																			'position') == "fixed") {
																refineSearch.effects
																		.push(new Effect.Morph(
																				'results_map',
																				{
																					style : 'margin-left: 256px;',
																					sync : true
																				}));
															}
														} else {
															refineSearch.effects
																	.push(new Effect.Morph(
																			'refine_wrapper',
																			{
																				style : 'margin-left: -591px'
																			}))
														}
													} else {
														refineSearch.opened = false;
														$m('refine_tab')
																.removeClassName(
																		'opened');

														refineSearch.effects
																.push(new Effect.Morph(
																		'refine_wrapper',
																		{
																			style : 'margin-left: -390px;',
																			sync : true
																		}));
														refineSearch.effects
																.push(new Effect.Morph(
																		'header',
																		{
																			style : 'left: 0px;',
																			sync : true
																		}));
														refineSearch.effects
																.push(new Effect.Morph(
																		'header_back',
																		{
																			style : 'padding-left: 0px;',
																			sync : true
																		}));
														refineSearch.effects
																.push(new Effect.Morph(
																		'footer_wrapper',
																		{
																			style : 'padding-left: 0px;',
																			sync : true
																		}));
														refineSearch.effects
																.push(new Effect.Morph(
																		'footer',
																		{
																			style : 'padding-left: 0px; left: 0px;',
																			sync : true
																		}));
														refineSearch.effects
																.push(new Effect.Morph(
																		'footer_inner',
																		{
																			style : 'left: 0px;',
																			sync : true
																		}));
														refineSearch.effects
																.push(new Effect.Morph(
																		'content',
																		{
																			style : 'left: 0px;',
																			sync : true
																		}));
														refineSearch.effects
																.push(new Effect.Morph(
																		'results_map',
																		{
																			style : 'margin-left: 156px;',
																			sync : true
																		}));
													}
													new Effect.Parallel(
															refineSearch.effects,
															{
																duration : 0.25,
																afterFinish : function() {
																	refineSearch.animating = false;
																}
															});
												}
											}).onclick = function() {
								return false;
							};
						});
	}
}

var ViewportMover = {
	topOffset : 20,
	bottomOffset : 200,
	refineStartPos : 160,
	mapStartPos : function() {
		return $m('whats_mojo').visible() ? $m('whats_mojo').getDimensions().height
				+ $m('whats_mojo').cumulativeOffset().top
				: 319;
	},

	watch : function() {
		var self = this;

		this.mapHeight = $m('results_map').getDimensions().height;

		new PeriodicalExecuter(
				function() {
					self.bodyHeight = document.body.getHeight();

					if ($m('input_related_follow') != null
							&& $m('input_related_follow').checked == true) {
						var offset = document.viewport.getScrollOffsets().top;
						var refinerHeight = $m('refine_wrapper').getDimensions().height;
						var pos = self.refineStartPos;

						if (offset > 0
								&& offset < (self.refineStartPos - self.topOffset)) {
							pos = self.refineStartPos - offset;
						} else if (offset > (self.refineStartPos - self.topOffset)) {
							if ((offset + refinerHeight + self.topOffset) > (self.bodyHeight - self.bottomOffset)) {
								pos = (self.bodyHeight - self.bottomOffset)
										- (offset + refinerHeight + self.topOffset);
							} else {
								pos = self.topOffset;
							}
						}
						$m('refine_wrapper').setStyle( {
							position : 'fixed',
							top : pos + 'px'
						});
					} else {
						$m('refine_wrapper').setStyle( {
							position : 'absolute',
							top : self.refineStartPos + 'px'
						});
					}

					if ($m('input_map_follow').checked == true) {
						var offset = document.viewport.getScrollOffsets().top;
						var pos = self.mapStartPos();

						var marginVal = 156 + parseInt($m('content').getStyle(
								'left'));

						if (offset > 0
								&& offset < (self.mapStartPos() - self.topOffset)) {
							pos = self.mapStartPos() - offset;
						} else if (offset > (self.mapStartPos() - self.topOffset)) {
							if ((offset + self.mapHeight + self.topOffset) > (self.bodyHeight - self.bottomOffset)) {
								pos = (self.bodyHeight - self.bottomOffset)
										- (offset + self.mapHeight + self.topOffset);
							} else {
								pos = self.topOffset;
							}
						}
						$m('results_map').setStyle( {
							position : 'fixed',
							padding : '0 0 0 3px',
							marginLeft : marginVal + 'px',
							top : pos + 'px'
						});
					} else {
						if ($m('whats_mojo').visible()) {
							$m('results_map')
									.setStyle(
											{
												position : 'absolute',
												padding : '0',
												marginLeft : '156px',
												top : $m('whats_mojo')
														.getDimensions().height + 'px'
											});
						} else {
							$m('results_map').setStyle( {
								position : 'absolute',
								padding : '0',
								marginLeft : '156px',
								top : 0 + 'px'
							});
						}
					}
				}, 0.025);
	}
}

$m(document).observe(
		'dom:loaded',
		function() {
			DOMUtilities.init();

			// Setup Cookies
			window.mojoCookies = new EasyCookie("/");

			if (mojoCookies.get('refine_follow') != null) {
				$m('input_related_follow').checked = mojoCookies
						.get('refine_follow');
			}
			if (mojoCookies.get('results_map_follow') != null) {
				$m('input_map_follow').checked = mojoCookies
						.get('results_map_follow');
			}

			
		});

function radioSelect( selected )
{
	var parentForm = selected.form;
	
	if( !selected.checked )
	{
		return;
	}
	
	var elements = Form.getInputs( parentForm, null, selected.name );
	elements.each( function( other ) {
		if( other != selected )
		{
			other.checked = false;
		}
	});
}

function doSearch( form )
{
	var searchTerm = $F(form['search_term']);
	var searchLoc = $F(form['search_location']);
	
	if( searchTerm == null || searchTerm.blank() || searchLoc == null || searchLoc.blank() ) 
	{
		alert( 'Sorry, you must provide a search location and query' );
		return false;
	}
	
	if( google != null )
	{
		lookupCoords( searchLoc, searchGeoCB, form );
	}
	
	return false;
}

function validateNotEmpty( fieldName, form, message )
{
	var value = $F(form[fieldName]);
	
	if( value == null || value.blank() )
	{
		alert( message );
		return false;
	}
	
	return true;
}

function searchGeoCB( resp )
{
	if( resp )
	{
		if( resp.postalCode )
		{
			resp.data['simple_location'].value = 'A;' + resp.loc + ';' + resp.postalCode + ';' + resp.lat + ';' + resp.lng;
		}
	}
	
	resp.data.submit();
}

function lookupCoords( loc, callback, data )
{
	var geocoder = new google.maps.Geocoder();
	
	geocoder.geocode(
		{ 'address': loc }, function( results, status ){
			if( status == google.maps.GeocoderStatus.OK && results.length )
			{
				var resp = { loc: loc, data: data };
				if( status != google.maps.GeocoderStatus.ZERO_RESULTS )
				{
					var type = results[0].types[0];
					if( type == 'street_address' )
					{
						resp = {
								loc: loc,
								lat: results[0].geometry.location.lat(),
								lng: results[0].geometry.location.lng(),
								data:data,
								postalCode: null
						};
						
						var address = results[0].address_components;
						for( var i = 0; i < address.length; i++ )
						{
							var component = address[i];
							
							if( component.types[0] == 'postal_code' )
							{
								resp.postalCode = component.long_name;
							}
						}
					}
				}
						
				callback( resp );
			}
		}
	);
}

function updateCoordsForm( form, cb )
{
	var streetName = $F(form['address.streetName']);
	var cityState = $F(form['address.city']);
	var zipCode = $F(form['address.postalCode']);
	
	var lookupLoc = streetName + ", " + cityState + " " + zipCode;
	
	var data = { form: form, cb: cb };
	
	lookupCoords( lookupLoc, updateCoordsFormCB, data )
}

function updateCoordsFormCB( resp )
{
	form = resp.data.form;
	cb = resp.data.cb;
		
	if( resp )
	{
		if( resp.postalCode )
		{
			form['latitude'].value = resp.lat;
			form['longitude'].value = resp.lng;
		}
	}
				
	if( cb )
	{
		cb( form );
	}else
	{
		form.submit();
	}
}

function submitBusDetails( form )
{
	updateCoordsForm( form, submitForm ); 
	return false;
}

function addBusDetails( form )
{
	updateCoordsForm( form );
	return false;
}

function submitReplace( form, replaceElem )
{
	if( checkLoggedIn() ) 
	{
		form.request(
		{
			onFailure: function()
			{
				alert("Failed");
			},
			onSuccess: function(t)
			{
				replaceElem.replace( t.responseText );
		}
		});
	}
	return false;
}
		
function submitReplaceBizCenter( form, replaceElem )  //Ahumes 10.30.2009 - Converted to use jQuery (from submitReplace, above).  Prototype version (above) was not working correctly in IE 7 for biz center claiming a business.  IE would load the 'ajax' content in a new window.  Needed one version for Biz Center and kept original for Tags, since they previously used same function.
{
	if( checkLoggedIn() ) 
	{
		if( $j('#phone').val() == "" ) {
			alert('You must provide a valid mobile phone number.');
		} else {
			$j(replaceElem).load("/business/sendVerify.ajax", {id: $j('#id').val(), phone: $j('#phone').val()} );
		}
	}
	return false;
}

function isLoggedIn()
{
	return loggedIn;
}

function setLoggedIn()
{
	loggedIn = true;	
}

function deactivateLogin()
{
	myLightWindow.deactivate();
}

function checkLoggedIn()
{
	if( !isLoggedIn() )
	{
		myLightWindow.activateWindow(
			{
				href: '/login.ajax',
				title: 'Login',
				width: '780',
				height: '280'
			}
		);
		
		return false;
	}
	
	return true;
}

function onUploadComplete( params )
{ 
	paramList = '';
	
	for (var mdName in params)
	{
		paramList += mdName + '=' + params[mdName];
		paramList += ' <br> ';
	}
	
	addMedia( 'videos', 'video', params.embed, params.previewUrl, 'VIDEO' );
	
	if (swfFileUploadCompleteCallback) {
		swfFileUploadCompleteCallback();
	}	
}

function submitForm( form, formCallback )
{ 
	if( checkLoggedIn() ) 
	{
		form.request({ 
			onFailure: function()
			{
				alert("Failed");
			},
			onSuccess: function(t)
			{
				form.replace(t.responseText);
				
	           	if( formCallback ) 
				{
					formCallback();
				}
	       	}
	   	}); 
	}
	return false;
}

function authWindow( lightwindow, anchor )
{
	if( checkLoggedIn() )
	{
		lightwindow.activate( null, anchor );
	}
	return false;
}

function flagReview( reason, reviewId, button )
{
	var adjustment = -1;
	if( button.checked )
	{
		// Send the request
		new Ajax.Request( '/review/flag',
				{
					method: 'post',
					parameters: { 'reason' : reason, 'r': reviewId }
				});
		
		adjustment = 1;
	}
	
	// Update the counter
	Element.extend( button );
	var counter = button.next();
	counter.update( parseInt( counter.innerHTML ) + adjustment );
}

var swfu = null;
var instrumentReviewForm=function()
{
	$$m(".ratingAdjuster").each( function(e) {
		e.observe('click', function() 
		{
			adjustRating();
		});
	});	
	
	$$m(".structureToggle").each( function(e) {
		e.observe('click', function()
		{
			toggleStructure( e );
		});
	});
	
	adjustRating();
	
	swfu = new SWFUpload({
		// Backend Settings
		upload_url: imgUploadUrl,
		post_params: { auth : authToken },
	
		// File Upload Settings
		file_size_limit : "2 MB",	// 2MB
		file_types : "*.jpg;*.png;*.gif",
		file_types_description : "JPG,PNG,GIF Images",
		file_upload_limit : "0",
	
		// Event Handler Settings - these functions as defined in Handlers.js
		//  The handlers are not part of SWFUpload but are part of my website and control how
		//  my website reacts to the SWFUpload events.
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,
	
		// Button Settings
		button_image_url : baseImgPath,
		button_placeholder_id : "spanButtonPlaceholder",
		button_width: 180,
		button_height: 18,
		button_text : '<span class="button">Select Images <span class="buttonSmall">(2 MB Max)</span></span>',
		button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }',
		button_text_top_padding: 0,
		button_text_left_padding: 18,
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		button_cursor: SWFUpload.CURSOR.HAND,
		
		// Flash Settings
		flash_url : swfUploadUrl,
	
		custom_settings : {
			upload_target : "divFileProgressContainer"
		},
		
		// Debug Settings
		debug: false
	});	
}

var toggleStructure=function( e )
{
	var structuredLink = e.up().select( '#structured' ).first();
	var unstructuredLink = e.up().select( '#unstructured' ).first();
	var reviewForm = e.up('#reviewForm');
	var extraReviewFields = reviewForm.select( '#extraReviewFields' ).first();
	
	if( e == unstructuredLink )
	{
		unstructuredLink.addClassName( 'orange' );
		structuredLink.removeClassName( 'orange' );
		extraReviewFields.addClassName( 'hide' );
	}else
	{
		structuredLink.addClassName( 'orange' );
		unstructuredLink.removeClassName( 'orange' );		
		extraReviewFields.removeClassName( 'hide' );
	}		
}

var clearRating=function()
{
	$$m(".ratingAdjuster").each( function(e) {
		e.setValue( '' );
	});
	
	adjustRating();
	
	return false;
}

var adjustRating=function()
{
	var value = parseInt( $$m('input:checked[type="radio"][name="value"]').pluck('value') );
	var quality = parseInt( $$m('input:checked[type="radio"][name="quality"]').pluck('value') );
	var service = parseInt( $$m('input:checked[type="radio"][name="service"]').pluck('value') );
	
	value = ( isNaN( value ) ) ? 0 : value;
	quality = ( isNaN( quality ) ) ? 0 : quality;
	service = ( isNaN( service ) ) ? 0 : service;
	
	var sum = value + quality + service;
	
	var ratingPercent = ( sum / 15.0 ) * 100.0;
	var overallRating = $m("overallRating");
	overallRating.setStyle( { 'width' : ratingPercent + '%' } );
}

var addMedia=function( containerId, formName, content, previewContent, type )
{
	var container = $m(containerId);
	var medias = container.select( '.media' );
	var maxId = medias.length;
	
	// Create all the fields we want to add for the new media.
	var formPrefix = formName + 'Data[' + maxId + ']';
	var contentField = new Element( 'input', { 'type': 'hidden', 'name' : formPrefix + '.content', 'value' : content } )
	var previewField = new Element( 'input', { 'type': 'hidden', 'name' : formPrefix + '.previewContent', 'value' : previewContent } );
	var typeField = new Element( 'input', { 'type': 'hidden', 'name' : formPrefix + '.type', 'value' : type } );
	var previewElement = new Element( 'img', { 'src' : previewContent, 'width' : 100, 'height' : 100, 'style' : 'display:none; float:left' } );
	
	// Create a div to contain all the fields and the preview.
	var containerDiv = new Element( 'div', { 'class' : 'media', 'id' : maxId } );
	
	// Now add everything to the page.
	containerDiv.appendChild( contentField );
	containerDiv.appendChild( previewField );
	containerDiv.appendChild( typeField );
	containerDiv.appendChild( previewElement );
	
	container.appendChild( containerDiv );
	
	previewElement.appear();
}

function hiddenLinkClick( anchor )
{
	var adUrl = anchor.getAttribute( "adUrl" );
	var localUrl = anchor.getAttribute( "local" );
	
	logClick( adUrl );
	logClick( localUrl );
	
	var logHidden = anchor.up( '.mpLogLink' ).select( '.mpLogHidden' ).first();
	var logShown = anchor.up( '.mpLogLink' ).select( '.mpLogShown' ).first();
	
	logHidden.show();
	logShown.hide();
	
	return false;
}

function logAndGo( anchor )
{
	var adUrl = anchor.getAttribute( "adUrl" );
	var goUrl = anchor.getAttribute( "goUrl" );
	
	if( adUrl != null )
	{
		logClick( adUrl );
	}
	
	// Give browsers a chance to actually create the image
	// and track the click before going to the next page.
	(function() { window.location = goUrl; }).delay(2);
	
	return false;
}

function logClick(url)
{
	if( url != null && !url.blank() )
	{
		var img = new Image();
		img.src = url;
	}
}

function imageUpload()
{
	swfu = new SWFUpload({
		// Backend Settings
		upload_url: imgUploadUrl,
		post_params: { auth : authToken },
	
		// File Upload Settings
		file_size_limit : "2 MB",	// 2MB
		file_types : "*.jpg;*.png;*.gif",
		file_types_description : "JPG,PNG,GIF Images",
		file_upload_limit : "0",
		file_queue_limit : "1",
	
		// Event Handler Settings - these functions as defined in Handlers.js
		file_queue_error_handler : imageError,
		file_dialog_complete_handler : fileDialogComplete,
		//upload_progress_handler : uploadProgress,
		upload_error_handler : imageError,
		upload_success_handler : profileImageUpdate,
		//upload_complete_handler : uploadComplete,
	
		// Button Settings
		button_image_url : baseImgPath,
		button_placeholder_id : "spanButtonPlaceholder",
		button_width: 130,
		button_height: 18,
		button_text : '<span class="button">Edit Image</span>',
		button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; }',
		button_text_top_padding: 0,
		button_text_left_padding: 18,
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		button_cursor: SWFUpload.CURSOR.HAND,
		
		// Flash Settings
		flash_url : swfUploadUrl,
	
		custom_settings : {
			upload_target : "divFileProgressContainer"
		},
		
		// Debug Settings
		debug: false
	});	
}

function imageError(file, errorCode, message)
{
	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			errorName = "You have attempted to queue too many files.";
		}

		if (errorName !== "") {
			alert(errorName);
			return;
		}
		
		alert(message);
	} catch (ex) {
		this.debug(ex);
	}
}

function profileImageUpdate( file, serverData )
{
	var uploadResponse = eval( '(' + serverData + ')' );
	
	var container = $m('changeImage');
	
	var contentField = new Element( 'input', { 'type': 'hidden', 'name' : 'content', 'value' : uploadResponse.file } )
	var previewField = new Element( 'input', { 'type': 'hidden', 'name' : 'previewContent', 'value' : uploadResponse.thumb } );
	var typeField = new Element( 'input', { 'type': 'hidden', 'name' : 'type', 'value' : 'PHOTO' } );
	
	// Create a div to contain all the fields and the preview.
	var containerDiv = new Element( 'div', { 'class' : 'media' } );
	
	// Now add everything to the page.
	containerDiv.appendChild( contentField );
	containerDiv.appendChild( previewField );
	containerDiv.appendChild( typeField );
	
	container.appendChild( containerDiv );
	
	submitForm( container );
}

function readMessage( messageId )
{
	var messageBodyDiv = $m( 'messageBody' + messageId );
	
	Effect.SlideDown( messageBodyDiv );
	
	messageAction( messageId, 'read' );
	
	return false;
}

function messageAction( messageId, action )
{
	// Send the request
	new Ajax.Request( '/personal/messageAction',
			{
				method: 'post',
				parameters: { 'id' : messageId, 'a': action }
			});
}

/* FShu - temporary fix; had to duplicate some of the location_interact_tabs js because 
 * i couldn't get the click event to fire by calling the tab from another link 
 * 
 * AHumes 1.12.10 - I updated the js to put this functionality into its own function, instead of being executed on each page load.
 *   Updated the search results page tabs to use this function onclick.
 */
function clickTab( tabId )
{
	var e = $m(tabId);
	if(!e) return false;
	
	var section = e.href.substr(e.href.lastIndexOf('#') + 1);
	var container = e.up('div#mpResult');
		
	if (!e.hasClassName('active')) {  /*if it's not active*/
		if( section == 'review-it' ) {
			if( !checkLoggedIn() ) {
				return false;
			}
		}
		
		e.up('ul.location_interact_tabs').select('a').invoke('removeClassName', 'active');
		
		var busId = e.up('.location_interact_tabs').down('span').identify();
		
		//hide any open section for all business listing results
		$$m('.location_interactions').each(function(s) {
		  s.hide();
		})
		  
		//remove any 'active' class on the page from each 'li a' element. cycling through each li item to make sure each is accounted for
		$$m('.location_container').each(function(r) {
		  for (i=0; i <= 5; i++) {  
			r.down('li', i).down('a').removeClassName('active');
		  }
		})
								
		e.addClassName('active');
		
		//for any business listing result, display that content in a dropdown/slide box
		$$m('.location_interactions_' + busId).each(function(i){   
			if (i.hasClassName('interact_' + section)) 
			{	
				var loadable = i.select( '.review-form' ).first();
				if( loadable != null )
				{
					new Ajax.Updater( 
						loadable, 
						'/review.ajax?business=' + loadable.id, 
						{method: 'get', evalScripts: true} 
					);
				}
				
				loadable = i.select( '.review-details' ).first();
				if( loadable != null && loadable.hasClassName( 'lazyLoad' ) )
				{
					new Ajax.Updater( loadable, '/biz/dummy/' + loadable.id + '/review-details.ajax', {method:'get', evalScripts:true} );
				}
				
				loadable = i.select( '.photos' ).first();
				if( loadable != null )
				{
					new Ajax.Updater( loadable, '/biz/dummy/' + loadable.id + '/photos.ajax', {method:'get', evalScripts: true} );
				}
				
				loadable = i.select( '.videos' ).first();
				if( loadable != null )
				{
					new Ajax.Updater( loadable, '/biz/dummy/' + loadable.id + '/videos.ajax', {method:'get', evalScripts: true} );
				}
		
				loadable = i.select( '.coupons' ).first();
				if( loadable != null )
				{
					new Ajax.Updater( loadable, '/biz/dummy/' + loadable.id + '/coupons.ajax', {method:'get', evalScripts: true} );
				}	
				
				loadable = i.select( '.details' ).first();
				if( loadable != null )
				{
					new Ajax.Updater( loadable, '/biz/dummy/' + loadable.id + '/details.ajax', {method:'get', evalScripts: true} );
				}
				
				//new Effect.SlideDown(i);
				//i.show();
				$j(i).slideDown("fast");
			}
			else {
				i.hide();
			}
		});
	} else {  /*if section is already active and user clicks on tab, close box */
		var busId = e.up('.location_interact_tabs').down('span').identify();
		$m('nav_container_' + busId).select('a').invoke('removeClassName', 'active');
		$m('loc_int_' + section + '_' + busId).hide();
		
	}
}
/*  
 * Moved this code from executing on the dom:loaded event to its own function using onclick.
 */ 
function collapseLink() {
	//if any 'collapse link' link is clicked, close all boxes on page
	$$m('.location_interactions').each(function(s) {
	  s.hide();
	})
		  
	//remove any 'active' class on the page from each 'li a' element. cycling through each li item to make sure each is accounted for
	$$m('.location_container').each(function(r) {
	  for (i=0; i <= 5; i++) {  
		r.down('li', i).down('a').removeClassName('active');
	  }
	})
} 
 
/* Pulls up the specified marker on the map next to search results */
function showOnMap(markerIndex) 
{
	if(marker_array != null && marker_array.length > markerIndex) {
		if(marker_array[markerIndex] != null) {
			var map = marker_array[markerIndex]['map'];
			var marker = marker_array[markerIndex]['marker'];
			var infoWindow = marker_array[markerIndex]['infoWindow'];
			infoWindow.open( map, marker );
		}
	}
}
function textCounter(field, cntfield, maxlimit) { 
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
		//otherwise, update 'characters left' counter
	else
		//alert(field.value + ", " + field.value.length);
		cntfield.innerHTML = maxlimit - field.value.length;  //alert(field.value + ", " + field.value.length);
}
function verify_checkbox(checkbox_name, submit_button) {
	if ( $j(checkbox_name).is(':checked') ) {
		$j(submit_button).show();
	} else {
		$j(submit_button).hide();
	};
}