/**
 * JS Code for the Community Pages
 */

var commMap;

var loadedNearby = false;
var commMarker;
var commMarkers = [];
var ytPlayer = false;
var gdir = false;
var commBalloonTemplate = $('<div class="tiny-pop-up" style="display:block;"><div class="top"></div><div class="mid"><b class="commName"></b><p class="commAddress"></p><a href="#" title="Currently Viewing this apartment">(Currently Viewing)</a></div><div class="btm"></div></div>').get(0);

var otherCommBalloonTemplate = '<div class="tiny-pop-up" style="display:block;"><div class="top"></div><div class="mid"><b class="commName"></b><p class="commAddress"></p><a  class="comm_link@href" href="#" title="View this {prop_type}\'s page!">View this {prop_type}\'s page!</a></div><div class="btm"></div></div>';

function initMap(div, directionsMode) {
	var marker;
	if (GBrowserIsCompatible()) {
		curMap = new GMap2(document.getElementById(div));
		
		// set controls
		curMap.setUIToDefault();
		curMap.disableScrollWheelZoom();
		curMap.disableDoubleClickZoom();
		
		// Initialize Icon
		var houseIcon = new GIcon(G_DEFAULT_ICON);
		houseIcon.image = "/images/icon-apt-green.png";
		houseIcon.shadow = "/images/icon-apt-shdw.png";
		houseIcon.iconSize = new GSize(24,30);
		houseIcon.shadowSize = new GSize(40,30);
		houseIcon.iconAnchor = new GPoint(12,30);
		
		var markerOptions = {
			icon : houseIcon,
			title : commInfo['name']
		};	
		
		var point = new GLatLng(parseFloat(commInfo['lat']), parseFloat(commInfo['lng']));
		if (directionsMode)
			marker = new GMarker(point, markerOptions);
		else commMarker = new GMarker(point, markerOptions);
		
		GEvent.addListener((directionsMode) ? marker : commMarker, "click", showBalloon=function(e) {
			var data = {
				commAddress: commInfo['address'],
				commName: (commInfo['commtype'] == 'apartment') ? commInfo['name'] : ''
			}
			var html = pure.autoRender(commBalloonTemplate, data);
			var div = $(html).get(0);
			// prevent clicks on the balloon from closing it
			if (e) {
			$(div).mousedown(function(e) {
				if (window.event)
				window.event.cancelBubble = true;
				else e.stopPropagation();
				return false;
			});
			}
			$("div.tiny-pop-up").remove();
			curMap.getPane(G_MAP_FLOAT_PANE).appendChild(div);
			
			positionBalloon(directionsMode ? marker : commMarker, div, true);
		});
		
		curMap.setCenter(point, 14);
		curMap.addOverlay((directionsMode) ? marker : commMarker);
		
		commMap = curMap;
		showBalloon(null);
		
		GEvent.addListener(curMap, "click", function(marker, point) {
			if (!marker && loadedNearby) {
				$("div.tiny-pop-up").remove();
			}
		});
		
		GEvent.addListener(curMap, "zoomend", function(marker, point) {
			$("div.tiny-pop-up").remove();
		});
		
		return curMap;
	}
}

$(document).ready(function() {
	
	if ($("#community-map-div").length)
		commMap = initMap("community-map-div", false);
	
	$("#show_nearby").click(function() {
		$("div.tiny-pop-up").remove();
		if (!loadedNearby) {
			
			blueHouseIcon = new GIcon(G_DEFAULT_ICON);
			blueHouseIcon.image = "/images/icon-apt-blue.png";
			blueHouseIcon.shadow = "/images/icon-apt-shdw.png";
			blueHouseIcon.iconSize = new GSize(24,30);
			blueHouseIcon.shadowSize = new GSize(40,30);
			blueHouseIcon.iconAnchor = new GPoint(12,30);
			
			var bounds = new GLatLngBounds();
			var isApartment = (commInfo['commtype'] == 'apartment') ? true : false;
			
			var comm_link = (commInfo['commtype'] == 'home') ? '/homes/rentals/' : '/apartments/community/';
			
			$.each(commInfo['nearby'], function(i) {
				var markerOptions = {
					icon : blueHouseIcon,
					title: commInfo['nearby'][i]['name']
				};
				var point = new GLatLng(parseFloat(commInfo['nearby'][i]['lat']), parseFloat(commInfo['nearby'][i]['lng']));
				var marker = (new GMarker(point, markerOptions));
				GEvent.addListener(marker, "click", function(e) {
					var data = {
						commAddress: commInfo['nearby'][i]['address'],
						commName: isApartment ? commInfo['nearby'][i]['name'] : '',
						comm_link: comm_link + commInfo['nearby'][i]['id'] + '.html'
					}
					
					var propType = (isApartment) ? 'apartment' : 'home';
					var finalTemplate = otherCommBalloonTemplate.replace(/{prop_type}/g, propType);
					
					var html = pure.autoRender($(finalTemplate).get(0), data);
					var div = $(html).get(0);
					// prevent clicks on the balloon from closing it
					$(div).mousedown(function(e) {
						if (window.event)
						window.event.cancelBubble = true;
						else e.stopPropagation();
						return false;
					});
					$("div.tiny-pop-up").remove();
					commMap.getPane(G_MAP_FLOAT_PANE).appendChild(div);
					
					positionBalloon(marker, div);
				});
				GEvent.trigger(marker, 'click');
				commMarkers.push(marker);
				bounds.extend(point);
				commMap.addOverlay(marker);	
			});
			
			bounds.extend(commMarker.getLatLng());
			
			var zoom = commMap.getBoundsZoomLevel(bounds);
			commMap.setCenter(bounds.getCenter(), zoom - 1);
			
			loadedNearby = true;
			var display_text = (commInfo['commtype'] == 'home') ? 'Home' : 'Community';
			$(this).text('Zoom to Current ' + display_text);
		}
		// zoom to current community
		else {
			
			for (var i in commMarkers) {
				commMap.removeOverlay(commMarkers[i]);	
			}
			commMarkers = [];
			
			var point = new GLatLng(parseFloat(commInfo['lat']), parseFloat(commInfo['lng']));
		
			commMap.setCenter(point, 14);
			var display_text = (commInfo['commtype'] == 'home') ? 'Homes' : 'Communities';
			$(this).text('Show Nearby ' + display_text);
			loadedNearby = false;
		}
		
		return false;
	});
	
	$("#show_directions").click(function() {
		$.get('/html/map_directions.php', {comm_id: commInfo['commid'], comm_type: commInfo['commtype']}, function(data) {
		
			var docWidth = $(document).width();
			var popupLeft = (docWidth - 820)/2;
		
			var pre = '<div id="directions_container" style="display:block;position:absolute;top:100px;left:' + popupLeft + 'px;z-index:1001;" class="pop-up big-module hd-viewer"> <div class="top"></div><div class="mid"><div class="mid-inside"><div class="mid-inside-container"><div class="close-button" id="close_directions"><a href="#"></a></div>';
			var post = '</div></div> <!-- mid-inside --></div> <!-- mid --><div class="btm"></div></div>';
				
			$(document).find('body').append('<div id="backgroundPopup"></div>').append(pre + '<iframe width="720" height="470" src="/html/map_directions.php?comm_id=' + commInfo['commid'] + '&comm_type=' + commInfo['commtype'] + '"></iframe>' + post);
		
			$("#backgroundPopup").css('height', $(document).height() + 'px').show().animate({opacity: "0.7"}, 1000).click(function() {
				disablePopup('directions_container');
				$("#directions_container").remove();
			});
			$("#close_directions").click(function() {	
				disablePopup('directions_container');
				$("#directions_container").remove();
			});
			var dirMap = initMap("directions_map", true);
			
		});
		return false;
	});
	
	//Availability of Floorplan/Unit Listing - Open/Close of unit list
    $('li.unit-container .expander').click(function(){
		var parent = $(this).parent();
		if ((children = parent.children('ul.specific-units')).length != 0) {
			if(parent.hasClass("closed")) {
				parent.removeClass('closed').addClass('open');
				children.fadeIn();
			} else {   
				parent.removeClass('open').addClass('closed');
				children.hide();
			}
		}
		return false;
    });
	
	
	
	$("li.unit-container").click(function() {
		var expander = $(this).find(".expander");
		if (expander.length) {
			// if there are units, expand this
			expander.click();
		} else {
			// there are no units, go to floor plan page
			var target = $(this).find("div.view-button a").attr('href');
			window.location = target;
		}
	});
	
    
//Unit <li> clicks, View links still working, all else do not close
    $("li.unit").click(function(e){
		var tgt = e.target;
		if($(tgt).parent("div").attr("class") == "unit-view forward-arrow"){
			window.location = $(tgt).attr("href");
		}
		$("li.unit").removeClass('showing');
		$(this).addClass('showing');
		return false;
	});
		
	$("div.view-button a").click(function(){
		window.location = $(this).attr("href");
	});

});

function setDirections(fromAddress, toAddress, locale) {
  gdir.load("from: " + fromAddress + " to: " + toAddress,
            { "locale": locale });
}

function onGDirectionsLoad(){
    // Use this function to access information about the latest load()
    // results.

    // e.g.
    // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
  // and yada yada yada...
}

function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		directionsAlert("That address could not be found.");
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		directionsAlert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		directionsAlert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
   
   //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
   //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	  
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		directionsAlert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
   
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		directionsAlert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	 
	else directionsAlert("An unknown error occurred.");
}

function directionsAlert(message) {
	$("#directions_dialog").html(message).dialog({modal: true, show: 'slide'});	
}

function positionBalloon(marker, balloon) {
	var balloonWidth = 166;
	var xOffset = 80;
	var yOffset = 0;
	
	var balloonHeight = $(balloon).height();
	
	var anchorX = marker.getIcon().iconAnchor.x;
	var anchorY = marker.getIcon().iconAnchor.y - marker.getIcon().infoWindowAnchor.y;
	var point = marker.getPoint();
	var screenPoint = commMap.fromLatLngToDivPixel(point);
	var balloonAnchor = new GPoint(screenPoint.x, screenPoint.y);
	var balloonCenterPix = new GPoint(balloonAnchor.x + balloon.offsetWidth/2 - xOffset, balloonAnchor.y - balloon.offsetHeight/2 - yOffset);
	var balloonCenter = commMap.fromDivPixelToLatLng(balloonCenterPix);
	
	balloon.style.left = screenPoint.x + anchorX - (balloonWidth/2) - 10 + 'px';
	balloon.style.top = screenPoint.y - anchorY - balloonHeight + 'px';
	
	commMap.panTo(balloonCenter);
}

/* youtube functions */

function onYouTubePlayerReady(playerId) {
	ytPlayer = document.getElementById("myytplayer");
}

