﻿//GoogleMapsV2.js
// Doug Rathbone - Alpha Salmon


var homeTitle;
var homeInfoHtml;


var map = null;
var mgr = null;


var station = true;
var app;
var prefix_image_file = "";

var icon_train_station = "/asset/img/googlemaps/icon_train_32.png";
var icon_shadow_train_station = "/asset/img/googlemaps/icon_shadow_32.png";
var icon_hotels = "/asset/img/googlemaps/icon_accommodation_32.png";
var icon_shadow_hotels = "/asset/img/googlemaps/icon_shadow_32.png";

//var icon_home = "/asset/img/layout/club_24.gif";
var icon_home = "/asset/img/googlemaps/icon_horseracing_32.png";


var icon_shadow_home = "/asset/img/googlemaps/icon_shadow_32.png";

var icon_shadow_default = "/asset/img/googlemaps/icon_shadow_32.png";

var main_marker;
var stateObject;
var locationObject;
var allmarkers = [];

var zoomLevelMedium = 7;
var zoomLevelLocation = 15;


function createMarker(posn, title, icon_image, icon_image_shadow) {
    var icon = getIcon(icon_image, icon_image_shadow);
    var marker = new GMarker(posn, { title: title, icon: icon, draggable: false });
    return marker;
}





function method_closure(object, method, opt_argArray) {
    return function() {
        return method.apply(object, opt_argArray);
    }
}

function getIcon(imgFile, shadowFile) {
    var icon = new GIcon();
    
    icon.iconAnchor = new GPoint(16, 16);
    icon.infoWindowAnchor = new GPoint(16, 0);
    
    if (imgFile!=null) {
        icon.image = prefix_image_file + imgFile;
        icon.iconSize = new GSize(49, 49);
    }
    else {
        icon.image = prefix_image_file + "/touristmap/asset/pin-icon.gif";
        icon.iconSize = new GSize(33, 39);
    }
    icon.shadow = prefix_image_file + shadowFile;
    icon.shadowSize = new GSize(59, 32);
    return icon;
}




function takeACloserLook(latitude, longitude, zoomLevel) {
    var center = new GLatLng(latitude, longitude)
    map.setCenter(center, zoomLevel);
}



function createMap(divObjectID, centralPointGLat, centralPointGLng, centralPointHtml) {
    $(document).ready(function() {
        var divMap = document.getElementById(divObjectID);
        if (divMap != null && GBrowserIsCompatible()) {

            map = new GMap2(divMap);
            map.enableContinuousZoom()
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            map.setMapType(G_NORMAL_MAP);
            var center = new GLatLng(centralPointGLat, centralPointGLng)

            map.setCenter(center, 4);
            mgr = new MarkerManager(map);

            //position the flickr overlay
            var pos = $("#" + divObjectID).offset();
            var width = $("#" + divObjectID).width();
            $("#FlickrInner").css({ "left": ((pos.left + width)-210) + "px", "top": (pos.top+30) + "px" });
        }
        return;
    });
}

function setupMarkersAll() {
    $(document).ready(function() {
        $.ajax({
            type: "POST",
            url: "/touristmap/touristmap.asmx/GetAllPointsOnMap",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
                //alert(response);
                var pointsOnMap = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : eval(response);

                allmarkers.length = 0;
                for (var i in pointsOnMap) {
                    var layer = pointsOnMap[i];
                    var markers = [];

                    for (var j in layer["Places"]) {
                        var place = layer["Places"][j];

                        var icon_img, icon_shadow_img, homeTypeLower;
                        icon_img = (place["Icon"]!="") ? place["Icon"] : "";
                        icon_shadow_img = (place["IconShadow"] != "") ? place["IconShadow"] : "";

                        var icon = getIcon(icon_img, icon_shadow_img);
                        var title = place["LocationName"];
                        var posn = new GLatLng(place["Latitude"], place["Longitude"]);

                        var marker = createMarker(posn, title, icon, place["CoOrdType"], place["LocationID"]);
                        markers.push(marker);
                        allmarkers.push(marker);
                    }
                    mgr.addMarkers(markers, layer["Zoom"][0], layer["Zoom"][1]);
                }
                mgr.refresh();
            },
            failure: function(msg) {
                alert("There was an error loading the information points on the map. Please refresh the page to try again");
            }
        });
    });
}
function createMarker(posn, title, icon, type, refID) {
    if (type == "state") {
        var marker = new GMarker(posn, {
            title: title,
            icon: icon//,
            //draggable: true
        });
    }
    else {
        var marker = new GMarker(posn, {
            title: title,
            icon: icon
        });
    }
    
    
    if (type == "state") {

        GEvent.addListener(marker, "click",
            function() {
                stateObject = this;
                WebServices.TouristMap.GetStateContentPopup(refID, StateCallBack);
            }
          );
        GEvent.addListener(marker, "dblclick",
            function() {
            takeACloserLook(posn.lat(), posn.lng(), zoomLevelMedium);
            }
          );
 
    }
    else if (type=="location"){
    GEvent.addListener(marker, "click",
            function() {
                locationObject = this;
                var newCenter = new GLatLng(posn.lat()+0.005, posn.lng() + 0.009);
                map.setCenter(newCenter);
                $("#divFlickr").show();
                flickrExecute(refID, "divFlickr");
                WebServices.TouristMap.GetLocationContentPopup(refID, LocationCallBack);

            }
          );
            GEvent.addListener(map, "infowindowclose",
            function() {
                if ($("#divFlickr").css('display') != 'none') {
                        $("#divFlickr").hide();
                    }
            });

    }
    else if (type == "midlocation") {
        GEvent.addListener(marker, "click",
            function() {
                locationObject = this;
                WebServices.TouristMap.GetMidLocationContentPopup(refID, MidLocationCallBack);
            });
        GEvent.addListener(marker, "dblclick",
            function() {
                takeACloserLook(posn.lat(), posn.lng(), zoomLevelLocation);
            }
          
          );
    }

    return marker;
}

function OpenShadowBox(url, width, height) {
    Shadowbox.open({
        content: url,
        player: "iframe",
        title: "",
        height: height,
        width: width
    });

}

function StateCallBack(results) {
    stateObject.openInfoWindowHtml(results);
}
function LocationCallBack(results) {
    var title = results[0];
    if (title.length > 20) {
        title = title.substring(0, 17) + "...";
    }
    $("#spnTitle").html(title);
    locationObject.openInfoWindowHtml(results[1]);
    
}
function MidLocationCallBack(results) {
    locationObject.openInfoWindowHtml(results);
}


function viewStateInfo(stateID) {
    OpenShadowBox("/touristmap/stateinformation.aspx?state="+stateID, 530 ,500);
}
function showMarkers() {
    mgr.show();
}





///////////////////////////////////////////FLICKR IMAGES

var flickrImageCount = 0;
var flickrTotalPages = 1;
var flickrCurrentPage = 1;
var flickrImagesPerPage = 20;
var flickrCurrentLocationID = 0;
var flickrContainer = null;
var flickrThrobber = "<img src=\"/touristmap/asset/ajax-loader.gif\" style=\"margin:0 auto;display:block;\"/>";
var flickrIsLoaded = false;

function flickrExecute(locationID, divID) {
    if (!flickrIsLoaded || flickrCurrentLocationID!=locationID)
    {
        flickrContainer = document.getElementById(divID);
        flickrCurrentLocationID = locationID;
        flickrLoad(flickrCurrentLocationID, flickrCurrentPage, flickrImagesPerPage);
        flickrIsLoaded = true;
    }
}
function flickrHide(locationID) {
}

function flickrLoad() {
    $("#flickrImages").html(flickrThrobber);
    $.ajax({
        type: "POST",
        url: "/touristmap/touristmap.asmx/GetFlickrImagesForLocation",
        data: "{'locationID':'" + flickrCurrentLocationID + "','pageSize':'" + flickrImagesPerPage + "','currentPage':'" + flickrCurrentPage + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            //alert(response);
            var images = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : eval(response);

            $("#flickrImages").html("");
            $("#flickrImages").append();
            for (var i in images) {
                var outputHTML = "<li><a href=\"{0}\"><img src=\"{1}\" alt=\"\"/></a></li>";

                //var outputHTML = "<div style=\"float:left;\"><a href=\"{0}\"><img src=\"{1}\"></a></div>";
                var linkToInsert = "javascript: OpenShadowBox('/touristmap/flickrimagedetailpage.aspx?image=" + images[i].LocalImageID + "', '500', '500');";
                var output = String.format(outputHTML, linkToInsert, images[i].ImageThumbURL)
                $("#flickrImages").append(output);
            }
            $("#flickrImages").html("<ul class=\"images\">" + $("#flickrImages").html() + "</ul>");
            flickrUpdateStats(flickrCurrentLocationID);
        },
        failure: function(msg) {
            //msg
        }
    });

}

function flickrControlPrevious() {
    if (flickrCurrentPage > 1) {
        $("#flickrImages").html(flickrThrobber);
        flickrCurrentPage = flickrCurrentPage - 1;
        flickrLoad();
    }
}
function flickrControlNext() {
    if (flickrCurrentPage < flickrTotalPages) {
        $("#flickrImages").html(flickrThrobber);
        flickrCurrentPage = flickrCurrentPage + 1;
        flickrLoad();
    }
}
function flickrSetImagesPerPage(imagesPerPage) {
    flickrImagesPerPage = imagesPerPage;
    flickrCurrentPage = 1;
    flickrLoad();
}
function flickrUpdatePageStats() {
    var format = "<span>{0}</span>/{1}";
    $("#divFlickrImageCount").html(String.format(format,flickrCurrentPage,flickrTotalPages));
}
function flickrUpdateStats(locationID) {
    $.ajax({
        type: "POST",
        url: "/touristmap/touristmap.asmx/GetTotalFlickrPicsForLocation",
        data: "{'locationID':'" + flickrCurrentLocationID + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            //set the total image count
            flickrImageCount = parseInt(response);
            //calculate the total amount of pages
            flickrTotalPages = parseInt(flickrImageCount / flickrImagesPerPage);
            flickrTotalPages = (flickrImageCount % flickrImagesPerPage > 0) ? flickrTotalPages + 1 : flickrTotalPages;

            flickrUpdatePageStats();
        },
        failure: function(msg) {
            //do nothing
        }
    });
}

////////////////AJAX FORMS
function SubmitFlickrImage(name, imageURL, locationID) {

    if (Page_ClientValidate()) {
        $("#divForm").animate({ top: "hide", opacity: "hide" }, 500, function() {
            $("#divThrobber").show();
        });
        WebServices.TouristMap.PostNewFlickrPick(imageURL, name, locationID, SubmitFlickrCallBack);
        return false;
    }

}
function FlickrSubmissionStartAgain(nameField,urlField) {
    $("#" + nameField).val("");
    $("#" + urlField).val("");
    $("#divThankyou").hide();
    $("#divForm").animate({ top: "show", opacity: "show" }, 500);

}
function SubmitFlickrCallBack(results) {
    if (results[0] == "true") {
        $("#divThrobber").hide();
        $("#divThankyou").animate({ top: "show", opacity: "show" }, 500);
    }
    else {
        if (results.length > 1) {
            alert(results[1]);
            $("#divThrobber").hide();
            $("#divThankyou").animate({ top: "show", opacity: "show" }, 500);
        }
        else {
            alert("There was an error while trying to submit your image, please try again");
            $("#divThrobber").hide();
            $("#divThankyou").animate({ top: "show", opacity: "show" }, 500);
        }
        $("#divThrobber").hide();
        $("#divForm").animate({ top: "show", opacity: "show" }, 500);
    }
}

/////////// AUTO COMPLETE
var SearchPointFound = false;
var SearchPointCoords = null;


$(document).ready(function() {
    var SearchFieldID = $(".dropDown").attr("id");
    $("#inpSearchWord").autocomplete("/touristmap/SearchHandler.aspx", {
        width: 189,
        max: 4,
        highlight: false,
        scroll: true,
        scrollHeight: 300,
        mustMatch: true//,
        //extraParams: { state: document.getElementById(SearchFieldID).options[document.getElementById(SearchFieldID).selectedIndex].text }
    });
});



function GoToSearch(StateField) {
    if ($("#inpSearchWord").val() == "") {
        var response = $("#" + StateField).val();
        var newCoords = eval("("+response+")");
        var newCenter = new GLatLng(newCoords.latitude, newCoords.longitude);
        map.setCenter(newCenter, zoomLevelMedium);
    }
    else {
        //alert($("option:selected", ".dropDown").text());
        $.ajax({
            type: "POST",
            url: "/touristmap/touristmap.asmx/GetKeyWordCoordinates",
            data: "{'search':'" + $("#inpSearchWord").val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
                var newCoords = eval("(" + response + ")");
                var newCenter = new GLatLng(newCoords.latitude, newCoords.longitude);
                map.setCenter(newCenter, zoomLevelLocation);                
            },
            failure: function(msg) {
                alert("We were unable to find your location, please try another phrase");
            }
        });
    }
}

function viewStateGallery(stateName)
{
var calss="."+stateName+" a:first";
$(calss).click();
}