﻿/*
* googleMaps.js
* Contains javascript for creating a google map from latitude/longitude coordinates.
* NOTE: This javascript is deeply connected to the findTravels.js javascript. This is due to the google API loading the map as a callback and not as part of the $.ready function. Changes made to these files should be done with care.
*/

var GoogleMap = {
    markersWithID: new Array(),
    map: null,
    bounds: null,
    infoWindow: null
}

var markerWithID = function () {
    marker = null;
    pageID = null;
}

var hotelMap = function () {
    markersWithID = new Array();
    map = null;
    bounds = null;
    infoWindow = null;
    divId = null;
    suffix = null;
}

// Calls inside synchronizeMarkersWithTags() are made to findTravels.js from initialize() so that the map markers are set if the page is reloaded using 'back' in the browser and the checkbox are reset to their previous values
function synchronizeMarkersWithTags() {
	$('#tp-tabs p input').each(function () {
        setMarkers();
        var listItem = $(this).val();
        if ($(this).is(':checked')) {
            selectedTags.push(listItem);
        }
        else {
            selectedTags = $.grep(selectedTags, function (value) {
                return value != listItem;
            });
        }
        toggleTravels();
    });
}

// this is provided as an empty callback to Google Maps API. If initializeGoogleMap() is used, the map is distorted when using jQuery Tools tab and the map is initally hidden
function fakeInitialize() { }

// this is used to initalize the Google Map when the tab is pressed
function initializeGoogleMap() {	
    var myOptions = {
        zoom: 8,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: google.maps.MapTypeId.TERRAIN,
        scrollwheel: false,
        mapTypeControl: false
    }
    GoogleMap.map = new google.maps.Map(document.getElementById("google_map"), myOptions);
    GoogleMap.infoWindow = new google.maps.InfoWindow();
    GoogleMap.bounds = new google.maps.LatLngBounds();

    var pathCoordinates = []; // pathcoordinates used for the polylines between the travel events on the map    
    var markers = $('#map_coordinates').find('input'); // The actual markers, should be defined in HTML as hidden input fields inside the coordinate container with ID #map_coordinates

    if (markers.length >= 1)
        $('#google_map').show(); // hides the map if there are no coordinates

    // for each travel event - add a marker on the map
       $.each(markers, function () {
       	try {
       		var latLng = new google.maps.LatLng($(this).attr('data-lat'), $(this).attr('data-lon'));
       		//adds lines between the markers if the data-showlines attribute in the hiddenfield == true            
       		if ($(this).attr('data-showlines') == 'True') {
       			pathCoordinates.push(latLng);
       		}

       		var contentString = '<div class="googleMapInfoBox">';
       		var markerIcon;
       		var markerShadow = null;

       		var innerContentString = '';

       		if ($(this).attr('data-link') != "")
       			innerContentString += '<a href="' + $(this).attr('data-link') + '">';
       		if ($(this).val() != "")
       			innerContentString += '<h3>' + $(this).val() + '</h3>';
       		if ($(this).attr('data-image') != "") {
       			markerIcon = new google.maps.MarkerImage(
                    $(this).attr('data-image'),
       			// This marker is 20 pixels wide by 16 pixels tall.
                    new google.maps.Size(20, 20),
       			// The origin for this image is 0,0.
                    new google.maps.Point(0, 0),
       			// The anchor for this image is at 9,6.
                    new google.maps.Point(10, 10),
                    new google.maps.Size(20, 20)
                );
       			markerShadow = new google.maps.MarkerImage(
                    '/static/css/images/marker_frame.png',
                    new google.maps.Size(26, 26),
                    new google.maps.Point(0, 0),
                    new google.maps.Point(13, 13)
                );
       			innerContentString += '<img src="' + $(this).attr('data-image') + '" title="' + $(this).attr('data-imagedescription') + '" alt="' + $(this).attr('data-imagedescription') + '" />';
       		}
       		else {
       			markerIcon = new google.maps.MarkerImage('/static/css/images/dot.png',
       			// This marker is 20 pixels wide by 16 pixels tall.
                new google.maps.Size(20, 16),
       			// The origin for this image is 0,0.
                new google.maps.Point(0, 0),
       			// The anchor for this image is at 9,6.
                new google.maps.Point(11, 6));
       		}
       		if ($(this).attr('data-link') != "")
       			innerContentString += '</a>';
       		if ($(this).attr('data-infotext') != "")
       			innerContentString += '<p>' + $(this).attr('data-infotext') + '</p>';
       		if ($(this).attr('data-link') != "" && $(this).attr('data-link') != null)
       			innerContentString += '<a href="' + $(this).attr('data-link') + '" class="goto_travel">Gå direkt till resan</a>';

       		contentString += innerContentString;
       		contentString += '</div>';

       		var marker = new google.maps.Marker({
       			position: latLng,
       			title: $(this).val(),
       			icon: markerIcon,
       			map: GoogleMap.map,
       			shadow: markerShadow
       		});

       		var mID = new markerWithID();
       		mID.marker = marker;
       		mID.pageID = $(this).attr('data-id');
       		GoogleMap.markersWithID.push(mID);
       		
       		GoogleMap.bounds.extend(latLng); // adds the marker to the bounds

       		// checks if all fields are empty and if so, prevents an info window from being added to the marker            
       		if (innerContentString != '') {
       			google.maps.event.addListener(marker, 'click', function () {
       				GoogleMap.infoWindow.setContent(contentString);
       				GoogleMap.infoWindow.open(GoogleMap.map, marker);
       			});
       		}
       	}
       	catch (err) { } // The marker is not added
       });       
    GoogleMap.map.fitBounds(GoogleMap.bounds); //fits the map to the bounds

    var mapLines = new google.maps.Polyline({
        path: pathCoordinates,
        strokeColor: "#FF0000",
        strokeOpacity: 0.2,
        strokeWeight: 5
    });
    mapLines.setMap(GoogleMap.map);
    synchronizeMarkersWithTags();
    isMapInitialized = true;    

    if (hotelsExits)
        makeMagic();
}

var callback = 'initializeGoogleMap';
function loadScript() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=" + callback;
    document.body.appendChild(script);
}

var mapArray = new Array();
var hotelsExits = false;
function makeMagic() {    
    var divs = $("div[id^=google_map_]");


    for (var i = 0; i < divs.length; i++) {
        var hMap = new hotelMap();
        hMap.divId = divs[i].id;
        hMap.suffix = divs[i].id.split('_')[2];
        hMap.markersWithID = new Array();
        mapArray.push(hMap);
    }

    var myOptions2 = {
        zoom: 8,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: google.maps.MapTypeId.TERRAIN,
        scrollwheel: false,
        mapTypeControl: false
    }

    for (var j = 0; j < mapArray.length; j++) {
        
        /* Base func */
        mapArray[j].map = new google.maps.Map(document.getElementById(mapArray[j].divId), myOptions2);
        mapArray[j].infoWindow = new google.maps.InfoWindow();
        mapArray[j].bounds = new google.maps.LatLngBounds();

        /* Marker init */        
        var pathCoordinates = []; // pathcoordinates used for the polylines between the travel events on the map    
        var markers = $('#map_coordinates_' + mapArray[j].suffix).find('input'); // The actual markers, should be defined in HTML as hidden input fields inside the coordinate container with ID #map_coordinates
        if (markers.length >= 1) {
            $('#' + mapArray[j].divId).show();
        }  // hides the map if there are no coordinates   


        /* Marker func  */

        $.each(markers, function () {
            try {
                var latLng = new google.maps.LatLng($(this).attr('data-lat'), $(this).attr('data-lon'));
                //adds lines between the markers if the data-showlines attribute in the hiddenfield == true            
                if ($(this).attr('data-showlines') == 'True') {
                    pathCoordinates.push(latLng);
                }

                var contentString = '<div class="googleMapInfoBox">';
                var markerIcon;
                var markerShadow = null;

                var innerContentString = '';

                if ($(this).attr('data-link') != "")
                    innerContentString += '<a href="' + $(this).attr('data-link') + '">';
                if ($(this).val() != "")
                    innerContentString += '<h3>' + $(this).val() + '</h3>';
                if ($(this).attr('data-image') != "") {
                    markerIcon = new google.maps.MarkerImage(
                    $(this).attr('data-image'),
                    // This marker is 20 pixels wide by 16 pixels tall.
                    new google.maps.Size(20, 20),
                    // The origin for this image is 0,0.
                    new google.maps.Point(0, 0),
                    // The anchor for this image is at 9,6.
                    new google.maps.Point(10, 10),
                    new google.maps.Size(20, 20)
                );
                    markerShadow = new google.maps.MarkerImage(
                    '/static/css/images/marker_frame.png',
                    new google.maps.Size(26, 26),
                    new google.maps.Point(0, 0),
                    new google.maps.Point(13, 13)
                );
                    innerContentString += '<img src="' + $(this).attr('data-image') + '" title="' + $(this).attr('data-imagedescription') + '" alt="' + $(this).attr('data-imagedescription') + '" />';
                }
                else {
                    markerIcon = new google.maps.MarkerImage('/static/css/images/dot.png',
                    // This marker is 20 pixels wide by 16 pixels tall.
                new google.maps.Size(20, 16),
                    // The origin for this image is 0,0.
                new google.maps.Point(0, 0),
                    // The anchor for this image is at 9,6.
                new google.maps.Point(11, 6));
                }
                if ($(this).attr('data-link') != "")
                    innerContentString += '</a>';
                if ($(this).attr('data-infotext') != "")
                    innerContentString += '<p>' + $(this).attr('data-infotext') + '</p>';                

                contentString += innerContentString;
                contentString += '</div>';

                var marker = new google.maps.Marker({
                    position: latLng,
                    title: $(this).val(),
                    icon: markerIcon,
                    map: mapArray[j].map,
                    shadow: markerShadow
                });

                var mID = new markerWithID();
                mID.marker = marker;
                mID.pageID = $(this).attr('data-id');
                
                mapArray[j].markersWithID.push(mID);
                mapArray[j].bounds.extend(latLng); // adds the marker to the bounds                                                                   
                // checks if all fields are empty and if so, prevents an info window from being added to the marker            
                if (innerContentString != '') {
                    var tempMap = mapArray[j];
                    google.maps.event.addListener(marker, 'click', function () {
                        tempMap.infoWindow.setContent(contentString);
                        tempMap.infoWindow.open(tempMap.map, marker);
                    });
                }
            }
            catch (err) { } // The marker is not added
        });


        /* End code */
//        google.maps.event.trigger(mapArray[j].map, 'resize');
//        mapArray[j].map.fitBounds(mapArray[j].bounds); //fits the map to the bounds        
        var mapLines = new google.maps.Polyline({
            path: pathCoordinates,
            strokeColor: "#FF0000",
            strokeOpacity: 0.2,
            strokeWeight: 5
        });
        mapLines.setMap(mapArray[j].map);        

        synchronizeMarkersWithTags();
        isMapInitialized = true;
    }
}

$(document).ready(function () {
	// If there are no "travels in focus" the current tab is set to the find_travels_tab        
	if ($('div.travel_in_focus').isVisible || $('#find_travel_tab').hasClass('current')) {
		$('ul#find_travels_tabs').tabs('#find_travels .pane', { initialIndex: 1 }); ;
	}
	// if the map is placed on the FindTravels-control and the find_travel_tab is not the current tab, special care must be taken, loading the map dynamically instead of on page load
	else if ($('#find_travels_tabs').length != 0) {
		callback = 'fakeInitialize';
	}
	else if ($('#show_on_map').length > 0 && !$('#show_on_map').parent('a').hasClass('current')) {
		callback = 'fakeInitialize';
	}
	if ($("#google_map").length > 0) {
		if (($("div[id^=google_map_]").length > 0 && $("#google_map_wrapper").length < 1) || $("div[id^=google_map_]").length > 1) {			
			hotelsExits = true;
		}
		else
			hotelsExits = false;
		loadScript();
	}

});
