var map;
var zoom;

var currentHiddenButtonId;

// for a map centred on a users postcode
function initNearest() 
{	
	    setUpMap();
	    plotNearest();	
    }

function plotNearest()
{
	showListings(); 
	var dealerPositions = getDealerPositions();
	if (dealerPositions.length > 0)
	{
		addZoomController();
		
		var userPosition = getUserPosition();
		if (userPosition == null)
		{
			userPosition = dealerPositons[0];
		}
			    
	    var bbox = getBBoxToFitAroundCenter(userPosition, dealerPositions);
	    var level = zoom.getZoomLevelToFitBoundingBox(bbox);
	    level = checkZoomLevel(level);
	    
		zoom.setZoomValue(level);

	    map.centerOnPosition(userPosition, function()
	    	{
				map.removeAllPins();
	    		addUserLocationPin();
	    		addDealerPins();
	    	});
	}
}

// for a map with multiple car supermarkets (centred on the centre position of the car supermarkets)
function initCarSupermarkets()
{	
		setUpMap();
		plotCarSupermarkets();
	}

function plotCarSupermarkets()
{
	showListings();
	var dealerPositions = getDealerPositions();	
	
	if (dealerPositions.length == 1)
	{
		plotCarSupermarket(getMinimumZoomLevel());
	}
	else if (dealerPositions.length > 0)
	{
		addZoomController();
		var level = zoom.getZoomLevelToFitPositions(dealerPositions);
		level = checkZoomLevel(level);
		zoom.setZoomValue(level);
		
  		var bbox = Utilities.positionsToBoundingBox(dealerPositions);
  		var centre = bbox.getCenterPosition();;		
		map.centerOnPosition(centre, function()
			{
				map.removeAllPins();
				addDealerPins();
			});
	}
}

function checkZoomLevel(level)
{
	if (level < getMinimumZoomLevel())
	{
		level = getMinimumZoomLevel();
	}
	return level;
}

// for a map with a single car supermarket
function initCarSupermarket()
{
		setUpMap();
		plotCarSupermarket(getAToZZoomLevel());
	}

function plotCarSupermarket(zoomLevel)
{	
	if (zoomLevel == null)
	{
		zoomLevel = getAToZZoomLevel();
	}
	showListings(); 
	var dealerPositions = getDealerPositions();	
	if (dealerPositions.length > 0)
	{
		addZoomController();
		zoom.setZoomValue(zoomLevel);
			
		map.centerOnPosition(dealerPositions[0], function()
			{
				map.removeAllPins();
				addDealerPin();
			});
	}	
}

// initial set up of the map
function setUpMap()
{
    map = new Map(document.getElementById("map"));
    map.authenticate(CONFIG.clientName, CONFIG.clientPassword);
    map.addCopyrightMessage(
        "Map data &#169; Tele Atlas, <a href=\"http://www.decarta.com/legal/TA_TOU.html\" target=\"_blank\">Terms of Use</a>");
    
    map.setConfiguration("uk-style-tile");
    map.setDragEnabled(false);
    map.setDoubleClickRecenteringEnabled(false);
    
	bubblePreLoader();
}

function addZoomController()
{    
    zoom = new ZoomController(null, null, "../img/zoomChecked.png", "../img/zoom.png", "../img/zoomTop.png", "../img/zoomBottom.png");     
    map.addZoomController(zoom);
    zoom.hide();
}

// returns an array of positions of all dealers (enhanced and standard) found in the generated data javascript
function getDealerPositions()
{
	var standardCarSupermarkets = getStandardCarSupermarkets();
	var enhancedCarSupermarkets = getEnhancedCarSupermarkets();
	var positions = new Array(enhancedCarSupermarkets.length + standardCarSupermarkets.length);
	
	for (var i=0; i<enhancedCarSupermarkets.length; i++)
	{
		var enhancedPos = new Position(enhancedCarSupermarkets[i].latitude, enhancedCarSupermarkets[i].longitude);
		positions[i] = enhancedPos;
	}
	for (var j=0; j<standardCarSupermarkets.length; j++)
	{
		var standardPos = new Position(standardCarSupermarkets[j].latitude, standardCarSupermarkets[j].longitude);
		positions[enhancedCarSupermarkets.length + j] = standardPos;
	}
	
	return positions;
}

// adds a single dealer pin (if more than one dealer in data.js will add the first enhanced dealer, or if no enhanced dealers, the first standard)
function addDealerPin()
{
	var enhancedCarSupermarkets = getEnhancedCarSupermarkets();	
	var standardCarSupermarkets = getStandardCarSupermarkets();	
	
	if (enhancedCarSupermarkets.length > 0)
	{	
		var enhancedMessage = getEnhancedMessage(enhancedCarSupermarkets[0]);
		plotPin(enhancedCarSupermarkets[0], getEnhancedIcon(null), enhancedMessage);
	}
	else if (standardCarSupermarkets.length > 0)
	{
		plotPin(standardCarSupermarkets[0], getStandardIcon(null), standardCarSupermarkets[0].companyName);
	}
}

function addDealerPins()
{
	var enhancedCarSupermarkets = getEnhancedCarSupermarkets();		
	for (var i=0; i<enhancedCarSupermarkets.length; i++)
	{
		var enhancedText = getTextOverlay(enhancedCarSupermarkets[i].dealerId, true);	
		var enhancedMessage = getEnhancedMessage(enhancedCarSupermarkets[i]);		
		plotPin(enhancedCarSupermarkets[i], getEnhancedIcon(enhancedText), enhancedMessage);
	}
	
	var standardCarSupermarkets = getStandardCarSupermarkets();	
	for (var j=0; j<standardCarSupermarkets.length; j++)
	{
		var standardText = getTextOverlay(standardCarSupermarkets[j].dealerId, false);	
		plotPin(standardCarSupermarkets[j], getStandardIcon(standardText), standardCarSupermarkets[j].companyName);
	}	
}

// creates a pin from the parameters given and plots it on the map
function plotPin(carSupermarket, icon, message)
{
	var pos = new Position(carSupermarket.latitude, carSupermarket.longitude);	
	var pin = new Pin(pos, message, null, icon);	
	pin.setId(carSupermarket.dealerId.toString());

	map.addPin(pin);
	EventRegistry.addListener(pin, "click", pinClicked);
	EventRegistry.addListener(pin, "mouseover", pinMouseOver);
	EventRegistry.addListener(pin, "mouseout", pinMouseOut);
}

// plots a pin on the map to represent the user positon
function addUserLocationPin()
{
	var userPosition = getUserPosition();
	if (userPosition != null)
	{
		var userPin = new Pin(userPosition, getUserPostcode(), null, getUserLocationIcon());
		map.addPin(userPin);
		EventRegistry.addListener(userPin, "mouseover", pinMouseOver);
		EventRegistry.addListener(userPin, "mouseout", pinMouseOut);
	}
}

function addMarkerPin(carSupermarket)
{
	map.removeAllPins();	
	var enhancedMessage = getEnhancedMessage(carSupermarket);
	plotPin(carSupermarket, getMarkerIcon(), enhancedMessage);
}

function getEnhancedIcon(textOverlay)
{
	var x = 26;
	var y = 27;
	var xOffset = (x / 2);
	var yOffset = y;
	return new Icon(getEnhancedPinImage(), xOffset, yOffset, x, y, textOverlay);
}
function getStandardIcon(textOverlay)
{
	var x = 20;
	var y = 22;
	var xOffset = (x / 2);
	var yOffset = (y / 2);
	return new Icon(getStandardPinImage(), xOffset, yOffset, x, y, textOverlay);
}
function getUserLocationIcon()
{
	var x = 18;
	var y = 18;
	var xOffset = (x / 2);
	var yOffset = (y / 2);
	return new Icon(getUserPinImage(), xOffset, yOffset, x, y);
}
function getMarkerIcon()
{
	var x = 20;
	var y = 34;
	var xOffset = (x / 2);
	var yOffset = y;
	return new Icon(getMarkerPinImage(), xOffset, yOffset, x, y);
}

function getTextOverlay(dealerId, enhanced)
{
	try
	{
		var order = (document.getElementById("count" + dealerId)).innerHTML
		var xOffset = 0;
		var yOffset = 0;
		if (order < 10)
		{
			if (enhanced) 
			{
				xOffset = 9;
				yOffset = 5;
			}
			else 
			{
				xOffset = 8;
				yOffset = 6;
			}
		}
		else
		{		
			if (enhanced)
			{
				xOffset = 3;
				yOffset = 5;
			}
			else
			{
				xOffset = 4;
				yOffset = 6;
			}
		}
		return new TextOverlay(order, xOffset, yOffset, "#000000", "8pt", "Arial");
	}
	catch (err) 
	{
		return null;
	}	
}

// returns a string containing the html for the popup to display on mouseover
function getEnhancedMessage(carSupermarket)
{
	var enhancedMessage = "<b>" + carSupermarket.companyName + "</b><br>";
	if (carSupermarket.miniMainLogo != "")
	{
		enhancedMessage += "<img height='40px' src='" 
			+ carSupermarket.miniMainLogo + "'/>";
	}
	return enhancedMessage;
}

// Info Window
function bubblePreLoader()
{     
     topRightBubble = new Image(getBubbleWidth(), getBubbleHeight());
     topRightBubble.src="../img/topRightBubble.gif";
     
     topLeftBubble = new Image(getBubbleWidth(), getBubbleHeight());
     topLeftBubble.src="../img/topLeftBubble.gif";
     
     bottomRightBubble = new Image(getBubbleWidth(), getBubbleHeight());
     bottomRightBubble.src="../img/bottomRightBubble.gif";
     
     bottomLeftBubble = new Image(getBubbleWidth(), getBubbleHeight());
     bottomLeftBubble.src="../img/bottomLeftBubble.gif";
}

function addInfoWindow(bubbleImage, xOffset, yOffset, imgYOffset)
{	
	var writableBubbleHeight = (getBubbleHeight() / 100 ) * 80;
	// create DIV
	var myInfoBubble = document.createElement("DIV");
	myInfoBubble.style.width=getBubbleWidth().toString() + "px";
	myInfoBubble.style.height=writableBubbleHeight.toString() + "px";
	
	// create IMG as background of the DIV
	var img = document.createElement("img");
	img.src=bubbleImage.src;
	
	// absolutely position in the DIV
	img.style.position="absolute";
	img.style.top=imgYOffset + "px";
	img.style.left="0px";

	img.height=getBubbleHeight();
	img.width=getBubbleWidth();
	img.style.zIndex=1;
	
	// add to DIV
	myInfoBubble.appendChild(img);
	myInfoBubble.style.position="absolute";
	myInfoBubble.style.zIndex=201;
	myInfoBubble.style.display="none";

	// create Objects and add to Map
	var closeButton = new Icon("../img/x.gif",1,1,1,1);
	var infoWindow = new InfoWindow(myInfoBubble,xOffset,yOffset,closeButton);
	map.addCustomInfoWindow(infoWindow);
	centerTextOnInfoWindow();
}

function centerTextOnInfoWindow()
{
	try
	{
		var bubbleContent = document.getElementById('bubbleContent');
		var paddingSize = 16;
		var width = getBubbleWidth() - (paddingSize * 2);
		bubbleContent.style.width = width.toString() + "px";
		bubbleContent.style.textAlign = "center";
	}
	catch (err) { }
}

function addTopRightInfoWindow(pinHeight)
{
	bubbleXOffset = getRightBubbleXOffset();
	bubbleYOffset = getBubbleHeight();
	imgYOffset = 0;
	addInfoWindow(topRightBubble, bubbleXOffset, bubbleYOffset, imgYOffset);
}
function addTopLeftInfoWindow(pinHeight)
{
	bubbleXOffset = getLeftBubbleXOffset();
	bubbleYOffset = getBubbleHeight();
	imgYOffset = 0;
	addInfoWindow(topLeftBubble, bubbleXOffset, bubbleYOffset, imgYOffset);
}
function addBottomRightInfoWindow(pinHeight)
{
	bubbleXOffset = getRightBubbleXOffset();
	bubbleYOffset = getBottomBubbleImgYOffset() + (pinHeight * -1);
	addInfoWindow(bottomRightBubble, bubbleXOffset, bubbleYOffset, getBottomBubbleImgYOffset());
}
function addBottomLeftInfoWindow(pinHeight)
{
	bubbleXOffset = getLeftBubbleXOffset();
	bubbleYOffset = getBottomBubbleImgYOffset() + (pinHeight * -1);
	addInfoWindow(bottomLeftBubble, bubbleXOffset, bubbleYOffset, getBottomBubbleImgYOffset());
}

function getRightBubbleXOffset()
{
	return (getBubbleWidth() / 100) * 6;
}
function getLeftBubbleXOffset()
{
	return (getBubbleWidth() / 100) * 86;
}
function getBottomBubbleImgYOffset()
{
	return ((getBubbleHeight() / 100 ) * 20) * -1;
}

function pinMouseOver(pin)
{
	try
	{
		var map = document.getElementById('map');
		var mapWidth = map.clientWidth;
		var mapHeight = map.clientHeight;
		
		var pinLeft = pin.pinTxt.offsetLeft;
		var pinTop = pin.pinTxt.offsetTop;
		var pinHeight = pin.pinImg.height
		
		if (pinLeft < (mapWidth / 2))
		{
			if (pinTop < (mapHeight / 2)) // pos is in top left of map
			{
				addBottomRightInfoWindow(pinHeight);
			}
			else // pos is in bottom left of map
			{
				addTopRightInfoWindow(pinHeight);
			}
		}
		else
		{
			if (pinTop < (mapHeight / 2)) // pos is in top right of map
			{
				addBottomLeftInfoWindow(pinHeight);
			}
			else // pos is in bottom right of map
			{
				addTopLeftInfoWindow(pinHeight);
			}
		}
	}
	catch (err) 
	{
		addTopRightInfoWindow();
	}
	pin.showInfoWindow();
}

function pinMouseOut(pin)
{
	pin.hideInfoWindow();
}

// pin clicked
function pinClicked(pos)
{
	window.location.href="#did" + pos.id;
}

// zoom in
function zoomIn(dealerId)
{
	hideListings(dealerId);
	
	var cs = findCarSupermarket(dealerId);
	changePageTitle(cs.companyName);
	
	var csPos = new Position(cs.latitude, cs.longitude);
	zoom.setZoomValue(getZoomedInZoomLevel());
	map.centerOnPosition(csPos, function()
		{
			addMarkerPin(cs);
		});
}

function findCarSupermarket(dealerId)
{
	var enhancedCarSupermarkets = getEnhancedCarSupermarkets();
	for (var ecs in enhancedCarSupermarkets)
	{
		if (enhancedCarSupermarkets[ecs].dealerId == dealerId)
		{
			return enhancedCarSupermarkets[ecs];
		}
	}	
	var standardCarSupermarkets = getStandardCarSupermarkets();
	for (var scs in standardCarSupermarkets)
	{
		if (standardCarSupermarkets[scs].dealerId == dealerId)
		{
			return standardCarSupermarkets[scs];
		}
	}
	return null;
}

// getters
function getEnhancedPinImage()
{
	return "../images/pointer.png";
}
function getStandardPinImage()
{
	return "../images/standardPoint.png";
}
function getUserPinImage()
{
	return "../img/userPin.gif";
}
function getMarkerPinImage()
{
	return "../img/marker.png";
}
function getAToZZoomLevel()
{
	return 10;
}
function getZoomedInZoomLevel()
{
	return 8;
}
function getMinimumZoomLevel()
{
	return 11;
}
function getBubbleWidth()
{
	return 250;
}
function getBubbleHeight()
{
	return 100;
}