﻿
var map;
var schemeName;

function initialize() {

    var myLatlng = new google.maps.LatLng(53.776186, -3.6);
    var myOptions = {
        zoom: 5,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    // ajax call to database for scheme info.
    RetrieveSchemeInformation(map, schemeRequestId); // schemeRequestId is from scheme/index.aspx for booking details page.

    $("#btnSchemeBooking").css('visibility', "hidden");
}

$(document).ready(function () {

    /* add an icon to the button */
    $('#btnRefresh').button({
        icons: {
            primary: "ui-icon ui-icon-refresh"
        }
    });

    $('#btnSchemeBooking').button({
        icons: {
            secondary: "ui-icon-circle-arrow-e"
        }
    });

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&region=gb&callback=initialize";
    document.body.appendChild(script);
});

function RetrieveSchemeInformation(map, schemeRequestId) {

    startAnim();

    var request = $.ajax({
        type: "GET",
        url: "Scheme/GetSchemes/",
        data: { id: schemeRequestId },
        dataType: "json",
        error: function (xhr, status, error) {
            alert(status);
            alert(xhr.statusText);
            stopAnim();
        },
        success: function (json) {
            AddMapOverlays(json, map, schemeRequestId);
            stopAnim();
        }
    });
}

function AddMapOverlays(json, map, schemeRequestId) {

    var markerArray = [], polygonArray = [], selectedMarker = null;

    // for each scheme returned.
    $.each(eval(json), function () {

        var cord = this.CenterLocation.split(",");
        var myCord = new google.maps.LatLng(cord[0], cord[1]);

        var marker = new google.maps.Marker({
            position: myCord,
            map: map,
            title: this.SchemeName
        });

        markerArray.push(marker);

        // get handle on scheme object.
        var myScheme = this;

        // this block of code is used for displaying by default a scheme that has been requested from the booking details page.
        if (schemeRequestId != '') {
            if (schemeRequestId == myScheme.Id) {
                map.setZoom(10);
                map.setCenter(myCord);
                // make sure there are polygon cords.
                //if (myScheme.PolygonCords != null) {
                    //viewSchemePolygon(myScheme.PolygonCords, map);
                    drawOperatingAreasOnMap(myScheme.OperatingAreas, map, polygonArray);
                //}

                //hideOtherMarkers(markerArray, marker);
                selectedMarker = changeSelectedMarker(selectedMarker, marker);
                displaySchemeInformation(myScheme);
                //return false;
            }
            //return;
        }

        // add listener to markers click event
        google.maps.event.addListener(marker, 'click', function () {
            map.setZoom(10);
            map.setCenter(myCord);
            // make sure there are polygon cords.
            //if (myScheme.PolygonCords != null) {
            //viewSchemePolygon(myScheme.PolygonCords, map);
            drawOperatingAreasOnMap(myScheme.OperatingAreas, map, polygonArray);
            //}

            //hideOtherMarkers(markerArray, marker);
            selectedMarker = changeSelectedMarker(selectedMarker, marker);
            displaySchemeInformation(myScheme);
        });
    });
}

function changeSelectedMarker(current, newSelected) {
    if (current != null) {
        current.setIcon(null);
    }

    newSelected.setIcon(selectedIconImage);
    return newSelected;
}

function hideOtherMarkers(markerArray, marker) {
    for (var i = 0; i < markerArray.length; i++) {
        // hide other markers than current
        if (markerArray[i] != marker) {
            markerArray[i].setMap(null);
        }
    }
}

// Draws all the operating areas on map.
// Coordinate string format: "lat,lng:lat,lng:lat,lng"...
function drawOperatingAreasOnMap(operatingAreas, map, polygonArray) {
    var coordArray, arrCoord, i = 0, latLng = null, schemeArea = null, schemeCoords = null;

    hideAndRemovePreviousPolygons(polygonArray);

    $.each(operatingAreas, function (index, item) {
        schemeCoords = new Array();
        coordArray = item.Coordinates.split(":");

        // create latlng from coordinate strings (divided by ',')
        for (i = 0; i < coordArray.length; i++) {
            arrCoord = coordArray[i].split(",");
            latLng = new google.maps.LatLng(arrCoord[0], arrCoord[1]);
            schemeCoords.push(latLng);
        }

        // Construct the polygon 
        // Note that we don't specify an array or arrays, but instead just 
        // a simple array of LatLngs in the paths property 
        schemeArea = new google.maps.Polygon({
            paths: schemeCoords,
            strokeColor: "#3A4045",
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: "#C0C0C0",
            fillOpacity: 0.35
        });

        polygonArray.push(schemeArea);
        schemeArea.setMap(map);
    });
}

function hideAndRemovePreviousPolygons(polygonArray) {
    $.each(polygonArray, function (index, item) {
        item.setMap(null);
    });

    // empty
    polygonArray.splice(0, polygonArray.length);
}

function resetMap() {
    schemeRequestId = '';
    $("#schemeInformation").css("display", "none");
    initialize();
}

function displaySchemeInformation(myScheme) {

    /*---------------------------------------------
       scheme types as defined in database.
       0=public, 1=publicWithMembership, 2=private
    ----------------------------------------------*/
    var schemeType = schemeType = "<span class='error'><b>Private Scheme</b></span>, you will need to contact the scheme if you wish to apply for its services.";
    
    switch (myScheme.SchemeType) {
        case 0:
            schemeType = "Public Scheme"
            break;
        case 1:
            schemeType = "Public Scheme With Membership"
            break;
    }

    var bookingBtnVisibility = (myScheme.BookingUrlValid ? "visible" : "hidden");
    $("#btnSchemeBooking").css('visibility', bookingBtnVisibility);
    
    $("#schemeInformation").css("visibility", "visible");
    $("#schemeInformation").css("display", "block");
    $("#schemeName").text(myScheme.SchemeName);
    $("#schemeDescription").html(myScheme.Description);
    $("#schemeType").empty().html(schemeType);
    $("#schemeEmail").empty().html("<a href='mailto:" + myScheme.Email + "'>" + myScheme.Email + "</a>");
    $("#schemeTelephone").empty().html(myScheme.Telephone);
    $("#schemeLogo").empty().html("<img src='http://www.opendrt.co.uk/UIContent/Images/" + myScheme.Id + ".gif' alt='Scheme logo' />");

    /* make sure valid url address */
    $("#schemeWebsite").empty(); // empty in any case
    if (myScheme.Website != null && isUrl(myScheme.Website))
        $("#schemeWebsite").html("<a href='#' onclick=displayWebsite('" + myScheme.Website + "')>Visit Website</a>");

    /* make sure valid url address for pricing url */
    $("#schemePriceURL").empty(); // empty in any case
    if (myScheme.PricingURL != null && isUrl(myScheme.PricingURL))
        $("#schemePriceURL").html("<a href='#' onclick=displayWebsite('" + myScheme.PricingURL + "')>Click here</a>");

    // update scheme id for selected scheme.
    schemeRequestId = myScheme.Id;
}

function startAnim() {
    $("#ajaxBusy").css("visibility", "visible");
    $("#ajaxBusy").css("display", "block");

}

function stopAnim() {
    $("#ajaxBusy").css("visibility", "hidden");
    $("#ajaxBusy").css("display", "none");
}

function displayWebsite(url) {
    window.open(url, "schemeSite");
    return false;
}

function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

function bookWithScheme() {
    window.location.href = "Scheme/BookWithScheme?id=" + schemeRequestId + "&name=" + $("#schemeName").text();
    return;
}

