﻿//One Stop Shop for modifying info related to the tour/map cookies, and adding that content to the map.
function MapTour(objMap, oButtons, isMapped)
{
    if (isMapped == null)
    {
        isMapped = true;
    }
    this.test = "ugo";
    this.directions = null;
    this.line = null;
    this.stops = new Hash();
    this.orderedTour = (MapTour.tourCookie.get("list") == null || MapTour.tourCookie.get("list") == '') ? [] : MapTour.tourCookie.get("list").split("|");
    this.tour = new Hash();
    this.mgr = null;

    for (var i=0; i < this.orderedTour.length; i++)
    {
        this.tour.set(this.orderedTour[i], 1);
    }
    
    MapTour.setMyTourNumber(this.orderedTour.length);

    if (isMapped)
    {
        this.map = objMap;

        //validate oOpts, and set defaults if needed.
        if (!oButtons) { var oButtons = {}; }
        this.imageRoot = "/_i/_markers/";
        this.standardImage = (oButtons.standard) ? oButtons.standard : this.imageRoot + "beach.png";
        this.tourImage = (oButtons.tour) ? oButtons.tour : this.imageRoot + "stop.png";

        this.baseIcon = new GIcon();
        this.baseIcon.shadow = this.imageRoot + "shadow.png";
        //this.baseIcon.transparent = "/gmap/markers/marker-1-percent.png";
        this.baseIcon.imageMap = [4,3,19,3,13,37];
        this.baseIcon.iconSize = new GSize(21, 31);
        this.baseIcon.shadowSize = new GSize(52, 29);
        this.baseIcon.iconAnchor = new GPoint(7, 32);
        this.baseIcon.infoWindowAnchor = new GPoint(11, 5);
        this.baseIcon.infoShadowAnchor = new GPoint(14, 34);
    }
}
MapTour.tourCookie = new Hash.Cookie('ugotour',{path: "/"});
//Class method for modifying the tour cookie. 
//	Returns the current tour count.
MapTour.setTourCookie = function(arrTour)
{
    MapTour.tourCookie.set("list",arrTour.join("|"));			
};

MapTour.setMyTourNumber = function(tourlength)
{
    document.getElementById("mytournumber").innerHTML = tourlength;
};

//oOpts is an object literal taking the following values:
//	adjust: bool - whether to zoom/pan to encompass the new points.
//	bubble: bool - whether to create an overlay bubble for each point.
//	line: bool - whether to draw a direction line between the points.
//	tourmarkers: bool - whether to display the special tour markers.
//	maxzoom: num - when adjusting, dont zoom any further than this (defaults to 11)
//	adjustzoom: num - adjusts the zoom by this value. can be positive or negative. (defaults to 0)
//	returnfunc: function - pass a function to call when the operation completes.
MapTour.prototype.placePoints = function(sQueryString, oOpts)
{
    //first save current criteria to a cookie.
    //query and add new marker set
    var _this = this;
    if (GBrowserIsCompatible()) {
        //get the data via ajax.
        GDownloadUrl(sQueryString, function(data, response) { _this._placePoints(data, response, oOpts); });
    }
};

function debug(msg)
{
    document.getElementById("test").innerHTML += msg+"<br>";
}

//inner function. called ansync from placePoints().
MapTour.prototype._placePoints = function(data, responseCode, oOpts) {

    //validate oOpts, and set defaults if needed.
    if (!oOpts) { var oOpts = {}; }
    if (!oOpts.adjustzoom) { oOpts.adjustzoom = 0; }
    if (!oOpts.maxzoom) { oOpts.maxzoom = 11; }

    //remove any existing markers
    this.clearMarkers();

    if (this.mgr == null)
    {
        this.mgr = new MarkerClusterer(this.map);
    }
    var linePoints = [];
    var points = eval(data); //data is returned in json format.

    var bPlacedPoints = false;
    var stops = [];
    for (var i=1; i < points.length; i++)
    {
        bPlacedPoints = true;
        if (this.tour.hasKey(points[i]["StopId"])) {
            var icon = new GIcon(this.baseIcon,this.tourImage);
        } else if (points[i]["CategoryIcon"] != "") {
            var icon = new GIcon(this.baseIcon, this.imageRoot + points[i]["CategoryIcon"]);
        } else {
            var icon = new GIcon(this.baseIcon,this.standardImage);
        }
        
        var tempPoint = new GLatLng(points[i]["Lat"], points[i]["Lng"]);
        linePoints.push(tempPoint); //add to the line array, in case we want to add a line overlay.

        var marker = new Hash();

        if (oOpts.tourmarkers)
        {
            marker.set("marker",new LabeledMarker(tempPoint, {title: points[i]["Name"], icon: icon, labelText: i, labelOffset: new GSize(-20,-33)}));
        } else {
            marker.set("marker",new GMarker(tempPoint, {title: points[i]["Name"], icon: icon}));
        }

        this.stops.set(points[i]["StopId"],marker);
        stops.push(this.stops.get(points[i]["StopId"]).get("marker"));
        //this.map.addOverlay(this.stops.get(points[i]["StopId"]).get("marker"));

        //add an event listener for this marker, so that we know to load the content when it is clicked.
        if (oOpts.bubble)
        {
            marker.set("clickhandler",GEvent.addListener(this.stops.get(points[i]["StopId"]).get("marker"), "click", GEvent.callbackArgs(this,this.loadBubbleContent, points[i]["StopId"])));
        }
    }
    
    this.mgr.addMarkers(stops);
    //this.mgr.refresh();
    //this.mgr.resetViewport();

    if (oOpts.line && points.length > 2)
    {
        //initialize directions the first time this is done
        if (this.directions == null) { this.directions = new GDirections(); }
        
        //query for line.
        this.directions.loadFromWaypoints(linePoints, {getPolyline: true});

        //onload, add line.
        GEvent.bind(this.directions, "load", this, function() {
            this.line = this.directions.getPolyline();
            this.map.addOverlay(this.line);

            //if adding a line, do the auto-adjust based on the bounds for the polyline.
            if (oOpts.adjust)
            {
                this.adjustMap(this.line.getBounds(),oOpts);
            }
        });	
    }
    else if (oOpts.adjust && points[0]["minLat"] != '' && points[0]["minLat"] != '999') {
        
        //set the center and zoom, using the bounds retrieved in the first array item.
        // first adjust the values so that they fit within the view box with some roon to spare.
        var minLat = parseFloat(points[0]["minLat"]);
        var minLng = parseFloat(points[0]["minLng"]);
        var maxLat = parseFloat(points[0]["maxLat"]);
        var maxLng = parseFloat(points[0]["maxLng"]);

        var bounds = new GLatLngBounds(new GLatLng(minLat,minLng),new GLatLng(maxLat,maxLng));
        this.adjustMap(bounds,oOpts);
    }

    //If the caller specified a function to call on completion, call it now, and pass whether any points were placed by the function.
    if (oOpts.returnfunc)
    {
        oOpts.returnfunc(bPlacedPoints);
    }
};

MapTour.prototype.loadBubbleContent = function(objStop)
{
    var markerData = this.stops.get(objStop);
    GEvent.removeListener(markerData.get("clickhandler"));

    markerData.set("bubble", new Element('div'));
    var _this = this;
    markerData.get("bubble").innerHTML = 'Loading UGoStop information...';		
    GDownloadUrl("_s/stop_data.ashx?details=yes&s="+objStop, function(data, response) { 
        var points = eval(data); //data is returned in json format.
        var currPoint = points[1];
        
        bPlacedPoints = true;
        var sAddToTour = '';
        if (_this.tour.hasKey(currPoint["StopId"])) {
            sAddToTour = '<a href="/myugotour/mytour.aspx" class="button tourbutton">View Trip</a>';
        } else {
            sAddToTour = '<a href="#" class="button tourbutton">Add to My Trip</a>';
        }
        
        var imgTxt = (currPoint["PhotoURL"] != "") ? '<img src="'+currPoint["PhotoURL"]+'">' : "";
        
        //Start building up a string to contain the HTML for the bubble's innards. This will have different contents depending on whether there's an image.
        var displayString=''; 
        
        displayString = '<div class="descBalloon" name="blurb"><h3 style="font-weight: bold;">'+currPoint["Name"]+'</h3>';
    
            if (imgTxt != "") {
                displayString += '<div class="balloon left" name="text">'+currPoint["Description"]; 
            } else {
                displayString += '<div class="balloon" name="text">'+currPoint["Description"];
            }
    
            if (imgTxt != "") {
                displayString += '</div><div class="balloon right" name="image">'+imgTxt;
            }
        
        var cleanedStopName = currPoint["Link"];//currPoint["Name"].replace(/[^\w\s]+/g,"").replace(/[\s]+/g,"-").toLowerCase();
        displayString += '</div><div style="clear: both;"></div><div class="balloon left mapbutton" name="text"><div class="mapbutton"><a href="'+cleanedStopName+'" class="button">View Stop</a></div></div><div class="balloon right mapbutton" name="buttonright"><div class="mapbutton">'+sAddToTour+'</div></div><div style="clear: both;"></div></div>';

        markerData.get("bubble").innerHTML = displayString;

        markerData.get("bubble").getElement("a.tourbutton").addEvent("click", _this.addPointToTour.bindWithEvent(_this,currPoint["StopId"]));

        markerData.get("marker").bindInfoWindow(markerData.get("bubble"));
        markerData.get("marker").openInfoWindow(markerData.get("bubble"));
    });

    markerData.get("marker").openInfoWindow(markerData.get("bubble"));

};

MapTour.prototype._loadBubbleContent = function(data, response) { };

MapTour.prototype.clearMarkers = function()
{
    //remove any existing markers
    if (this.mgr != null)
    {
        this.mgr.clearMarkers();
    }
    var _this = this;
    this.stops.each(function(val, key) { _this.map.removeOverlay(val.get("marker"));});
    this.stops.empty();
    if (this.line != null)
    {
        this.map.removeOverlay(this.line);
    }
};

MapTour.prototype.adjustMap = function(bounds, oOpts)
{
    var zoom = this.map.getBoundsZoomLevel(bounds);
    //adjusting the zoom to be sure that all points fit in the box.
    //	also, don't let the zoom level be any higher than 11. otherwise it gets confusing.
    if (zoom <= oOpts.maxzoom) {
        zoom = zoom + oOpts.adjustzoom;
    } else {
        zoom = oOpts.maxzoom;
    }
    this.map.setCenter(bounds.getCenter(),zoom);
};

MapTour.prototype.addPointToTour = function(event,stopId) {

    //add the point
    if (!this.tour.hasKey(stopId)) {
        this.orderedTour.push(stopId);
        this.tour.set(stopId,1);

        MapTour.setTourCookie(this.orderedTour);		
    }

    var markerData = this.stops.get(stopId);
    //change the icon
    markerData.get("marker").setImage(this.tourImage);
    
    //change the bubble text
    if (markerData.hasKey("bubble"))
    {
        var tourlink = markerData.get("bubble").getElement("a.tourbutton");
        
        var newtourlink = new Element("a", {'class': 'button', 'href':'/myugotour/mytour.aspx'});
        newtourlink.innerHTML = "View Trip";
        
        newtourlink.injectBefore(tourlink);
        tourlink.remove();	
    }

    //change the number in the nav.
    MapTour.setMyTourNumber(this.orderedTour.length);
    //MapTour.setTourDetails(markerData.get("marker").getTitle());
    
    return false;
};

MapTour.prototype.addPointToTourNoBubble = function(stopId, link) {

    //add the point
    if (!this.tour.hasKey(stopId)) {
        this.orderedTour.push(stopId);
        this.tour.set(stopId,1);
        MapTour.setTourCookie(this.orderedTour);
        var newLink = new Element("a", {'class': 'button', 'href':'/myugotour/mytour.aspx'});
        newLink.innerHTML = "View Trip";
        newLink.injectBefore(link);
        link.remove();
    }

    //change the number in the nav.
    MapTour.setMyTourNumber(this.orderedTour.length);
    //MapTour.setTourDetails(markerData.get("marker").getTitle());
    
    return false;
};


//If bUseTour, will map the current tour. Otherwise, will map the first stop. (There should only be one in cases where this is used)
MapTour.prototype.directionsPop = function(startDirections, bUseTour) 
{
    var queryTxt = "http://maps.google.com/maps?saddr="+startDirections;
    var bFirstWaypoint = true;

    var arrDirections = [];
    if (bUseTour)
    {
        this.orderedTour = MapTour.tourCookie.get("list").split("|");
        for (var i=0; i < this.orderedTour.length; i++)
        {
            if (this.stops.get(this.orderedTour[i]))
            {
                arrDirections.push(this.stops.get(this.orderedTour[i]).get("marker"));
            }
        }
    } else {
        var tempArr = this.stops.values();
        arrDirections.push(tempArr[0].get("marker"));
    }

    for (var i=0; i < arrDirections.length; i++)
    {
        if (bFirstWaypoint) {
            queryTxt += "&daddr=";
            bFirstWaypoint = false;
        } else {
            queryTxt += "+to:";
        }
        queryTxt += encodeURIComponent(arrDirections[i].getTitle()+"@")+arrDirections[i].getPoint().lat()+","+arrDirections[i].getPoint().lng();
    }

    var newwindow = window.open(queryTxt,'name');
    if (window.focus) { newwindow.focus(); }
};

function toggleElement(id, bValue)
{
      var targetObj = document.getElementById(id);
      if (targetObj.style.display == "none")
      {
        targetObj.style.display = "block";
      }
      else
      {
        targetObj.style.display = "none";
      }
}

function setPhoto(targetObjId, src)
{
    var targetObj = document.getElementById(targetObjId)
    targetObj.src = src;
}
