

function $(id) { 
	return document.getElementById(id); 
}

    var xmlHttp=null;

function GetXmlHttpObject()
{
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    //xmlHttp.setRequestHeader("charset", "utf-8");

    return xmlHttp;
}

function MyHandleTokenError() {
    alert('The token is invalid.');
}

function MyHandleTokenExpire() {
    alert('Expired token.');
}

function mapZoomEnd(e) {

    currentZoomLevel = e.zoomLevel;
    var theLayer = shapeLayer;

    // If current zoom level is bigger or same as the zoom threshold, the poi images should change to bigger ones 
    // do this, unless the images has already been changed	
    if (currentZoomLevel >= zoomThreshold && !bigIcons) {
        bigIcons = true;
        updatePois(theLayer);
    }

    if (currentZoomLevel < zoomThreshold && bigIcons) // Zooming out below threshold, change to smaller images 
    {
        bigIcons = false;
        updatePois(theLayer);
    }
}

// Loop through all shapes on layer and update their icons
function updatePois(layer) {
    for (var i = 0; i < layer.GetShapeCount(); i++) {
        var theShape = layer.GetShapeByIndex(i);
        setPoiIcon(theShape);
    }
}


// Set poi icon depending on type and size
function setPoiIcon(theShape) {
    var imageUrl = '/templates/ContentBlocks/Units/Search/images/';

    var bigSaifa = imageUrl + 'saifa_logo.png';
    var smallSaifa = imageUrl + 'saifa_mini_logo.png';
    var bigPreem = imageUrl + 'preem_logo.png';
    var smallPreem = imageUrl + 'preem_mini_logo.png';

    var icon = new VECustomIconSpecification();

    if (theShape.type == "såifa" || theShape.type == "saifa" || theShape.type == "extern")
        icon.Image = bigIcons ? bigSaifa : smallSaifa;
    else
        icon.Image = bigIcons ? bigPreem : smallPreem;

    theShape.SetCustomIcon(icon);
}



function PageLoad()
{
	// Sanity check
	if (typeof VEMap === 'undefined')
		return;

    map = new VEMap(mapId); //From litMapName
    map.SetClientToken(token);
    
    map.AttachEvent("ontokenerror", MyHandleTokenError);
    map.AttachEvent("ontokenexpire", MyHandleTokenExpire);
    
    // MapIcons 
    map.AttachEvent("onendzoom", mapZoomEnd); 

	// Om man scrollar med musen på kartan så scrollas även sidan i FF3.5. Detta är en fix för det
	// Credits: http://rbrundritt.spaces.live.com/Blog/cns!E7DBA9A4BFD458C5!960.entry
	if (navigator.userAgent.indexOf("Firefox/3.5") != -1)
    {
        $(mapId).addEventListener('DOMMouseScroll', WindowMouseWheelHandler, false);
    }

    shapeLayer = new VEShapeLayer();
    routeLayer = new VEShapeLayer();
    
    map.SetDashboardSize(VEDashboardSize.Small);
	
    map.LoadMap(new VELatLong(63, 16), 4, VEMapStyle.Road); //new VELatLong(63, 16), 4, VEMapStyle.Road

    map.AddShapeLayer(shapeLayer);
    map.AddShapeLayer(routeLayer);
    
	map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
	
	/*
	
	var clusterOptions = new VEClusteringOptions();
	clusterOptions.Callback = clusteringCallback;
	var icon = new VECustomIconSpecification();
	icon.Image = "/templates/ContentBlocks/Units/Search/images/preempoimultiple.gif";
	clusterOptions.Icon = icon;
	*/
	//shapeLayer.SetClusteringConfiguration(VEClusteringType.Grid, clusterOptions);

	if (typeof(loadData) != "undefined" ) loadData();

	if (typeof(startPoint) != "undefined" &&
		typeof(endPoint) != "undefined" &&
		typeof(setupMap) != "undefined")
		setupMap();
}

function WindowMouseWheelHandler(e)
{
    e.stopPropagation();
    e.preventDefault();
    e.cancelBubble = false;
    return false;
}

function clusteringCallback(clusters)
{
	for (var i=0; i < clusters.length; ++i)
	{
		var cluster = clusters[i];
		var clusterShape = cluster.GetClusterShape();

		clusterShape.SetTitle("Stationer");
		var desc = "den h&auml;r ikonen d&ouml;ljer " + cluster.Shapes.length + " stationer. Zooma in mer f&ouml;r att se de enskilda stationerna";

		var maxPOIs = 10;
		var s = "";
		var isNumbered = false;
		var clusteredNumbers = [];
		for (var j=0; j < cluster.Shapes.length && j < maxPOIs; j++)
		{
			var shape = cluster.Shapes[j];
			if (typeof(shape.GetCustomIcon()) != "object")
			{
				var icon = shape.GetCustomIcon();
				var n = icon.substring(icon.indexOf('>') +1, icon.lastIndexOf('<'));
				clusteredNumbers.push(n);
				isNumbered = true;
				maxPOIs = 3;
			}

			s += shape.GetTitle() + ":&nbsp;<a href='" + shape.GetMoreInfoURL() + "'>Detaljer</a><br/>";
		}
		
		if (isNumbered == true){
			if (cluster.Shapes.length > maxPOIs){
				clusteredNumbers.push('...');
			}

			var combinedN = clusteredNumbers.join(',&nbsp;');
				
			clusterShape.SetCustomIcon('<span style="padding: 0px 3px 2px; font-weight: bold; font-size: x-small; color:#008C3A; background-color:#FAC11D; padding:3px; border:1px solid #008C3A;">' + combinedN + '</span>');
		}
		if (cluster.Shapes.length > maxPOIs){
			s += "(visar de " + maxPOIs + " första)";		
		}
		clusterShape.SetDescription(desc + "<br/>" + s);
	      
	}
}

//var icon = null;
//if (typeof VECustomIconSpecification  !== 'undefined')
//{
//	icon = new VECustomIconSpecification();
//	icon.Image = '/templates/ContentBlocks/Units/Search/images/preempoimini.gif';
//}

function a(lat, lon, title, description, hlink, labelText, type)
{
	// Sanity check
	if (typeof VEMap === 'undefined')
		return;

	var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon)); 
	shapes.push(shape);
	shape.SetTitle(title);
	shape.SetMoreInfoURL(hlink);
	
	if (hlink != ''){
		shape.SetDescription(description + '&nbsp;<a href="' + hlink + '">Detaljer</a>');
	}
	else {
		shape.SetDescription(description);
	}

	shape.type = type; // Add type (micro, såifa etc) to the shape-object

	setPoiIcon(shape);  
	
	
//	if (labelText == ''){
//		shape.SetCustomIcon(icon);
//		//shape.SetCustomIcon("/templates/ContentBlocks/Units/Search/images/preempoimini.gif");
//	}
//	else{
//		shape.SetCustomIcon('<span style="padding: 0px 3px 2px; font-weight: bold; font-size: x-small; color:#008C3A; background-color:#FAC11D; padding:3px; border:1px solid #008C3A;">' + labelText + '</span>');
//	}
}

