// General gui functions
var gui = function () {
	return {
		// we pass in the page name to call functions needed for the page.
		init: function (pagename) {
			switch (pagename) {
				case 'index':
					this.home();
				break;
				case 'detail':
					this.profile();
					break;
				case 'guestcard':
					this.guestcard();
					break;
			default:
				break;
			}
		},
		
		home: function () {			
			// Search form
			$('#city, #state').bind('blur', 
			function () {
				if ($(this).val() == '') {
					$(this).prev().addClass('txtError');
				}else{
					$(this).prev().removeClass('txtError');
				}
			});
			// On submit
			$('#search').submit( 
			function () {
				try {
				// trigger validation in case the blur event was never triggered
				$('#city, #state').trigger('blur');
				// check for error classes
				var errors = $('.txtError').get();
				if (errors.length > 0) {
					alert('Necesitamos su ciudad y estado');
					return false;
				}else{
					return true
				}
				}catch (e) { /*alert(e);*/ }
			});
		},
		
		profile: function () {
			// guest card form
			var inputs = ['#nombre','#apellido','#correoelectronico'];
			var labels = new Array();
			$(inputs).each(
				function () {
					// collecting the inputs and labels to use later
					var inputId = this.toString();
					var inputLabel = $(inputId).val();
					labels[inputId] = inputLabel;
					
					$(inputId).bind('click focus', function() {
						var label = labels['#'+this.id];
						if ($(this).val() == label) {
							$(this).val('');
						}
					}).bind('blur', function () {
						var label = labels['#'+this.id];
						if ($(this).val() == '') {
							$(this).val(label);
						}
					});
				}
			);
			
			// delete default values from form when submitted if they exists
			$('#profile-form').submit(function () {
				$(inputs).each(
				function () {
					if ($(this.toString()).val() == labels[this.toString()]) {
						$(this.toString()).val('');
					}
				});
				return true;				
			});
			
			// start up the map
			bingMap.init();
			
			// Map toggle
			if ($('.j-toggleMap')) {
				$('.j-toggleMap').toggle(
				function () {
					$('#mvmap').hide();
					$('#imageMap').show();
					$(this).html('Vea mapa electronico');
				},
				function () {
					$('#mvmap').show();
					$('#imageMap').hide();
					$(this).html('Vea mapa sencilla');
				}
				);
			}
		
		},
		
		guestcard: function () {			
			$("#fecha").datepicker({ minDate:+1 });
			
			$('#guestcard').submit(function () {
				var errors = new Array();
				var required = ['#email_address','#first_name','#last_name'];
				
				for (x in required) {
					if ($(required[x]).val() == '') {
						$(required[x]).parent().addClass('txtError');
						errors.push(required[x]);
					}
				}
				
				if (errors.length > 0) {
					return false;
				}
				
				return true;
			});
		}
	}
}();

/**
 * Bing Map
 */
var bingMap = function () {
	
	return {
		
		/* Holds the instance of the map */
		map: null,
		
		/* Map Div ID */
		mapId: "mvmap",
		
		/* Holds a reference to the points on the map */
		points: new Array(),
		
		layers: new Array(),
	
		/* Initialize Function */
		init: function (mapId) {
			if (mapId) {
				this.mapId = mapId.toString();
			}
			
			if (this.mapId != "") {
				this.load();
				
				// Deletes the map on document unload
				$(document).unload(function() { bingMap.dispose(); });
				
				this.getData();
			}
		},
		
		/* Load Map Function */
		load: function () {
			
			if (this.mapId && this.map == null && document.getElementById(this.mapId)) {
				this.map = new VEMap(this.mapId.toString());
				this.map.LoadMap();
			}
			
		},
		
		/* Get the map data from the hidden div that holds the json string of data */
		getData: function () {
			
			var results = new Array();
			
			$('.j-mapdata').each(function () {				
				if ($(this).text() != "") {
					results.push(jQuery.parseJSON($(this).text()));
				}
			});
			
			if (results.length > 0) {
				this.loadResults(results);
			}		
		},
		
		/* Loads the results to the map */
		loadResults: function (results) {	        
		
			try {
	        
				for (var index in results) {
		        	if (results[index].latitude != "0" && results[index].longitude != "0") {
		        		var point = new VELatLong(results[index].latitude, results[index].longitude);
			        	this.points.push(point);
		        	
		        	}else if (results[index].address != "" && results[index].city != "" && results[index].state != "" && results[index].zip != "") {
		        		var address = results[index].address;
		        		address += ', ' + results[index].city + ', ' + results[index].state + ', ' + results[index].zip;
		        		this.map.Find(null, address, null, null, 0, 10, true, false, false, true, bingMap.loadAddressPoint);
		        	}
		        }			
		        
		        this.map.SetMapView(this.points);
		        
		        var layer = new VEShapeLayer();
		        for (var index in results) {
		        	if (this.points[index] && results[index].latitude != "0" && results[index].longitude != "0") {
			        	var shape = new VEShape(VEShapeType.Pushpin, this.points[index]);		        	
			        	var icon = this.getIcon(results[index].matchType);
			        	
			        	shape.SetCustomIcon(icon);
			        	shape.SetDescription(this.getMarker(results[index]));
			        	layer.AddShape(shape);	   
		        	}	        	
		        }
		        
		        this.map.ClearInfoBoxStyles();
				this.map.AddShapeLayer(layer);
				
				this.layers['points'] = layer;
			
			}catch (e) {
				//alert(e.message);
			}

		},
		
		loadAddressPoint: function (layer, resultsArray, places, hasMore, veErrorMessage) {
			try {
			$(places).each(function () {
				var pin = new VEShape(VEShapeType.Pushpin, this.LatLong);
				pin.SetTitle(this.Name);
				pin.SetDescription(this.Description);
				pin.SetCustomIcon(bingMap.getIcon('house'));								
				bingMap.map.AddShape(pin);
			});
			}catch (e) { /*alert(e.message);*/ }
		},
		
		/* Creates a marker icon on the map */
		getMarker: function (data) {
			
			var marker = "";
			
			switch (data.page) {
			case 'search':
				marker += '<div id="propMapResult1-hcard" class="infoBoxContainer vcard">';
				marker += '<a class="mapResultImage" onmousedown="javascript:write_event(\'Profile_Page_View_Search_Map_Hover\',' + data.siteId + ',\'site\');" href="' + data.profileLink + '" target="_self" title="' + data.title + '">';
				marker += '<img class="photo" src="' + data.imageSrc + '" width="60" height="52" alt="' + data.title + '" title="' + data.title + '" />';
				marker += '</a>';
				marker += '<h3 class="mapResultName fn org"><a onmousedown="javascript:write_event(\'Profile_Page_View_Search_Map_Hover\',' + data.siteId + ',\'site\');" href="' + data.profileLink + '" target="_self" title="' + data.title + '" style="text-decoration: none;">' + data.title + '</a></h3>';
				marker += '<a class="closeMapInfoBox" onclick="bingMap.map.HideInfoBox();" title="Close Property Information Box">Close Property Information Box</a>';
				marker += '<ul class="mapResultInfo adr">';
				marker += '<li class="street-address">' + data.address + '</li><li><strong class="locality">' + data.city + '</strong>,&nbsp;<abbr class="region" title="' + data.state + ', USA">' + data.state + '</abbr>&nbsp;<strong class="postal-code">' + data.zip + '</strong></li><li class="note"><a onmousedown="javascript:write_event(\'Profile_Page_View_Search_Map_Hover\',' + data.siteId + ',\'site\');" href="' + data.profileLink + '" target="_self" title="' + data.floorplan + '">' + data.floorplan + '</a></li>';
				marker += '</ul>';
				marker += '<ul class="geo"><li><abbr class="latitude" title="' + data.latitude + '">' + data.latitude + '</abbr>&nbsp;<abbr class="longitude" title="' + data.longitude + '">' + data.longitude + '</abbr></li></ul>';
				marker += '</div>';
				break;
			case 'compare':
				marker += '<div id="propMapResult1-hcard" class="infoBoxContainer vcard">';
				marker += '<a class="mapResultImage" href="' + data.profileLink + '" target="_self" title="' + data.title + '">';
				marker += '<img class="photo" src="' + data.imageSrc + '" width="60" height="52" alt="' + data.title + '" title="' + data.title + '" />';
				marker += '</a>';
				marker += '<h3 class="mapResultName fn org"><a href="' + data.profileLink + '" target="_self" title="' + data.title + '" style="text-decoration: none;">' + data.title + '</a></h3>';
				marker += '<a class="closeMapInfoBox" onclick="bingMap.map.HideInfoBox();" title="Close Property Information Box">Close Property Information Box</a>';
				marker += '<ul class="mapResultInfo adr">';
				marker += '<li class="street-address">' + data.address + '</li><li><strong class="locality">' + data.city + '</strong>,&nbsp;<abbr class="region" title="' + data.state + ', USA">' + data.state + '</abbr>&nbsp;<strong class="postal-code">' + data.zip + '</strong></li><li class="note"><a href="' + data.profileLink + '" target="_self" title="' + data.floorplan + '">' + data.floorplan + '</a></li>';
				marker += '</ul>';
				marker += '<ul class="geo"><li><abbr class="latitude" title="' + data.latitude + '">' + data.latitude + '</abbr>&nbsp;<abbr class="longitude" title="' + data.longitude + '">' + data.longitude + '</abbr></li></ul>';
				marker += '</div>';
				break;
			case 'profile':
				break;
			}
			
			return marker;
			
		},
		
		getIcon: function (type) {
			
			switch (type) {
			case 'exact':
				return '<img src="http://images.forrent.com/sites/frc/design/redstar.gif" alt="Exact Property Search Match - ForRent.com" title="Exact Property Search Match - ForRent.com" width="18" height="18" />';
				break;
			case 'close':
				return '<img src="http://images.forrent.com/sites/frc/design/bluestar.gif" alt="Close Property Search Match - ForRent.com" title="Close Property Search Match - ForRent.com" width="18" height="18" />';
				break;
			case 'house':
				return 'http://images.forrent.com/imgs/fr/siteFiles/design/mc/mark.png'
				break;
			}
			
		},
		
		/* Displays places of interest on the map */
		showPlaceOfInterest: function (placeOfInterest) {
			
			// Holds the text sent to bing maps and the image icon
			var pois = {
					entertainment:["entertainment", "entertainment.gif"],
					fitnesscenter:["fitness center", "fitnesscenter.gif"], 
					food:["food","fooddrink.gif"],
					grocery:["grocery","grocerystore.gif"],
					pets:["pets","pet.gif"],
					schools:["schools","shool.gif"],
					shopping:["shopping","shopping.gif"],
					transportation:["public transporation","transportation.gif"]
			};
			
			if (pois[placeOfInterest]) {
				
				if (!this.layers[placeOfInterest]) {
				
					this.layers[placeOfInterest] = new VEShapeLayer();
					this.map.AddShapeLayer(this.layers[placeOfInterest]);

					for (ptIndex in this.points) {
					
						this.map.Find(pois[placeOfInterest][0], this.points[ptIndex], null,
							this.layers[placeOfInterest], 0, 9, false, false, true, false,
		                    function (layer, resultsArray, places, hasMore, veErrorMessage) {
								
								$(resultsArray).each(function(){
									var pin = new VEShape(VEShapeType.Pushpin, this.LatLong);
									pin.SetTitle(this.Name);
									pin.SetDescription(this.Description);
									pin.SetCustomIcon( 'http://images.forrent.com/sites/frc/design/mapIcons/'+pois[placeOfInterest][1] );								
									layer.AddShape(pin);
								});
							}
						);
						
					}
					
					var clusterOptions =  new VEClusteringOptions();
					clusterOptions.Callback = function (clusters) {
						for (var i=0; i < clusters.length; ++i)
						{
							var cluster = clusters[i];
							var clusterShape = cluster.GetClusterShape();
							clusterShape.SetTitle(pois[placeOfInterest][0].toUpperCase());
							clusterShape.SetDescription(cluster.Shapes.length + " " + pois[placeOfInterest][0].toUpperCase() + " places near location.<br />Zoom in for more details.");
						}
					};
	
					var customIcon = new VECustomIconSpecification();
					customIcon.Image = 'http://images.forrent.com/sites/frc/design/mapIcons/'+pois[placeOfInterest][1];					
					clusterOptions.Icon = customIcon;
	
					this.layers[placeOfInterest].SetClusteringConfiguration(VEClusteringType.Grid, clusterOptions);
					
				}else if (!this.layers[placeOfInterest].IsVisible()) {
					this.layers[placeOfInterest].Show();
				}else{
					this.layers[placeOfInterest].Hide();
				}
			}
		},
		
		scrollMap: function (mapContainer, topAlignElem, defaultTopPos) {
			
			if (!mapContainer) {
				var mapContainer = '#loading';
			}
			
			if (!topAlignElem) {
				var topAlignElem = null;
			}
			
			if (!defaultTopPos) {
				var defaultTopPos = 10;
			}
			
			// if you want to see where the elements are un-comment this and below
			//$('body').append('<div id="test" style="position:fixed;top:0;left:0px;"></div>');
			
			var scrolled = {
				canvas: null,
				top: 0,
				bottom: 600,
				jump: function(top) {
					scrolled.canvas.animate(
						{'top': top + 'px'},
						{'duration': 600, 'queue': false, 'easing': 'swing'}
						);
				}
			};
			
			scrolled.canvas = $(mapContainer);
			scrolled.bottom = $(scrolled.canvas).prev().innerHeight() - scrolled.canvas.outerHeight();
			
			$(window).scroll(function() {
				var top = $(document).scrollTop();
				var newTop = defaultTopPos;
				
				scrolled.top = Math.round($(scrolled.canvas).prev().parent().offset().top);
				var diff = Math.round(top - scrolled.top);
				
				//$('#test').html('diff: ' + diff + '<br />bottom: ' + scrolled.bottom + '<br />map top: ' + scrolled.top + '<br />win top: ' + top);
				
				if (top > scrolled.top) {
					if (diff <= scrolled.bottom && diff > 0) {
						newTop = diff;
					
					} else if (diff > scrolled.bottom && diff > 0) {
						newTop = scrolled.bottom;
					}
				}
				
				scrolled.jump(newTop);
			});
		},
		
		/* Deletes the map instance */
		dispose: function () {
			if (this.map) {
				this.map.dispose();
			}
		}
	
	}
}();
