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()
{
	$j('#mp_login').load('/login/header.ajax', function() {});
	$j('#nav-header').load('/navigation/header.ajax', function() {
		showAccountMenu();
	});
	myLightWindow.deactivate();
}

function checkLoggedIn()
{
	if( !isLoggedIn() )
	{
		myLightWindow.activateWindow(
			{
				href: '/login.ajax',
				title: 'Login',
				//width: '780',
				width: '750',
				height: '310'
			}
		);
		
		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 submitFormJquery( form, action )	//this version uses jQuery to submit a form using Ajax, since Prototype wasn't working with IE7
{ 
	if( checkLoggedIn() ) 
	{
	   	$j.post(action, $j(form).serialize(), function(data) { $j(form).html(data); });
	}
	return false;
}

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

function flagReview( reason, reviewId )
{
	if( checkLoggedIn() )
	{
		// Send the request
		new Ajax.Request( '/report/form',
				{
					method: 'post',
					parameters: { 'flag' : reason, 'rating': reviewId, flagType: 'REVIEW', formView: '/st/blank' }
				});
				
		return true;
	}
	
	return false;
}

function shareTrack( reviewId, businessId, type )
{
	if( isLoggedIn() )
	{
		new Ajax.Request( '/report/share',
				{
					method: 'post',
					parameters: { business : businessId, review : reviewId, type : type }
				});	
	}
	
	return false; 
}

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 = eval( anchor.getAttribute( "adUrl" ) );
	var localUrl = eval( 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();
	
	//move phone number left so links don't wrap onto two lines.  had to select trackingLinksContainer because using mpLogLink wasn't working for IE7 only
	var shiftPhone = anchor.up('.trackingLinksContainer');
	shiftPhone.setStyle({marginLeft: '-31px'});
	
	return false;
}
function hiddenLinkClickNew( 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();
	
	//move phone number left so links don't wrap onto two lines.  had to select trackingLinksContainer because using mpLogLink wasn't working for IE7 only
	//var shiftPhone = anchor.up('.trackingLinksContainerNew');
	//shiftPhone.setStyle({marginLeft: '-31px'});
	
	return false;
}

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

var loadingEvents = [];
var loadCallback = null;

function waitForLoadEvents( callback )
{
	loadCallback = callback;
	checkLoading();
}

function popLoads( srcObj )
{
	loadingEvents = $j.grep( loadingEvents, function(value){ return value != srcObj} );
	checkLoading();
}

function checkLoading()
{
	if( loadingEvents.length == 0 && loadCallback)
	{
		loadCallback();
	}
}

function logClick(url)
{
	if( url != null && !url.blank() )
	{
		remoteLog( 'LOGCLICK', url );
		var img = new Image();
		img.src = url;
		
		var loadComplete = function() { popLoads( img ); };
		$j( img ).load( loadComplete );
		$j( img ).error( loadComplete );
		
		loadingEvents.push( img );
	}
}

function remoteLog( category, msg )
{
	var logUrl = '/log';
	logUrl += '?c=' + escape( category ) + '&m=' + escape( msg );
	
	var img = new Image();
	img.src = logUrl;
	
	var loadComplete = function() { popLoads( img ); };
	$j( img ).load( loadComplete );
	$j( img ).error( loadComplete );
	
	loadingEvents.push( img );
}

function uncode( urlParts )
{
	var decoded = urlParts.join( "/" );
	return unescape( decoded );
}

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_image_url : "/mstatic/images/edit_image_btn.png",
		button_placeholder_id : "editImageButton",
		//button_width: 130,
		//button_height: 18,
		//button_text : '<span class="button">Edit Image</span>',
		//button_text_style : '.button { font-family: Verdana, Helvetica, Arial, sans-serif; font-size: 20px; border: 1px solid; display: block;}',
		button_width: 90,
		button_height: 22,
		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 }
			});
}
/*
 *	5/5/2010 - Replaced clickTab(tabId) and  collapseLink() functions with listingDropdown and closeListingDropdown
*/

 
function listingDropdown( bizId, type )
{
	closeListingDropdown();
	$j("#loc_int_" + bizId).slideDown(600);
	$j("#loc_int_" + bizId + "_container").load("/biz/dummy/" + bizId + "/" + type + ".ajax");
	$j("#nav_" + type + "_" + bizId).css('color', '#000');		//change link's text color to black when selected
	return false;
}
 
function closeListingDropdown()
{
	$j('.location_dropdown').each(function() {
  		$j(this).slideUp(200);
	});
	
	$j('.listing_link').each(function() {
  		$j(this).css('color', '#39C');		//change link's text color back to blue when its no longer selected
	});
}

function listingDropdownNew( bizId, type )
{
	closeListingDropdownNew();
	$j("#listing_dropdown_" + bizId).slideDown(600);
	$j("#listing_dropdown_container_" + bizId).load("/biz/dummy/" + bizId + "/" + type + ".ajax");
	$j("#nav_" + type + "_" + bizId).css('color', '#000');		//change link's text color to black when selected
}
 
function closeListingDropdownNew()
{
	$j('.listing_dropdown').each(function() {
  		$j(this).slideUp(200);
	});
	
	$j('.listing_link').each(function() {
  		$j(this).css('color', '#39C');		//change link's text color back to blue when its no longer selected
	});
}

function share( bizId )
{
	$j( "#icon_container" ).load( "/biz/" + bizId + "/share.ajax" );
}

 
/* Pulls up the specified marker info window on the map next to search results. 
** showInfoWindow is used to display the infowindow only when the mouse is over the biz result icon, and not the result container itself.
*/
function showOnMap(markerIndex, showInfoWindow) 
{	
	var markerDiv = $j('div[title="' + markerIndex + '"]');
	markerDiv.attr('id', 'mapIcon' + markerIndex);
	markerDiv.attr('class', 'mapIcon');
	var markerDivOffset = markerDiv.offset();
	var mapCanvasOffset = $j('#map-canvas').offset();
	
	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'];
			
			marker.setIcon("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chs=21x32&chld=" + markerIndex + "|FF7B24|FFFFFF&ext=.png");
			marker.setZIndex(300);
			
			if (showInfoWindow == "true") {
				$j('#map_infowindow' + markerIndex).css('left', markerDivOffset.left - 278);
				$j('#map_infowindow' + markerIndex).css('top', markerDivOffset.top - 100);
				
				//if map marker is outside of map canvas (230x300), don't display info box.
				//adding 10-20 px to account for part of the div still showing in map so it will still function

				if ( (markerDivOffset.top + 20 > mapCanvasOffset.top) && (markerDivOffset.top < mapCanvasOffset.top + 300) && (markerDivOffset.left + 10 > mapCanvasOffset.left) && (markerDivOffset.left < mapCanvasOffset.left + 230) ) {	
					$j('#map_infowindow' + markerIndex).css('display', 'block');
				} else {
					marker.setIcon("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chs=21x32&chld=" + markerIndex + "|2E93D2|FFFFFF&ext=.png");
					$j('#map_infowindow' + markerIndex).css('display', 'none');
				}
			}
		}
	}
}

function removeFromMap(markerIndex) {	
	//Search Results page map icon mouseout, close map info window, change back to orig map marker color
	var marker = marker_array[markerIndex]['marker'];
	marker.setIcon("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chs=21x32&chld=" + markerIndex + "|2E93D2|FFFFFF&ext=.png");		//change marker color back to non-hover color
	marker.setZIndex(200);
	$j('.mapInfoWindowContainer').css('display', 'none');
}

function loadMap() {
	$j('head').append('<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.3&sensor=false&callback=initializeMap"><\/script>');
}

function addMarker( map, markerText, latitude, longitude, name, index )
{
	var iconOptions = {
		width: 21,
		height: 32,
		primaryColor: "#2E93D2",
		textColor: "#FFFFFF"
	}
	
	var iconImg = MapIconMaker.createMarkerIcon( markerText, iconOptions );
	var indexToString = index.toString();		//converting the index to a string, then use it as the marker title to uniquely identify the marker div later
	
	var marker = new google.maps.Marker({
		position: new google.maps.LatLng( latitude, longitude ),
		map: map,
		title: indexToString,
		icon: iconImg
	});
	
	$j('#map_infowindow' + index).detach().appendTo('#mp');						//move infobox from each listing to bottom of #mp container, in order to absolute position it where the marker is.

	google.maps.event.addListener( marker, 'mouseover', function(e){
		marker.setIcon("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chs=21x32&chld=" + index + "|FF7B24|FFFFFF&ext=.png");
		
		if ( $j('#resultContainer' + index).hasClass('b') )			//make biz listing container yellow on map pin mouseover 
		{
			$j('#resultContainer' + index).removeClass('bGradient');
			$j('#resultContainer' + index).addClass('yGradient');
		}
		
		var markerDiv = $j('div[title="' + indexToString + '"]');	//find div that holds map icon based on the title in order to add an id and class to it for use later
		markerDiv.attr('id', 'mapIcon' + index);
		markerDiv.attr('class', 'mapIcon');
		marker.setTitle("");								//remove title so when user mouses over marker, default google maps title box doesn't appear.  adding it back on mouseout since the title is used to get the div
		marker.setZIndex(300);
		var offset = markerDiv.offset();
		$j('#map_infowindow' + index).css('left', offset.left - 278);			//position infobox to left of marker. 
		$j('#map_infowindow' + index).css('top', offset.top - 100);
		$j('#map_infowindow' + index).css('display', 'block');
	});

	google.maps.event.addListener( marker, 'mouseout', function(){
		marker.setTitle(indexToString);
		marker.setIcon("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chs=21x32&chld=" + index + "|2E93D2|FFFFFF&ext=.png");		//change marker color on hover
		marker.setZIndex(200);
		$j('#search_listing_business_map_icon' + index).css('background-position', '-310px -390px');		//make biz listing number back to blue on map pin mouseover

		if ( $j('#resultContainer' + index).hasClass('b') )			//make biz listing container blue on map pin mouseover 
		{			
			$j('#resultContainer' + index).removeClass('yGradient');
			$j('#resultContainer' + index).addClass('bGradient');
		}

		$j('#map_infowindow' + index).css('display', 'none');
	});
	
	// store these so the rest of the page can interact with the map
	if(index != null) {
		marker_array[index] = new Array();
		marker_array[index]['marker'] = marker;
		marker_array[index]['map'] = map;
	}
}

//Simplified version for Business Details page map
function addMarkerBizDetails( map, markerText, latitude, longitude, name )	
{
	var iconOptions = {
		width: 21,
		height: 32,
		primaryColor: "#2E93D2",
		textColor: "#FFFFFF"
	}
	
	var iconImg = MapIconMaker.createMarkerIcon( markerText, iconOptions );
	var nameToString = name.toString();		//converting the index to a string, then use it as the marker title to uniquely identify the marker div later
	
	var marker = new google.maps.Marker({
		position: new google.maps.LatLng( latitude, longitude ),
		map: map,
		title: nameToString,
		icon: iconImg
	});
}

function loadVideoAdLightbox(listingId, url) 
{
	logClick( url );
	
	var marginLeft = $m('video' + listingId).getWidth() / 2;  
	$j.blockUI({
		message: $j('#video' + listingId),
		centerX: true,
		centerY: true,
			css: 
			{
				left : '50%',
				marginLeft : -marginLeft,
				cursor: 'auto'
			} 
		});
	  
	$j('.blockOverlay').attr('title','Click to close').click($j.unblockUI);
	return false;
}

/**
 * Tells client how many characters they have left to enter
 * and will trim the characters if they have exceeded maxLimit.
 */
function textCounter(field, cntfield, maxlimit ) 
{
	if (field.val().length > maxlimit) 
	{
		field.val(field.val().substring(0, maxlimit));
	} else 
	{
		charsLeft = maxlimit - field.val().length;
		cntfield.html(charsLeft);
	}
}

function textCounterRange(field, cntfield, maxlimit, minlimit ) 
{
	if (field.val().length > maxlimit) 
	{
		field.val(field.val().substring(0, maxlimit));
	}
	
	if( field.val().length < minlimit )
	{
		charsLeft = minlimit - field.val().length;
		cntfield.html(charsLeft + ' characters needed');
		return;
	}
	
	if( field.val().length > maxlimit )
	{
		charsLeft = maxlimit - field.val().length;
		cntfield.html(charsLeft + ' characters over');
		return;
	}
	
	cntfield.html( '' );
}

function verify_checkbox(checkbox_name, submit_button) {
	if ( $j(checkbox_name).is(':checked') ) {
		$j(submit_button).show();
	} else {
		$j(submit_button).hide();
	};
}

//adjust size of Review lightwindow for smaller screens
function adjustReviewWindow() 
{
	$j(document).ready(function() 
	{
		var windowHeight = $j(window).height();
		
		if ( windowHeight < 700 ) 
		{ 
			$j('.resultContainer').css('overflow', 'auto');
			$j('.resultContainer').css('position', 'relative');		//IE7 fix
			$j('.resultContainer').css('height', '200px');
		}
	});
}

var directionsDisplay;
var directionsMap;
function initializeDirections(bizID, bizLat, bizLong) {
	var scrollTop = document.documentElement.scrollTop >= document.body.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;	//IE, Chrome, and Safari will use only document.body.scrollTop, FF will only use document.documentElement.scrollTop. 
	var windowTop = scrollTop + 20;						//place top of directions window 20px from top of browser viewable window
	
	var browserWidth = $j(window).width();
	var widthDifference = browserWidth - 700;					//find difference between width of browser and width of the review window (which is set to 700px)
	var windowLeft = widthDifference / 2;					//left position of review window will be the difference divided by 2
	
	$j.ajax({
		url: "/biz/dummy/" + bizID + "/directions.ajax",
		cache: true,
		success: function(data) {
			$j('body').append('<div id="directions-modal-panel"></div>');
			$j('#directions-modal-panel').html(data);
			
			$j.blockUI({ 
				message: $j('#directions-modal-panel'),  
			    centerX: true,
				centerY: false,
				css: {
					top: windowTop,
					left: windowLeft,
					position: 'absolute',
					width: '700px',
			     	cursor: 'auto'
				},
			    overlayCSS:  { 
			        backgroundColor: '#000',
			        cursor: 'auto', 
			        opacity: 0.25
			    }
			});
			
			//since loading a map in ajax lightwindow, need to manually trigger resize event to get the map to display correctly (Bug 1876)
			google.maps.event.trigger(directionsMap, 'resize');
			
			//setting center of map after map is created in the ajax lightwindow
			var bizLocation = new google.maps.LatLng(bizLat, bizLong);
			directionsMap.setCenter(bizLocation);
		}
	});		
}

function printPromoSetup(bizId) {

	var voteButtonOffset = $j('#printPromoButton').offset();
	var documentHeight = $j(document).height();
	var windowHeight = $j(window).height();
	var voteButtonMinHeight = documentHeight - voteButtonOffset.top;
	var heightDifference = documentHeight - windowHeight; 
	
	var scrollTop = document.documentElement.scrollTop >= document.body.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;	//IE, Chrome, and Safari will use only document.body.scrollTop, FF will only use document.documentElement.scrollTop. 
	var reviewWindowTop = scrollTop + 20;						//place top of review window 20px from top of browser viewable window
	
	var browserWidth = $j(window).width();
	var widthDifference = browserWidth - 700;					//find difference between width of browser and width of the review window (which is set to 700px)
	var reviewWindowLeft = widthDifference / 2;					//left position of review window will be the difference divided by 2 

    printPromo(bizId, reviewWindowLeft, reviewWindowTop);
    
}
/**
 * Loads the print promo modal panel.
 */
function printPromo(bizId, leftPosition, topPosition) {
	$j.ajax({
		url: "/business/printPromo.ajax",
		data: {
			bizId: bizId
		},
		cache: false,
		success: function(data) {
			// 1) Load the data into the review panel
			$j('#printPromo-modal-panel').html(data);

			// 2) Pop the light window
			$j.blockUI({
				message: $j('#printPromo-modal-panel'),
				centerX: true,
				centerY: false,
				css: {
					textAlign: 'left',
					top: topPosition,
					left: leftPosition,
					position: 'absolute',
					width: '700px',
			     	cursor: 'auto'
				},
			    overlayCSS:  { 
			        backgroundColor: '#000',
			        cursor: 'auto', 
			        opacity: 0.25
			    }
			});
		}
	});
}

function calcRoute(bizLat, bizLong) {
	var directionsService = new google.maps.DirectionsService();
	var start = document.getElementById("start").value;
	var end = document.getElementById("end").value;
    var request = {
        origin: start, 
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    
    if (start == '' || end == '')
    {
    	$j("#directions_error").html("Please enter a starting and ending address (ex: '<span class='italic'>123 Some St.</span>' or '<span class='italic'>Solana Beach, CA</span>').").css('display', 'block');
    } else {
    	directionsService.route(request, function(response, status) {
    		if (status == google.maps.DirectionsStatus.OK) {
    			$j("#directions_error").html("").css('display', 'none');
    	    	$j("#directions_map").css('width', '60%');				//changing map size to display directions text on right
    	    	google.maps.event.trigger(directionsMap, 'resize');		//triggering resize event so map adjusts itself 
    	    	directionsDisplay.setDirections(response);
    		} else {
    			//alert(status);
    			$j("#directions_error").html("No route could be determined between the start and end addresses.").css('display', 'block');
    		}
    	});
    }
}

function printSelection(node, start, end){
	
	var content = node.innerHTML
	var pwin = window.open('','print_content','width=700,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,menubar=no');
	pwin.blur();
	//pwin.moveTo(0,0);
	pwin.document.open();
	pwin.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">');
	
	var links = window.document.getElementsByTagName('link');
	for ( var i=0; i < links.length; i++ )
	{
		if(links[i].rel.toLowerCase()=='stylesheet') 
		{
			pwin.document.write('<link type="text/css" rel="stylesheet" href="'+links[i].href+'"></link>');
		}
	}
	var styles = window.document.getElementsByTagName('style');
	for ( var i=0; i < styles.length; i++ )
	{
		pwin.document.write('<style type="text/css">'+styles[i].innerHTML+'</style>');
	}
	
	pwin.document.write('<body onload="window.print()" style="background: #FFF;">'+content+'</body></html>');
	pwin.document.getElementById('print_start').innerHTML = start;
	pwin.document.getElementById('print_end').innerHTML = end;
	pwin.document.close();
	 
	setTimeout(function(){pwin.close();},1000);
}

function sendKudosPopup( userId, url ) {
	var scrollTop = document.documentElement.scrollTop >= document.body.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;	//IE, Chrome, and Safari will use only document.body.scrollTop, FF will only use document.documentElement.scrollTop. 
	var sendKudosPopupTop = scrollTop + 20;						//place top of review window 20px from top of browser viewable window
	
	var browserWidth = $j(window).width();
	var widthDifference = browserWidth - 520;					//find difference between width of browser and width of the send kudos window (which is set to 520px)
	var windowLeft = widthDifference / 2;
	
	if( url == null || url == undefined )
	{
		url = '/report/kudosform.ajax';
	}
	
	if( checkLoggedIn() ) 
	{
		$j.ajax({
			url: url,
			data: {
				u: userId
			},
			cache: true,
			success: function(data) {
				$j('body').append('<div id="kudos-modal-panel"></div>');
				$j('#kudos-modal-panel').html(data);
				
				$j.blockUI({
					message: $j('#kudos-modal-panel'),
					centerX: true,
					centerY: false,
					css: {
						top: sendKudosPopupTop,
						left: windowLeft,
						position: 'absolute',
						width: '520px',
						cursor: 'auto',
						textAlign: 'left'
					},
				    overlayCSS:  { 
				        backgroundColor: '#000',
				        cursor: 'auto', 
				        opacity: 0.25
				    }
				});
				
			}
		});	
	}
	
	return false;
}

function cityLeaderboard( cityId ) {
	var browserWidth = $j(window).width();
	var widthDifference = browserWidth - 800;					//find difference between width of browser and width of the review window (which is set to 700px)
	var directionsWindowLeft = widthDifference / 2;
	
	$j.ajax({
		url: "/city/cityLeaders.ajax",
		data: {
			city: cityId
		},
		cache: true,
		success: function(data) {
			$j('body').append('<div id="city-leaderboard-modal-panel" style="display: none;"></div>');
			$j('#city-leaderboard-modal-panel').html(data);
			
			$j.blockUI({
				message: $j('#city-leaderboard-modal-panel'),
				centerX: true,
				centerY: false,
				css: {
					top: '50px',
					left: directionsWindowLeft,
					position: 'absolute',
					width: '800px',
			     	cursor: 'auto'
				},
			    overlayCSS:  { 
			        backgroundColor: '#000',
			        cursor: 'auto', 
			        opacity: 0.25
			    }
			});
			
		}
	});	
	
}

function userAlmostKudosPopup( activityCounterId, userId ) {
	var browserWidth = $j(window).width();
	var widthDifference = browserWidth - 520;					//find difference between width of browser and width of the window (which is set to 520px)
	var windowLeft = widthDifference / 2;
	
	$j.ajax({
		url: "/user-profile/userAlmost.ajax",
		data: {
			activityCounter: activityCounterId,
			user: userId
		},
		cache: true,
		success: function(data) {
			$j('body').append('<div id="user-kudos-modal-panel" style="display: none;"></div>');
			$j('#user-kudos-modal-panel').html(data);
			
			$j.blockUI({
				message: $j('#user-kudos-modal-panel'),
				centerX: true,
				centerY: false,
				css: {
				top: '50px',
				left: windowLeft,
				position: 'absolute',
				width: '520px',
		     	cursor: 'auto',
		     	textAlign: 'left'
			},
		    overlayCSS:  { 
		        backgroundColor: '#000',
		        cursor: 'auto', 
		        opacity: 0.25
		    }	
			});
			
		}
	});	
	
}

function userKudosPopup( userCounterId, userId ) {
	var browserWidth = $j(window).width();
	var widthDifference = browserWidth - 520;					//find difference between width of browser and width of the window (which is set to 520px)
	var windowLeft = widthDifference / 2;
	
	$j.ajax({
		url: "/user-profile/userKudos.ajax",
		data: {
			userCounter: userCounterId,
			user: userId
		},
		cache: true,
		success: function(data) {
			$j('body').append('<div id="user-kudos-modal-panel" style="display: none;"></div>');
			$j('#user-kudos-modal-panel').html(data);
			
			$j.blockUI({
				message: $j('#user-kudos-modal-panel'),
				centerX: true,
				centerY: false,
				css: {
				top: '50px',
				left: windowLeft,
				position: 'absolute',
				width: '520px',
		     	cursor: 'auto',
		     	textAlign: 'left'
			},
		    overlayCSS:  { 
		        backgroundColor: '#000',
		        cursor: 'auto', 
		        opacity: 0.25
		    }	
			});
			
		}
	});	
	
}

function cashbackPopup(bizID) {
	var scrollTop = document.documentElement.scrollTop >= document.body.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;	//IE, Chrome, and Safari will use only document.body.scrollTop, FF will only use document.documentElement.scrollTop. 
	var windowTop = scrollTop + 20;						//place top of directions window 20px from top of browser viewable window
	
	var browserWidth = $j(window).width();
	var widthDifference = browserWidth - 520;					//find difference between width of browser and width of the window (which is set to 520px)
	var windowLeft = widthDifference / 2;
	
	$j.ajax({
		url: "/biz/dummy/" + bizID + "/cashbackInfo.ajax",
		cache: true,
		success: function(data) {
			$j('body').append('<div id="cashbackInfo-modal-panel"></div>');
			$j('#cashbackInfo-modal-panel').html(data);
			
			$j.blockUI({ 
				message: $j('#cashbackInfo-modal-panel'),  
			    centerX: true,
				centerY: false,
				css: {
					top: windowTop,
					left: windowLeft,
					position: 'absolute',
					width: '520px',
			     	cursor: 'auto'
				},
			    overlayCSS:  { 
			        backgroundColor: '#000',
			        cursor: 'auto', 
			        opacity: 0.25
			    }
			});
		}
	});	
	
}

function closeLightwindow() {
	$j.unblockUI();
}

function installMavenLabelHandler( selector )
{
	$j( selector ).hover( 
		function(e)
		{
			var info = $j("#maven_info");
			var offset = $j(this).offset();		
			info.show();
			info.offset( {left: offset.left + $j(this).outerWidth() + 5, top: offset.top} );
		},
		function(e)
		{
			var info = $j("#maven_info");
			info.hide();
		}
	);
}

function embedAward(offset, width, parent, sitename) 
{
	//Create code to go in embed box 
	var parentHtml = $j(parent).html();
	$j('#mp').append('<div id="embed_badge_code_container"><div id="yourAwardsCategoryAward">' + parentHtml + '</div></div>');		//changing yourAwardsCategoryAward to be the id instead of the class so that loading of the css file does not change the display of the main site (css file is bases all its rules off of #yourAwardsCategoryAward).
	$j('#embed_badge_code_container .yourAwardsCategoryAwardName, #embed_badge_code_container .overflowHidden').remove();		//take out "Category: catName" and "Embed Award" and "Buy Plaque" buttons
	$j('#embed_badge_code_container').prepend('<link rel="stylesheet" type="text/css" href="http://' + sitename + '/mstatic/styles/embed_award_badge.css">');		//add css file
	
	var bizLink = $j('.yourAwardsBizName').attr('href');		
	var fullBizLink = "http://" + sitename + bizLink;		//add hostname to biz details link href
	$j('.yourAwardsBizName').attr('href', fullBizLink);
	
	var catLink = $j('.mojoAwardLabel').attr('href');		
	var fullCatLink = "http://" + sitename + catLink;		//add hostname to category page link href
	$j('.mojoAwardLabel').attr('href', fullCatLink);
	
	//Create Embed Badge popup that displays embed code created above
	$j('#mp').append('<div id="embed_badge_popup" class="mojoPopup"></div>');
	$j("#embed_badge_popup").css('top', offset.top);
	$j("#embed_badge_popup").css('left', offset.left + (width + 5));	//position popup 5 pixels to right of the link clicked
	$j("#embed_badge_popup").html('<div class="new_popup"><div class="new_popup_header">Embed this badge on your site!</div><div class="new_popup_content">Copy and paste the following code onto your site:<textarea id="embed_badge_code" readonly="true">' + $j('#embed_badge_code_container').html() + '</textarea><div class="mojoPopupCloseContainer"><a class="mojoPopupClose" onclick="mojoPopupClose($j(this))">close</a></div></div></div>');
}

function buyAwardPlaque(offset, width) 
{
	$j('#mp').append('<div id="buy_plaque_popup" class="mojoPopup"></div>');
	$j("#buy_plaque_popup").css('top', offset.top);
	$j("#buy_plaque_popup").css('left', offset.left + (width + 5));	//position popup 5 pixels to right of the link clicked
	$j("#buy_plaque_popup").html('<div class="new_popup"><div class="new_popup_header">Purchase an Award Plaque</div><div class="new_popup_content"><div class="floatL" style="width: 40%;"><div id="buyPlaqueImage"></div><a id="buy_plaque_preview_link" onclick="buyAwardPlaquePreview()">Preview</a></div><div class="floatR" style="width: 60%;">To purchase an award plaque for your place of business, please call:<br/><br/><span class="bold">(866) 964-0866</span></div><div class="mojoPopupCloseContainer"><a class="mojoPopupClose" onclick="mojoPopupClose($j(this))">close</a></div></div></div>');
}

function buyAwardPlaquePreview()
{
	$j('#mp').append('<div id="buy_plaque_preview"><div id="buy_plaque_preview_image"></div></div>');
	$j('#buy_plaque_preview').append('<a class="lightwindow_close_x" onclick="closeLightwindow();"></a>');
	
	var scrollTop = document.documentElement.scrollTop >= document.body.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;	//IE, Chrome, and Safari will use only document.body.scrollTop, FF will only use document.documentElement.scrollTop. 
	var windowTop = scrollTop + 20;						//place top of directions window 20px from top of browser viewable window
	
	var browserWidth = $j(window).width();
	var contentWidth = $j('#buy_plaque_preview').outerWidth();
	var widthDifference = browserWidth - contentWidth;					//find difference between width of browser and width of the content
	var windowLeft = widthDifference / 2;
	
	$j.blockUI({ 
		message: $j('#buy_plaque_preview'),  
		centerX: true,
		centerY: false,
		css: {
			top: windowTop,
			left: windowLeft,
			position: 'absolute',
			cursor: 'auto'
		},
	    overlayCSS:  { 
	        backgroundColor: '#000',
	        cursor: 'auto', 
	        opacity: 0.25
	    }
	});
}

function mojoPopupClose(elem) 
{
	elem.parents(".mojoPopup").remove();
}

function emailSettingsPopup(offset, width, userid) 
{
    var yerl = "/personal/emailSettings.ajax" + "?userId=" + userid;
	$j.ajax({
		url: yerl,
		cache: true,
		success: function(data) {
			$j('#mp').append('<div id="email_settings_popup" class="mojoPopup"></div>');
			$j("#email_settings_popup").css('top', offset.top);
			$j("#email_settings_popup").css('left', offset.left + (width + 5));	//position popup 5 pixels to right of the link clicked
			$j("#email_settings_popup").html(data);
		}
	});	
}

function emailSettingsPopupClose(elem) 
{
    document.forms["emailSettingsForm"].submit();
	elem.parents(".mojoPopup").remove();
}

function searchListingReviewExpand(id, reviewType) {
	$j('#featured_'+reviewType+'_review_text_'+id+'').css('height', 'auto');
	$j('#featured_'+reviewType+'_review_more_'+id+'').css('display', 'none');
	$j('#featured_'+reviewType+'_review_details_'+id+'').css('display', 'block');
}

function vipReviewerPopup(elem) 
{
	$j("#vipReviewPopup").remove();
	
	$j("#mp").append('<div id="vipReviewPopup" class="new_popup mojoPopup"></div>');
	var width = elem.parent().outerWidth();
	var offset = elem.offset();
	
	$j("#vipReviewPopup").css('top', offset.top);
	$j("#vipReviewPopup").css('left', offset.left + width + 15);
	$j("#vipReviewPopup").html('<div class=\"new_popup_header\">What\'s This?</div><div class=\"new_popup_content\">A VIP Reviewer is someone who we\'ve tapped as extra special. Lots of times this is because they write great reviews and are a social influencer in the city. They get cool rewards such as invites to exclusive events and local deals.<br/><br/>If you think you have what it takes to be a VIP, shoot us a quick email us and tell us why at <a href="mailto:vip@mojopages.com">VIP@mojopages.com</a>. A few hints...we love it when you have filled out your profile, and when you are an active member on the site!<a onclick=\"mojoPopupClose($j(this));\" class="mojoPopupClose">close</a></div>');
}
		
function popularCities() {
	var position = $j('#chooseACityLink').position();
	$j('#popularCities').animate({
		marginLeft: '0',
		left: position.left + 10	//adding 10px to match the left margin added to the chooseACityLink
	}, 1000);
}

var thisDay = new Date();
var dateFutureYear = thisDay.getFullYear();		//use same 4 digit year as current year
var dateFutureMonth = thisDay.getMonth() + 1;	//get 0-11 month, add 1 to offset array position
var dateFutureDay = 0;							//set day, hour, min, sec to Sunday at 00:00 when awards voting ends
var dateFutureHours = 0;
var dateFutureMins = 0;
var dateFutureSeconds = 0;
function GetCount(){
	
	var dateNow = new Date();									//grab current date
	var amount = dateFuture.getTime() - dateNow.getTime();		//calc milliseconds between dates
	delete dateNow;
	
	// time is already past
	if (amount < 0) {
		document.getElementById('countbox_biz_details').innerHTML="MojoAwards countdown complete!";
	} else {	// date is still good
		var days = 0;
		var hours = 0;
		var mins = 0;
		var secs = 0;
		var out = "";

		amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs

		days=Math.floor(amount/86400);//days
		if ( days < 10 ) {
		    days = "0" + days;
		}
		amount=amount%86400;

		hours=Math.floor(amount/3600);//hours
		if ( hours < 10 ) {
		    hours = "0" + hours;
		}
		amount=amount%3600;

		mins=Math.floor(amount/60);//minutes
		if ( mins < 10 ) {
		    mins = "0" + mins;
		}				
		amount=amount%60;

		secs=Math.floor(amount);//seconds
		if ( secs < 10 ) {
		    secs = "0" + secs;
		}
		
        document.getElementById('days').innerHTML = days;
        document.getElementById('hours').innerHTML = hours;
        document.getElementById('mins').innerHTML = ":" + mins;
        document.getElementById('secs').innerHTML = ":" + secs;		        
		setTimeout("GetCount()", 1000);
	}
}
var shareIconArray = ['rotate_facebook_icon', 'rotate_twitter_icon', 'rotate_myspace_icon', 'rotate_digg_icon', 'rotate_delicious_icon', 'rotate_stumbleupon_icon', 'rotate_reddit_icon'];
var shareIconCount = 0;
function rotateShareIcon() {
	if (shareIconCount > shareIconArray.length) {	//reset to 0 when it pasts the last in the list
		shareIconCount = 0;
	} else {
		$j('#rotate_icon').attr("class", shareIconArray[shareIconCount]);	//set class of the icon style name
		shareIconCount += 1;
	}
	setTimeout(rotateShareIcon, 2000);
}

function switchText( element ) {
	element.parent().hide();
	$j(".fullReviewText").show();
}
	
function showAllSources() {
	$j("#allSources").slideDown("slow");
	return false;
}
/*
 *	Events occurring when document is ready
 */
$j(document).ready(function() {	
	//Nav bar Search button hover
	$j('#search_button').hover(
		function() {
			$j(this).css('background-position', '-1030px -50px');
		},
		function() {
			$j(this).css('background-position', '-1030px 0');
		}
	);
	
	//Search Results page changing listing and pin color on mouseover
	$j('.resultContainer').hover(
		function() {
			if ( $j(this).hasClass('b') ) {
				$j(this).removeClass('bGradient');
				$j(this).addClass('yGradient');
				$j(this).find('.search_listing_business_map_icon').css('background-position', '-1190px -463px');		//change listing pin icon to orange
			}
		},
		function() {
			if ( $j(this).hasClass('b') ) {
				$j(this).removeClass('yGradient');
				$j(this).addClass('bGradient');
				$j(this).find('.search_listing_business_map_icon').css('background-position', '-310px -390px');
			}
		}
	);
	
	//When on Search results page, move filters pane to bottom of #mp on page load in order to position on left
	if ($j('#filtersContainer').length) { 		
		//For some reason, .contents() works only on IE and breaks FF/Chrome, and vice versa.
		if ($j.browser.msie) {
			$j('#filtersContainer').contents().detach().appendTo('#mp');
		}
		else 
		{
			$j('#filtersContainer').detach().appendTo('#mp');
		}
	}
	
	/*
	 * User Profile page popups
	 */
		$j("#kudos_popup_link").hover(
			function() {
				$j('#mp').append('<div id="kudos_popup"></div>');
				$j("#kudos_popup").css('display', 'block');
				$j("#kudos_popup").html('<div class=\"new_popup\"><div class=\"new_popup_header\">Kudos</div><div class=\"new_popup_content\">Kudos recognize the great things you do on MojoPages. They reward you for your activity, jazz up your profile and individualize you from other members.<br/><br/>Like pizza? Earn the Extra Cheesy Kudos for voting for pizza places.  Enjoy working out?  We\'ve got a Kudos for that too - the Buff Kudos! Like to share on Facebook and Twitter?  Earn a Kudos for those too.<br/><br/>There are hundreds Kudos you can earn, so get out there and earn some Kudos!</div></div>');
			},
			function() {
				$j("#kudos_popup").css('display', 'none');
				$j("#kudos_popup").remove();
			}
		);
	 	
		$j("#trusted_cities_popup_link").click(function() {
			$j(this).next().show();
			$j("#trusted_cities_arrow").css('background', 'url("/mstatic/images/popup_arrow2.png")');
			$j("#trusted_cities_header").css('background', 'url("/mstatic/images/trusted_cities_header.png")');
			$j("#trusted_cities_inner").css('background', 'url("/mstatic/images/popup_inner_content.png") bottom right');
		});
		
		$j("#trusted_popup_question").click(function() {
			$j(this).next().show();
			$j("#trusted_question_arrow").css('background', 'url("/mstatic/images/popup_arrow2.png")');
			$j("#trusted_question_header").css('background', 'url("/mstatic/images/trusted_cities_header.png")');
			$j("#trusted_question_inner").css('background', 'url("/mstatic/images/popup_inner_content.png") bottom right');
		});
		
		$j("#trust_points_popup_link").click(function() {
			$j("#trust_points_popup").css('display', 'block');
			$j("#trust_points_popup").css('background', 'url("/mstatic/images/trust_points_popup.png")');
		});
		
		$j("#trust_points_popup_close, #trusted_cities_popup_close, #kudos_popup_close").click(function() {
			$j(this).parent().css('display', 'none');
		});
	
	$j(".lightwindow_close_x, #directions_close").click(function(){
		$j.unblockUI();
	});
	
	$j("#other_categories_popup_link").click(function() {
		$j(this).next().css('display', 'block');
		$j("#trusted_cities_arrow").css('background', 'url("/mstatic/images/popup_arrow2.png")');
		$j("#other_categories_header").css('background', 'url("/mstatic/images/other_categories_header.png")');
		$j("#trusted_cities_inner").css('background', 'url("/mstatic/images/popup_inner2.png") bottom right');
	});	
	
	//select all the a tag with name equal to modal
	$j('a[name=modal]').click(function(e) {
		e.preventDefault();		//Cancel the link behavior
		var id = $j(this).attr('href');		//Get the A tag href, which is the id of the element that's appearing
		$j(id).show("fast"); 
	});
	
	$j('a[name=close]').click(function(e) {
		e.preventDefault();		//Cancel the link behavior
		var id = $j(this).attr('href');		//Get the A tag href, which is the id of the element that's appearing
		$j(id).hide("fast"); 	
	});
		
	installMavenLabelHandler( '#trusted_members_maven_label, #trusted_members_maven_label_150, #city_leaderboard_maven_label' );
	
	// For the what's mojo hover description. Putting it here so it's in a cached js instead
	// of repeated on all our pages.
	$j( '#mp' ).append( '<div id="maven_info" style="display:none">\
		<div class="new_popup">\
			<div class="new_popup_header">\
				<div>What\'s this?</div>\
			</div>\
			<div class="new_popup_content">\
			A Maven on MojoPages is the most trusted individual in a city. They\'ve earned this coveted title by writing the most helpful reviews.<br/><br/>Like Webster says, mavens have great experience or knowledge. <br/><br/>So who better to give you the most trustworthy advice on local businesses?\
			</div>\
		</div>\
	</div>' );
	$j('#maven_info').offset( {left: 0, top: 0} );
	
	$j('#popularCities').mouseleave(function() {
		$j('#popularCities').animate({
			marginLeft: '-1000px'
		}, 1000);
	});
	
	/**********************************************
	* Biz Details Page
	*/
	
	//if close button is clicked
	$j('#close_share_btn').click(function (e) {
		e.preventDefault();		//Cancel the link behavior
		$j('.closeModal').hide("fast");
	});	
	
	$j.each($j('.mpFeaturedReviewText'), function() {
		if ($j(this).html().split(' ').length > 150) {	//if a Featured pos/neg Review is more than 150 words, show truncated version with 'more' link
			var fullReviewText = $j(this).html(); 					//store orig full review to display when 'more' link clicked.
			var editedText = $j(this).html().split(' ', 150);		//break up review to 150 words into array created by split.  
			var shortReviewText = "";
			
			for(i = 0; i < editedText.length; i++){
				shortReviewText += editedText[i] + ' '; 			//separate each word and put a space after it.
			}
			
			$j(this).html(shortReviewText);							//display shortend version at first
			$j(this).append('... <a class="featuredReviewLink" onclick="switchText($j(this));">more</a>');		//add more link to bottom right corner
			
			$j(this).after('<p class=\"mpFeaturedReviewText fullReviewText\" style=\"display: none;\"></p>');	//create p container for the orig full review text
			$j(this).next().html(fullReviewText);
		}
	});
	
});	

