var supportsFixedPosition = function () {
	var container = document.body;
	if (document.createElement && container && container.appendChild && container.removeChild) {
	  var el = document.createElement('div');
	  if (!el.getBoundingClientRect) return null;
	  el.innerHTML = 'x';
	  el.style.cssText = 'position:fixed;top:100px;';
	  container.appendChild(el);
	  var originalHeight = container.style.height,
	      originalScrollTop = container.scrollTop;
	  container.style.height = '3000px';
	  container.scrollTop = 500;
	  var elementTop = el.getBoundingClientRect().top;
	  container.style.height = originalHeight;
	  var isSupported = !!(elementTop === 100);
	  container.removeChild(el);
	  container.scrollTop = originalScrollTop;
	  return isSupported;
	}
	else {
	  return false;
	}
}

var creds = (typeof sbBingApiKey == "undefined")? "AqcaAPmJVVSfVa0KQdMw-6S0uV-mKIOR3gO2o9hlW0E0pcSyoEQwhxL7BiTorDeE" : sbBingApiKey;

var mapOptions = {
	credentials: creds,
	mapTypeId: Microsoft.Maps.MapTypeId.road
};

var mapLocs = [];

var dealerGroup = false;
var dealerGroupBackLabel = (typeof sbBackLabel != "undefined")? sbBackLabel : "Back";
var dealerGroupSelectLabel = (typeof sbSelectDealerLabel != "undefined")? sbSelectDealerLabel : "Select dealer";
var dealerGroupTitleStr = (typeof dealerGroupTitle != "undefined")? dealerGroupTitle : "Group Dealers";


$(function(){
	// Is this a dealer group page?
	if (typeof isDealerGroupPage != "undefined"){
		if (isDealerGroupPage == true) {
			$('.dealer').hide().find('.address-details').append('<a href="#" class="back">&lt; '+dealerGroupBackLabel+'</a>');
			$('.dealer:first').before('<h1 class="dealer-group-title">'+dealerGroupTitleStr+'</h1><p class="dealer-group-subhead">'+dealerGroupSelectLabel+'</p>');
			dealerGroup = true;
		}
	}
	

	$('#map-holder-block').each(function(){
		// First, lets create a Bing Maps object for the page
		var map = new Microsoft.Maps.Map(document.getElementById('map-holder-block'), mapOptions);
	
	
		var p = 0;
		$('.coordinates').each(function(){
	
			var t = String.fromCharCode(65+p);
	
			// Get the location information for each result from the html
			var lat = $(this).find('li.lat').html();
			var lng = $(this).find('li.lng').html();
	
			// Get the rest of the info for the pin info
			var pinTitle = ($(this).parent().find('#dealerName').length < 1)? $(this).parent().find('h3 span:eq(0)').html() : $(this).find('#dealerName').text();
			var pinAddress = ($(this).parent().find('#address').length < 1)? $(this).parent().find('address').html() : $(this).find('#address').text();
	
			// Use that data to set up a location object
			var loc = new Microsoft.Maps.Location(lat, lng);
			mapLocs.push(loc);
	
			// Add a pin to the map
	        var pin = new Microsoft.Maps.Pushpin(loc, {icon: "/c/images/dealer-locator-pin-small.png", text: t, zIndex: 10-p}); 
	        
	        // Create the info box for the pin
	        var pinInfoBox = new Microsoft.Maps.Infobox(loc, {title: pinTitle, description: pinAddress, zIndex: 20, visible: false});
	
	        // Add a handler for the pushpin click event.
	        if (dealerGroup == true) {
				var dealer = $(this).parents('.dealer');
				Microsoft.Maps.Events.addHandler(pin, 'click', displayDealer);
			} else {
				Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox);
			}
	
	
	        // Hide the info box when the map is moved.
	        Microsoft.Maps.Events.addHandler(map, 'dblclick', hideInfobox);
	
	        // Hide the info box when the close button is clicked
	        $('.Infobox .infobox-close').live('click', function(e){
		        console.log('close')
	        	e.preventDefault();
	        	e.stopPropagation();
	        	hideInfobox(e);
	        	return false;
	        });
	
	        map.entities.push(pin);
	        map.entities.push(pinInfoBox);
	
	        $(this).parent().find('h3').click(function(e){
				e.preventDefault();
				e.stopPropagation();
				displayInfobox(e);
				return false;
			});
	
	
	
	        function displayInfobox(e) {
	        	Microsoft.Maps.Events.invoke(map, 'dblclick');
	        	var point = new Microsoft.Maps.Point(-50, 50);
	        	map.setView({center: loc, centerOffset: point});
	        	pinInfoBox.setOptions({ visible:true });
	        }
	
	        function hideInfobox(e) { 
	        	pinInfoBox.setOptions({ visible: false });
	        	return false;
	        }
	
	        function displayDealer(e) {
		        $('.dealer-group-title, .dealer-group-subhead').hide();
	        	$(dealer).show();
	        	
	        	var pins = [];
	
	        	var entitiesLength = map.entities.getLength();
	        	for (var i = 0, max = entitiesLength; i < max; i++) {
	        		if (map.entities.get(i).getVisible() == true) {
	        			pins.push(map.entities.get(i));
	        			map.entities.get(i).setOptions({visible : false});
	        		}
	        	}
	        	pin.setOptions({visible : true});
	        	map.setView({center: pin.getLocation(), zoom: 13});
	
	        	$(dealer).find('.back').click(function(){
	        		$('.dealer').hide();
	        		$('.dealer-group-title, .dealer-group-subhead').show();
	        		for (var q = 0, max = pins.length; q < max; q++) {
	        			pins[q].setOptions({visible : true});
	        		}
	        		var mapBounds = Microsoft.Maps.LocationRect.fromLocations(mapLocs);
					map.setView({bounds: mapBounds, padding: 100});
	        		return false;
	        	});
	        	
	        }
	
	        p = p+1;
		});
	
		if(mapLocs.length > 1){
			var mapBounds = Microsoft.Maps.LocationRect.fromLocations(mapLocs);
			map.setView({bounds: mapBounds, padding: 100});
		} else {
			map.setView({center: mapLocs[0], zoom: 13});
		}
		
	
		var resultsLength = $('.coordinates').length;
		for (var r = 0, max = resultsLength; r < max; r++) {
		
			var thisResult = $('.coordinates').eq(r).parent();
			var rl = resultsLength;
	
			$(thisResult).each(function(){
				var rc = r;
				var currentDealer = (rl - rc);
				var targetPin = map.entities.get(map.entities.getLength()-(currentDealer*2));
	
				$(this).mouseenter(function(){
	        		targetPin.setOptions({
	        			width: 35,
	        			height: 55,
	        			icon: "/c/images/dealer-locator-pin-large.png",
	        			textOffset: new Microsoft.Maps.Point(0,10),
	        			zIndex: 10
	        		});
				});
				$(this).mouseleave(function(){
	        		targetPin.setOptions({
	        			width: 25,
	        			height: 39,
	        			icon: "/c/images/dealer-locator-pin-small.png",
	        			textOffset: new Microsoft.Maps.Point(0,5),
	        			zIndex: 10-rc
	        		});
				});
				
			});
		}
	
		if($('#TB_wrapper-container').length < 10) {
			var mapContainer = $('div#dealer-search-results-block div.map-block');
			var bottomPagination = $('div#dealer-search-results-block').next('div.pagination');
			var bottom = (bottomPagination.position().top + bottomPagination.height()) - mapContainer.height();
			var top = mapContainer.offset().top - parseFloat(mapContainer.css('margin-top').replace(/auto/, 0));
	
			var win = $(window);
			var elem = $('div.map-block');
	
			var supported = supportsFixedPosition();
	
			$(win).scroll(function (event) {
				var y = $(this).scrollTop();
			  	var offset = $(elem).parent().offset();
				var yT = (y - offset.top) + 10;
	
				if ( supported == true ) {
					if (y >= top && y <= bottom) {
			    		$('div.map-block').addClass('fixed');
			  		} else {
			    		var mapTop = (y > bottom) ? bottom - mapContainer.parent().position().top : 0;
			    		$('div.map-block').removeClass('fixed');
			    		mapContainer.css({ top: mapTop });
			  		}
				} else {
					
				    //console.log(bottom + ',' + y);
				    if (y >= top && y <= bottom) {
				    	$(elem).css('top', yT + "px");
				    } else {
				    	var mapTop = (y > bottom) ? bottom - mapContainer.parent().position().top : 0;
				    	mapContainer.css({ top: mapTop });
				    }
				}
			});
		}
	});
	
	$('fieldset.dealer-search').each(function(){
		$(this).find('input, select').change(function(){
			$('#lat, #lon').val('');
		});
	});
	
	$('fieldset.filter').each(function(){
		$(this).find('select').change(function(){
			$(this).parents('form').submit();
		});
	});

/*
	// Add the autocomplete trigger for wildcard searches
	$("#nm").autocomplete({
		appendTo: '#content-body div.dealer-search-block',
		
		source: dealers,
		minLength: 3	//require a minumium of 3 characters before doing auto complete.
	});
*/
});
