﻿// JScript File

var map;
var geocoder;
var restaurantsString;
var selectedCategory;

var savedCoordinatesX;
var savedCoordinatesY;
var savedZoom;

//<![CDATA[
/*
* Description:
* This function is called when the google map control is going to be created.
* It takes two parameters:
* var1 == All of the restauranings that belongs to the selected category.
* var2 == The actual category that has been selected.
*/
function load(var1, var2, var3, var4, var5) {
    // Make sure the browser is compatible with the control.
    if (GBrowserIsCompatible()) {
        restaurantsString = var1;
        //this.RestaurantsInCategory = this.RestaurantsInCategory.Replace("'", "^");
        restaurantsString = restaurantsString.replace("^", "'");
        selectedCategory = var2;

        // Create the google map control and add an interface that allows zooming and movement.
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GSmallMapControl());

        // Geocoder is a conversion tool, which converts an address consisting of a steet name, city etc. into coordinates.
        geocoder = new GClientGeocoder();

        // default address (centers over Jönköping)
        if (savedCoordinatesX != null) {
            CenterAtCoordinates(savedCoordinatesX, savedCoordinatesY, savedZoom);
        }
        else {

            if (var4 != null && var5 != null)
            { CenterAtCoordinates(var4, var5, var3) }
            else {
                CenterAtCoordinates(57.780000, 14.168800, var3);
            }
        }

        // Place markers for each of the restaurants in the category.
        UpdateRestaurants();

    }
}

function CenterAtCoordinates(coordX, coordY, zoom) {
    if (map != null) {
        map.setCenter(new GLatLng(coordX, coordY), zoom);

        savedCoordinatesX = null;
        savedCoordinatesY = null;
        savedZoom = null;
    }
    else {
        // map was not defined, save the coordinates in a variable to be used later.
        savedCoordinatesX = coordX;
        savedCoordinatesY = coordY;
        savedZoom = zoom;
    }
}


/*
* Description:
* Loops through all of the restaurants of the selected category and places a marker at the coordinates.
*/
function UpdateRestaurants() {
    // Converts the restaurant string into an array list.
    var restaurantArray = restaurantsString.split('~');
    // The number of columns on each row.
    var nr_columns = restaurantArray[0];
    // The number of rows. The subtraction by two is to exclude the first element and also the last one, which it empty.
    var nr_rows = (restaurantArray.length - 2) / nr_columns;

    // Today's date.
    var today = new Date();

    var previousPoint;
    var html_to_marker;
    var CombinedHTMLCode = "";
    var CombinedNames = "";
    var UseCombined;

    for (var i = 0; i < nr_rows; i++) {
        // Is is important that the 'day'-variables is being defined within the loop.
        // Since their values is likely to change further down.
        var dayNumber = today.getDay();
        var dayHour = today.getHours();
        var dayMinutes = today.getMinutes();

        // The start index for the row in the array.
        var startIndex = (i * nr_columns) + 1;

        // Collect a few necessary variables for the maker and save them into seperate "easy-to-read" variables.
        var id = restaurantArray[(startIndex)];
        var name = restaurantArray[(startIndex + 1)];
        var address = restaurantArray[(startIndex + 2)]; // Ta bort
        var category = restaurantArray[(startIndex + 3)]; // Ta bort
        var description = restaurantArray[(startIndex + 4)];
        var point = restaurantArray[(startIndex + 5)];
        var menuChange = restaurantArray[(startIndex + 8)];
        var menuChange_hour = (menuChange.split(':'))[0];
        var menuChange_minutes = (menuChange.split(':'))[1];
        var weeksAlternative = restaurantArray[(startIndex + 18)];


        // Check and see if it's to late to take the "todays lunch",
        // If it is, show the lunch for the next day.
        var useTomorrow = false;

        if (dayHour > menuChange_hour)
            useTomorrow = true;
        if (dayHour == menuChange_hour && dayMinutes >= menuChange_minutes)
            useTomorrow = true;

        if (useTomorrow) {
            dayNumber++;

            // If the dayNumber exceedes the number of days in the week, start over.
            // Please have in mind that dayNumber goes between 0 and 6 (which give you 7 days, obviously).
            if (dayNumber > 6)
                dayNumber = 0;
        }

        var sundayMenuIndex = (startIndex + 15);
        var mondayMenuIndex = (startIndex + 9);
        var tuesdayMenuIndex = (startIndex + 10);
        var wednesdayMenuIndex = (startIndex + 11);
        var thursdayMenuIndex = (startIndex + 12);
        var fridayMenuIndex = (startIndex + 13);
        var saturdayMenuIndex = (startIndex + 14);
        var selectedMenuIndex = -1;
        var beginningOfMenu = "";

        var todaysMenu = "";
        if (restaurantArray[sundayMenuIndex].length > 0 || restaurantArray[mondayMenuIndex].length > 0 || restaurantArray[tuesdayMenuIndex].length > 0 || restaurantArray[wednesdayMenuIndex].length > 0 || restaurantArray[thursdayMenuIndex].length > 0 || restaurantArray[fridayMenuIndex].length > 0 || restaurantArray[saturdayMenuIndex].length > 0) {
            beginningOfMenu = "<b>Dagens meny</b>"; // The begining of the menu string is needed further down.
            todaysMenu = beginningOfMenu;

            // Make sure the menu being rendered contains text.
            // If not, loop through the menus until one is found.
            // PLEASE NOTE: THIS FUNCTION IS CURRENTLY DISABLED
            // TO ENABLE IT, SET THE FIRST OCCURENCE OF "var menuFound = true;" to false.            
            for (var j = 0; j < 7; j++) {
                var menuFound = true;

                switch (dayNumber) {
                    case 0:
                        // Sunday:
                        if (restaurantArray[sundayMenuIndex].length > 0) {
                            menuFound = true;
                            selectedMenuIndex = sundayMenuIndex;
                            todaysMenu += " (Söndag):<br />";
                            todaysMenu += restaurantArray[sundayMenuIndex];
                        }
                        break;
                    case 1:
                        // Monday:
                        if (restaurantArray[mondayMenuIndex].length > 0) {
                            menuFound = true;
                            selectedMenuIndex = mondayMenuIndex;
                            todaysMenu += " (Måndag):<br />";
                            todaysMenu += restaurantArray[mondayMenuIndex];
                        }
                        break;
                    case 2:
                        // Tuesday:
                        if (restaurantArray[tuesdayMenuIndex].length > 0) {
                            menuFound = true;
                            selectedMenuIndex = tuesdayMenuIndex;
                            todaysMenu += " (Tisdag):<br />";
                            todaysMenu += restaurantArray[tuesdayMenuIndex];
                        }
                        break;
                    case 3:
                        // Wednesday:
                        if (restaurantArray[wednesdayMenuIndex].length > 0) {
                            menuFound = true;
                            selectedMenuIndex = wednesdayMenuIndex;
                            todaysMenu += " (Onsdag):<br />";
                            todaysMenu += restaurantArray[wednesdayMenuIndex];
                        }
                        break;
                    case 4:
                        // Thursday:
                        if (restaurantArray[thursdayMenuIndex].length > 0) {
                            menuFound = true;
                            selectedMenuIndex = thursdayMenuIndex;
                            todaysMenu += " (Torsdag):<br />";
                            todaysMenu += restaurantArray[thursdayMenuIndex];
                        }
                        break;
                    case 5:
                        // Friday:
                        if (restaurantArray[fridayMenuIndex].length > 0) {
                            menuFound = true;
                            selectedMenuIndex = fridayMenuIndex;
                            todaysMenu += " (Fredag):<br />";
                            todaysMenu += restaurantArray[fridayMenuIndex];
                        }
                        break;
                    case 6:
                        // Saturday:
                        if (restaurantArray[saturdayMenuIndex].length > 0) {
                            menuFound = true;
                            selectedMenuIndex = saturdayMenuIndex;
                            todaysMenu += " (Lördag):<br />";
                            todaysMenu += restaurantArray[saturdayMenuIndex];
                        }
                        break;
                }

                // If a valid menu has been found, end search.
                // If the current dayNumber didn't have a valid menu - go to the next day.
                if (menuFound)
                    break;
                else {
                    dayNumber++;
                    // If the dayNumber exceedes the number of days in the week, start over.
                    // Please have in mind that dayNumber goes between 0 and 6 (which give you 7 days, obviously).
                    if (dayNumber > 6)
                        dayNumber = 0;
                }

            }
        }

        // If all that the menu variable contains is the header-text. Clear it.
        if (todaysMenu.length == beginningOfMenu.length) {
            todaysMenu = "";
        }


        // Create a marker for the current restaurant and add it as an overlay.
        // If the current point is the same as the previous one then, obviously, the restaurant-marker
        // will be set at the same position. Instead of creating seperate markers for each of the restaurants -
        // Reuse the same one and place the different restaurants that has the same coordinates on the same marker.
        // (the array is being sort when gathered from the database through SQL-query).

        var previousPoint;
        var currentPoint;
        var nextPoint;

        var previousPointArrayIndex = (parseInt(startIndex) + 5) - parseInt(nr_columns);
        var nextPointArrayIndex = (parseInt(startIndex) + 5) + parseInt(nr_columns);

        currentPoint = point;


        // Make sure the indeces are inside the bounds of the array.
        if (previousPointArrayIndex >= 0)
            previousPoint = restaurantArray[parseInt(previousPointArrayIndex)]; // the position of the previous restaurant's point.     
        if (nextPointArrayIndex <= restaurantArray.length)
            nextPoint = restaurantArray[parseInt(nextPointArrayIndex)];     // the position of the next restaurant's point.


        if (currentPoint == nextPoint) {
            CombinedHTMLCode += createMakerHTML(id, name, selectedCategory, todaysMenu, weeksAlternative);
            CombinedHTMLCode += "<br />";

            if (CombinedNames.length > 0) {
                // If the variable already contains a name, place a seperator.
                CombinedNames += ", ";
            }
            CombinedNames += name;

            // If we're in the last step in the loop, then there's no opportunity for
            // the else-case to be executed. But since we need a marker, create one here.      
            if (i == (nr_rows - 1)) {
                // When here, last step in the loop
                map.addOverlay(createMarker(CombinedNames, CombinedHTMLCode, currentPoint));
            }

            continue;
        }
        else {
            if (CombinedHTMLCode.length > 0) {
                CombinedHTMLCode += createMakerHTML(id, name, selectedCategory, todaysMenu, weeksAlternative);

                if (CombinedNames.length > 0) {
                    // If the variable already contains a name, place a seperator.
                    CombinedNames += ", ";
                }
                CombinedNames += name;

                map.addOverlay(createMarker(CombinedNames, CombinedHTMLCode, previousPoint));
                CombinedHTMLCode = "";
                CombinedNames = "";
            }
            else {
                map.addOverlay(createMarker(name, createMakerHTML(id, name, selectedCategory, todaysMenu, weeksAlternative), currentPoint));
            }
        }
    }
}


function createMakerHTML(id, name, category, description, weeksAlternative) {

    // Insert name and description of the restaurant into the "bubble" that shows.                        
    var htmlCode = "<div style='line-height:12px;'><span style='font-family:Arial;font-size:18px;'> " + name + "</span><br /><br />";
    if (description.length > 0) {
        htmlCode += "<span style='font-family:Arial;font-size:11px;'>" + description + "</span><br/><br/>";
    }

    if (weeksAlternative.length > 0) {
        htmlCode += "<span style='font-family:Arial;font-size:11px;'><b/>Veckans alternativ:</b></span><br />";
        htmlCode += "<span style='font-family:Arial;font-size:11px;'>" + weeksAlternative + "</span><br/><br/>";
    }

    if (category != null)
        htmlCode += "<a style='font-size:12px;' href=\"http://www.jlunch.se/" + category + "/Restaurang/" + name + "\">Mer information</a></div>";
    else
        htmlCode += "<a style='font-size:12px;' href=\"http://www.jlunch.se/Restaurang/" + name + "\">Mer information</a></div>";

    return htmlCode;
}


function createMarker(names, htmlCode, point) {
    // Convert the point from a spring into an array for the coordinates.
    point = point.slice(1, point.length - 1);
    var coordinates = point.split(',');

    // Create the marker at the coordinates.
    marker = new PdMarker(new GLatLng(parseFloat(coordinates[0]), parseFloat(coordinates[1])));

    marker.setTooltip(names);
    marker.bindInfoWindowHtml(htmlCode);
    marker.setOpacity(0);


    return marker;
}

/*
* Description:
* Centers the camera over an address.
* The function takes one parameter that should consist of street name, city etc.
* The format of the address should look like this: "[Street name] [Street number], [Postal number] [City], [County], [Country]".
*/
function showAddress(address) {

    geocoder.getLatLng(address,
    function(point) {
        if (!point) {
            // The address could not be found, show error message.
            alert(address + " hittades ej!");
        }
        else {
            // When here, the address has been found.
            // Center the camera over it with the zoom level of 13.
            map.setCenter(point, 13);
        }
    });
}
