﻿// JScript File

function RegionalCenter(id, name, lat, lng, junction) {
    this.Name = name || "unknown";
    this.Id = id || -1;
    this.Lat = lat || 0;
    this.Lng = lng || 0;
    this.Point = new GLatLng(this.Lat, this.Lng);
    this.selected = false;
    this.highlighted = false;
    this.Circle;
    this.marker = null;
    this.endpoints = new Array();

    if (junction) {
        this.CreateMarker = function() {
            var point = new GLatLng(this.Lat, this.Lng);
            var icon = null;
            var lat = this.Lat;
            var lng = this.Lng;
            var marker = new GMarker(point, { icon: getJunctionIcon(), clickable: false });
            var name = this.Name;

            this.marker = marker;
            return marker;
        }
        return;
    }

    this.CreateMarker = function() {
        var point = new GLatLng(this.Lat, this.Lng);
        var icon = null;
        var lat = this.Lat;
        var lng = this.Lng;
        var marker = new GMarker(point, { icon: getIcon() });
        var name = this.Name;

        GEvent.addListener(marker, "click", function() {

            var html = "<div class='infowindow' style='width:250px; border:solid 1px #999999; margin:3px; padding:5px;'><span style='color: #000000;'><b>" + name + "</b></span><br /><br />"; //class='infowindow'
            html += "To learn more about the amenities in this area, go to ";
            html += "<a target='_blank' href='http://www.walkscore.com/get-score.php?street=" + lat + "%2C+" + lng + "&go=Go' style='text-decoration:underline'>Walk Score</a>.<br /><br />";
            html += "This web site catalogues amenities that create walkable neighborhoods.";

            var header = "<div style='margin:0px; padding:0px;'><span style='color: #000000;'><b>" + name + "</b></span><br /><br />";
            var tab1 = new GInfoWindowTab("Info", '<div id="tab1">' + html + '</div>');
            var tab2 = new GInfoWindowTab("MapTab", '<div>' + header + '</div><div id="detailmap"></div>');
            var infoTabs = [tab2, tab1];
            var size = new GSize(50, 50);
            try {
                _gmap.openInfoWindowTabsHtml(marker.getLatLng(), infoTabs, { pixelOffset: new GSize(0, -2) });
                //marker.openInfoWindowTabsHtml(infoTabs, { "pixelOffset": size });
                var detailMap;
                var dMapDiv = $("#detailmap")[0];
                if (dMapDiv) {
                    detailMap = new GMap2(dMapDiv);
                    //Perhaps add a timeout here to let the map load?

                    detailMap.setCenter(point, 14);
                    detailMap.setMapType(G_HYBRID_MAP);
                    detailMap.addControl(new GSmallMapControl());

                    var CopyrightDiv = dMapDiv.firstChild.nextSibling;
                    var CopyrightImg = dMapDiv.firstChild.nextSibling.nextSibling;
                    CopyrightDiv.style.display = "none";
                    CopyrightImg.style.display = "none";
                }
            }
            catch (e) {
                //Proceed
            }
        });

        GEvent.addListener(marker, "mouseover", function() {
            handleRegionalCenterHover(name);
        });

        GEvent.addListener(marker, "mouseout", function() {
            handleRegionalCenterHoverOut(name);
        });

        this.marker = marker;
        return marker;
    }

    this.AddEndPointNames = function(endpointNames) {
        this.endpoints.push(endpointNames);
    }

    //Selected is when part of a trip
    this.SetSelected = function(blnSelected) {
        this.selected = blnSelected;
        //Add Highlighed Color if true
        if (this.selected) {
            this.marker.setImage(_regionalCenterMarkerHighlight);
        }
        else {
            this.marker.setImage(_regionalCenterMarkerImage);
        }
    }

    this.IsSelected = function() {
        return this.selected;
    }

    this.IsHighlighted = function() {
        return this.highlighted;
    }
}

function RegionalCenters() {
    this.centers = new Array();
    this.selectedCount = 0;
    this.highlightedCount = 0;
    
    this.Add = function(regionalCenter) {
        this.centers.push(regionalCenter);
    }

    this.Count = function() {
        return this.centers.length;
    }

    this.ClearSelected = function() {
        for (var i = 0; i < this.centers.length; i++) {
            this.centers[i].SetSelected(false);
        }
        this.selectedCount = 0;
    }
    
    this.FindByName = function(regionalCenterName) {
        var regionalCenter = null;
        for (var i = 0; i < this.centers.length; i++) {
            if (this.centers[i].Name == regionalCenterName) {
                regionalCenter = this.centers[i];
                break;
            }
        }
        return regionalCenter;
    }

    this.FindByID = function(Id) {
        var regionalCenter = null;
        for (var i = 0; i < this.centers.length; i++) {
            if (this.centers[i].Id == Id) {
                regionalCenter = this.centers[i];
                break;
            }
        }
        return regionalCenter;
    }

    this.GetItem = function(i) {
        return this.centers[i];
    }

    this.GetSelectedCenters = function() {
        var selCenterArray = new Array();
        for (var i = 0; i < this.centers.length; i++) {
            if (this.centers[i].IsSelected()) {
                selCenterArray.push(this.centers[i]);
            }
        }
        return selCenterArray;
    }
    
    this.GetHighlightedCenters = function() {
        var selCenterArray = new Array();
        for (var i = 0; i < this.centers.length; i++) {
            if (this.centers[i].IsHighlighted()) {
                selCenterArray.push(this.centers[i]);
            }
        }
        return selCenterArray;
    }

    this.SelectedCount = function() {
        var sc = 0;
        for (var i = 0; i < this.centers.length; i++) {
            if (this.centers[i].IsSelected()) {
                sc++;
            }
        }
        this.selectedCount = sc;
        return this.selectedCount;
    }
    
    this.HighlightedCount = function() {
        var hc = 0;
        for (var i = 0; i < this.centers.length; i++) {
            if (this.centers[i].IsHighlighted()) {
                hc++;
            }
        }
        this.highlightedCount = hc;
        return hc;
    }
}

function Corridor(id, name, segId) {
    this.Id = id || -1;
    this.Name = name || "unknown";
    this.visible = true;
    this.Line = null;
    this.PolyLine = null;
    this.Vertices = new Array();
    this.defaultWeight = 10; //10
    this.defaultOpacity = 0.75;
    this.hoverWeight = 15;
    this.selected = false;
    this.highlighted = false;
    this.endpoints = new Array(); //Which regional center objects are on either end of this corridor.
    this.routeIDs = new Array(); // Which corridor IDs make up possible routes between the endpoints
    this.routePart = false;  //Keeps track of whether this corridor is part of a possible route
    this.tripPart = false; //Keeps track of whether this corridor is part of a trip
    this.clickListener = null; //Will hold the GoogleEventListener for click.  Used to unregister the event to re-register updated events.
    this.SegID = segId; //1.2, 3.4 etc.

    //Cost Attributes
    this.Riders = 0; //Riders per mile
    this.Benefits = 0;
    this.CapitalCost = 0;
    this.OperatingCost = 0;
    this.TravelTime = 0;
   
    this.AddVertex = function(point) {
        this.Vertices.push(point);
    }
    
    //Defines one end of the corridor.  Takes the RegionalCenter object as an argument.
    this.AddEndPoint = function(regionalCenter) {
        //this.endpoints.push(regionalCenter);
    }

    //Holds arrays of corridors that are alternates to the direct connection of endpoints
    this.AddRouteID = function(routeIDArray) {
        this.routeIDs.push(routeIDArray);
    }

    this.IsSelected = function() {
        return this.selected;
    }

    this.IsHighlighted = function() {
        return this.highlighted;
    }

    this.IsRoutePart = function() {
        return this.routePart;
    }

    this.IsTripPart = function() {
        return this.tripPart;
    }

    this.SetAsRoutePart = function(isRoutePart, routeId) {
        this.routePart = isRoutePart;
        if (!isRoutePart) {
            //this.RestoreCorridorHTMLonClick();
        }
    }

    this.RestoreCorridorHTMLonClick = function() {
    }

    this.SetAsTripPart = function(isTripPart) {
        this.tripPart = isTripPart;
    }

    this.SetSelected = function(blnSelected) {
        this.selected = blnSelected;
        //Add Highlighed Color if true
        if (this.visible) {
            if (this.selected) {
                this.Line.setStrokeStyle({ color: _highlightedColor });
            }
            else {
                this.Line.setStrokeStyle({ color: _defaultColor });
            }
        }
    }
    
    this.ToggleSelection = function() {
        this.Selected = !this.Selected;
    }

    this.GetHoverWeight = function() {
        return this.hoverWeight;
    }

    this.GetDefaultWeight = function() {
        return this.defaultWeight;
    }

    this.CreateLine = function() {
        var polyline = new GPolyline(this.Vertices, _defaultColor, _corridorWidth, _corridorOpacity);
        var name = this.Name
        //var infoHTML = this.GenerateInfoHTML(false);  //not higlighted by default

        this.clickListener = GEvent.addListener(polyline, "click", function() {
        _gmap.openInfoWindowHtml(polyline.getBounds().getCenter(), _corridors.FindByName(name).GenerateInfoHTML(_corridors.FindByName(name).selected));
        $('.wesLightRail').cluetip({
            splitTitle: '|',
            arrows: false,
            dropShadow: false,
            sticky: false,
            mouseOutClose: true,
            closePosition: 'title',
            closeText: '<img src="images/cancel.gif" alt="Close" />',
            cluetipClass: 'jtip'
        });

        });

        GEvent.addListener(polyline, "mouseover", function() {
            handleCorridorMouseOver(name, polyline);

        });

        GEvent.addListener(polyline, "mouseout", function() {
            handleCorridorMouseOut(name, polyline);

        });

        this.Line = polyline;
        return polyline;
    }

    this.GetPolyLine = function() {
        return this.Line;
    }

    this.GenerateInfoHTML = function(isHighlighted) {
        var html = null;

        html = "<div class='infowindow' style='width:250px; border:solid 1px #999999; margin:3px; padding:5px;'>";
        html += "<span style='color: #000000;font-weight:bold;font-size:1.1em;'>" + this.Name + "</span>";
        if (isWESCorridor(this.SegID)) {
            html += " - <a href='#' onclick='return false;' class='wesLightRail' Title='New Light Rail|Although this corridor already has WES commuter rail service, the costs and benefits illustrated in the tool represent building light rail in the corridor and increasing service frequency to every ten minutes in the peak hour and 15 minutes all day.'>New Light Rail</a>";
        }
        html += "<br><br><span style='color: #000000;'>Information about this transit corridor:</span><br><div style='font-size:10px;marign:15px auto 0px;padding:0px 10px'>";
        html += "<table><tbody>";
        html += "<tr><td class='infoWindowLeftLabel'>Capital cost:</td>";
        html += "<td style='padding:1px'><img alt='' class='infoWindowImage' src='" + _capitalCostImageBaseURL + this.CapitalCost + _gifExtension + "' /></td></tr>";
        html += "<tr><td class='infoWindowLeftLabel'>Operating cost:</td>";
        html += "<td style='padding:1px'><img alt='' class='infoWindowImage' src='" + _operatingCostImageBaseURL + this.OperatingCost + _gifExtension + "' /></td></tr>";
        html += "<tr><td style='text-align:right;padding:1px;font-size:1.2em;'>Ridership:</td>";
        html += "<td style='padding:1px'><img alt='' class='infoWindowImage' src='" + _riderImageBaseURL + this.Riders + _gifExtension + "' /></td></tr>";
        html += "<tr><td class='infoWindowLeftLabel'>Environmental<br/>benefits:</td>";
        html += "<td style='padding:1px'><img alt='' class='infoWindowImage' src='" + _benefitsImageBaseURL + this.Benefits + _gifExtension + "' /></td></tr>";
        html += "<tr><td class='infoWindowLeftLabel'>Transit travel<br/>time (mins):</td>";
        html += "<td style='padding:1px'><img alt='' class='infoWindowImage' src='" + _timeImageBaseURL + this.TravelTime + _gifExtension + "' /></td></tr>";
        html += "</tbody></table></div></div><br>";

        html += "<div style='text-align:center;'>";
        if (!isHighlighted) {
            if ((_system.CapitalCost + this.CapitalCost) <= _maxCost) { //Under the allowed cost
                html += "<input type='image' src='images/select.gif' alt='Select' onclick='AddSegmentToTrip(" + this.Id + ");' style='cursor:pointer'/> &nbsp;&nbsp;<input type='image' src='images/close.gif' alt='Close' onclick='_gmap.closeInfoWindow()' style='cursor:pointer' />";
            }
            else {
                html += "<div style='width:250px;font-weight:bold;font-size:1.2em;text-align:left;margin-bottom:2px;'>Budget limit met</div>";
                html += "<div style='color:#000000;width:250px;font-size:10px;text-align:left;margin-bottom:3px;'>This corridor can not be selected because selecting it would exceed your maximum budget. If you would like to add this line, you'll need to remove a line from your system.</div>";
                html += "<input type='image' src='images/close.gif' alt='Close' onclick='_gmap.closeInfoWindow();' style='cursor:pointer'/>";
            }
        }
        else {
            html += "<input type='image' src='images/unselect.gif' alt='Unselect' onclick='RemoveCorridorFromCurrentSystem(" + this.Id + ")' style='cursor:pointer'/> &nbsp;&nbsp;<input type='image' src='images/close.gif' alt='Close' onclick='_gmap.closeInfoWindow()' style='cursor:pointer'/>";                
        }

        html += "</div>";
        return html;
    }
}

//holds collection of Corridor objects
function Corridors() {
    this.lines = new Array();
    this.selectedCount = 0;

    this.Add = function(corridor) {
        this.lines.push(corridor);
    }

    this.Count = function() {
        return this.lines.length;
    }

    this.ClearSelected = function() {
        //Clear any selected corridors
        for (var i = 0; i < this.lines.length; i++) {
            this.lines[i].SetSelected(false);
            this.lines[i].SetAsRoutePart(false);
        }
    }

    //Pass in an array with 2 regionalCenter objects. Return the corridor ID that connects them.
    this.GetCorridorIDByEndPoints = function(centerArray) {
        var corridorArray = new Array();
        for (var i = 0; i < this.lines.length; i++) {
            if ((this.lines[i].endpoints[0].Name == centerArray[0] && this.lines[i].endpoints[1].Name == centerArray[1]) || (this.lines[i].endpoints[0].Name == centerArray[1] && this.lines[i].endpoints[1].Name == centerArray[0])) {
                return this.lines[i].Id;
            }
        }
        return -1; //if no matches found
    }

    this.FindByName = function(corridorName) {
        var corridor = null;
        for (var i = 0; i < this.lines.length; i++) {
            if (this.lines[i].Name == corridorName) {
                corridor = this.lines[i];
                break;
            }
        }
        return corridor;
    }

    this.FindByID = function(Id) {
        for (var i = 0; i < this.lines.length; i++) {
            if (this.lines[i].Id == Id) {
                return this.lines[i];
            }
        }
        return null; //by default
    }

    this.GetItem = function(i) {
        return this.lines[i];
    }
}

/****** BEGIN Submit Data to Database ******/
function SubmitSelectedSystems() {
    var subFlag = false;
    var corridorJson = { "corridorArray": [] };
    try {
        //Change label
        _systemDisplay.SetSubmittingMode('s');
        for (var i = 0; i < _systemCollection.systems.length; i++) {
            if (_systemCollection.systems[i]) {
                if (_systemCollection.systems[i].selected) {
                    var sysIds = null;
                    for (var u = 0; u < _systemCollection.systems[i].segments.length; u++) {
                        if (_systemCollection.systems[i].segments[u]) {
                            //gather system segment ids
                            if (u == 0) {
                                sysIds = _systemCollection.systems[i].segments[u].SegID;
                            }
                            else {
                                sysIds += "," + _systemCollection.systems[i].segments[u].SegID;
                            }
                        }
                    }
                    _systemCollection.systems[i].submitted = true;
                    corridorJson.corridorArray.push(sysIds);
                    subFlag = true;
                }
            }
        }
    }
    catch (ex) {
        $("#uxPrevSysLabel")[0].innerHTML = ex;
        _systemDisplay.SetSubmittingMode('e');        
    }
    
    if (!subFlag) {
        alert("No Systems selected.");
        _systemDisplay.SetSubmittingMode('d');        
    }
    else {
        submitSystemToDatabase("SubmitSystemService.asmx/SubmitSystemToDatabase", $.toJSON(corridorJson))
    }
}

function submitSystemToDatabase(serviceURL, corridorArray) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: serviceURL,
        data: corridorArray,
        dataType: "json",
        success:
       function(msg) {
           _systemDisplay.SetSubmittingMode('f'); //f for finished
       },
        error:
       function(XMLHttpRequest, textStatus, errorThrown) {
        _systemDisplay.SetSubmittingMode('e');
           //$("#uxPrevSysLabel")[0].innerHTML = "Error submitting system.";
           //alert("Error Occured!");
       }
    });
}

/****** END Submit Data to Database ******/


