google.load("search", "1");



var DOMUtilities = {
	targetBlank: function(locality){
		// XHTML 1.0 Strict work around for external links
		$(locality+' a[rel*="external"]').attr("target","_blank");
	},
	inputAutoClear: function(locality){
		$(locality+' input.clearField').focus(function(){
			if(this.defaultValue == this.value){
				this.value='';
				$(this).addClass('entered');
			}
		}).blur(function(){
			if(this.value == ''){
				this.value = this.defaultValue;
				$(this).removeClass('entered');
			}
		});
	},
	imgRollover: function(locality){
		// Image roll-over setup
		$(locality+' img.rollOver, '+locality+' input[type="image"].rollOver')
			.mouseenter(function(){
				if (this.src.indexOf("_i.") != -1) {
					this.src = this.src.replace("_i.", "_o.");
				}
			}).mouseleave(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.");
				}
			}).filter("input").mousedown(function(){
				this.src = this.src.replace("_o.","_a.");
			}).mouseup(function(){
				this.src = this.src.replace("_a.","_i.");
			});
	},
	initialize: function(locality){
		if(locality == null) {
			locality = "body";
		}
		this.targetBlank(locality);
		this.inputAutoClear(locality);
		this.imgRollover(locality);
	}
};



var MapControl = {
	options: {
		zoom: 8,
		minZoom: 1,
		maxZoom: 16,
		disableDefaultUI: true
	},
	mapVisible: false,
	current: '',
    amenities: [],
    order: '',
	markers: [],
	infos: [],
	searchResults: [],
	
	switchActions: function(action){
        $('#map_actions').removeClass('closed');
		$('#map_actions .resultsAction').hide();
		$('#map_' + action).show();
		
		$('#map_actions .nav').attr('class','nav');
		$('#map_actions .nav').addClass(action);
	},
	
	switchHeader: function(){
		if(this.mapVisible === false){
			$('#map_welcome').fadeOut(500);
			$('#map_interaction').fadeIn(500);
		} else {
			$('#map_welcome').fadeIn(500);
			$('#map_interaction').fadeOut(500);
		}
		this.mapVisible = !this.mapVisible;
	},
	
	updateZoom: function(){
		var currentZoom = this.map.getZoom();
		
		$('#map_control_zoom ul li').each(function(ind, el){
			if(8 - Math.round(currentZoom/2) <= ind){
				$(el).addClass('zoom');
			} else {
				$(el).removeClass('zoom');
			}
		});
	},
	
	setupZoomControl: function(){
		$('#map_control_zoom a').click(function(event){
			event.preventDefault();
			var currentZoom = MapControl.map.getZoom(),
				direction = this.href.split('#')[1];
			
			if(direction == "in"){
				MapControl.map.setZoom(Math.min(MapControl.options.maxZoom, currentZoom + 1));
			} else {
				MapControl.map.setZoom(Math.max(MapControl.options.minZoom, currentZoom - 1));
			}
		});
		
		$('#map_control_zoom ul li').click(function(event){
			event.preventDefault();
			var zoomLevel = 8 - $('#map_control_zoom ul li').index(this) + 1;
			MapControl.map.setZoom(zoomLevel * 2);
		});
		
		google.maps.event.addListener(this.map, 'zoom_changed', function(){
			MapControl.updateZoom();
		});
        
        MapControl.map.controls[google.maps.ControlPosition.TOP_LEFT].push(document.getElementById('map_control_zoom'));
        MapControl.map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(document.getElementById('choose_area_blocker'));

		this.updateZoom();
	},
	
	setupSearchControl: function(){
		$('#map_search .link_clear').click(function(event){
			event.preventDefault();
			$('#map_search_results_container, #map_search').slideUp(500);
			
			MapControl.clearMarkers();
			MapControl.dirRenderer.setMap(null);
			MapControl.clearSearchResults();
			MapControl.showLocation(MapControl.current);
			$('#glocal_search_query').val("");
		});
		
		google.maps.event.addListener(MapControl.infoWindow, 'closeclick', function(){
			MapControl.unselectSearchMarkers();
		});
		this.search.setSearchCompleteCallback(null, this.updateSearchResults);

		$('#map_search form.resultsForm').submit(function(event){
			event.preventDefault();
			MapControl.search.execute($('#glocal_search_query').val());
		});
		
		$('#map_canvas .gmnoprint a.gs-directions').live('click', function(event){
			event.preventDefault();
			var hrefPieces = this.href.split("&");
			for(var p in hrefPieces){
				var keyVal = hrefPieces[p].split("=");
				if(keyVal[0] == "daddr"){
					MapControl.switchActions('directions');
					
					var daddr = unescape(keyVal[1]).replace(/\+/g," ");
						daddr = daddr.substring(0,daddr.indexOf(" @"));
					$('#directions_finish').val(daddr);
					$('#directions_start').focus();
				}
			}
		});
        
        MapControl.map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('map_actions'));
        //MapControl.map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(document.getElementById('choose_area'));
	},
	
	clearSearchResults: function(){
		MapControl.searchwell.innerHTML = "";
		for (var i = 0; i < MapControl.searchResults.length; i++) {
			MapControl.searchResults[i].marker().setMap(null);
		}
	},
	
	unselectSearchMarkers: function(){
		for(var i = 0; i < MapControl.searchResults.length; i++) {
    		MapControl.searchResults[i].unselect();
  		}
	},
	
	updateSearchResults: function(){
		if(!MapControl.search.results) return;

		// Clear the map and the old search well
		MapControl.clearSearchResults();
		
		this.searchResults = [];
		for (var i = 0; i < MapControl.search.results.length; i++) {
			MapControl.searchResults.push(new LocalResult(MapControl.search.results[i]));
			MapControl.bounds.extend(new google.maps.LatLng(parseFloat(MapControl.search.results[i].lat), parseFloat(MapControl.search.results[i].lng)));
		}
		
		var attribution = MapControl.search.getAttribution();
		if (attribution) {
			MapControl.searchwell.appendChild(attribution);
		}

		MapControl.map.fitBounds(MapControl.bounds);
		
		$('#map_search_results_container').slideDown(500,function(){
			MapControl.searchScroller.resize();
		});
	},
	
	updateMarkers: function(locations, region){
		// Clear markers by removing references and reseting array
		MapControl.clearMarkers();
		
		for(var i=0; i<locations.length; i++){
			var last = (i == locations.length - 1 ? true : false);
			MapControl.addMarker(locations[i], region, i, last);
			MapControl.addSearchResults(locations[i],region,i);
		}
	},
	
	clearMarkers: function(){
		if(this.markers.length > 0){
			for(var i=0; i<this.markers.length; i++){
				this.markers[i].setMap(null);
			}
			this.infoWindow.close();

			this.bounds = new google.maps.LatLngBounds();
			this.markers = [];
		}
	},
	
	infoMarkup: function(loc,region){
		var template = '<div class="result" style="width:240px;height:140px;overflow:hidden;">';
            template+= '<div class="img-container"><div class="img-inner"><img src="/img/hotels/thumbnails/' + loc.name_url + '.jpg" alt="" height="50" /></div></div>';
            template+= '<a href="/#{url}" class="title">#{title}</a><div class="meta">#{address}</div><div class="actions"><a href="#directions" class="directions">Get Directions To Here</a>';
            //template+= '<a href="javascript:void(null);" onclick="jQuery.scrollTo(\'#hotel_listing_' + loc.name_url + '\',{duration:1000,easing:\'swing\',offset:{left:0,top:-20}});">View Hotel Summary</a>';
            //template+= '<form action="/reservations/submit" method="post" target="_blank">' + $('#hotel_listing_' + loc.name_url + ' .meta form.book-now-form').clone()[0].innerHTML + '</form>';
            template+= '</div></div>';
		
		var locParams = {
			url: ["hotels",region.name_url,loc.name_url].join("/") ,
			title: loc.name,
            thumb_url: loc.thumbnail_url,
			address: '<span class="address_street">' + loc.address_street + '</span><br /><span class="city_state">' + loc.city + ", " + loc.state + "</span><br />" + loc.phone
		};
		
		var locStr = template;
		for(var k in locParams){
			var regKey = new RegExp('\#\{' + k + '\}', 'g');
			locStr = locStr.replace(regKey, locParams[k]);
		}
		
		return locStr;
	},
	
	addMarker: function(loc,region,i,last){
		if(typeof(last) == 'undefined'){
			last = false;
		}

		var latLng = new google.maps.LatLng(loc.lat, loc.lng);
		
		if(i == 0){
			MapControl.search.setCenterPoint(latLng);
		}
		
		MapControl.bounds.extend(latLng);
		
		var theMarker = new google.maps.Marker({
			position: latLng,
			title: loc.name,
			map: MapControl.map,
			icon: new google.maps.MarkerImage(
				"/img/hotels/home.dt/bright_blue_map_marker.png",
				new google.maps.Size(33,39),
				new google.maps.Point(0,0),
				new google.maps.Point(17,38)
			),
			shadow: new google.maps.MarkerImage(
				"/img/hotels/home.dt/bright_blue_map_marker_shadow.png",
				new google.maps.Size(57,34),
				new google.maps.Point(0,0),
				new google.maps.Point(20,26)
			)
		});
		MapControl.markers.push(theMarker);
		
		var region = region;
		var loc = loc;
		
		google.maps.event.addListener(theMarker, 'click', function(){
            $('#map_actions').addClass('closed').find('.nav').removeClass('search directions');

			MapControl.infoWindow.setContent(MapControl.infoMarkup(loc,region));
			MapControl.infoWindow.open(MapControl.map, theMarker);
		});
//        $('a.loc_' + loc.name_url).click(function(event){
//            event.preventDefault();
//            
//            $('#map_actions').addClass('closed').find('.nav').removeClass('search directions');
//
//			MapControl.infoWindow.setContent(MapControl.infoMarkup(loc,region));
//			MapControl.infoWindow.open(MapControl.map, theMarker);
//            //MapControl.map.setCenter(latLng);
//        });
        
		if(last === true){
            
            var lat = MapControl.bounds.getNorthEast().lat();
            var lng = MapControl.bounds.getNorthEast().lng();
            
            var lngE = MapControl.bounds.getNorthEast().lng();
            var lngW = MapControl.bounds.getSouthWest().lng();
            var lngN = MapControl.bounds.getNorthEast().lat();
            var lngS = MapControl.bounds.getSouthWest().lat();
            
            var hDiff = Math.abs(lngE - lngW);
            var vDiff = Math.abs(lngN - lngS);
            
            var point = '';
            if(hDiff == 0){
                point = new google.maps.LatLng(lat,( lng + 0.05 ), true);
            }else{
                if( MapControl.current == 'all' ){
                    point = new google.maps.LatLng(lat + 0.13,( lng + ( Math.max(hDiff, vDiff) /1.5 ) ), true);
                }else{
                    // multiply by three because we want it to fit (roughly) in the left third of the view.
                    point = new google.maps.LatLng(lat + (vDiff/2),( lng + ( Math.max(hDiff, vDiff ) * 3 ) ), true);
                }
                
            }
            
            MapControl.bounds.extend( point );
            if( typeof(MapControl.map) != 'undefined' ){
                MapControl.map.fitBounds(MapControl.bounds);
            }
		}
	},
	
	setupDirectionsControl: function(){
		$('#map_directions .resultsForm a.btn_flip').click(function(event){
			event.preventDefault();
			var start = $('#directions_start').val();
			var finish = $('#directions_finish').val();
			$('#directions_start').val(finish);
			$('#directions_finish').val(start);
		});
		
		$('#map_directions .resultsForm').submit(function(event){
			event.preventDefault();
			
			var start = $('#directions_start').val();
			var finish = $('#directions_finish').val();
			
			MapControl.dirService.route({
				origin: start,
				destination: finish,
				travelMode: google.maps.DirectionsTravelMode.DRIVING,
				unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL
			}, MapControl.showDirections);
		});
		
		$('#map_directions .link_clear').click(function(event){
			event.preventDefault();
			$('#map_directions_results_container').slideUp(500);
			
            $('#map_actions').addClass('closed').find('.nav').removeClass('search directions');

			MapControl.dirRenderer.setMap(null);
			MapControl.clearSearchResults();
			MapControl.showLocation(MapControl.current);
			$('#directions_start').val("");
			$('#directions_finish').val("");
		});
	},
	
	showDirections: function(dirResult, dirStatus){
		if(dirStatus == google.maps.DirectionsStatus.OK){
			$('#map_directions_results_container').slideDown(500, function(){
                MapControl.directionsScroller.resize();
            });
			MapControl.dirRenderer.setMap(MapControl.map);
			MapControl.dirRenderer.setPanel(MapControl.dirContainer);
			MapControl.dirRenderer.setDirections(dirResult);
		}
	},
	
	setupChooser: function(){
        // Sidebar region chooser and region chooser on California map
		$('.chooseArea .topLevel>li>a, #map_welcome a.location').click(function(event){
            if (this.href.split("#").length > 1) {
                event.preventDefault();
                
                var loc = this.href.split("#")[1];
                $('.chooseArea .topLevel>li').removeClass('active');
                if(loc != "affiliate"){
            		$('#main .chooseArea .subLevel').not($('#nav_' + loc + ' .subLevel')).slideUp(500);
                    MapControl.mapVisible = false;
                    MapControl.showLocation(loc);
                }
            }
		});
	},
	
	showLocation: function(loc){
		if(this.mapVisible === false){
			this.switchHeader();
		}
		
        this.current = loc;
		$('#sort_by_price').val("");
        
        $('#sort_by_price').val("");
        $('.filterForm .typeFilter a.btn').removeClass('active');

		var locStr = loc == "all" ? 'All Hotels' : this.locations[loc];
        
		$.ajax({
			url: "/hotels/results.json",
			type: 'post',
			dataType: 'json',
			data: "data[region_slug]=" + loc,
			complete: function(request, status){
				var requestJSON = jQuery.parseJSON(request.responseText);

				// Clear markers by removing references and reseting array
				MapControl.clearMarkers();
                
                var totalLocs = 0;
                for(var r in requestJSON){
    				var locations = requestJSON[r].locations;
    				var region = requestJSON[r].region;
                    
    				for(var i=0; i<locations.length; i++){
    					var last = (i == locations.length - 1 ? true : false);
    					MapControl.addMarker(locations[i], region, i, last);
                        totalLocs++;
    				}
                    
                    if(totalLocs == 1){
                        MapControl.map.setZoom(13);
                    }
                }

                $('.resultsBar h2.georgia').html("Results for " + locStr + " (" + totalLocs + ")");
    			
				// Clear search results in map
				$('#map_search_results_container').slideUp(500, function(){
					$($(this).children()[0]).html("");
				});
        
                MapControl.updateListings("data[region_slug]=" + loc);
			}
		});
	},
	
	updateListings: function(data){
        $.ajax({
            url: "/hotels/listings",
            data: data,
            type: "post",
            beforeSend: function(){
                $('#listings_results').append('<div id="listings_results_mask"></div>');
                $('#listings_results_mask').css({
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: $('#listings_results').width(),
                    height: $('#listings_results').height(),
                    opacity: '0.5',
                    background: "url(/img/hotels/home.dt/loading_large.gif) center 150px no-repeat #fff"
                });
            },
            complete: function(request){
                if( document.location.hash != '#/map' ){
                    $('div.resultsBar, #listings_results').show();
                }
                $('#listings_results').html(request.responseText);
                Compare.reset();
            }
        });
	},
	
	initialize: function(){
		this.mapContainer = document.getElementById('map_canvas');
		this.dirContainer = document.getElementById('map_directions_results');
		this.searchwell = document.getElementById('map_search_results');
	
		this.dirService = new google.maps.DirectionsService();
		this.dirRenderer = new google.maps.DirectionsRenderer();
        this.geocoder = new google.maps.Geocoder();
		this.bounds = new google.maps.LatLngBounds();
		this.search = new google.search.LocalSearch();
        
		this.options.mapTypeId = google.maps.MapTypeId.ROADMAP;
        
		this.infoWindow = new google.maps.InfoWindow({ maxWidth: 240 });
		
		this.options.center = this.geocoder.geocode({
			address: "San Francisco, CA"
		}, function(results, status){
			if(status == google.maps.GeocoderStatus.OK){
				MapControl.options.center = new google.maps.LatLng(results[0].geometry.location.b, results[0].geometry.location.c);

				MapControl.map = new google.maps.Map(MapControl.mapContainer, MapControl.options);
		        
                // "Show Map" corner link to display map
				$('#map_welcome a.btnShowMap').click(function(event){
					event.preventDefault();
					MapControl.switchHeader();
				});
				
                // Search/Directions tabs in map view
				$('#map_actions .nav a').click(function(event){
					event.preventDefault();
					MapControl.switchActions(this.href.split("#")[1]);
				});
				
				MapControl.setupZoomControl();
				MapControl.setupDirectionsControl();
				MapControl.setupChooser();
				MapControl.setupSearchControl();
				
				$('#map_directions_results_container').hide();
                
                MapControl.directionsScroller = $('#map_directions_results_container').scrollbar({scrollspeed:50,arrows:true,arrowPosition:'bottom'});
                MapControl.searchScroller = $('#map_search_results_container').scrollbar({scrollspeed:50,arrows:true,arrowPosition:'bottom'});
			}
		});
        
        this.overlay = new google.maps.OverlayView();
        this.overlay.setMap(this.map);
        
        // "Get Directions" links in info boxes when clicking on a location in the map
		$('.result .actions a.directions').live('click', function(event){
			event.preventDefault();
			
			var loc = {
				address: $(this).parents('.result').find('.address_street').html(),
				city_state: $(this).parents('.result').find('.city_state').html()
			};
			
			MapControl.switchActions('directions');
			$('#directions_finish').val(loc.address + " " + loc.city_state);
			$('#directions_start').focus();
		});
        
        // Price sort drop-down
        $('#sort_by_price').change(function(){
            $('.filterForm .typeFilter a.btn').removeClass('active');
            
            MapControl.order = "Hotel.price_point " + this.value;
			MapControl.updateListings("data[region_slug]=" + MapControl.current + "&data[order]=" + MapControl.order + "&data[amenities]=" + MapControl.amenities);
        });
        
        // Hip, Classic, Luxury filter buttons in result listings
        $('.filterForm .typeFilter a.btn').click(function(event){
            event.preventDefault();
            
            $('#sort_by_price').val("");
            $('.filterForm .typeFilter a.btn').removeClass('active');
            $(this).addClass('active');
            
            MapControl.order = "Hotel.rating_" + this.href.split("#")[1] + " DESC";
            MapControl.updateListings("data[region_slug]=" + MapControl.current + "&data[order]=" + MapControl.order + "&data[amenities]=" + MapControl.amenities);
        });
        
        // Region chooser on detail view
        $('.detail_regions a').click(function(event){
            event.preventDefault();
            var loc = this.href.split("#")[1];
            MapControl.current = loc;
            
            $('.detail_regions a, .typeFilter a').removeClass("active");
            $(this).addClass("active");
            
            //MapControl.updateListings("data[region_slug]=" + loc);
            MapControl.updateListings("data[region_slug]=" + MapControl.current + "&data[order]=" + MapControl.order + "&data[amenities]=" + MapControl.amenities);

        });
        
	}
};


// A class representing a single Local Search result returned by the
// Google AJAX Search API.
function LocalResult(result){
	var me = this;
	
	this.node = function(){
		if (this.resultNode_) 
			return this.resultNode_;
		return this.html();
	};
	
	// Returns the GMap marker for this result, creating it with the given
	// icon if it has not already been created.
	this.marker = function(){
		var me = this;
		if (me.marker_) 
			return me.marker_;
		var marker = me.marker_ = new google.maps.Marker({
			position: new google.maps.LatLng(parseFloat(me.result_.lat), parseFloat(me.result_.lng)),
			map: MapControl.map
		});
		google.maps.event.addListener(marker, "click", function(){
			me.select();
		});
		return marker;
	};
	
	// Unselect any selected markers and then highlight this result and
	// display the info window on it.
	this.select = function(){
		MapControl.unselectSearchMarkers();
		this.selected_ = true;
		MapControl.infoWindow.setContent(this.html(true));
		MapControl.infoWindow.open(MapControl.map, this.marker());
		MapControl.map.setCenter(new google.maps.LatLng(parseFloat(this.result_.lat), parseFloat(this.result_.lng)))
	};
	
	// Remove any highlighting on this result.
	this.unselect = function(){
		this.selected_ = false;
	};
	
	// Returns the HTML we display for a result before it has been "saved"
	this.html = function(){
		var me = this;
		var container = document.createElement("div");
		container.className = "unselected";
		container.appendChild(me.result_.html.cloneNode(true));
		return container;
	}

	me.result_ = result;
	me.resultNode_ = me.node();
	me.marker_ = me.marker();
	google.maps.event.addDomListener(me.resultNode_, 'mouseover', function(){
		me.select();
	});
	google.maps.event.addDomListener(me.resultNode_, 'mouseout', function(){
		me.unselect();
	});
	MapControl.searchwell.appendChild(me.resultNode_);
};



var Compare = {
	limit: 3,
	locations: [],
	checkboxElements: '.compare input[type="checkbox"]',
	submitElements: '.compareLink',
	
	add: function(location_id){
		if (this.locations.length < this.limit) {
			var exists = false;
			
			for (var i in this.locations) {
				if (location_id == i) {
					exists = true;
				}
			}
			
			if (exists === false) {
				this.locations.push(location_id);
			}
		}
		this.update();
	},
	
	remove: function(location_id){
		var index = -1;
		for (i=0; i<this.locations.length; i++) {
			if(location_id == this.locations[i]){
				index = i;
			}
		}
		
		if(index != -1){
			this.locations.splice(index,1);
		}
		
		this.update();
	},
	
	reset: function(){
		this.locations = [];
	},
	
	update: function(){
		if(this.locations.length >= this.limit){
			$(this.checkboxElements).not(':checked').attr('disabled',true);
		} else {
			$(this.checkboxElements).attr('disabled',false);
		}
		
		if(this.locations.length > 1){
			$(this.submitElements).removeClass('disabled');
		} else {
			$(this.submitElements).addClass('disabled');
		}
	},
	
	initialize: function(){
		$(this.checkboxElements).live('click', function(){
			if(this.checked == true){
				Compare.add(this.value);
			} else {
				Compare.remove(this.value);
			}
		});
		
		$(this.submitElements).live('click', function(event){
			event.preventDefault();
			
			if (Compare.locations.length > 1 && !$(this).hasClass('disabled')) {
				$.ajax({
					url: '/hotels/compare',
					type: 'post',
					data: 'data[locations]=' + Compare.locations.join(","),
					success: function(request){
						$.fancybox(request, {
							padding: 0,
							margin: 0,
							autoScale: false,
							autoDimensions: true,
							scrolling: 'no',
							overlayOpacity: 0.7,
							overlayColor: '#000',
							titleShow: false,
							showNavArrows: false,
							onComplete: function(){
								DOMUtilities.initialize('#fancybox-inner');
							}
						});
					}
				});
            }
		});
		
		this.update();
	}
};

function viewModeSwitcher( mode ){
    switch( mode ){
        case 'map':
            $('#main').show();
            $('#chooser_hotel_list').show();
            $('.bookNow.container').show();
            
            $('#body .resultsBar').hide();
            $('#body #listings_results').hide();
            $('#detail_regions_wrapper').hide();
            
            $('#choose_area a').removeClass("active");
            $('#choose_area a[href$="all"]').addClass("active");
            MapControl.mapVisible = true;
            MapControl.switchHeader();
            
            $('body').attr('id','map_view');
        break;
        case 'list':
            $('#main').hide();
            $('#chooser_hotel_list').hide();
            $('.bookNow.container').hide();
            
            $('#body .resultsBar').show();
            $('#body #listings_results').show();
            $('#detail_regions_wrapper').show();
            
            $('body').attr('id','list_view');
        break;
        case 'detail':
            $('#main').hide();
            $('#chooser_hotel_list').hide();
            $('.bookNow.container').hide();
            
            $('#body .resultsBar').show();
            $('#body #listings_results').show();
            $('#detail_regions_wrapper').show();
            
            $('body').attr('id','detail_view');
        break;
    }
    Cufon.replace('.cufon', { autoDetect: true, hover: true });
}


$(document).ready(function(){
	DOMUtilities.initialize();
	Compare.initialize();
    
    if( $('#chooser_hotel_list').length ){
        $('.hotels_list-region.affiliated ul').append('<li><a href="http://www.hoteltheodore.com/" target="_blank">Hotel Theodore</a></li>');
    }
    
    if( $('#amenities_list').length ){
        $('#amenities_list ul input:checked').removeAttr('checked');
        // Amenities Click
        $('#amenities_list #amenities_link').bind('click', function(event){
            event.preventDefault();
            
            $('#amenities_list ul').show();
            $('#amenities_list').addClass('active');
        });
        
        // Amenities Leave
        $('#amenities_list').bind('mouseleave', function(event){
            $('#amenities_list ul').hide();
            $(this).removeClass('active');
        });
        
        $('#amenities_list ul input').bind('click', function(event){
            if (document.amenitiesTimer) clearTimeout(document.amenitiesTimer);
            document.amenitiesTimer = setTimeout(function(){
                amenities = [];
                $('#amenities_list ul input:checked').each(function(){
                    amenities.push(this.id.split('_')[1]);
                });
                
                MapControl.amenities = amenities;
                //console.log(amenities);
                MapControl.updateListings("data[region_slug]=" + MapControl.current + "&data[order]=" + MapControl.order + "&data[amenities]=" + MapControl.amenities );
                
            },1000);
            return true;
        });
    }
    
    if( $('#map_welcome a.location').length ){
        var tooltip = $('#location_tooltip');
        $('#map_welcome a.location, #choose_area .topLevel a').bind({
            mouseenter: function(event){
                // this way both hover locations use the same set of target elements.
                var elem = $("#map_welcome a[href$='"+ this.href.split('#')[1] +"']")[0];
                
                // no tooltip for "Viw All Hotels"
                if(!elem){
                    return false;
                }
                
                tooltip.find(".name").html($(elem).find('.name').text());
                tooltip.find(".number").html($(elem).find('.number').text());
                tooltip.css({
                    left: parseInt($(elem).css('left')) + 25 + "px",
                    top: parseInt($(elem).css('top')) + -25 + "px",
                    position: 'absolute'
                });
                tooltip.show();
            },
            mouseleave: function(event){
                tooltip.hide();
            },
            click: function(){
                var elems = $("#choose_area a[href$='"+ this.href.split('#')[1] +"'], .detail_regions a[href$='"+ this.href.split('#')[1] +"']");
                $('#choose_area .topLevel a, .detail_regions a').removeClass("active");
                elems.addClass("active");
            }
        });
        
        var locations = $('#map_welcome a.location');
        var map_div = $('#map_welcome');
        for (var i=0 ; i < locations.length ; i++) {
            var left = parseInt($(locations[i]).css('left')) + 4;
            var top = parseInt($(locations[i]).css('top')) + 8;
            map_div.append('<div class="shadow" style="position: absolute; left:'+left+'px; top:'+top+'px;"></div>');
        };        
    }
    
    
    MapControl.mapVisible = true;
    MapControl.showLocation('all');
    
    if($('#mode_chooser').length){
        $('#mode_chooser a').bind('click', function(event){
            event.preventDefault();
            $(this).parents('ul').find('li').removeClass('active');
            $(this).parents('li').addClass('active');
            var mode = this.href.split('#/')[1];
            document.location.hash = '#/' + mode;
            viewModeSwitcher( mode );
        });
    }
    
    if( !document.location.hash.match(/#\/map/) ){
        document.location.hash = '#/map';
    }else{
        //$('a[href="' + document.location.hash.match(/#\/map|#\/detail|#\/list/)[0] + '"]').trigger('click')
    }
    $('body').attr('id','map_view');
    
    $('.bookForm .bookInputsDate input[type="text"]').datepicker({
        onSelect: function(dateText, inst){
            $('#data_stay_month').val(inst.currentYear + "_" + (inst.currentMonth + 1));
            $('#data_stay_day').val(inst.currentDay);
        }
    });
});
$(window).load(function(){
	MapControl.initialize();
});
