var map;

var MapHelper = {

    iObject: null,

    Init: function(iObject) {

        MapHelper.iObject = iObject;
        MapHelper.MoveMap();

        MapHelper.LoadScripts();

    },

    LoadScripts: function() {

        $.ajaxSetup({ async: false });

        if (!($.browser.msie)) {
            $.getScript('http://dev.virtualearth.net/mapcontrol/v6.2/js/atlascompat.js');
        }
        $.getScript('http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&mkt=nl-nl&onScriptLoad=MapHelper.InitializeMap');

        $.ajaxSetup({ async: true });

    },

    InitializeMap: function() {

        map = new VEMap('map');

        if (MapHelper.iObject)
            map.onLoadMap = eval('MapHelper.' + MapHelper.iObject);

        map.LoadMap();

        map.ClearInfoBoxStyles();
        map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);

        // map.AttachEvent('onclick', MapHelper.GetLatLong);

    },

    InitializeObject: function(iObject) {

        var interval = setInterval(function() {

            if ((eval('typeof VEMap') != 'undefined')) {

                clearInterval(interval);

                MapHelper.iObject = iObject;
                MapHelper.MoveMap();

                var fn = eval('MapHelper.' + MapHelper.iObject + '()');

            }
        }, 10);

    },

    ResizeMap: function(mapWidth, mapHeight) {

        map.Resize(mapWidth, mapHeight);

        $('#map').css({ 'width': mapWidth + 'px', 'height': mapHeight + 'px' });

    },

    MoveMap: function() {

        $('.map.' + MapHelper.iObject).append(
			$('#map').remove()
		);

    },

    AddPin: function(LatLong, PinType) {

        var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(LatLong[0], LatLong[1]));
        pin.SetCustomIcon('<div class="pin ' + PinType + '"></div>');

        map.AddShape(pin);

        return pin.GetID();

    },

    AddPolygon: function(LatLongs) {

        var ArrPolygon = new Array();

        $.each(LatLongs, function(key, value) {
            ArrPolygon[key] = new VELatLong(value[0], value[1]);
        });

        var shape = new VEShape(VEShapeType.Polygon, ArrPolygon);
        shape.HideIcon();

        map.AddShape(shape);

        return shape.GetID();

    },

    SetOverlayColor: function(shapeId, colorKey) {

        var shape = map.GetShapeByID(shapeId);
        var color = MapData.colors[colorKey];

        shape.SetLineColor(new VEColor(color[0], color[1], color[2], 1.0));
        shape.SetLineWidth(2);
        shape.SetFillColor(new VEColor(color[0], color[1], color[2], 0.5));

    },

    SetOverlayDescription: function(neighborhood) {

        var box = $('#map-boxes-container .overlays').clone();

        $('.body h4', box).html(neighborhood['name']);

        var shape = map.GetShapeByID(neighborhood['id']);
        shape.SetDescription(box.html());
    },

    SetV2HouseDescription: function(house) {
        var box;
        if (house['status'] == 'other') {
            box = $('#map-boxes-container .register').clone();
        }
        else {
            box = $('#map-boxes-container .houses').clone();
            $('.body h4', box).html(house['address']);
        }

        var shape = map.GetShapeByID(house['id']);
        shape.SetDescription(box.html());
    },


    SetHouseDescription: function(house) {

        var box;
        var shape = map.GetShapeByID(house['id']);

        if (house['status'] == 'other') {
            box = $('<div class="m51-target" style="width:1px;height:1px"></div>');
        }
        else {
            $('#map-boxes-container').find('input[name$=mapHouseLatLon]').each(function() {
                var text = $(this).val();
                var textArr = text.split(',');

                if (textArr[0] == shape.Latitude && textArr[1] == shape.Longitude) {
                    var mapHouseLatLon = $(this).select();

                    var houses = mapHouseLatLon.parents('.houses');

                    box = houses.clone();
                    $('.body h4', box).html(house['address']);
                }
            });
        }

        shape.SetDescription(box.html());

    },

    SetM30HouseDescription: function(house) {

        var box;
        var shape = map.GetShapeByID(house['id']);

        if (house['status'] == 'other') {
            box = $('<div class="m51-target" style="width:1px;height:1px"></div>');
        }
        else {
            $('#map-boxes-container').find('input[name$=mapHouseLatLon]').each(function() {
                var text = $(this).val();
                var textArr = text.split(',');

                if (textArr[0] == shape.Latitude && textArr[1] == shape.Longitude) {
                    var mapHouseLatLon = $(this).select();

                    var houses = mapHouseLatLon.parents('.houses');

                    box = houses.clone();
                }
            });
        }

        shape.SetDescription(box.html());

    },

    SetOverlayLegenda: function(scoreKey) {

        $('.market-legendas > div').hide();
        $('.market-legendas > div:eq(' + (scoreKey) + ')').show();

    },

    ShowInfoBox: function(e) {

        map.HideInfoBox();

        if (e.elementID) {

            var x = e.mapX;
            var y = e.mapY;
            var shape = map.GetShapeByID(e.elementID);

            if (shape)
                map.ShowInfoBox(shape, new VEPixel(x, y));

        }

        return false;

    },

    ShowHouseDetail: function(e) {

        map.HideInfoBox();

        if (e.elementID) {

            var x = e.mapX;
            var y = e.mapY;
            var shape = map.GetShapeByID(e.elementID);

            if (shape) {
                $('.top-houses').hide();
                $('.house-detail').show();
            }

        }

        return false;

    },

    ShowV93HouseDetail: function(e) {

        map.HideInfoBox();

        if (e.elementID) {

            var x = e.mapX;
            var y = e.mapY;
            var shape = map.GetShapeByID(e.elementID);

            if (shape) {
                var mapLatLon;

                var tempMapLocation = shape.Latitude + "," + shape.Longitude;

                //if count of houses at the same location is greater than 1 then we will not show house details on right side
                var countOfHouses = $('.right').find('input[value="' + tempMapLocation + '"]').length;

                if (countOfHouses == 1) {
                    $('.house-detail').each(function() {
                        $(this).hide();
                    });

                    $('.top-houses').hide();

                    $('.right').find('input[name$=mapLatLon]').each(function() {
                        var text = $(this).val();
                        var textArr = text.split(',');

                        if (textArr[0] == shape.Latitude && textArr[1] == shape.Longitude) {
                            mapLatLon = $(this).select();

                            var houseDetail = mapLatLon.parents('.house-detail');
                            houseDetail.show();
                        }
                    });
                }
            }
        }

        return false;

    },

    GetLatLong: function(e) {

        var x = e.mapX;
        var y = e.mapY;

        pixel = new VEPixel(x, y);
        latLong = map.PixelToLatLong(pixel);

        alert(latLong);

    },

    AddSitePins: function() {

        $.each(MapData.sites, function(key, value) {
            $.each(value, function() {
                MapHelper.AddPin(this['lat-long'], key);
            });
        });

    },

    AddHousePins: function(result) {

        $.each(MapData.houses[result], function(key, value) {

            shapeId = MapHelper.AddPin(value['lat-long'], value['status']);

            MapData.houses[result][key]['id'] = shapeId;
            MapHelper.SetHouseDescription(value);

        });
    },

    AddHousePinsBulkL24: function(result) {

        var shapes = new Array();
        var shapeLayer = new VEShapeLayer();

        var clusterOptions = new VEClusteringOptions();
        clusterOptions.Icon = new VECustomIconSpecification();
        clusterOptions.Icon.CustomHTML = '<div class="pin offered"></div>';
        clusterOptions.Callback = clusteringCallback;

        $.each(result, function(key, value) {

            var box;
            var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(value['lat-long'][0], value['lat-long'][1]));
            shape.SetCustomIcon('<div class="pin ' + value['status'] + '"></div>');

            if (value['status'].indexOf('houses-') != -1 || value['status'].indexOf('other-') != -1) {
                box = $('#map-boxes-container .houses-more').clone();
                $('.body', box).html('<ol>' + value['address'] + '</ol>');
            }
            else {
                box = $('#map-boxes-container .houses').clone();
                $('.body a', box).attr("href", "/Pages/huis-detail.aspx?dossierId=" + value['dossierId']);
                $('.body a', box).attr("title", value['address']);
                $('.body a', box).text(value['address']);
            }

            shape.SetDescription(box.html());
            shapes.push(shape);

        });

        shapeLayer.SetClusteringConfiguration(VEClusteringType.Grid, clusterOptions);
        map.AddShapeLayer(shapeLayer);

        shapeLayer.AddShape(shapes);

    },

    AddHousePinsV93: function(houses) {

        $.each(houses, function(key, value) {

            shapeId = MapHelper.AddPin(value['lat-long'], value['status']);

            houses[key]['id'] = shapeId;
            MapHelper.SetHouseDescription(value);

        });
    },

    AddHousePinsV2: function(houses) {

        $.each(houses, function(key, value) {

            shapeId = MapHelper.AddPin(value['lat-long'], value['status']);

            houses[key]['id'] = shapeId;
            MapHelper.SetV2HouseDescription(value);

        });
    },

    AddNeighborhoodScoreOverlay: function(scoreKey) {

        $.each(MapData.neighborhoods, function(key, value) {

            shapeId = MapHelper.AddPolygon(value['lat-long']);

            MapData.neighborhoods[key]['id'] = shapeId;

            MapHelper.SetOverlayColor(shapeId, value['market-score'][scoreKey]);
            MapHelper.SetOverlayDescription(value);

        });

        MapHelper.SetOverlayLegenda(scoreKey);

    },

    ChangeMarketScore: function(scoreKey) {

        scoreKey = scoreKey - 1;

        $.each(MapData.neighborhoods, function(key, value) {

            MapHelper.SetOverlayColor(value['id'], value['market-score'][scoreKey]);
            MapHelper.SetOverlayDescription(value);

        });

        MapHelper.SetOverlayLegenda(scoreKey);

    },

    AddNeighborhoodSearchOverlay: function() {

        $('.refine .select-district ul').children().remove();

        $.each(Neighborhoods, function(key, value) {

            Neighborhoods[key]['shapes'] = new Array();

            $.each(value['lat-long'], function(orderId, latLong) {

                shapeId = MapHelper.AddPolygon(latLong);

                Neighborhoods[key]['shapes'].push(shapeId);

                MapHelper.SetOverlayColor(shapeId, value['color']);

            });

            $('.refine .select-district ul').append(
				$('<li>').html(
					'<a href="javascript:;" class="{areaKey:\'' + key + '\', shapeId:\'' + Neighborhoods[key]['shapes'].join(',') + '\'}">' + value['name'] + ' (' + value['result'] + ')</a>'
				)
				.prepend('<input type="checkbox" name="neighborhoods[]" value="' + key + '" />')
			);

        });

        $('.refine .select-district ul a').click(function() {
            MapHelper.ToggleNeighborhood($(this));
        });

        $('.refine .select-district ul input:checkbox').click(function() {
            $('.refine .select-district ul a[class^={areaKey:\'' + $(this).val() + '\']').trigger('click');
        });

        $('.refine input:checkbox').uniform({
            checkboxClass: 'custom-checkbox'
        });


        $.each(Neighborhoods, function(key, value) {
            if (value['selected'])
                $('.refine .select-district ul a[class^={areaKey:\'' + key + '\']').trigger('click');
        });

    },

    ClickNeighborhood: function(e) {

        if (e.elementID) {

            var x = e.mapX;
            var y = e.mapY;
            var shape = map.GetShapeByID(e.elementID);

            if (shape) {

                var shapeId = shape.GetID();

                $('.refine .select-district ul a').each(function() {

                    if ($(this).metadata().shapeId.search(shapeId) !== -1) {

                        MapHelper.ToggleNeighborhood($(this));

                    }

                });
            }
        }

        return false;

    },

    OverNeighborhood: function(e) {

        if (e.elementID) {

            var x = e.mapX;
            var y = e.mapY;
            var shape = map.GetShapeByID(e.elementID);

            if (shape) {

                var shapeId = shape.GetID();

                $('.refine .select-district ul a').each(function() {

                    if ($(this).metadata().shapeId.search(shapeId) !== -1) {

                        MapHelper.HoverNeighborhood($(this), 'over');

                    }

                });

            }
        }

        return false;

    },

    OutNeighborhood: function(e) {

        if (e.elementID) {

            var x = e.mapX;
            var y = e.mapY;
            var shape = map.GetShapeByID(e.elementID);

            if (shape) {

                var shapeId = shape.GetID();

                $('.refine .select-district ul a').each(function() {

                    if ($(this).metadata().shapeId.search(shapeId) !== -1) {

                        MapHelper.HoverNeighborhood($(this), 'out');

                    }

                });
            }
        }

        return false;

    },

    ToggleNeighborhood: function(obj) {

        var $li = obj.parent().toggleClass('selected');

        $li.find(':checkbox')
			.attr('checked', $li.hasClass('selected'))
			.closest('span').toggleClass('checked', $li.hasClass('selected'));

        var areaKey = obj.metadata().areaKey;
        var shapes = obj.metadata().shapeId.split(',');

        var color = (!$li.hasClass('selected')) ? Neighborhoods[areaKey]['color'] : 2;

        for (id in shapes) {

            MapHelper.SetOverlayColor(shapes[id], color);

        }

    },

    HoverNeighborhood: function(obj, event) {

        var $li = obj.parent();

        var areaKey = obj.metadata().areaKey;
        var shapes = obj.metadata().shapeId.split(',');

        var color, transparency;

        for (id in shapes) {

            shape = map.GetShapeByID(shapes[id]);

            /*
            shape.SetZIndex(null, 1000);
			
			if(event == 'over') 
            shape.SetZIndex(null, 1001);
			
			shape.SetLineColor(new VEColor(color[0], color[1], color[2], 1.0));
            */

            color = shape.GetFillColor();
            transparency = (event == 'over') ? 0.2 : 0.5;

            shape.SetFillColor(new VEColor(color.R, color.G, color.B, transparency));

        }

    },

    SetCenter: function(zoomLevel, latLong) {

        map.DeleteAllShapes();
        map.DeleteRoute();

        zoomLevel = (zoomLevel) ? zoomLevel : 14;
        latLong = (latLong) ? latLong : MapData.house['lat-long'];

        map.SetCenterAndZoom(new VELatLong(latLong[0], latLong[1]), zoomLevel);

    },

    SetL24Center: function(zoomLevel, latLong) {

        zoomLevel = (zoomLevel) ? zoomLevel : 14;

        latLongArr = (latLong) ? latLong : MapData.house['lat-long'];

        map.SetCenterAndZoom(new VELatLong(latLongArr[0], latLongArr[1]), zoomLevel);
    },

    CenterM30: function() {

        var latLong;
        if (m30houses.length > 0) {
            latLong = m30houses[0]['lat-long'];
        }

        MapHelper.SetL24Center(12, latLong);
    },

    SetV2Center: function(zoomLevel, latLong) {

        zoomLevel = (zoomLevel) ? zoomLevel : 14;

        latLongArr = (latLong) ? latLong.split(',') : MapData.house['lat-long'];

        map.SetCenterAndZoom(new VELatLong(latLongArr[0], latLongArr[1]), zoomLevel);
    },

    SetCenterHouse: function(zoomLevel) {

        MapHelper.SetCenter(zoomLevel);

        MapHelper.AddPin(MapData.house['lat-long'], 'iblue');

    },

    GetDirections: function() {

        $('.p47 .route').hide();

        map.DeleteAllShapes();

        var options = new VERouteOptions;
        options.SetBestMapView = true;
        options.ShowDisambiguation = true;
        options.DistanceUnit = VERouteDistanceUnit.Kilometer;
        options.RouteCallback = MapHelper.onGotRoute;

        var destination = new Array;

        if ($('#streetname').val().length) {

            destination.push($('#streetname').val());

            if ($('#housenumber').val().length)
                destination[0] = destination[0] + ' ' + $('#housenumber').val();

        }

        if ($('#city').val().length)
            destination.push($('#city').val());

        var locations = new Array(
			new VELatLong(MapData.house['lat-long'][0], MapData.house['lat-long'][1]),
			destination.join()
		);

        map.GetDirections(locations, options);

    },

    onGotRoute: function(route) {

        if (!route)
            return false;

        map.DeleteAllShapes();

        var legs = route.RouteLegs;

        $('.p47 .route h4 span').html(
			route.Distance.toFixed(1) + ' km, ' + Math.round(route.Time / 60) + ' minuten'
		);

        $('.p47 .route table tr').remove();

        $.each(legs, function(key, leg) {

            for (var j = 0; j < leg.Itinerary.Items.length; j++) {

                turn = leg.Itinerary.Items[j];

                $('.p47 .route table').append(
					$('<tr>').html(
						'<td class="first">' + (j + 1) + '.</td><td>' + turn.Text + '</td><td class="last">' + turn.Distance.toFixed(1) + ' km</td>'
					)
				);

            }

        });

        $('.p47 .route').show();

        // start
        MapHelper.AddPin(MapData.house['lat-long'], 'iblue');
        // end
        MapHelper.AddPin([turn.LatLong.Latitude, turn.LatLong.Longitude], 'site-3');
        $('.pin.site-3').show();

    },

    P7: function() {
        MapHelper.ResizeMap(428, 288);

        var latLong = $('input[name$=mapHouseLatLon]').val();

        if (latLong) {
            latLongArr = latLong.split(',');
            map.SetCenterAndZoom(new VELatLong(latLongArr[0], latLongArr[1]), 14);
            MapHelper.AddPin([latLongArr[0], latLongArr[1]], 'result');
        }
        else {
            latLongArr = MapData.house['lat-long'];
            map.SetCenterAndZoom(new VELatLong(latLongArr[0], latLongArr[1]), 14);
        }
    },

    P33: function() {

        MapHelper.ResizeMap(618, 410);

        map.ShowDashboard();

        MapHelper.SetCenterHouse();
        MapHelper.AddSitePins();

        $(':checkbox[name=sites]:checked').each(function() {
            $('.pin.site-' + $(this).val()).show();
        });

    },

    P43: function() {

        var selectIndex = parseFloat($('select#market').val()) - 1;

        MapHelper.ResizeMap(618, 410);

        map.ShowDashboard();

        MapHelper.SetCenterHouse(13);
        MapHelper.AddNeighborhoodScoreOverlay(selectIndex);
        map.AttachEvent('onmouseover', MapHelper.ShowInfoBox);

    },

    P47: function() {

        MapHelper.ResizeMap(618, 410);

        map.ShowDashboard();

        MapHelper.SetCenterHouse();

    },

    M28_refine: function() {

        MapHelper.ResizeMap(450, 322);

        map.ShowDashboard();

        var mapCenter = NeighborhoodsMapCenter.split(',');
        MapHelper.SetCenter(NeighborhoodsZoomLevel, mapCenter);

        MapHelper.AddNeighborhoodSearchOverlay();

        map.AttachEvent('onclick', MapHelper.ClickNeighborhood);

        map.AttachEvent('onmouseover', MapHelper.OverNeighborhood);
        map.AttachEvent('onmouseout', MapHelper.OutNeighborhood);
    },

    M28_refine_more: function() {

        MapHelper.ResizeMap(450, 322);

        map.ShowDashboard();

        var mapCenter = NeighborhoodsMapCenter.split(',');
        MapHelper.SetCenter(NeighborhoodsZoomLevel, mapCenter);

        MapHelper.AddNeighborhoodSearchOverlay();

        map.AttachEvent('onclick', MapHelper.ClickNeighborhood);
    },

    M30: function() {

        MapHelper.ResizeMap(698, 348);

        var latLong;
        if (m30houses.length > 0) {
            latLong = m30houses[0]['lat-long'];
        }

        MapHelper.SetL24Center(12, latLong);

        MapHelper.AddHousePinsBulkL24(m30houses);

        map.ShowDashboard();
    },

    L24: function() {

        MapHelper.Helper();

        var latLong;
        if (l24houses.length > 0) {
            latLong = l24houses[0]['lat-long'];
        }

        MapHelper.SetL24Center(12, latLong);

        MapHelper.AddHousePinsBulkL24(l24houses);

        map.ShowDashboard();
    },

    L29: function() {

        MapHelper.Helper();
        MapHelper.SetCenter(13);
        MapHelper.AddNeighborhoodScoreOverlay(0);

        map.AttachEvent('onmouseover', MapHelper.ShowInfoBox);

    },

    L28: function() {

        MapHelper.Helper();
        MapHelper.SetCenter(13);
        MapHelper.AddNeighborhoodScoreOverlay(1);

        map.AttachEvent('onmouseover', MapHelper.ShowInfoBox);

    },

    L27: function() {

        MapHelper.Helper();
        MapHelper.SetCenter(13);
        MapHelper.AddNeighborhoodScoreOverlay(2);

        map.AttachEvent('onmouseover', MapHelper.ShowInfoBox);

    },

    P60: function() {

        MapHelper.Helper();
        MapHelper.SetCenter(14);
        MapHelper.AddHousePins('result');

    },

    V2: function() {
        var latLong = $('input[name$=hndV2Center]').val();

        MapHelper.ResizeMap(314, 218);

        MapHelper.SetV2Center(12, latLong);

        MapHelper.AddHousePinsV2(v2houses);

        map.HideDashboard();
    },

    V88: function() {

        MapHelper.ResizeMap(458, 345);
        MapHelper.SetCenter(13);
        MapHelper.AddHousePins('result');

        map.ShowDashboard();
        map.AttachEvent('onclick', MapHelper.ShowHouseDetail);

    },

    V93: function() {

        MapHelper.ResizeMap(458, 345);

        var latLong;
        if (v93houses.length > 0) {
            latLong = v93houses[0]['lat-long'];
        }

        MapHelper.SetL24Center(13, latLong);

        MapHelper.AddHousePinsV93(v93houses);

        map.ShowDashboard();
        map.AttachEvent('onclick', MapHelper.ShowV93HouseDetail);

    },

    Helper: function() { // ...

        MapHelper.ResizeMap(618, 410);

        map.ShowDashboard();

    }

}

function clusteringCallback(clusters) {

    for (var i = 0; i < clusters.length; ++i) {
    
        var cluster = clusters[i];
        var clusterShape = cluster.GetClusterShape();
        
        var shape = cluster.Shapes[0];
        var description = shape.GetDescription();
        var icon = shape.GetCustomIcon();
        
        clusterShape.SetDescription(description);
        clusterShape.SetTitle('');
        clusterShape.SetCustomIcon(icon);
        
    }
}