/**
 * Hawaii Life search & map functions
 * @package HawaiiLife
 * @version 6.0
 * @author Yacine Merzouk
 * @author Brian Schemp
 * @copyright Hawaii Life 2010
 */

//***************************** GLOBAL VARIABLES
var map;												//The Google Map object
var customTooltip;							//The small overlays with property info that show up on map marker mouseover
var markerArray = new Array();	//The map markers array
var searchSpeed = 0;						//Used to track the speed of the search routine.
var icon_image;
var icon_image_rollover;


//***************************** SEARCH ROUTINE CHECKS
//var isPageRefresh = true;				//Used to let the map know it has to zoom in on properties (DEPRECATED???)
//var isTextSearch = false;				//Used to differenciate text searches from map searches and DDL searches (DEPRECATED???)
var searchInProgress = false;		//Used to avoid multiple simultaneous searches
var isMapIdle = true;
var mapCanBeSearched = false;		//Used to allow or disallow automatic map centering
var mapBeingDragged = false;		//Used to avoid multiple bounds_changed events firing at the same time
var searchProgressTimer;				//Timeout var used when checking for the end of the search routine
var getPropertiesFinished = true;	//Used to track down the end of the getProperties ajax callback
var centerMapFinished = true;					//Used to track down the end of the centerMap ajax callback
var getPropertyMarkersFinished = true;	//Used to track down the end of the getPropertyMarkers ajax callback
var isMLSSearch = false;	//Used to know when to auto-popup
var showAdvancedOptions = false;
//var singleMLSAlreadyShown = false; //Used to cancel detail page auto-popup

//***************************** SEARCH FUNCTION
// Possible searchType values
// -basic
// -text
// -map
// -update
function search( searchType ){

	//////console.log("Search in progress: "+searchInProgress);
	
	//Never run 2 searches at the same time
	if(!searchInProgress){

		//Write progress to console
		//////console.log("Starting the search routine. Search type: "+searchType);
		
		//Start timeloop that makes sure the search routine is completed before wrapping it up	
		searchInProgress = true;
		searchSpeed = 0;
		getPropertiesFinished = false;
		centerMapFinished = false;
		getPropertyMarkersFinished = false;
		searchProgressTimer = setTimeout(isSearchRoutineFinished, 100);
		
		//Show "Searching..." loader
		showLoader();
	
		//This prevents the bounds_changed event from firing when the map zooms on the search results
		//It is referenced in event listeners
		if ( searchType != "map" ){
			mapCanBeSearched = false;
		}
	
		// Get an array of properties
		// Each property in the properties array is an assoc array representation of the Property class
		// The search criteria are always saved to session as soon as they are selected.
		$.post("/search-ajax/index.php",
			{
				action: "getProperties",
				searchType: searchType
			},
			
			//results.search_results_text
			//results.property_results
			//results.refine_search_top_ui
			//results.refine_search_bottom_ui
			//results.listings
			//results.pagination
			//results.special_instructions
			//results.search_box_text
			function(results){
			
				//console.log( results );
							
				if( typeof(results) != "undefined" && results != null ){
		
					// Properties are from a single island
					if(resultsCanBeDisplayed(results)  && typeof(results.search_results_text) != "undefined" && typeof(results.property_results) != "undefined" && results.refine_search_top_ui){
										
						// Update search results
						updateSearchResults(results.search_results_text);
						
						// Update search interface
						updateSearchInterface(results.refine_search_top_ui, results.refine_search_bottom_ui, results.listings, results.pagination);
						
						removeLoader();
						searchInProgress = false;
						
						// Add markers to map and zoom to markers
						// 1. Add all markers
						// 2. Add event listeners (mouse over, mouseout, click)
						// 3. Zoom to markers
						// The updateMap function is also the longest to execute, so it does:
						// 1. Hide any background messages or images.
						updateMap(results, searchType);
											
						//reset all pop-up links.
						// Deprecated since HL6.1
						//repimpLinks();
						
						//Show popup when mls search
						if (isMLSSearch == true){
						  // window.location = "/detail-standalone.php?mls_no="+results.property_results[0].mls_no+"&z=2";

						  isMLSSearch = false;
						}

						
						//Update text search box
						$("#input").val(results.search_box_text);
					
					//Results cannot be displayed because properties from different islands have been found.
					}else{
																			
						//Show island selection popup
						showIslandSelection();	
								
					}
	
				//0 properties found
				}else{
				
					//console.log("No property found");
					
					// Update search results
					updateSearchResults(results.search_results_text);

					// Update search interface
					updateSearchInterface(results.refine_search_top_ui, results.refine_search_bottom_ui, results.listings, results.pagination);

					updateMap(results, searchType);

					
					//reset all pop-up links.
					// Deprecated since HL6.1
					//repimpLinks();
					
					removeLoader();
					
				}
				
				getPropertiesFinished = true;
	
			},
			"json"
		);		

	}

}

//***************************** CHECKS IF A SEARCH ROUTINE IS OVER
// Checks if a search routine has been completed
// Triggers the endSearch function or restarts the searchProgress timeout
function isSearchRoutineFinished(){
	
	//Track search speed - see global vars at top of page
	searchSpeed += 100;

	//These vars are set to true at the end of ajax callback.
	//Since ajax runs asynchronously we never know which order they will be completed in
	if(getPropertiesFinished && centerMapFinished && getPropertyMarkersFinished){

		//Wrap up the search routine
		endSearch();		
	
	//Search isn't done yet
	}else{
	
		//Reset setTimeout var
		searchProgressTimer = setTimeout(isSearchRoutineFinished, 100);
	
	}

}

//***************************** UPDATES UI AND VARS WHEN SEARCH ROUTINE IS OVER
// Updates the UI and resets search check variables when a search is completed
function endSearch(){

	//Remove loader UI elements
	removeLoader();
	
	//Don't zoom too much!
  if(map.getZoom() > 19){
  	//////console.log("Zooming out to minimum zoom level.");
  	map.setZoom(19);
  	
  	//Wait until zoom is 19 or less before running the entire function
  	setTimeout(endSearch,500);
  	return false;
  }

	//Reset the global var that prevents extra searches
	searchInProgress = false;
	mapCanBeSearched = true;

	//Output search speed to console
	//////console.log("Search routine completed in "+searchSpeed+" milliseconds");

	//Stop the setTimeout loop
	clearTimeout(searchProgressTimer);	
	
}


/*
 * Determines if the property search results can be displayed. Check if all search results
 * contain the same island_id.
 * 
 * @param array results
 * @returns true if properties can be displayed false otherwise.
 */
function resultsCanBeDisplayed(results){

	var island_id = 0;
	var resultsCanBeDisplayedFlg = true;
		
	//loop over results.property_results array to determine if all results contain same island_id.
	if(typeof(results) != "undefined" && results != null && typeof(results.property_results) != "undefined"){
	
		$.each(results.property_results, function(i, data){
		
			if(i == 0){
				island_id = data.island_id;
			}else{
				if(island_id != data.island_id){
					resultsCanBeDisplayedFlg = false;
					return false;				
				}
			}
		});
	
	}else{
		resultsCanBeDisplayedFlg = false;
	}
	
	return resultsCanBeDisplayedFlg;
}

//***************************** SHOW ISLAND SELECTION
/*
 * Display a overlay that allows the user to select the island
 * to search.
 * 
 * @param array results
 */
function showIslandSelection(){
	//variables.
	var main_container = $('<div id="loader" style="overflow: hidden;"></div>');
	var island_choices_container = $('<div class="choose"></div>');
	var island_choices = $('<p class="islands"></p>');
		
	//add heading to island choices container.
	$('<h2>Choose an Island</h2><p>MLS rules and regulations do not allow properties from<br />multiple islands to be displayed at the same time.</p>').appendTo(island_choices_container);

	//add island choices to its container.
	island_choices.appendTo(island_choices_container);
	
	$('<a style="margin: 0 0 0 10px;" href="javascript:goToLocation(\'island\',1)">Oahu</a>').appendTo(island_choices);
	$('<a style="margin: 0 0 0 10px;" href="javascript:goToLocation(\'island\',2)">Maui</a>').appendTo(island_choices);
	$('<a style="margin: 0 0 0 10px;" href="javascript:goToLocation(\'island\',3)">Big Island</a>').appendTo(island_choices);
	$('<a style="margin: 0 0 0 10px;" href="javascript:goToLocation(\'island\',4)">Kauai</a>').appendTo(island_choices);
	$('<a style="margin: 0 0 0 10px;" href="javascript:goToLocation(\'island\',5)">Molokai</a>').appendTo(island_choices);
	$('<a style="margin: 0 0 0 10px;" href="javascript:goToLocation(\'island\',6)">Lanai</a>').appendTo(island_choices);

	
	//add island choices container to the main container.
	island_choices_container.appendTo(main_container);
	
	//set styles for dialog.
	var loader = $("#update-dialog");
	loader.css({
		"left": "35%",
		"top": "200px",
		"width": "30%"
	});
	
	//Display links to correct search results
	$("#overlay-update").css("visibility", "visible");
	//$("#update-dialog").html("<div id='loader' style='overflow:hidden;'><div class='choose'>"+island_choices.html()+"</div></div>");	
	main_container.appendTo(loader);
	
	//remove loader.
	removeLoader()
}

//***************************** UPDATE SEARCH RESULTS
/*
 * Update the search results text display.
 */
function updateSearchResults(search_results_text){
	$("#dynamic-search-title").html(search_results_text);
}

//***************************** UPDATES SEARCH UI
/*
 * Update the search interface. Includes search results text, refine search options, property listings
 * and pagination.
 * 
 * @param string refine_search_top_ui
 * @param string refine_search_bottom_ui
 * @param string listings
 * @param string pagination
 */
function updateSearchInterface(refine_search_top_ui, refine_search_bottom_ui, listings, pagination){
	$("#locationDDL").html("").html(refine_search_top_ui);
	$("#search-mini").html(refine_search_bottom_ui);
	$("#listings").html(listings);
	$("#pagination").html('<p id="viewing">'+pagination+'</p>');
	if(showAdvancedOptions){
		$("#advanced-options").show().offset( $("#map").offset() );
	}else{
		$("#advanced-options").hide();
	}
}

//***************************** UPDATE MAP
/*
 * Centers map
 * Clear old markers
 * Add markers for new results
 * Zoom map to results
 */
function updateMap(results, searchType){
	
	//Get map location with ajax call
	$.post(
		"/search-ajax/index.php",
		{
			action: "centerMap",
			properties: results.property_results
		},
		function(coord){
						
			//Get center of map
			lat = coord[0];
			lng = coord[1];
			var latlng = new google.maps.LatLng(lat,lng);
			
			//Get map options
		  if(!map){
			  var mapOptions = {
			    zoom: 11,
			    center: latlng,
			    mapTypeId: google.maps.MapTypeId.HYBRID
			  };
			  initializeMap( mapOptions );		  
		  }

			//Get map bounds
		  var sw = new google.maps.LatLng(coord[2],coord[3]);
		  var ne = new google.maps.LatLng(coord[4],coord[5]);
		  var bounds = new google.maps.LatLngBounds(sw,ne);
		  
		  //Zoom map to bounds
		  if(searchType != "map" && searchType != "update"){
  	 		isMapIdle = false;
			  map.fitBounds(bounds);			  
	  	}
			  
			//remove markers.
			clearMarkers();

			//set property markers.
			$.post(
				"/search-ajax/index.php",
				{
					action: "getPropertyMarkers",
					properties: results.property_results
				},
				function(markerList){	
				
					//console.log(markerList);
				
					$.each(markerList, function(i, data){
						addMarker.call(this, data.kind, data.mls_no, data.tooltip, data.lat, data.lon, data.address);
					});
					
					centerMapFinished = true;
					getPropertyMarkersFinished = true;		
					
				},
				"json"
			);
			
	  	
		},
		"json"
	);
}



	 
//***************************** LOAD SEARCH
/*
 * Called when the property search page is intially called. 
 * Get a list of islands for the user to select.
 */ 
function loadSearch(){

	//////console.log("in loadSearch");
			
	//call ajax post for property search.
	$.post(
		"/search-ajax/index.php",
		{
			action: "loadSearch"
		},
		function(results){
			
			if(results.island_selected > 0){
			
				search(results.searchType);
				
			//island has not been selected, display a list of island choices.
			}else{

				showIslandSelection();

			}
		},
		"json"
	);//end ajax post call.	
}
	 

//***************************** ADJUST HEIGHT
//Makes the search page full-screen
function adjustHeight(){
	
	// Get browser height
	var browseHeight = $(window).height();
	
	// Substract header, footer, search heights
	var headerHeight = $("#head").height();
	var footerHeight = $("#footer").height();
	var searchHeight = $("#search-title").height() + $("#results").height();
	var pagHeight = $("#pagination").height();
	var spacers = 40;
	var displayHeight = browseHeight - (headerHeight + footerHeight + spacers);
	var mapHeight = displayHeight;
	var listingHeight = displayHeight - ($("#search-mini").height() + pagHeight +80);
	
	var displayWidth = $('#search-holder').width();
	var listingsWidth = $('#listings').width();
	var mapWidth = displayWidth - listingsWidth - 23;
	
	if(displayHeight < 300){
		// Set results height
		$("#listings").css("height","380");
		// Set map height
		$("#map").css("height", "400");

	}else{
		// Set results height
		$("#listings").css("height", listingHeight);
		// Set map height & width
		$("#map").css("height", mapHeight);
		$("#map").css("width", mapWidth);			
	}
	
}

//***************************** SHOW LOADER ("SEARCHING..." MESSAGE)
/*
 * Display indicators while searching for properties.
 */
function showLoader(){

	//Display links to correct search results
	$("#overlay-update").css("visibility", "visible");
	$("#overlay-update").css("z-index", "150");

	//cache html elements.
	var loader_element = $("#update-dialog");
	var listings_element = $("#listings");
	var viewing_element = $("#viewing");
	var head_element = $("#head");
	
	//set css styles
	loader_element.css("left", listings_element.width() + ((document.body.offsetWidth - listings_element.width() - 180) / 2));
	loader_element.css("top", head_element.height() + ((document.body.offsetHeight - head_element.height()) / 2 - 60));
	loader_element.width(250);
	loader_element.css("right", "0");	
	loader_element.css("font-size", "13px");
	loader_element.html('<div id="loader">Searching...<br /><img src="/img/HL5/loader-50.gif" width="220" height="19" style="margin-top:5px;" /></div>');
	listings_element.html("<br /><span style='background:#276d8c;font-family:Arial, Helvetica, sans-serif;font-weight:bold;padding:5px 10px;font-size:12px;color:#fff; margin:9px 9px'>Loading listings...</span>");
	viewing_element.html('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
 }


//***************************** REMOVES "SEARCHING..." MESSAGE
function removeLoader(){
	$("#loader").remove();
	$("#overlay-update").css("visibility", "hidden");
}


/*
 * Called when submitting the 'More Options' form. The form wil be a pop-up displaying
 * multiple options to refine a property listing search.
 */
function processMoreOptionsSearch(){
	
	//get the mls number from the pop-up iframe.
	var mlsNumber = $("#nyroModalIframe").contents().find("#mlsSearch").val();
	
	//if a mls number was found, perform a mls number search.
	if(mlsNumber.length > 0){
		runTextSearch(mlsNumber);
		
	//no mls number was found.
	}else{	
		$.nyroModalRemove();
		search("update");
	}
}

/*
 * Determine if value is a MLS #
 * 
 * @param string mls_no
 */
function isMLSNumber(mls_no){
	if((mls_no.length == 6 || mls_no.length == 7) && (/[0-9]{6}/.test(mls_no) || /[0-9]{7}/.test(mls_no))){
		return true;
	}else{
		return false;
	}
}
		
	/**
 * Runs a search when a page link is clicked
 */
function changePage(page){
	isTextSearch = true;
	
	//call ajax post for property search to change page.
	$.post(
		"/search-ajax/index.php",
		{
			action: "changePage",
			page: page
		},
		function(result){
			if(result){
				search("basic");
			}
		},
		"json"
	);//end ajax post call.
}


/**
 * Runs a search when a DDL is changed (search page only)
 */
function changeLocation(depth, id, name){		
	
	showLoader();

	isTextSearch = true;
			
	//call ajax post for property search.
	$.post(
		"/search-ajax/index.php",
		{
			action: "changeLocation",
			depth: depth,
			name: name,
			id: id
		},
		function(results){
				search("basic");
		},
		"json"
	);//end ajax post call.
}

function goToLocation(depth,id){
	
	alert(window.location);
	showLoader();

	//call ajax post for property search.
	$.post(
		"/search-ajax/index.php",
		{
			action: "goToLocation",
			depth: depth,
			id: id
		},
		function(e){
		
			////////console.log(e);
			//alert(e);
			//call function to display the search results.
			window.location = "/re/";
		}
	);//end ajax post call.
}

/**
 * Save a single search option from the advanced options on search/ (inc/search_form2.php)
 * Will save bad values (like minPrice > maxPrice) because of bad design.  Definitely fixable though)
 */	
function saveSearchOption(id, value, autoSubmit){

	//determine if price and property type contain valid values prior to searching.
	/*if(validatePrice() && validatePropertyType()){
		//call ajax post for property search.
		$.post(
			"/search-ajax/index.php",
			{
				action: "modifySearchOption",
				id: id,
				value: value
			},
			function(result){

				if(result && autoSubmit){

					search("update");
				}
			},
			"json"
		);			
	}*/
	
	if( autoSubmit ){
		showLoader();
	}
	
	$.post(
			"/search-ajax/index.php",
			{
				action: "modifySearchOption",
				id: id,
				value: value
			},
			function(result){

				if(result && autoSubmit){

					search("update");
				}
			},
			"json"
		);
}

function toggleOptions(){
	var advancedOptions = $("#advanced-options");
	
	if(advancedOptions.is(":visible")){	
		advancedOptions.hide();
		showAdvancedOptions = false;
	}else{
		advancedOptions.show().offset( $("#map").offset() );
		showAdvancedOptions = true;
	}
}

function editSavedSearch(search_id){
	$.post(
		"/search-ajax/index.php",
		{
			action: "editSavedSearch",
			id: search_id
		},
		function(results_html){
			displayMessage();
		},
		"json"
	);//end ajax post call.
}

function runTextSearch(target_value){

	//var target = $(target);
	
	//////console.log("Searching for '"+target.val()+"'");
	
	$.post(
		"search-ajax/index.php",
		{
			action: "runTextSearch",
			input: target_value
		},
		function(results){

			if(results.match == "uniqueMatch"){
				
				//////console.log(results);
				
				goToLocation( results.matches.depth, results.matches.id );		
			
			}else if(results.match == "zip"){
			
				search("basic");
				
			}else if(results.match == "mls"){
				
				isMLSSearch = true;
				search("basic");
				
			}else if(results.match == "mlsArray"){
				
				search("basic");
				
			}else if(results.match == "noMatch"){
			
				alert("No match for this keyword, zip, or MLS#");
				
			}else if(results.match == "multipleMatches"){
			
				//console.log(results);
				
				//variables.
				var main_container = $('<div id="loader" style="overflow: hidden; text-align:left; width:430px;"></div>');
				var island_choices_container = $('<div class="choose" style="text-align:left;"></div>');
				var island_choices = $('<p class="islands" style=" text-align:left;"></p>');
					
				//add heading to island choices container.
				$('<h2 style="text-align:left; margin:0 20px; width:400px;">Which one did you mean?</h2><p>We found multiple matches for your search term.</p>').appendTo(island_choices_container);
			
				//add island choices to its container.
				island_choices.appendTo(island_choices_container);
				
				//Add option to remove loader
				$('<ul style="text-align:left;">').appendTo(island_choices);
				$('<li style="margin-left:10px; width:400px; line-height:24px;"><a style="margin: 0 0 0 10px; color:#CC0000" href="javascript:removeLoader()">Cancel</a></li>').appendTo(island_choices);
			
				//List matches
				for(var x = 0; x < results.matches.length; x++){
					var loc = results.matches[x];
					$('<li style="margin-left:10px; width:350px; line-height:24px;"><a style="margin: 0 0 0 10px;" href="javascript:goToLocation(\''+loc.depth+'\','+loc.id+')">'+loc.fullname+'</a></li>').appendTo(island_choices);
				}

				$('</ul>').appendTo(island_choices);
				
				//add island choices container to the main container.
				island_choices_container.appendTo(main_container);
				
				//set styles for dialog.
				var loader = $("#update-dialog");
				loader.css({
					"left": "35%",
					"top": "200px",
					"width": "30%"
				});
				
				//Display links to correct search results
				$("#overlay-update").css("visibility", "visible");
				//$("#update-dialog").html("<div id='loader' style='overflow:hidden;'><div class='choose'>"+island_choices.html()+"</div></div>");	
				main_container.appendTo(loader);
				
			}


		},
		"json"
	);
}


/**
 * Runs a search when a the map is dragged, moved, or zoomed
 */	
function runMapSearch( mapBounds ){
	
	//////console.log("In runMapSearch.");
	//console.assert( typeof(mapBounds) == "object", "Map bounds could not be found");
	
	$("#input").val("Searching For Properties Within Map");
	
	isTextSearch = true;
	
	sw = mapBounds.getSouthWest();
	ne = mapBounds.getNorthEast();
	s = sw.lat();
	w = sw.lng();
	n = ne.lat();
	e = ne.lng();
	
	showLoader();
		

	//call ajax post for property search.
	$.post(
		"/search-ajax/index.php",
		{
			action: "runMapSearch",
			s: s,
			w: w,
			n: n,
			e: e
		},
		function(results){
		
			//alert(results);
		
			//call function to display the search results.
			search("map");
		},
		"json"
	);//end ajax post call.	
}

/**
 * Order the property search results.
 */
function orderBy(order_by_value){
	$.post(
		"/search-ajax/index.php",
		{
			action: "orderBy",
			column: order_by_value
		},
		function(results){
			search("update");
		},
		"json"
	);
}



	


// ***************************** MAP STUFF - Formerly /js/HL5/map.js


/*
 * Initialize the map. Now called in updateMap() during the first search call
 */
function initializeMap( options ){
	
	//Declare vars out of ajax scope
	var lat;
	var lng;
	
	//var latlng = new google.maps.LatLng(20.585,-157.290);
	
  map = new google.maps.Map(document.getElementById("map"), options);

	//Every time the map has finished updating, we restart the eventListener
	//The addListenerOnce method automatically removes the listener every time it's triggered
	//This prevents infinite loops when moving the map.
  google.maps.event.addListener( map, 'bounds_changed', function() { 
    
    //alert(mapCanBeSearched+" "+mapBeingDragged+" "+searchInProgress);
    
  	//We don't want to trigger map search unless map is being dragged by user
  	if ( isMapIdle && mapCanBeSearched && !mapBeingDragged && !searchInProgress && $("#move_checkbox").attr("checked") ){
  		runMapSearch( map.getBounds() );
  	}
  	
  });		

  google.maps.event.addListener( map, 'dragstart', function(){ 
 		mapBeingDragged = true;
	});

  google.maps.event.addListener( map, 'idle', function(){ 
 		isMapIdle = true;
	});

  google.maps.event.addListener( map, 'dragend', function() { 
 		mapBeingDragged = false;

  	//We don't want to trigger map search unless map is being dragged by user
  	if ( isMapIdle && mapCanBeSearched && !mapBeingDragged && $("#move_checkbox").attr("checked") ){
  		runMapSearch( map.getBounds() );
  	}

	});

}

/*
 * Add markers for a property.
 * 
 * @param string kind
 * @param string mlsNo
 * @param sting propertyId
 * @param string tooltip
 * @param string lat
 * @param string lon
 * @param string address
 * @param int selected
 */
function addMarker(kind, mlsNo, tooltip, lat, lon, address) {
	//variables.
	var marker;
	var customTooltip;

	setIconImage(kind);
	
	//set latitude and longitude
	var myLatLng = new google.maps.LatLng(lat, lon);
	
	//create marker
	marker = new google.maps.Marker({
		position: myLatLng,
		map: map,
		icon: icon_image,
		markerId: mlsNo,
		tooltipHTML: tooltip,
		kind: kind,
		mlsNo: mlsNo
	});
		
	
	//add maker to the marker array.
	markerArray.push(marker);
		
	//add mouse-over event for marker.
	google.maps.event.addListener(marker, 'mouseover', function(event) {
		//display overlay
		showPropertyMapOverlay(marker, tooltip);
		highlightItem(marker.mlsNo);
	});
	
	//add mouse-out event for marker.
	google.maps.event.addListener(marker, 'mouseout', function(evt) {

		lowlightItem(marker.mlsNo);
		
		//remove the custom tooltip.
		$(".markerTooltip").remove();
	});

	//add click event for marker.
	google.maps.event.addListener(marker, 'click', function(evt) {	  
	  window.location = "/mls/"+mlsNo+"/";
	});	
	
}


function showPropertyMapOverlay(marker, tooltip){

		
		//variables.
		/*
		Marker y position relative to document =
		map top value relative to document + ( map height in px *  (	1 - ratio of map between top y and marker y ) )
		Round it to int
	
		Marker x position relative to document =
		map left value relative to document + ( map width in px *  (	1 - ratio of map between left x and marker x ) )
		Round it to int
		*/
	
		var mapBounds = map.getBounds();
		var mapSW = mapBounds.getSouthWest();
		var mapNE = mapBounds.getNorthEast();
		var mapProjection = map.getProjection();
		mapSWPoints = mapProjection.fromLatLngToPoint(mapSW);
		mapNEPoints = mapProjection.fromLatLngToPoint(mapNE);
		
		var mapTopInPixels = $("#map").offset().top;
		var mapHeightInPixels = $("#map").height();
		var mapHeightInPoints = mapSWPoints.y - mapNEPoints.y;
		var mapBottomInPoints = mapSWPoints.y;
	
		var markerPoints = mapProjection.fromLatLngToPoint(marker.getPosition());
		var markerYInPoints = markerPoints.y;
		var ratioY = (mapBottomInPoints - markerPoints.y) / mapHeightInPoints;
		var markerTopInPixels = Math.round( mapTopInPixels + ( mapHeightInPixels * ( 1 - ratioY ) ) );
	
		var mapLeftInPixels = $("#map").offset().left;
		var mapWidthInPixels = $("#map").width();
		var mapWidthInPoints = mapNEPoints.x - mapSWPoints.x;
		var mapRightInPoints = mapNEPoints.x;
		var mapLeftInPoints = mapSWPoints.x;
	
		var markerXInPoints = markerPoints.x;
		var ratioX = (mapRightInPoints - markerPoints.x) / mapWidthInPoints;
		var markerLeftInPixels = Math.round( mapLeftInPixels + ( mapWidthInPixels * ( 1 - ratioX ) ) );
	
		////console.log("marker (x,y): ("+markerLeftInPixels+","+markerTopInPixels+")");
		////console.log("map left x"+mapLeftInPixels);
		////console.log("map top y"+mapTopInPixels);
		////console.log("ratio X"+ratioX);

		var window_height = $(window).height();
		var window_width = $(window).width();
		var marker_x = markerLeftInPixels
		var marker_y = markerTopInPixels
		var tooltip_x = 0;
		var tooltip_y = 0;
		
		//determine if there is enough room for the y position for the tooltip
		//without displaying scroll-bars on the browser window.
		if(window_height - marker_y <= 350){
			tooltip_y = marker_y - 190;
		}else{
			tooltip_y = marker_y - 28;
		}
		
		//determine if there is enough room for the x position for the tooltip
		//without displaying scroll-bars on the browser window.		
		if(window_width - marker_x <= 250){
			tooltip_x = marker_x - 200;
		}else{
			tooltip_x = marker_x + 8;
		}		
			
		//add the custom tooltip.
		customTooltip = $('<div class="markerTooltip"></div>');
		customTooltip.append(tooltip);
		
		//set the tooltip style.
		customTooltip.css({
			'position': 'absolute',
			'left': tooltip_x + 'px',
			'top': tooltip_y + 'px'
		});
			
		//append the custom tooltip to the body tag.
		$("body").append(customTooltip);
	 
}


function highlightItem(mls_no) {


	$("#"+mls_no).css("background","#ddd");
	
	for(var i=0; i< markerArray.length; i++){	
		if(markerArray[i].markerId == mls_no){
	
			showPropertyMapOverlay(markerArray[i], markerArray[i].tooltipHTML);
			//set icon.
			setIconImage(markerArray[i].kind);
			markerArray[i].setIcon(icon_image_rollover);

			
		}
	}	
}

function lowlightItem(mls_no){
	//remove the custom tooltip.
	$(".markerTooltip").remove();
	$("#"+mls_no).css("background","white");


	for(var i=0; i< markerArray.length; i++){	
		if(markerArray[i].markerId == mls_no){

			setIconImage(markerArray[i].kind);
	
			//set icon.
			markerArray[i].setIcon(icon_image);

			
		}
	}	


}


function setIconImage(kind){
	//set icons for the property type.
	//set home icon.
	if (kind == "home" || kind == "res"){
		icon_image = "http://www.hawaiilife.com/img/marker-h.png";
		icon_image_rollover = "http://www.hawaiilife.com/img/marker-h-hot.png";
		
	//set land icon.
	}else if (kind == "land"){
		icon_image = "http://www.hawaiilife.com/img/marker-l.png";
		icon_image_rollover = "http://www.hawaiilife.com/img/marker-l-hot.png";
		
	//set condo icon.
	}else{
		icon_image = "http://www.hawaiilife.com/img/marker-c.png";
		icon_image_rollover = "http://www.hawaiilife.com/img/marker-c-hot.png";
	}

}




/*
 * Remove all markers from the map.
 */
function clearMarkers(){
	//loop over the marker array and remove each individually.
	for(var i=0; i < markerArray.length; i++){
		markerArray[i].setMap(null);
	}
	
	//remove all markers from marker array.
	markerArray.splice(0, markerArray.length);
}


/** 
 * Updates the map type links: hybrid, satellite, or normal/roadmap
  */
function setMapType(type){
	if(type == "HYBRID"){
		map.setMapTypeId(google.maps.MapTypeId.HYBRID);
		$("#type_hybrid").addClass('curr_type');
		$("#type_satellite").removeClass('curr_type');
		$("#type_normal").removeClass('curr_type');
	}else if(type == "SATELLITE"){
		map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
		$("#type_satellite").addClass('curr_type');
		$("#type_normal").removeClass('curr_type');
		$("#type_hybrid").removeClass('curr_type');
	}else{
		map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
		$("#type_satellite").removeClass('curr_type');
		$("#type_hybrid").removeClass('curr_type');
		$("#type_normal").addClass('curr_type');
	}
}

