<commit_before>var routePlan;
var map = null;
var bb = null;

var busStopIcon;
var walkStopIcon;
var startIcon;
var endIcon;

var routePlanStart = null;
var routePlanEnd = null;
var routePlanStartDefault = null;
var routePlanEndDefault = null;

/**
 * Setup locations based on previous browser locations or cookie. Call
 * during or after location changes. Returns true if we should try to load
 * a path, false otherwise.
 */
function setupRoutePlanForm(state) {
    // first, set defaults

    // if no cookie yet exists, no biggie, these values just won't get set
    // to anything
    // FIXME: Actually no, you see null on internet explorer. must fix.
    routePlanStartDefault = YAHOO.util.Cookie.getSub("routeplan", "start");
    routePlanEndDefault = YAHOO.util.Cookie.getSub("routeplan", "end");

    if (state == "default") {
        // if no history state, then (try) to load locations from cookies

        document.getElementById('routePlanStart').value = routePlanStartDefault;
        document.getElementById('routePlanEnd').value = routePlanEndDefault;

        return false;
    }

    // otherwise we try to get history out of json
    // FIXME: no error handling here yet
    var stateHash = YAHOO.lang.JSON.parse(state);
    document.getElementById('routePlanStart').value = stateHash.saddr;
    document.getElementById('routePlanEnd').value = stateHash.daddr;
    document.getElementById('time').value = stateHash.time;

    return true;
}

/**
 * Initialize icons. Call once during load.
 */
function initIcons() {
    /*
    walkStopIcon = new CM.Icon();
    walkStopIcon.image = "site_media/images/marker_walk.png";
    walkStopIcon.iconSize = new GSize(46, 36);
    walkStopIcon.iconAnchor = new GPoint(1, 35);

    ferryStopIcon = new CM.Icon();
    ferryStopIcon.image = "site_media/images/marker_ferry.png";
    ferryStopIcon.iconSize = new GSize(46, 36);
    ferryStopIcon.iconAnchor = new GPoint(1, 35);

    switchStopIcon = new CM.Icon();
    switchStopIcon.image = "site_media/images/marker_switch.png";
    switchStopIcon.iconSize = new GSize(46, 36);
    switchStopIcon.iconAnchor = new GPoint(1, 35);
    */
    startIcon = new CM.Icon();
    startIcon.image = "site_media/images/marker_from.png";
    startIcon.iconSize = new CM.Size(34, 36);
    startIcon.iconAnchor = new CM.Point(11, 35);

    endIcon = new CM.Icon();
    endIcon.image = "site_media/images/marker_to.png";
    endIcon.iconSize = new CM.Size(34, 36);
    endIcon.iconAnchor = new CM.Point(11, 35);
}

function reverseDirections() {
    var tmp = document.getElementById('routePlanStart').value;
    document.getElementById('routePlanStart').value = document.getElementById('routePlanEnd').value;
    document.getElementById('routePlanEnd').value = tmp;
}

// Capitalizes a string, first letter in upper case and the rest in lower case.
// Created: 2005.11.20  - Modified 2005.11.21
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/string/capitalize [rev. #1]
String.prototype.capitalize = function(){
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase();
    });
};

function reset() {
    // reset everything, called on first load (if no trip) and in case
    // of error
    document.getElementById('route-plan').style.display = 'none';
    map.setCenter(bb.getCenter(), map.getBoundsZoomLevel(bb)+1);
    map.clearOverlays();
}

function addLine(routePath, colour) {
    if (routePath.length > 0) {
        var polyline = new CM.Polyline(routePath, colour, 5);
        map.addOverlay(polyline);
    }
}

function updateMapBounds(actions) {

    var bound_latlngs = new Array();

    for (var i = 0; i < actions.length; ++i) {
        // only alight and pass actions have latlng info
        if (actions[i].type == "alight" || actions[i].type == "pass") {
            bound_latlngs[bound_latlngs.length] = new CM.LatLng(actions[i].lat, actions[i].lng);
        }
    }

    var bounds = new CM.LatLngBounds(bound_latlngs);
    var zoom = map.getBoundsZoomLevel(bounds);

    map.setCenter(bounds.getCenter(), zoom);
}

function updateMapDirections(start, end, actions) {

    // add start and end markers
    function orderOfCreation(marker,b) {
        return 1;
    }

    var routePath = new Array();
    var walkPathColour = "#004";
    var busPathColour = "#22f";

    // before doing anything else, set bounds (if we're loading
    // directions on a new page, we need to do this before adding overlays)
    updateMapBounds(actions);

    // nuke any existing map overlays
    map.clearOverlays();

    map.addOverlay(new CM.Marker(new CM.LatLng(start.lat, start.lng),
                                 { icon: startIcon, title: "start" }));
    map.addOverlay(new CM.Marker(new CM.LatLng(end.lat, end.lng),
                                 { icon: endIcon, title: "end" }));
    routePath[routePath.length] = new CM.LatLng(start.lat, start.lng);

    for (var i = 0; i < actions.length; ++i) {
        var latlng = new CM.LatLng(actions[i].lat, actions[i].lng);

        if (actions[i].type == "alight" || actions[i].type == "pass") {
            // also add any shape to the path
            if (actions[i].shape) {
                for (var j=0; j<actions[i].shape.length; ++j) {
                    routePath[routePath.length] = new CM.LatLng(
                        actions[i].shape[j][0], actions[i].shape[j][1]);
                }
            } else {
                routePath[routePath.length] = latlng;
            }
        }

        if (actions[i].type == "board") {
            routePath[routePath.length] = latlng;

            var icon = new CM.Icon();
            icon.image = "site_media/images/bus/marker_bus_" +
            actions[i].route_shortname + ".png"
            icon.iconSize = new CM.Size(76, 36);
            icon.iconAnchor = new CM.Point(1, 35);
            map.addOverlay(new CM.Marker(latlng,
                                         { icon: icon, title: "Board" }));

            addLine(routePath, walkPathColour);
            routePath = new Array();
            routePath[routePath.length] = latlng;
        } else if (actions[i].type == "alight") {
            addLine(routePath, busPathColour);
            routePath = new Array();
        }

        // if we have to get off and walk, show a nice icon
        if (i>0 && actions[i-1].type == "alight" &&
            actions[i].type != "board") {
            var icon = new CM.Icon();
            icon.image = "site_media/images/marker_walk.png"
            icon.iconSize = new CM.Size(46, 36);
            icon.iconAnchor = new CM.Point(1, 35);
            map.addOverlay(new CM.Marker(latlng,
                                         { icon: icon, title: "Walk" }));
        }
    }

    routePath[routePath.length] = new CM.LatLng(end.lat, end.lng);
    addLine(routePath, walkPathColour);
}

function showMapLink(latlngStr) {
    routePlan += " [Map]";
}

var submitCallbackError = function(o) {
    // reset plan button
    planButton = document.getElementById('plan-button');
    planButton.value = 'Plan!';
    planButton.style.color = "#000";

    // show the error message
    document.getElementById('error-submit').style.display = 'block';
    reset();
}

var submitCallback = function(o) {
    // reset plan button
    planButton = document.getElementById('plan-button');
    planButton.value = 'Plan!';
    planButton.style.color = "#000";

    // clear any previous submit error notices
    document.getElementById('error-submit').style.display = 'none';

    myresponse = YAHOO.lang.JSON.parse(o.responseText);

    // check for fails
    errors = myresponse['errors'];
    if (errors) {
        for (var i in errors) {
            if (errors[i] == "start_latlng_decode") {
                document.getElementById('routePlanStart').className = 'text text_error';
                document.getElementById('error-from').style.display = 'block';
            }
            if (errors[i] == "end_latlng_decode") {
                document.getElementById('routePlanEnd').className = 'text text_error';
                document.getElementById('error-to').style.display = 'block';
            }
        }

        reset();
        return;
    }

    YAHOO.util.Cookie.setSubs("routeplan",
                              { start: routePlanStart,
                                  end: routePlanEnd },
                              { expires: new Date("January 12, 2025") });

    actions = myresponse['actions'];
    routePlan = "";

    if (map) {
        updateMapDirections(myresponse['start'], myresponse['end'], actions);
    }

    if (actions.length == 0) {
        routePlan = "
Couldn't find a path!
";
    } else {
        var origin_str = document.getElementById('routePlanStart').value.capitalize();
        var dest_str = document.getElementById('routePlanEnd').value.capitalize();

        first_stop = "";
        for (var i = 0; i < actions.length; ++i) {
            if (actions[i].route_id >= 0) {
                firstStop = actions[i].stopname;
                firstStopLatlng = actions[i].lat + "," + actions[i].lng;
                break;
            }
        }
        if (firstStop == "")
            firstStop = dest_str;

        routePlan += "
";
        routePlan += "
" + myresponse['departure_time'] + ": ";
        routePlan += "Start at " + origin_str + ".
";
        routePlan += "
" + actions[0].time + ": ";
        routePlan += "Walk to " + firstStop + ".";
        if (!map) {
            showMapLink(firstStopLatlng);
        }
        routePlan += "
";

        for (var i = 0; i < actions.length; ++i) {

            if (actions[i].type == "board") {
                routePlan += "
" + actions[i].time + ": ";
                routePlan += "Board the " + actions[i].route_shortname + " (";
                routePlan += actions[i].route_longname + ").";
            } else if (actions[i].type == "alight") {
                var previd = actions[i-1].dest_id;
                routePlan += "
" + actions[i].time + ": ";
                routePlan += "Descend at " + actions[i].stopname;

                if (actions.length > i+1 && actions[i].type == "alight" &&
                    actions[i+1].type != "board") {
                    routePlan += " and walk to " + dest_str;
                }
                routePlan += ".";
                if (!map) {
                    showMapLink(actions[i].lat + "," + actions[i].lng);
                }
                routePlan += "
";
            }

            if (i==(actions.length-1)) {
                routePlan += "
" + actions[i].time + ": ";
                routePlan += "Arrive at " + dest_str + ".";
            }
        }

        routePlan += "
";
    }

    // show the route plan (and options), hide the about box
    document.getElementById('route-plan-content').innerHTML = routePlan;
    //document.getElementById('route-plan-options').style.display = 'block';
    document.getElementById('route-plan').style.display = 'block';
    document.getElementById('intro').style.display = 'none';
}

function showDebugInfo(actions) {
    var debug_str = "
";
    for (var i = 0; i < actions.length; ++i) {
        debug_str += "Action " + i + ":";
        debug_str += " id=" + actions[i].id;
        debug_str += "; route_id=" + actions[i].route_id;
        debug_str += "; type=" + actions[i].type;
        debug_str += "; time=" + actions[i].time;
        debug_str += "; lat=" + actions[i].lat;
        debug_str += "; lng=" + actions[i].lng;
        debug_str += "; stopname=" + actions[i].stopname;
        debug_str += "
\n";
    }
    debug_str += "
";

    debug_div = document.getElementById("debug");
    if (!debug_div) {
        document.getElementById("footer").innerHTML += "

";
        debug_div = document.getElementById("debug");
    }
    debug_div.innerHTML = debug_str;
}

function resetPlanButton() {
    planButton = document.getElementById('plan-button');
    planButton.value = 'Plan!';
    planButton.style.color = "#000";
}

function submitRoutePlan() {
    routePlanStart = document.getElementById('routePlanStart').value;
    routePlanEnd = document.getElementById('routePlanEnd').value;

    // clear errors
    document.getElementById('error-from').style.display = 'none';
    document.getElementById('routePlanStart').className = 'text';
    document.getElementById('error-to').style.display = 'none';
    document.getElementById('routePlanEnd').className = 'text';

    // let user know something exciting is about to happen!
    planButton = document.getElementById('plan-button');
    planButton.value = 'Working...';
    planButton.style.color = "#aaa";

    time = document.getElementById('time').value;

    var currentState = YAHOO.util.History.getCurrentState("plan");
    var newState = YAHOO.lang.JSON.stringify({ saddr: routePlanStart,
                                               daddr: routePlanEnd,
                                               time: time });

    // if currentState is equal to newState, then we've already set the
    // browser history state to the appropriate value: proceed to plan trip
    // otherwise, we want to setup the history before doing anything else
    if (currentState !== newState) {
        YAHOO.util.History.navigate("plan", newState);
    } else {

        YAHOO.util.Connect.asyncRequest("GET", "/json/routeplan" +
                                        "?start=" + routePlanStart + "&end=" + routePlanEnd +
                                        "&time=" + time,
                                        { success:submitCallback, failure:submitCallbackError }, null);

    }
}

function locationInputFocused(location) {
    if (location == "start" &&
        document.getElementById('routePlanStart').value == routePlanStartDefault) {
        document.getElementById('routePlanStart').select();
    } else if (location == "end" && document.getElementById('routePlanEnd').value == routePlanEndDefault) {
        document.getElementById('routePlanEnd').select();
    }
}
<commit_msg>URL encode locations when submitting json<commit_after>var routePlan;
var map = null;
var bb = null;

var busStopIcon;
var walkStopIcon;
var startIcon;
var endIcon;

var routePlanStart = null;
var routePlanEnd = null;
var routePlanStartDefault = null;
var routePlanEndDefault = null;

/**
 * Setup locations based on previous browser locations or cookie. Call
 * during or after location changes. Returns true if we should try to load
 * a path, false otherwise.
 */
function setupRoutePlanForm(state) {
    // first, set defaults

    // if no cookie yet exists, no biggie, these values just won't get set
    // to anything
    // FIXME: Actually no, you see null on internet explorer. must fix.
    routePlanStartDefault = YAHOO.util.Cookie.getSub("routeplan", "start");
    routePlanEndDefault = YAHOO.util.Cookie.getSub("routeplan", "end");

    if (state == "default") {
        // if no history state, then (try) to load locations from cookies

        document.getElementById('routePlanStart').value = routePlanStartDefault;
        document.getElementById('routePlanEnd').value = routePlanEndDefault;

        return false;
    }

    // otherwise we try to get history out of json
    // FIXME: no error handling here yet
    var stateHash = YAHOO.lang.JSON.parse(state);
    document.getElementById('routePlanStart').value = stateHash.saddr;
    document.getElementById('routePlanEnd').value = stateHash.daddr;
    document.getElementById('time').value = stateHash.time;

    return true;
}

/**
 * Initialize icons. Call once during load.
 */
function initIcons() {
    /*
    walkStopIcon = new CM.Icon();
    walkStopIcon.image = "site_media/images/marker_walk.png";
    walkStopIcon.iconSize = new GSize(46, 36);
    walkStopIcon.iconAnchor = new GPoint(1, 35);

    ferryStopIcon = new CM.Icon();
    ferryStopIcon.image = "site_media/images/marker_ferry.png";
    ferryStopIcon.iconSize = new GSize(46, 36);
    ferryStopIcon.iconAnchor = new GPoint(1, 35);

    switchStopIcon = new CM.Icon();
    switchStopIcon.image = "site_media/images/marker_switch.png";
    switchStopIcon.iconSize = new GSize(46, 36);
    switchStopIcon.iconAnchor = new GPoint(1, 35);
    */
    startIcon = new CM.Icon();
    startIcon.image = "site_media/images/marker_from.png";
    startIcon.iconSize = new CM.Size(34, 36);
    startIcon.iconAnchor = new CM.Point(11, 35);

    endIcon = new CM.Icon();
    endIcon.image = "site_media/images/marker_to.png";
    endIcon.iconSize = new CM.Size(34, 36);
    endIcon.iconAnchor = new CM.Point(11, 35);
}

function reverseDirections() {
    var tmp = document.getElementById('routePlanStart').value;
    document.getElementById('routePlanStart').value = document.getElementById('routePlanEnd').value;
    document.getElementById('routePlanEnd').value = tmp;
}

// Capitalizes a string, first letter in upper case and the rest in lower case.
// Created: 2005.11.20  - Modified 2005.11.21
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/string/capitalize [rev. #1]
String.prototype.capitalize = function(){
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase();
    });
};

function reset() {
    // reset everything, called on first load (if no trip) and in case
    // of error
    document.getElementById('route-plan').style.display = 'none';
    map.setCenter(bb.getCenter(), map.getBoundsZoomLevel(bb)+1);
    map.clearOverlays();
}

function addLine(routePath, colour) {
    if (routePath.length > 0) {
        var polyline = new CM.Polyline(routePath, colour, 5);
        map.addOverlay(polyline);
    }
}

function updateMapBounds(actions) {

    var bound_latlngs = new Array();

    for (var i = 0; i < actions.length; ++i) {
        // only alight and pass actions have latlng info
        if (actions[i].type == "alight" || actions[i].type == "pass") {
            bound_latlngs[bound_latlngs.length] = new CM.LatLng(actions[i].lat, actions[i].lng);
        }
    }

    var bounds = new CM.LatLngBounds(bound_latlngs);
    var zoom = map.getBoundsZoomLevel(bounds);

    map.setCenter(bounds.getCenter(), zoom);
}

function updateMapDirections(start, end, actions) {

    // add start and end markers
    function orderOfCreation(marker,b) {
        return 1;
    }

    var routePath = new Array();
    var walkPathColour = "#004";
    var busPathColour = "#22f";

    // before doing anything else, set bounds (if we're loading
    // directions on a new page, we need to do this before adding overlays)
    updateMapBounds(actions);

    // nuke any existing map overlays
    map.clearOverlays();

    map.addOverlay(new CM.Marker(new CM.LatLng(start.lat, start.lng),
                                 { icon: startIcon, title: "start" }));
    map.addOverlay(new CM.Marker(new CM.LatLng(end.lat, end.lng),
                                 { icon: endIcon, title: "end" }));
    routePath[routePath.length] = new CM.LatLng(start.lat, start.lng);

    for (var i = 0; i < actions.length; ++i) {
        var latlng = new CM.LatLng(actions[i].lat, actions[i].lng);

        if (actions[i].type == "alight" || actions[i].type == "pass") {
            // also add any shape to the path
            if (actions[i].shape) {
                for (var j=0; j<actions[i].shape.length; ++j) {
                    routePath[routePath.length] = new CM.LatLng(
                        actions[i].shape[j][0], actions[i].shape[j][1]);
                }
            } else {
                routePath[routePath.length] = latlng;
            }
        }

        if (actions[i].type == "board") {
            routePath[routePath.length] = latlng;

            var icon = new CM.Icon();
            icon.image = "site_media/images/bus/marker_bus_" +
            actions[i].route_shortname + ".png"
            icon.iconSize = new CM.Size(76, 36);
            icon.iconAnchor = new CM.Point(1, 35);
            map.addOverlay(new CM.Marker(latlng,
                                         { icon: icon, title: "Board" }));

            addLine(routePath, walkPathColour);
            routePath = new Array();
            routePath[routePath.length] = latlng;
        } else if (actions[i].type == "alight") {
            addLine(routePath, busPathColour);
            routePath = new Array();
        }

        // if we have to get off and walk, show a nice icon
        if (i>0 && actions[i-1].type == "alight" &&
            actions[i].type != "board") {
            var icon = new CM.Icon();
            icon.image = "site_media/images/marker_walk.png"
            icon.iconSize = new CM.Size(46, 36);
            icon.iconAnchor = new CM.Point(1, 35);
            map.addOverlay(new CM.Marker(latlng,
                                         { icon: icon, title: "Walk" }));
        }
    }

    routePath[routePath.length] = new CM.LatLng(end.lat, end.lng);
    addLine(routePath, walkPathColour);
}

function showMapLink(latlngStr) {
    routePlan += " [Map]";
}

var submitCallbackError = function(o) {
    // reset plan button
    planButton = document.getElementById('plan-button');
    planButton.value = 'Plan!';
    planButton.style.color = "#000";

    // show the error message
    document.getElementById('error-submit').style.display = 'block';
    reset();
}

var submitCallback = function(o) {
    // reset plan button
    planButton = document.getElementById('plan-button');
    planButton.value = 'Plan!';
    planButton.style.color = "#000";

    // clear any previous submit error notices
    document.getElementById('error-submit').style.display = 'none';

    myresponse = YAHOO.lang.JSON.parse(o.responseText);

    // check for fails
    errors = myresponse['errors'];
    if (errors) {
        for (var i in errors) {
            if (errors[i] == "start_latlng_decode") {
                document.getElementById('routePlanStart').className = 'text text_error';
                document.getElementById('error-from').style.display = 'block';
            }
            if (errors[i] == "end_latlng_decode") {
                document.getElementById('routePlanEnd').className = 'text text_error';
                document.getElementById('error-to').style.display = 'block';
            }
        }

        reset();
        return;
    }

    YAHOO.util.Cookie.setSubs("routeplan",
                              { start: routePlanStart,
                                  end: routePlanEnd },
                              { expires: new Date("January 12, 2025") });

    actions = myresponse['actions'];
    routePlan = "";

    if (map) {
        updateMapDirections(myresponse['start'], myresponse['end'], actions);
    }

    if (actions.length == 0) {
        routePlan = "
Couldn't find a path!
";
    } else {
        var origin_str = document.getElementById('routePlanStart').value.capitalize();
        var dest_str = document.getElementById('routePlanEnd').value.capitalize();

        first_stop = "";
        for (var i = 0; i < actions.length; ++i) {
            if (actions[i].route_id >= 0) {
                firstStop = actions[i].stopname;
                firstStopLatlng = actions[i].lat + "," + actions[i].lng;
                break;
            }
        }
        if (firstStop == "")
            firstStop = dest_str;

        routePlan += "
";
        routePlan += "
" + myresponse['departure_time'] + ": ";
        routePlan += "Start at " + origin_str + ".
";
        routePlan += "
" + actions[0].time + ": ";
        routePlan += "Walk to " + firstStop + ".";
        if (!map) {
            showMapLink(firstStopLatlng);
        }
        routePlan += "
";

        for (var i = 0; i < actions.length; ++i) {

            if (actions[i].type == "board") {
                routePlan += "
" + actions[i].time + ": ";
                routePlan += "Board the " + actions[i].route_shortname + " (";
                routePlan += actions[i].route_longname + ").";
            } else if (actions[i].type == "alight") {
                var previd = actions[i-1].dest_id;
                routePlan += "
" + actions[i].time + ": ";
                routePlan += "Descend at " + actions[i].stopname;

                if (actions.length > i+1 && actions[i].type == "alight" &&
                    actions[i+1].type != "board") {
                    routePlan += " and walk to " + dest_str;
                }
                routePlan += ".";
                if (!map) {
                    showMapLink(actions[i].lat + "," + actions[i].lng);
                }
                routePlan += "
";
            }

            if (i==(actions.length-1)) {
                routePlan += "
" + actions[i].time + ": ";
                routePlan += "Arrive at " + dest_str + ".";
            }
        }

        routePlan += "
";
    }

    // show the route plan (and options), hide the about box
    document.getElementById('route-plan-content').innerHTML = routePlan;
    //document.getElementById('route-plan-options').style.display = 'block';
    document.getElementById('route-plan').style.display = 'block';
    document.getElementById('intro').style.display = 'none';
}

function showDebugInfo(actions) {
    var debug_str = "
";
    for (var i = 0; i < actions.length; ++i) {
        debug_str += "Action " + i + ":";
        debug_str += " id=" + actions[i].id;
        debug_str += "; route_id=" + actions[i].route_id;
        debug_str += "; type=" + actions[i].type;
        debug_str += "; time=" + actions[i].time;
        debug_str += "; lat=" + actions[i].lat;
        debug_str += "; lng=" + actions[i].lng;
        debug_str += "; stopname=" + actions[i].stopname;
        debug_str += "
\n";
    }
    debug_str += "
";

    debug_div = document.getElementById("debug");
    if (!debug_div) {
        document.getElementById("footer").innerHTML += "

";
        debug_div = document.getElementById("debug");
    }
    debug_div.innerHTML = debug_str;
}

function resetPlanButton() {
    planButton = document.getElementById('plan-button');
    planButton.value = 'Plan!';
    planButton.style.color = "#000";
}

function submitRoutePlan() {
    routePlanStart = document.getElementById('routePlanStart').value;
    routePlanEnd = document.getElementById('routePlanEnd').value;

    // clear errors
    document.getElementById('error-from').style.display = 'none';
    document.getElementById('routePlanStart').className = 'text';
    document.getElementById('error-to').style.display = 'none';
    document.getElementById('routePlanEnd').className = 'text';

    // let user know something exciting is about to happen!
    planButton = document.getElementById('plan-button');
    planButton.value = 'Working...';
    planButton.style.color = "#aaa";

    time = document.getElementById('time').value;

    var currentState = YAHOO.util.History.getCurrentState("plan");
    var newState = YAHOO.lang.JSON.stringify({ saddr: routePlanStart,
                                               daddr: routePlanEnd,
                                               time: time });

    // if currentState is equal to newState, then we've already set the
    // browser history state to the appropriate value: proceed to plan trip
    // otherwise, we want to setup the history before doing anything else
    if (currentState !== newState) {
        YAHOO.util.History.navigate("plan", newState);
    } else {

        YAHOO.util.Connect.asyncRequest("GET", "/json/routeplan" +
                                        "?start=" + escape(routePlanStart) + "&end=" + escape(routePlanEnd) +
                                        "&time=" + time,
                                        { success:submitCallback, failure:submitCallbackError }, null);

    }
}

function locationInputFocused(location) {
    if (location == "start" &&
        document.getElementById('routePlanStart').value == routePlanStartDefault) {
        document.getElementById('routePlanStart').select();
    } else if (location == "end" && document.getElementById('routePlanEnd').value == routePlanEndDefault) {
        document.getElementById('routePlanEnd').select();
    }
}
<|endoftext|>


<commit_before>(function(){
    var Bokeh
    if (this.Bokeh){
	Bokeh = this.Bokeh;
    }else{
	Bokeh = {};
	this.Bokeh = Bokeh;
    }
    Bokeh.Collections = {}
    Bokeh.register_collection = function(key, value){
	Bokeh.Collections[key] = value;
	value.bokeh_key = key;
    }

    //BokehView
    //Regular backbone view, except, it gets assigned an id.
    //this id can be used to auto-create html ids, and pull out
    //d3, and jquery nodes based on those dom elements

    var BokehView = Backbone.View.extend({
	initialize : function(options){
	    var self = this;
	    if (!_(options).has('id')){
		self.id = _.uniqueId('BokehView');
	    }
	},
	tag_id : function(tag){
	    return "tag" + "-" + this.id;
	},
	tag_el : function(tag){
	    return $("#" + this.tag_id());
	},
	tag_d3 : function(tag){
	    return d3.select("#" + this.tag_id());
	},
    });

    //ObjectArrayDataSource (may want general data source later)
    var HasReference = Backbone.Model.extend({
	type : null,
	ref : function(){
	    return {'type' : this.type,
		    'id' : this.id};
	}
    });

    var ObjectArrayDataSource = HasReference.extend({
    });

    //hasparent
    //display_options can be passed down to children
    //defaults for display_options should be placed
    //in a class var display_defaults
    //the get function, will resolve an instances defaults first
    //then check the parents actual val, and finally check class defaults.
    //display options cannot go into defaults

    var HasParent = HasReference.extend({
	initialize : function(attrs, options){
	    var self = this;
	    if (!_.isNullOrUndefined(attrs['parent'])){
		self.parent_id = attrs['parent']['id'];
		self.parent_type = attrs['parent']['type'];
		self.parent = self.get_parent();
	    }
	},
	get_parent : function(){
	    var self = this;
	    return Bokeh.Collections[self.parent_type].get(self.parent_id);
	},
	get : function(attr){
	    var self = this
	    if (_.has(self.attributes, attr)){
		return self.attributes[attr];
	    }else if (
		!_.isUndefined(self.parent) &&
		_.indexOf(self.parent.parent_properties, attr) >= 0 &&
		    !_.isUndefined(self.parent.get(attr))){
		return self.parent.get(attr);
	    }else if (_.has(self.display_defaults, attr)){
		return self.display_defaults[attr];
	    }
	},
	display_defaults: {}
    });

    //Component
    var Component = HasParent.extend({
	initialize : function(attrs, options){
	    var self =  this;
	    if (!_(attrs).has('id')){
		self.id = _.uniqueId('BokehView');
	    }
	},
	defaults : {
	    parent : null
	},
	display_defaults : {
	    width : 200,
	    height : 200,
	    position : 0,
	},
	default_view : null
    });

    //Plot
    var Plot = Component.extend({
	type : Plot,
    });
    _.extend(Plot.prototype.defaults,
	     {
		 'data_sources' : {},
		 'renderers' : [],
		 'legends' : [],
		 'tools' : [],
		 'overlays' : []
	     });
    _.extend(Plot.prototype.display_defaults,
	     {
		 'background-color' : "#fff",
		 'foreground-color' : "#aaa"
	     });

    //PlotView
    var PlotView = BokehView.extend({
	initialize : function(options){
	    var self = this;
	    BokehView.prototype.initialize.call(self, options);
	    var view, model, model_id, options;
	    self.renderers = {};
	    _(self.model.get('renderers')).each(function(spec){
		model_id = spec['id'];
		model = Bokeh.Collections[spec['type']].get(model_id);
		options = _.extend({}, spec['options'], {'el' : self.el});
		view = new model.default_view(options);
		self.renderers[view.id] = view;
	    });
	},
	render : function(){
	    var self = this;
	    var width = self.model.get('width')
	    var height = self.model.get('height')
	    console.log([width, height]);
	    d3.select(self.el).append('svg')
	    	.attr("width", width)
		.attr("height", height)
		.append('rect')
		.attr('fill', self.model.get('background-color'))
		.attr('stroke', self.model.get('foreground-color'))
		.attr("width", width)
		.attr("height", height);
	    _(self.renderers).each(function(view){view.render()});
	    if (!self.model.get('parent')){
		self.$el.dialog();
	    }
	    console.log('ok');
	}
    });

    //ScatterRenderer
    var ScatterRendererView = BokehView.extend({
	render : function(){
	    var self =  this;
	    var svg = d3.select(self.el).select('svg').append('g')
		.attr('id', self.tag_id('g'))
		.append('circle').attr('cx');
	}
    });

    var ScatterRenderer = Component.extend({
	defaults : {
	    data_source : null,
	    xfield : '',
	    yfield : '',
	    mark : 'circle',
	},
	type : 'ScatterRenderer',
	default_view : ScatterRendererView
    });

    //GridPlotContainer
    var GridPlotContainer = Component.extend({
	type : "GridPlotContainer",
	defaults : {
	    rows: 0,
	    columns : 0,
	    children : [[]]
	}
    });
    _.extend(GridPlotContainer.prototype.defaults,
	     {'shape' : [0,0]});

    var GridPlotContainerView = BokehView.extend({
	render: function(){
	    var self = this;
	    var row;
	    self.$el = $(self.el);
	    self.$el.append("

");
	    _.each(_.range(self.model.get('rows')), function(xidx){
		row = $("

");
		_.each(_.range(self.model.get('columns')), function(yidx){

		});
	    });

	}
    });

    //RegisterModels
    var Plots = Backbone.Collection.extend({
	model : Plot,
	url : "/",
    });

    var ScatterRenderers = Backbone.Collection.extend({
	model : ScatterRenderer,
	url : "/",
    });

    var ObjectArrayDataSources = Backbone.Collection.extend({
	model : ObjectArrayDataSource,
	url : "/",
    });

    Bokeh.register_collection('Plot', new Plots());
    Bokeh.register_collection('ScatterRenderer', new ScatterRenderers());
    Bokeh.register_collection('ObjectArrayDataSource', new ObjectArrayDataSources());

    Bokeh.ObjectArrayDataSource = ObjectArrayDataSource;
    Bokeh.HasParent = HasParent;
    Bokeh.Component = Component;
    Bokeh.Plot = Plot;

    Bokeh.BokehView = BokehView;
    Bokeh.PlotView = PlotView;

})();<commit_msg>moved id code into HasReference Class<commit_after>(function(){
    var Bokeh
    if (this.Bokeh){
	Bokeh = this.Bokeh;
    }else{
	Bokeh = {};
	this.Bokeh = Bokeh;
    }
    Bokeh.Collections = {}
    Bokeh.register_collection = function(key, value){
	Bokeh.Collections[key] = value;
	value.bokeh_key = key;
    }

    //BokehView
    //Regular backbone view, except, it gets assigned an id.
    //this id can be used to auto-create html ids, and pull out
    //d3, and jquery nodes based on those dom elements

    var BokehView = Backbone.View.extend({
	initialize : function(options){
	    var self = this;
	    if (!_(options).has('id')){
		self.id = _.uniqueId('BokehView');
	    }
	},
	tag_id : function(tag){
	    return "tag" + "-" + this.id;
	},
	tag_el : function(tag){
	    return $("#" + this.tag_id());
	},
	tag_d3 : function(tag){
	    return d3.select("#" + this.tag_id());
	},
    });

    //HasReference
    //Backbone model, which can output a reference (combination of type, and id)
    //also auto creates an id on init, if one isn't passed in.
    var HasReference = Backbone.Model.extend({
	type : null,
	initialize : function(attrs, options){
	    var self = this;
	    if (!_(attrs).has('id')){
		self.id = _.uniqueId(self.type);
	    }
	},
	ref : function(){
	    return {'type' : this.type,
		    'id' : this.id};
	}
    });

    //ObjectArrayDataSource (may want general data source later)
    var ObjectArrayDataSource = HasReference.extend({
    });

    //hasparent
    //display_options can be passed down to children
    //defaults for display_options should be placed
    //in a class var display_defaults
    //the get function, will resolve an instances defaults first
    //then check the parents actual val, and finally check class defaults.
    //display options cannot go into defaults

    var HasParent = HasReference.extend({
	initialize : function(attrs, options){
	    var self = this;
	    if (!_.isNullOrUndefined(attrs['parent'])){
		self.parent_id = attrs['parent']['id'];
		self.parent_type = attrs['parent']['type'];
		self.parent = self.get_parent();
	    }
	},
	get_parent : function(){
	    var self = this;
	    return Bokeh.Collections[self.parent_type].get(self.parent_id);
	},
	get : function(attr){
	    var self = this
	    if (_.has(self.attributes, attr)){
		return self.attributes[attr];
	    }else if (
		!_.isUndefined(self.parent) &&
		_.indexOf(self.parent.parent_properties, attr) >= 0 &&
		    !_.isUndefined(self.parent.get(attr))){
		return self.parent.get(attr);
	    }else if (_.has(self.display_defaults, attr)){
		return self.display_defaults[attr];
	    }
	},
	display_defaults: {}
    });

    //Component
    var Component = HasParent.extend({
	defaults : {
	    parent : null
	},
	display_defaults : {
	    width : 200,
	    height : 200,
	    position : 0,
	},
	default_view : null
    });

    //Plot
    var Plot = Component.extend({
	type : Plot,
    });
    _.extend(Plot.prototype.defaults,
	     {
		 'data_sources' : {},
		 'renderers' : [],
		 'legends' : [],
		 'tools' : [],
		 'overlays' : []
	     });
    _.extend(Plot.prototype.display_defaults,
	     {
		 'background-color' : "#fff",
		 'foreground-color' : "#aaa"
	     });

    //PlotView
    var PlotView = BokehView.extend({
	initialize : function(options){
	    var self = this;
	    BokehView.prototype.initialize.call(self, options);
	    var view, model, model_id, options;
	    self.renderers = {};
	    _(self.model.get('renderers')).each(function(spec){
		model_id = spec['id'];
		model = Bokeh.Collections[spec['type']].get(model_id);
		options = _.extend({}, spec['options'], {'el' : self.el});
		view = new model.default_view(options);
		self.renderers[view.id] = view;
	    });
	},
	render : function(){
	    var self = this;
	    var width = self.model.get('width')
	    var height = self.model.get('height')
	    console.log([width, height]);
	    d3.select(self.el).append('svg')
	    	.attr("width", width)
		.attr("height", height)
		.append('rect')
		.attr('fill', self.model.get('background-color'))
		.attr('stroke', self.model.get('foreground-color'))
		.attr("width", width)
		.attr("height", height);
	    _(self.renderers).each(function(view){view.render()});
	    if (!self.model.get('parent')){
		self.$el.dialog();
	    }
	    console.log('ok');
	}
    });

    //ScatterRenderer
    var ScatterRendererView = BokehView.extend({
	render : function(){
	    var self =  this;
	    var svg = d3.select(self.el).select('svg').append('g')
		.attr('id', self.tag_id('g'))
		.append('circle').attr('cx');
	}
    });

    var ScatterRenderer = Component.extend({
	defaults : {
	    data_source : null,
	    xfield : '',
	    yfield : '',
	    mark : 'circle',
	},
	type : 'ScatterRenderer',
	default_view : ScatterRendererView
    });

    //GridPlotContainer
    var GridPlotContainer = Component.extend({
	type : "GridPlotContainer",
	defaults : {
	    rows: 0,
	    columns : 0,
	    children : [[]]
	}
    });
    _.extend(GridPlotContainer.prototype.defaults,
	     {'shape' : [0,0]});

    var GridPlotContainerView = BokehView.extend({
	render: function(){
	    var self = this;
	    var row;
	    self.$el = $(self.el);
	    self.$el.append("

");
	    _.each(_.range(self.model.get('rows')), function(xidx){
		row = $("

");
		_.each(_.range(self.model.get('columns')), function(yidx){

		});
	    });

	}
    });

    //RegisterModels
    var Plots = Backbone.Collection.extend({
	model : Plot,
	url : "/",
    });

    var ScatterRenderers = Backbone.Collection.extend({
	model : ScatterRenderer,
	url : "/",
    });

    var ObjectArrayDataSources = Backbone.Collection.extend({
	model : ObjectArrayDataSource,
	url : "/",
    });

    Bokeh.register_collection('Plot', new Plots());
    Bokeh.register_collection('ScatterRenderer', new ScatterRenderers());
    Bokeh.register_collection('ObjectArrayDataSource', new ObjectArrayDataSources());

    Bokeh.ObjectArrayDataSource = ObjectArrayDataSource;
    Bokeh.HasParent = HasParent;
    Bokeh.Component = Component;
    Bokeh.Plot = Plot;

    Bokeh.BokehView = BokehView;
    Bokeh.PlotView = PlotView;

})();<|endoftext|>


<commit_before>'use strict'

class Link {

    get id() {

        return (this.linkElement) ? this.linkElement.id : undefined;

    };

    set id(newId) {

        this.linkElement.id = newId; // <? catch?

    };

    get path() {

        return this.linkElement.getAttribute('d');

    };

    set path(newPath) {

        this.linkElement.setAttribute('d', newPath);

    }

    constructor(startDock, snapDock = undefined) {

        this.startDock = startDock;
        this.type = startDock.type;

        this.createLink();

        this.id = startDock.id;

        if (snapDock) {

            this.snapDock = snapDock;
            this.update(snapDock.position);
            this.set();

        }

        this.startDock.link.push(this);

        // right-sided data docks are never occupied
        startDock.occupied = !(startDock.isRight && startDock.type == 'data');

    };

    createLink() {

        let template = document.querySelector('template#link');
        template = document.importNode(template.content, true);

        this.linkElement = template.querySelector('path');
        this.linkElement.style.stroke = Link.color[ this.type ];
        this.linkElement.style.strokeWidth = Link.width[ this.type ];

        Canvas.linkArea.appendChild(this.linkElement);

    };

    edit() {

        delete link[ this.id ];

        this.snapDock.link = []; // reset the old snapDock
        this.snapDock.occupied = false;

        delete this.snapDock;

        return this;

    };

    static updateAll() {

        Object.entries(link).forEach(([ id, link ]) => {

            link.update();

        });

    };

    update(endPoint) {

        if (!endPoint) {

            this.path = Curve.get(this.startDock.position, this.snapDock.position);

        } else if (this.startDock.isRight) {

            this.path = Curve.get(this.startDock.position, endPoint);

        } else {

            this.path = Curve.get(endPoint, this.startDock.position);

        }

    };

    remove() {

        this.linkElement.remove();

        // make it a Dock method <Dock>.unpin(this) where this is <Link>
        const linkIndexStartDock = this.startDock.link.findIndex(link => link.id == this.id);
        this.startDock.link.splice(linkIndexStartDock, 1);

        this.startDock.occupied = false;

        if (this.snapDock) {

            const linkIndexSnapDock = this.snapDock.link.findIndex(link => link.id == this.id);
            this.snapDock.link.splice(linkIndexSnapDock, 1);

            this.snapDock.occupied = false;

        }

    };

    set() {

        this.snapDock.link.push(this); // <- add to snapDock
        this.snapDock.occupied = true;

        // swap startDock and snapDock if necessary
        if (this.snapDock.isRight) {

            [ this.startDock, this.snapDock ] = [ this.snapDock, this.startDock ];

        }

        const linkId = this.startDock.id + Link.separator + this.snapDock.id;
        this.id = linkId;

        // this link already exists
        if (link[ linkId ]) {

            this.remove();

        // link doesn't yet exist
        } else {

            link[ linkId ] = this;

        }

    };

    static destruct(link) {

        return [ link.startDock.id, link.snapDock.id ];

    };

}; let link = {};

Object.assign(Link, {

    separator: '-',

    color: {
        data: 'green',
        exe: 'blue'
    },

    width: {
        data: 3,
        exe: 4
    }

});
<commit_msg>when snapping a link the interpreter will run<commit_after>'use strict'

class Link {

    get id() {

        return (this.linkElement) ? this.linkElement.id : undefined;

    };

    set id(newId) {

        this.linkElement.id = newId; // <? catch?

    };

    get path() {

        return this.linkElement.getAttribute('d');

    };

    set path(newPath) {

        this.linkElement.setAttribute('d', newPath);

    }

    constructor(startDock, snapDock = undefined) {

        this.startDock = startDock;
        this.type = startDock.type;

        this.createLink();

        this.id = startDock.id;

        if (snapDock) {

            this.snapDock = snapDock;
            this.update(snapDock.position);
            this.set();

        }

        this.startDock.link.push(this);

        // right-sided data docks are never occupied
        startDock.occupied = !(startDock.isRight && startDock.type == 'data');

    };

    createLink() {

        let template = document.querySelector('template#link');
        template = document.importNode(template.content, true);

        this.linkElement = template.querySelector('path');
        this.linkElement.style.stroke = Link.color[ this.type ];
        this.linkElement.style.strokeWidth = Link.width[ this.type ];

        Canvas.linkArea.appendChild(this.linkElement);

    };

    edit() {

        delete link[ this.id ];

        this.snapDock.link = []; // reset the old snapDock
        this.snapDock.occupied = false;

        delete this.snapDock;

        return this;

    };

    static updateAll() {

        Object.entries(link).forEach(([ id, link ]) => {

            link.update();

        });

    };

    update(endPoint) {

        if (!endPoint) {

            this.path = Curve.get(this.startDock.position, this.snapDock.position);

        } else if (this.startDock.isRight) {

            this.path = Curve.get(this.startDock.position, endPoint);

        } else {

            this.path = Curve.get(endPoint, this.startDock.position);

        }

    };

    remove() {

        // make sure the link is deleted in links! <? link with an "s"!!
        delete link [ this.id ];

        this.linkElement.remove();

        // make it a Dock method <Dock>.unpin(this) where this is <Link>
        const linkIndexStartDock = this.startDock.link.findIndex(link => link.id == this.id);
        this.startDock.link.splice(linkIndexStartDock, 1);

        this.startDock.occupied = false;

        if (this.snapDock) {

            const linkIndexSnapDock = this.snapDock.link.findIndex(link => link.id == this.id);
            this.snapDock.link.splice(linkIndexSnapDock, 1);

            this.snapDock.occupied = false;

        }

    };

    set() {

        this.snapDock.link.push(this); // <- add to snapDock
        this.snapDock.occupied = true;

        // swap startDock and snapDock if necessary
        if (this.snapDock.isRight) {

            [ this.startDock, this.snapDock ] = [ this.snapDock, this.startDock ];

        }

        const linkId = this.startDock.id + Link.separator + this.snapDock.id;
        this.id = linkId;

        // this link already exists
        if (link[ linkId ]) {

            this.remove();

        // link doesn't yet exist
        } else {

            link[ linkId ] = this;

            this.snapDock.node.solveDependency();

        }

    };

    static destruct(link) {

        return [ link.startDock.id, link.snapDock.id ];

    };

}; let link = {};

Object.assign(Link, {

    separator: '-',

    color: {
        data: 'green',
        exe: 'blue'
    },

    width: {
        data: 3,
        exe: 4
    }

});
<|endoftext|>


<commit_before>/*
 stripe the tables, take out when can figure how to do in wicket
 */
var setupTableStriping = function(){
    $('table').each(function(){
        $(this).find('tr:even').addClass('even');
    });
};

/*
 eliminate whitespace only text nodes
 needed to style the wicket pager
 */
jQuery.fn.htmlClean = function(){
    this.contents().filter(function(){
        if (this.nodeType != 3) {
            $(this).htmlClean();
            return false;
        }
        else {
            return !/\S/.test(this.nodeValue);
        }
    }).remove();
};

/*
 add css classes to wicket pager based on block having a link or not
 */
jQuery.fn.cssInstrument = function(){
    $('.pager > span').each(function(i){
        if ($(this).find('a').length === 1) {
            $(this).addClass('linky');
        }
        else {
            $(this).addClass('nolinky');
        }
    });
};

//toggle a fade
jQuery.fn.fadeToggle = function(speed, easing, callback){
    return this.animate({
        opacity: 'toggle'
    }, speed, easing, callback);

};

var setupMenus = function(){
    $('tr').mouseenter(function(){
        $(this).find('.actionPanelTrig').show();
    });
    $('tr').mouseleave(function(){
        $(this).find('.actionPanelTrig').hide();
    });
    $('.actionPanelTrig').click(function(e){
        e.preventDefault();
        $(this).closest('tr').addClass('focusedRow');
        var pos = $(this).closest('td.action').position();
        var height = $(this).closest('td').height();
        $('.actionPanel').hide();
        $(this).parent('td').find('.actionPanel').css({
            'position': 'absolute',
            'left': pos.left - 190,
            'top': pos.top + 3
        }).toggle();
    });

    $('.actionPanel').mouseleave(function(){
        $(this).hide();
        $(this).closest('tr').removeClass('focusedRow');
    });
};

var setupLinks = function(){
    $('.itemLink').click(function(e){
        e.preventDefault();
        var actionLink = "";
        var action = "";
        var link = $(this).attr('href');
        var title = $(this).text();
        var parentRow = $(this).closest('tr');
        var colCount = $(parentRow).find('td').length;
        var parentCell = $(this).closest('td');

        var itemType = $(this).closest('tr').find('.itemType').text();
        var entityReference = $(this).closest('tr').find('.entityReference').text();
        var callBackUrl = $(this).closest('body').find('.callBackUrl').text();

        //if disclosure in DOM, either hide or show, do not request data
        if ($(parentRow).next('tr.newRow').length === 1) {
            $(parentRow).next('tr.newRow').find('.results').fadeToggle('fast', '', function(){
                if ($(parentRow).next('tr.newRow').find('.results:visible').length === 0) {
                    $(parentCell).attr('class', 'tab');
                }
                else {
                    $(parentCell).attr('class', 'activeCell tab');
                }
            });
        }
        else {
            $(parentCell).attr('class', 'activeCell tab');
            params = {
                'entityType': itemType,
                'entityReference': entityReference
            };
            jQuery.ajax({
                url: callBackUrl,
                type: 'post',
                cache: false,
                data: JSON.stringify(params),
                contentType: 'application/json',
                dataType: 'json',
                success: function(json){
                    var results = '
';
                    if (json.order.length !== 0) {

                        $(json.order).each(function(i){
                            var o = this;
                            if (o.length > 1) {
                                results = results + '
'
                                for (i = 0; i < o.length; i++) {
                                    if (json[o[i].toString()]) {
                                        results = results + '' + json[o[i].toString()] + ' ';
                                    }
                                }
                                results = results + '
';
                            }
                            else {
                                var w = o.toString()
                                if (w === 'description' && json[w]) {
                                    results = results + '
' + json[w] + '
';
                                }
                                if (w === 'attachments' && json[w]) {
                                    var atts = "";
                                    for (i = 0; i < json[w].length; i++) {

                                        atts = atts + '
' + json[w][i]['attachment-title'] + '
';
                                    }
                                    results = results + '
' + atts + '
';
                                }
                                if (w === 'more-info' && json[w]) {
                                    var moreinfo = "";
                                    for (i = 0; i < json['more-info'].length; i++) {
                                        var target ="";
                                        var size ="";
                                        if (json['more-info'][i]['info_link-target']){
                                            target = 'target=\"' + json['more-info'][i]['info_link-target'] +'\"'
                                        }
                                        if (json['more-info'][i]['info_link-size']){
                                            size = ' (' + json['more-info'][i]['info_link-size'] +') '
                                        }

                                        moreinfo = moreinfo + '' + json['more-info'][i]['info_link-title'] + '' + size + '';
                                        ;
                                    }

                                    results = results + '
' + moreinfo + '

';
                                }

                            }

                        });

                    }
                    else {
                        results = results + 'This item type has not specified an order :(
';
                    }
                    $('
' + results + '
').insertAfter(parentRow);
                    $(parentRow).next('tr.newRow').find('.results').slideDown('slow', function(){
                        resizeFrame('grow');
                    });

                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    alert("error :" + XMLHttpRequest.responseText);
                }
            });
        }

    });
};

var setupLang = function(){
    langdata = eval('(' + $('#lang-holder').text() + ')');
};

var setupIcons = function(){
    $('.itemLink').each(function(i){
        if ($(this).closest('tr').find('.itemType').text() === 'resource') {
            $(this).addClass(getFileExtension($(this).attr('href')));
        }
    });
    function getFileExtension(filename){
        var ext = /^.+\.([^.]+)$/.exec(filename);
        return ext === null ? "" : ext[1].toLowerCase();
    }
};

/*
 resize the iframe based on the contained document height.
 used after DOM operations that add or substract to the doc height
 */
var resizeFrame = function(updown){
    var clientH;
    if (top.location !== self.location) {
        var frame = parent.document.getElementById(window.name);
    }
    if (frame) {
        if (updown === 'shrink') {
            clientH = document.body.clientHeight;
        }
        else {
            clientH = document.body.clientHeight + 50;
        }
        $(frame).height(clientH);
    }
    else {
        // throw( "resizeFrame did not get the frame (using name=" + window.name + ")" );
    }
};
<commit_msg>DASH-43 - correct some malformed results<commit_after>/*
 stripe the tables, take out when can figure how to do in wicket
 */
var setupTableStriping = function(){
    $('table').each(function(){
        $(this).find('tr:even').addClass('even');
    });
};

/*
 eliminate whitespace only text nodes
 needed to style the wicket pager
 */
jQuery.fn.htmlClean = function(){
    this.contents().filter(function(){
        if (this.nodeType != 3) {
            $(this).htmlClean();
            return false;
        }
        else {
            return !/\S/.test(this.nodeValue);
        }
    }).remove();
};

/*
 add css classes to wicket pager based on block having a link or not
 */
jQuery.fn.cssInstrument = function(){
    $('.pager > span').each(function(i){
        if ($(this).find('a').length === 1) {
            $(this).addClass('linky');
        }
        else {
            $(this).addClass('nolinky');
        }
    });
};

//toggle a fade
jQuery.fn.fadeToggle = function(speed, easing, callback){
    return this.animate({
        opacity: 'toggle'
    }, speed, easing, callback);

};

var setupMenus = function(){
    $('tr').mouseenter(function(){
        $(this).find('.actionPanelTrig').show();
    });
    $('tr').mouseleave(function(){
        $(this).find('.actionPanelTrig').hide();
    });
    $('.actionPanelTrig').click(function(e){
        e.preventDefault();
        $(this).closest('tr').addClass('focusedRow');
        var pos = $(this).closest('td.action').position();
        var height = $(this).closest('td').height();
        $('.actionPanel').hide();
        $(this).parent('td').find('.actionPanel').css({
            'position': 'absolute',
            'left': pos.left - 190,
            'top': pos.top + 3
        }).toggle();
    });

    $('.actionPanel').mouseleave(function(){
        $(this).hide();
        $(this).closest('tr').removeClass('focusedRow');
    });
};

var setupLinks = function(){
    $('.itemLink').click(function(e){
        e.preventDefault();
        var actionLink = "";
        var action = "";
        var link = $(this).attr('href');
        var title = $(this).text();
        var parentRow = $(this).closest('tr');
        var colCount = $(parentRow).find('td').length;
        var parentCell = $(this).closest('td');

        var itemType = $(this).closest('tr').find('.itemType').text();
        var entityReference = $(this).closest('tr').find('.entityReference').text();
        var callBackUrl = $(this).closest('body').find('.callBackUrl').text();

        //if disclosure in DOM, either hide or show, do not request data
        if ($(parentRow).next('tr.newRow').length === 1) {
            $(parentRow).next('tr.newRow').find('.results').fadeToggle('fast', '', function(){
                if ($(parentRow).next('tr.newRow').find('.results:visible').length === 0) {
                    $(parentCell).attr('class', 'tab');
                }
                else {
                    $(parentCell).attr('class', 'activeCell tab');
                }
            });
        }
        else {
            $(parentCell).attr('class', 'activeCell tab');
            params = {
                'entityType': itemType,
                'entityReference': entityReference
            };
            jQuery.ajax({
                url: callBackUrl,
                type: 'post',
                cache: false,
                data: JSON.stringify(params),
                contentType: 'application/json',
                dataType: 'json',
                success: function(json){
                    var results = '
';
                    if (json.order.length !== 0) {

                        $(json.order).each(function(i){
                            var o = this;
                            if (o.length > 1) {
                                results = results + '
'
                                for (i = 0; i < o.length; i++) {
                                    if (json[o[i].toString()]) {
                                        results = results + '' + json[o[i].toString()] + ' ';
                                    }
                                }
                                results = results + '
';
                            }
                            else {
                                var w = o.toString()
                                if (w === 'description' && json[w]) {
                                    results = results + '
' + json[w] + '
';
                                }
                                if (w === 'attachments' && json[w]) {
                                    var atts = "";
                                    for (i = 0; i < json[w].length; i++) {

                                        atts = atts + '
' + json[w][i]['attachment-title'] + '
';
                                    }
                                    results = results + '
' + atts + '
';
                                }
                                if (w === 'more-info' && json[w]) {
                                    var moreinfo = "";
                                    for (i = 0; i < json['more-info'].length; i++) {
                                        var target ="";
                                        var size ="";
                                        if (json['more-info'][i]['info_link-target']){
                                            target = 'target=\"' + json['more-info'][i]['info_link-target'] +'\"'
                                        }
                                        if (json['more-info'][i]['info_link-size']){
                                            size = ' (' + json['more-info'][i]['info_link-size'] +') '
                                        }

                                        moreinfo = moreinfo + '' + json['more-info'][i]['info_link-title'] + '' + size + '';
                                        ;
                                    }

                                    results = results + '
' + moreinfo + '
';
                                }

                            }

                        });
                        results = results + '
'
                    }
                    else {
                        results = results + 'This item type has not specified an order :(
';
                    }
                    $('
' + results + '
').insertAfter(parentRow);
                    $(parentRow).next('tr.newRow').find('.results').slideDown('slow', function(){
                        resizeFrame('grow');
                    });

                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    alert("error :" + XMLHttpRequest.responseText);
                }
            });
        }

    });
};

var setupLang = function(){
    langdata = eval('(' + $('#lang-holder').text() + ')');
};

var setupIcons = function(){
    $('.itemLink').each(function(i){
        if ($(this).closest('tr').find('.itemType').text() === 'resource') {
            $(this).addClass(getFileExtension($(this).attr('href')));
        }
    });
    function getFileExtension(filename){
        var ext = /^.+\.([^.]+)$/.exec(filename);
        return ext === null ? "" : ext[1].toLowerCase();
    }
};

/*
 resize the iframe based on the contained document height.
 used after DOM operations that add or substract to the doc height
 */
var resizeFrame = function(updown){
    var clientH;
    if (top.location !== self.location) {
        var frame = parent.document.getElementById(window.name);
    }
    if (frame) {
        if (updown === 'shrink') {
            clientH = document.body.clientHeight;
        }
        else {
            clientH = document.body.clientHeight + 50;
        }
        $(frame).height(clientH);
    }
    else {
        // throw( "resizeFrame did not get the frame (using name=" + window.name + ")" );
    }
};
<|endoftext|>


<commit_before>/**
 * @preserve Copyright 2012 Martijn van de Rijdt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var CACHE_CHECK_INTERVAL = 3600*1000;

/**
 * Cache Class deals with the HTML5 applicationCache
 * @constructor
 */
function Cache(){
	'use strict';
}

/**
 * Initializes Cache object
 * @return {boolean} returns false if applicationCache is not supported
 */
Cache.prototype.init = function(){
	var appCache,
		that = this;

	//first check if it is supported
	if (!this.isSupported){
		return false;
	}

	appCache = window.applicationCache;
	//TODO: USE NOUPDATE EVENT INSTEAD!
	setTimeout(function(){
		if (appCache.status === 1){
			gui.updateStatus.offlineLaunch(true);
			that.showBookmarkMsg();
		}
	}, 60 * 1000);

	if (appCache.status === appCache.UPDATEREADY){
		this.onUpdateReady();
	}
	if (appCache.status === appCache.OBSOLETE){
		this.onObsolete();
	}

	//manifest is no longer served (form removed or offline-launch disabled)
	$(appCache).on('obsolete', function(){that.onObsolete();});

	//the very first time an application cache is saved
	$(appCache).on('cached', function(){that.onCached();});

	//when an updated cache is downloaded and ready to be used
	$(appCache).on('updateready', function(){that.onUpdateReady();});

	//when an error occurs (not necessarily serious)
	$(appCache).on('error', function(e){that.onErrors(e);});

	setInterval(function(){
		that.update();
		//applicationCache.update();
	}, CACHE_CHECK_INTERVAL);

	return true;
};

/**
 * Checks for manifest changes which would trigger an applicationCache update
 */
Cache.prototype.update = function(){
	window.applicationCache.update();
};

/**
 * Handler for cache obsolete event
 */
Cache.prototype.onObsolete = function(){
	store.removeRecord('__bookmark');
	gui.confirm({
		msg: 'Refreshing the page may restore it.',
		heading: 'Offline-disabled.',
		errorMsg: 'Application/form is no longer able to launch offline. '
	},{
		posButton: 'Ok',
		negButton: 'Refresh',
		posAction: function(){},
		negAction: function(){document.location.reload(true);}
	});
	gui.updateStatus.offlineLaunch(false);
};

/**
 * Handler for newly-cached event
 */
Cache.prototype.onCached = function(){
	this.showBookmarkMsg('This form works offline!
', true);
	gui.updateStatus.offlineLaunch(true);
};

/**
 * Handler for cache update-ready event
 */
Cache.prototype.onUpdateReady = function(){
	applicationCache.swapCache();
	gui.feedback("A new version of this application or form has been downloaded. "+
		"Refresh this page to load the updated version.", 20, 'Updated!',  {
			posButton: 'Refresh',
			negButton: 'Cancel',
			posAction: function(){document.location.reload(true);}
		}
	);
};

/*
gui.confirm({
			msg: '
A new version of this application has been downloaded.
'+
				'
 Refresh the window to start using it.',
			heading: 'Updated!'
		},{
			posButton: 'Refresh',
			negButton: 'Cancel',
			posAction: function(){document.location.reload(true);}
		});
*/

/**
 * Handler for cache error
 * @param  {*} e jQuery error object
 */
Cache.prototype.onErrors = function(e){
	if (connection.currentOnlineStatus === true){
		console.error('HTML5 cache error event', e);
		gui.alert('There is a new version of this application or form available but an error occurs when'+
			' trying to download it. Please try to refresh the page or send a bug report to '+
			''+settings['supportEmail']+'.');
		// Possible to trigger cache problem for testing? ->
		// 1. going offline, 2.manifest with unavailable resource, 3. manifest syntax error
	}
};

/**
 * Shows a bookmark advisory message. The first time this is prepended with an 'Offline-capable!' message
 *
 * @param  {string=} prepend message to prepend to standard bookmark message
 * @param  {boolean=} force   whether to force the message regardless of how many times it has been shown already
 */
Cache.prototype.showBookmarkMsg = function(prepend, force){
	var bookmark, shown;
	prepend = prepend || '';
	force = force || false;
	//reminder to bookmark page will be shown 3 times
	bookmark = store.getRecord('__bookmark');
	shown = (bookmark) ? bookmark['shown'] : 0;
	if(force || shown < 3){
		gui.feedback(prepend+'Bookmark this form for easy '+
			'offline access. ', 15);
			//'This reminder will be shown '+(2-shown)+' more '+time+'.', 20);
		shown++;
		store.setRecord('__bookmark', {'shown': shown});
	}
};

/**
 * check if applicationCache is supported in browser
 * @return {boolean} [description]
 */
Cache.prototype.isSupported = function(){
	return (window.applicationCache) ? true : false;
};

<commit_msg>using no update event for bookmark reminder, closes #260<commit_after>/**
 * @preserve Copyright 2012 Martijn van de Rijdt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Cache Class deals with the HTML5 applicationCache
 * @constructor
 */
function Cache(){
	'use strict';
	this.CACHE_CHECK_INTERVAL = 3600*1000;
}

/**
 * Initializes Cache object
 * @return {boolean} returns false if applicationCache is not supported
 */
Cache.prototype.init = function(){
	var appCache,
		that = this;

	//first check if it is supported
	if (!this.isSupported){
		return false;
	}

	appCache = window.applicationCache;
	//TODO: USE NOUPDATE EVENT INSTEAD!
	/**setTimeout(function(){
		if (appCache.status === 1){
			gui.updateStatus.offlineLaunch(true);
			that.showBookmarkMsg();
		}
	}, 60 * 1000);**/

	if (appCache.status === appCache.UPDATEREADY){
		this.onUpdateReady();
	}
	if (appCache.status === appCache.OBSOLETE){
		this.onObsolete();
	}

	//manifest is no longer served (form removed or offline-launch disabled)
	$(appCache).on('obsolete', function(){that.onObsolete();});

	//the very first time an application cache is saved
	$(appCache).on('cached', function(){that.onCached();});

	//when an updated cache is downloaded and ready to be used
	$(appCache).on('updateready', function(){
		if (appCache.status === appCache.UPDATEREADY){
			that.onUpdateReady();
		}
	});

	//when an error occurs (not necessarily serious)
	$(appCache).on('error', function(e){that.onErrors(e);});

	$(appCache).on('noupdate', function(){that.onNoUpdate();});

	setInterval(function(){
		that.update();
		//applicationCache.update();
	}, this.CACHE_CHECK_INTERVAL);

	return true;
};

/**
 * Checks for manifest changes which would trigger an applicationCache update
 */
Cache.prototype.update = function(){
	window.applicationCache.update();
};

/**
 * Handler for cache obsolete event
 */
Cache.prototype.onObsolete = function(){
	store.removeRecord('__bookmark');
	gui.confirm({
		msg: 'Refreshing the page may restore it.',
		heading: 'Offline-disabled.',
		errorMsg: 'Application/form is no longer able to launch offline. '
	},{
		posButton: 'Ok',
		negButton: 'Refresh',
		posAction: function(){},
		negAction: function(){document.location.reload(true);}
	});
	gui.updateStatus.offlineLaunch(false);
};

/**
 * Handler for newly-cached event
 */
Cache.prototype.onCached = function(){
	this.showBookmarkMsg('This form works offline!
', true);
	gui.updateStatus.offlineLaunch(true);
};

/**
 * Handler for no-update event
 */
Cache.prototype.onNoUpdate = function(){
	this.showBookmarkMsg();
	gui.updateStatus.offlineLaunch(true);
};

/**
 * Handler for cache update-ready event
 */
Cache.prototype.onUpdateReady = function(){
	applicationCache.swapCache();
	gui.feedback("A new version of this application or form has been downloaded. "+
		"Refresh this page to load the updated version.", 20, 'Updated!',  {
			posButton: 'Refresh',
			negButton: 'Cancel',
			posAction: function(){document.location.reload(true);}
		}
	);
};

/*
gui.confirm({
			msg: '
A new version of this application has been downloaded.
'+
				'
 Refresh the window to start using it.',
			heading: 'Updated!'
		},{
			posButton: 'Refresh',
			negButton: 'Cancel',
			posAction: function(){document.location.reload(true);}
		});
*/

/**
 * Handler for cache error
 * @param  {*} e jQuery error object
 */
Cache.prototype.onErrors = function(e){
	if (connection.currentOnlineStatus === true){
		console.error('HTML5 cache error event', e);
		gui.alert('There is a new version of this application or form available but an error occurs when'+
			' trying to download it. Please try to refresh the page or send a bug report to '+
			''+settings['supportEmail']+'.');
		// Possible to trigger cache problem for testing? ->
		// 1. going offline, 2.manifest with unavailable resource, 3. manifest syntax error
	}
};

/**
 * Shows a bookmark advisory message. The first time this is prepended with an 'Offline-capable!' message
 *
 * @param  {string=} prepend message to prepend to standard bookmark message
 * @param  {boolean=} force   whether to force the message regardless of how many times it has been shown already
 */
Cache.prototype.showBookmarkMsg = function(prepend, force){
	var bookmark, shown;
	prepend = prepend || '';
	force = force || false;
	//reminder to bookmark page will be shown 3 times
	bookmark = store.getRecord('__bookmark');
	shown = (bookmark) ? bookmark['shown'] : 0;
	if(force || shown < 3){
		gui.feedback(prepend+'Bookmark this form for easy '+
			'offline access. ', 15);
			//'This reminder will be shown '+(2-shown)+' more '+time+'.', 20);
		shown++;
		store.setRecord('__bookmark', {'shown': shown});
	}
};

/**
 * check if applicationCache is supported in browser
 * @return {boolean} [description]
 */
Cache.prototype.isSupported = function(){
	return (window.applicationCache) ? true : false;
};

<|endoftext|>


<commit_before>import gulp from 'gulp'
import nodemon from 'gulp-nodemon'
import livereload from 'gulp-livereload'
import config from './config'
import { watch, bundle } from './tasks/browserify'
import { lessDev, lessDist } from './tasks/less'
import { spawn } from 'child_process'
import { debounce } from 'lodash'
import upload from './tasks/upload'
import updateHeroku from './tasks/updateHeroku'
import rev from 'gulp-rev'
import { exec } from 'shelljs'

// make gulp respond to Ctrl-C
process.once('SIGINT', () => process.exit(0))

gulp.task('watch-js', watch)
gulp.task('build-dev-css', lessDev)

gulp.task('serve', function () {
  nodemon({
    script: './src/server',
    exec: './node_modules/.bin/babel-node',
    ignore: ['public/**/*']
  })
})

gulp.task('autotest', function () {
  gulp.watch(['src/**/*', 'test/**/*'], debounce(function () {
    let cmd = 'env LOG_LEVEL=warn npm test -- -R progress'.split(' ')
    spawn(cmd[0], cmd.slice(1, cmd.length), {stdio: 'inherit'})
  }, 500, true))
})

gulp.task('watch', function () {
  if (config.livereload) livereload.listen()
  gulp.watch('css/**/*.less', ['build-dev-css'])
})

gulp.task('default', ['watch-js', 'serve', 'watch'])

// ---------------------------------------------------------------------
// deployment tasks
// ---------------------------------------------------------------------

gulp.task('clean-dist', function () {
  return exec('rm -r dist', {silent: true})
})

gulp.task('copy-dist-images', function () {
  return gulp.src('public/img/**/*', {base: 'public'})
  .pipe(rev())
  .pipe(gulp.dest('dist'))
  .pipe(rev.manifest({base: 'dist', path: 'dist/manifest.json', merge: true}))
  .pipe(gulp.dest('dist'))
})

gulp.task('build-dist-js', bundle)
gulp.task('build-dist-css', ['copy-dist-images'], lessDist)
gulp.task('build-dist', ['clean-dist', 'copy-dist-images', 'build-dist-js', 'build-dist-css'])
gulp.task('upload', upload)
gulp.task('updateHeroku', updateHeroku)
<commit_msg>add deploy gulp task<commit_after>import gulp from 'gulp'
import nodemon from 'gulp-nodemon'
import livereload from 'gulp-livereload'
import config from './config'
import { watch, bundle } from './tasks/browserify'
import { lessDev, lessDist } from './tasks/less'
import { spawn } from 'child_process'
import { debounce } from 'lodash'
import upload from './tasks/upload'
import updateHeroku from './tasks/updateHeroku'
import rev from 'gulp-rev'
import { exec } from 'shelljs'

// make gulp respond to Ctrl-C
process.once('SIGINT', () => process.exit(0))

gulp.task('watch-js', watch)
gulp.task('build-dev-css', lessDev)

gulp.task('serve', function () {
  nodemon({
    script: './src/server',
    exec: './node_modules/.bin/babel-node',
    ignore: ['public/**/*']
  })
})

gulp.task('autotest', function () {
  gulp.watch(['src/**/*', 'test/**/*'], debounce(function () {
    let cmd = 'env LOG_LEVEL=warn npm test -- -R progress'.split(' ')
    spawn(cmd[0], cmd.slice(1, cmd.length), {stdio: 'inherit'})
  }, 500, true))
})

gulp.task('watch', function () {
  if (config.livereload) livereload.listen()
  gulp.watch('css/**/*.less', ['build-dev-css'])
})

gulp.task('default', ['watch-js', 'serve', 'watch'])

// ---------------------------------------------------------------------
// deployment tasks
// ---------------------------------------------------------------------

gulp.task('clean-dist', function () {
  return exec('rm -r dist', {silent: true})
})

gulp.task('copy-dist-images', function () {
  return gulp.src('public/img/**/*', {base: 'public'})
  .pipe(rev())
  .pipe(gulp.dest('dist'))
  .pipe(rev.manifest({base: 'dist', path: 'dist/manifest.json', merge: true}))
  .pipe(gulp.dest('dist'))
})

gulp.task('build-dist-js', bundle)
gulp.task('build-dist-css', ['copy-dist-images'], lessDist)
gulp.task('build-dist', ['clean-dist', 'copy-dist-images', 'build-dist-js', 'build-dist-css'])

// these are for testing individual steps
gulp.task('upload', upload)
gulp.task('updateHeroku', updateHeroku)

// these are for enforcing the sequence of tasks
gulp.task('deploy-1', ['build-dist'], upload)
gulp.task('deploy', ['deploy-1'], updateHeroku)
<|endoftext|>


<commit_before>/*jshint browser: true, jquery: true */
/*global clique, _ */

function bigramGraph() {
    "use strict";

    return $.getJSON("assets/bigram.json").then(function (bigram) {
        var alphabet = "abcdefghijklmnopqrstuvwxyz",
            nodes = [],
            links = [],
            threshold = 1 / 676,
            aCodePoint = "a".codePointAt(0);

        _.each(alphabet, function (letter) {
            nodes.push({
                name: letter
            });
        });

        _.each(alphabet, function (first) {
            _.each(alphabet, function (second) {
                if (first !== second && bigram[first + second] > threshold) {
                    links.push({
                        source: first.codePointAt(0) - aCodePoint,
                        target: second.codePointAt(0) - aCodePoint
                    });
                }
            });
        });

        return {
            nodes: nodes,
            links: links
        };
    });
}

$(function () {
    "use strict";

    bigramGraph().then(function (graphData) {
        var graph,
            view,
            info;

        window.graph = graph = new clique.Graph({
            adapter: new clique.adapter.NodeLinkList(graphData)
        });

        $("#seed").on("click", function () {
            var name = $("#name").val().trim(),
                spec,
                radiusText = $("#radius").val().trim(),
                radius = Number(radiusText);

            if (name === "" || radiusText === "" || isNaN(radius)) {
                return;
            }

            spec = {
                name: name
            };

            graph.adapter.findNode(spec)
                .then(function (center) {
                    if (center) {
                        graph.addNeighborhood(center, radius);
                    }
                });
        });

        window.view = view = new clique.view.Cola({
            model: graph,
            el: "#content",
            linkDistance: 200,
            fill: function (d) {
                var colors = [
                    "rgb(166,206,227)",
                    "rgb(31,120,180)",
                    "rgb(178,223,138)",
                    "rgb(51,160,44)",
                    "rgb(251,154,153)",
                    "rgb(227,26,28)",
                    "rgb(253,191,111)",
                    "rgb(255,127,0)",
                    "rgb(202,178,214)",
                    "rgb(106,61,154)",
                    "rgb(255,255,153)",
                    "rgb(177,89,40)"
                ];

                return colors[(d.data.name.codePointAt(0) - "a".codePointAt(0)) % colors.length];
            }
        });

        info = new clique.view.SelectionInfo({
            model: view.selection,
            el: "#info",
            graph: graph,
            nodeButtons: [
                {
                    label: "Hide",
                    color: "purple",
                    icon: "eye-close",
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.hideNode, this)(node);
                    }
                },
                {
                    label: function (node) {
                        return node.getData("deleted") ? "Undelete" : "Delete";
                    },
                    color: "red",
                    icon: "remove",
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.deleteNode, this)(node);
                    }
                },
                {
                    label: "Ungroup",
                    color: "blue",
                    icon: "scissors",
                    callback: function (node) {
                        console.log(node);
                    },
                    show: function (node) {
                        return node.getData("grouped");
                    }

                },
                {
                    label: "Expand",
                    color: "blue",
                    icon: "fullscreen",
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.expandNode, this)(node);
                    }
                },
                {
                    label: "Collapse",
                    color: "blue",
                    icon: "resize-small",
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.collapseNode, this)(node);
                    }
                }
            ],
            selectionButtons: [
                {
                    label: "Hide",
                    color: "purple",
                    icon: "eye-close",
                    repeat: true,
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.hideNode, this)(node);
                    }
                },
                {
                    label: "Delete",
                    color: "red",
                    icon: "remove",
                    repeat: true,
                    callback: function (node) {
                        return _.bind(clique.view.SelectionInfo.deleteNode, this)(node);
                    }
                },
                {
                    label: "Expand",
                    color: "blue",
                    icon: "fullscreen",
                    repeat: true,
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.expandNode, this)(node);
                    }
                },
                {
                    label: "Collapse",
                    color: "blue",
                    icon: "resize-small",
                    repeat: true,
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.collapseNode, this)(node);
                    }
                }
            ]
        });
        info.render();
    });
});
<commit_msg>Make example graph a bit sparser<commit_after>/*jshint browser: true, jquery: true */
/*global clique, _ */

function bigramGraph() {
    "use strict";

    return $.getJSON("assets/bigram.json").then(function (bigram) {
        var alphabet = "abcdefghijklmnopqrstuvwxyz",
            nodes = [],
            links = [],
            threshold = 3 * (1 / 676),
            aCodePoint = "a".codePointAt(0);

        _.each(alphabet, function (letter) {
            nodes.push({
                name: letter
            });
        });

        _.each(alphabet, function (first) {
            _.each(alphabet, function (second) {
                if (first !== second && bigram[first + second] > threshold) {
                    links.push({
                        source: first.codePointAt(0) - aCodePoint,
                        target: second.codePointAt(0) - aCodePoint
                    });
                }
            });
        });

        return {
            nodes: nodes,
            links: links
        };
    });
}

$(function () {
    "use strict";

    bigramGraph().then(function (graphData) {
        var graph,
            view,
            info;

        window.graph = graph = new clique.Graph({
            adapter: new clique.adapter.NodeLinkList(graphData)
        });

        $("#seed").on("click", function () {
            var name = $("#name").val().trim(),
                spec,
                radiusText = $("#radius").val().trim(),
                radius = Number(radiusText);

            if (name === "" || radiusText === "" || isNaN(radius)) {
                return;
            }

            spec = {
                name: name
            };

            graph.adapter.findNode(spec)
                .then(function (center) {
                    if (center) {
                        graph.addNeighborhood(center, radius);
                    }
                });
        });

        window.view = view = new clique.view.Cola({
            model: graph,
            el: "#content",
            linkDistance: 200,
            fill: function (d) {
                var colors = [
                    "rgb(166,206,227)",
                    "rgb(31,120,180)",
                    "rgb(178,223,138)",
                    "rgb(51,160,44)",
                    "rgb(251,154,153)",
                    "rgb(227,26,28)",
                    "rgb(253,191,111)",
                    "rgb(255,127,0)",
                    "rgb(202,178,214)",
                    "rgb(106,61,154)",
                    "rgb(255,255,153)",
                    "rgb(177,89,40)"
                ];

                return colors[(d.data.name.codePointAt(0) - "a".codePointAt(0)) % colors.length];
            }
        });

        info = new clique.view.SelectionInfo({
            model: view.selection,
            el: "#info",
            graph: graph,
            nodeButtons: [
                {
                    label: "Hide",
                    color: "purple",
                    icon: "eye-close",
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.hideNode, this)(node);
                    }
                },
                {
                    label: function (node) {
                        return node.getData("deleted") ? "Undelete" : "Delete";
                    },
                    color: "red",
                    icon: "remove",
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.deleteNode, this)(node);
                    }
                },
                {
                    label: "Ungroup",
                    color: "blue",
                    icon: "scissors",
                    callback: function (node) {
                        console.log(node);
                    },
                    show: function (node) {
                        return node.getData("grouped");
                    }

                },
                {
                    label: "Expand",
                    color: "blue",
                    icon: "fullscreen",
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.expandNode, this)(node);
                    }
                },
                {
                    label: "Collapse",
                    color: "blue",
                    icon: "resize-small",
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.collapseNode, this)(node);
                    }
                }
            ],
            selectionButtons: [
                {
                    label: "Hide",
                    color: "purple",
                    icon: "eye-close",
                    repeat: true,
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.hideNode, this)(node);
                    }
                },
                {
                    label: "Delete",
                    color: "red",
                    icon: "remove",
                    repeat: true,
                    callback: function (node) {
                        return _.bind(clique.view.SelectionInfo.deleteNode, this)(node);
                    }
                },
                {
                    label: "Expand",
                    color: "blue",
                    icon: "fullscreen",
                    repeat: true,
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.expandNode, this)(node);
                    }
                },
                {
                    label: "Collapse",
                    color: "blue",
                    icon: "resize-small",
                    repeat: true,
                    callback: function (node) {
                        _.bind(clique.view.SelectionInfo.collapseNode, this)(node);
                    }
                }
            ]
        });
        info.render();
    });
});
<|endoftext|>


<commit_before>jQuery(function ($) {

    'use strict';

    var starIcon = L.icon({
        iconUrl:      'static/images/star_icon.png',
        iconSize:     [30, 30],
        shadowSize:   [0, 0],
        iconAnchor:   [15, 15],
        shadowAnchor: [0, 0],
        popupAnchor:  [-15, -15]
    });

    var mapParams = {
        attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
        subdomains: 'abcd',
        minZoom: 0,
        maxZoom: 18,
    };

    if ($('#homepage-map').length) {
        var map = L.map('homepage-map').setView([45.0649, 7.6767], 15);
        L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}.png', mapParams).addTo(map);
        L.marker([45.0649, 7.6952], {icon: starIcon}).addTo(map);
        L.marker([45.0654, 7.6585], {icon: starIcon}).addTo(map);
    }

    // --------------------------------------------------------------------
    // One Page Navigation
    // --------------------------------------------------------------------

    (function () {
        $(window).scroll(function () {
            var nav = $('nav.navbar');

            if (nav.closest('.home').length != 0) {
                if ($(this).scrollTop() >= 40) {
                    nav.addClass('sticky-nav');
                }
                else {
                    nav.removeClass('sticky-nav');
                }
            }
            else {
                if ($(this).scrollTop() > 0) {
                    nav.addClass('sticky-nav');
                }
                else {
                    nav.removeClass('sticky-nav');
                }
            }
        });
    }());

    // --------------------------------------------------------------------
    // Smooth scrolling, requires jump.js
    // --------------------------------------------------------------------

    var elements = document.querySelectorAll('ul.navbar-nav li a');
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        element.addEventListener('click', function(e) {
            // Don't execute the animation if the user is using a browser not
            // supporting the API (Opera Mini and IE9)
            if (window.requestAnimationFrame) {

                // Do the nice scrolling only if we're in the current page
                if (this.pathname == document.location.pathname) {
                    e.preventDefault();

                    Jump(this.hash, {
                        duration: 1500,
                    });
                }
            }
        }.bind(element));
    }

    // --------------------------------------------------------------------
    // Closes the Responsive Menu on Menu Item Click
    // --------------------------------------------------------------------

    (function () {
        $('.navbar-collapse ul li a').on('click', function () {
            if ($(this).attr('class') != 'dropdown-toggle active' && $(this).attr('class') != 'dropdown-toggle') {
                $('.navbar-toggle:visible').trigger('click');
            }
        });
    }());

    $('#contactForm').submit(function(e) {
        e.preventDefault();
        var button = $(this).find('button[type=submit]');
        button.prop('disabled', true);

        $.ajax({
            url: 'static/register.php',
            method: 'POST',
            data: {
                email: $(this).find('input[name=email]').val(),
                mode: 'js'
            },
            success: function(data) {
                if (data == 'ok') {
                    button.text('Iscritto!');
                }
                else {
                    button.text('Errore!');
                    button.prop('disabled', false);
                }
            },
            error: function() {
                button.text('Errore!');
                button.prop('disabled', false);
            }
        });
    });

    $('#C4PForm').submit(function(e) {
        e.preventDefault();
        var button = $(this).find('button[type=submit]');
        button.prop('disabled', true);

        $.ajax({
            url: 'https://postegg.madbob.org/save/1e91d390-dc60-11e7-9e12-1dc6a5470eaa',
            method: 'POST',
            data: $(this).serialize(),
            success: function(data) {
                button.text('Candidatura inviata!');
            },
            error: function() {
                button.text('Errore!');
                button.prop('disabled', false);
            }
        });
    });

}); // JQuery end
<commit_msg>soppressa gestione JS del form candidature C4P (facciamola facile...)<commit_after>jQuery(function ($) {

    'use strict';

    var starIcon = L.icon({
        iconUrl:      'static/images/star_icon.png',
        iconSize:     [30, 30],
        shadowSize:   [0, 0],
        iconAnchor:   [15, 15],
        shadowAnchor: [0, 0],
        popupAnchor:  [-15, -15]
    });

    var mapParams = {
        attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
        subdomains: 'abcd',
        minZoom: 0,
        maxZoom: 18,
    };

    if ($('#homepage-map').length) {
        var map = L.map('homepage-map').setView([45.0649, 7.6767], 15);
        L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}.png', mapParams).addTo(map);
        L.marker([45.0649, 7.6952], {icon: starIcon}).addTo(map);
        L.marker([45.0654, 7.6585], {icon: starIcon}).addTo(map);
    }

    // --------------------------------------------------------------------
    // One Page Navigation
    // --------------------------------------------------------------------

    (function () {
        $(window).scroll(function () {
            var nav = $('nav.navbar');

            if (nav.closest('.home').length != 0) {
                if ($(this).scrollTop() >= 40) {
                    nav.addClass('sticky-nav');
                }
                else {
                    nav.removeClass('sticky-nav');
                }
            }
            else {
                if ($(this).scrollTop() > 0) {
                    nav.addClass('sticky-nav');
                }
                else {
                    nav.removeClass('sticky-nav');
                }
            }
        });
    }());

    // --------------------------------------------------------------------
    // Smooth scrolling, requires jump.js
    // --------------------------------------------------------------------

    var elements = document.querySelectorAll('ul.navbar-nav li a');
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        element.addEventListener('click', function(e) {
            // Don't execute the animation if the user is using a browser not
            // supporting the API (Opera Mini and IE9)
            if (window.requestAnimationFrame) {

                // Do the nice scrolling only if we're in the current page
                if (this.pathname == document.location.pathname) {
                    e.preventDefault();

                    Jump(this.hash, {
                        duration: 1500,
                    });
                }
            }
        }.bind(element));
    }

    // --------------------------------------------------------------------
    // Closes the Responsive Menu on Menu Item Click
    // --------------------------------------------------------------------

    (function () {
        $('.navbar-collapse ul li a').on('click', function () {
            if ($(this).attr('class') != 'dropdown-toggle active' && $(this).attr('class') != 'dropdown-toggle') {
                $('.navbar-toggle:visible').trigger('click');
            }
        });
    }());

    $('#contactForm').submit(function(e) {
        e.preventDefault();
        var button = $(this).find('button[type=submit]');
        button.prop('disabled', true);

        $.ajax({
            url: 'static/register.php',
            method: 'POST',
            data: {
                email: $(this).find('input[name=email]').val(),
                mode: 'js'
            },
            success: function(data) {
                if (data == 'ok') {
                    button.text('Iscritto!');
                }
                else {
                    button.text('Errore!');
                    button.prop('disabled', false);
                }
            },
            error: function() {
                button.text('Errore!');
                button.prop('disabled', false);
            }
        });
    });

}); // JQuery end
<|endoftext|>