<commit_before>'use strict';

var logger = require('log4js').getLogger('cloudify.blueprints');
/**
 * @typedef {object} Blueprint
 *
 * @property {string} id The identifier of the blueprint
 * @property {number} created_at timestamp of blueprint creation
 * @property {object} the contents of the blueprint. plan Gets the plan the blueprints represents: nodes, relationships etc..
 */

/**
 * @description
 * collection of API calls for blueprints
 * @class BlueprintsClient
 * @param {ClientConfig} config
 * @constructor
 */
function BlueprintsClient( config ){
    this.config = config;
}

/**
 * @param {IncludeParam} [_include] list of fields to include in response
 * @param {ApiCallback} callback body gets a list of blueprints
 */
BlueprintsClient.prototype.list = function( _include, callback ){
    logger.trace('listing blueprints');
    var qs = {};
    if ( !!_include ){
        qs._include = _include;
    }
    return this.config.request( {
        'method' : 'GET',
        'url' : this.config.endpoint + '/blueprints',
        'qs' : qs
    }, callback );
};

/**
 * @description
 * Gets  a bluprint by its id.
 * @param {string} blueprint_id Blueprint's id to get
 * @param {IncludeParam} [_include] List of fields to include in response
 * @param {ApiCallback} callback body gets the blueprint
 */
BlueprintsClient.prototype.get = function (blueprint_id, _include, callback) {
    logger.trace('getting blueprint by id');
    var qs = {};
    if (!!_include) {
        qs._include = _include;
    }

    return this.config.request({
            'method': 'GET',
            'url': String.format(this.config.endpoint + '/blueprints/{0}', blueprint_id ),
            'qs': qs
        }, callback );
};

/**
 * @description Deltes the blueprint whose id matches the provided blueprint id.
 * @param {string} blueprint_id the id of the blueprint to be deleted
 * @param {ApiCallback} callback body gets the deleted blueprint
 */
BlueprintsClient.prototype.delete = function(blueprint_id, callback ){
    logger.trace('deleting blueprint');
    return this.config.request({
        'method' : 'DELETE',
        'url' : String.format(this.config.endpoint + '/blueprints/{0}', blueprint_id )
    }, callback );
};

///// ONLY ADD FUNCTION THAT MIGHT NOT BE IMPLEMENTED FROM THIS POINT ON..

// ignore undefined variables.
/* jshint unused: false */
/**
 *
 * @description
 * uploads a blueprint to cloudify's manager.
 *
 * @exception error if function is not implemented. not all clients implement this function.
 *
 * @param {string} [blueprint_path] main blueprint yaml file path.
 * @param {string} blueprint_id id of the uploaded blueprint
 * @param {ApiCallback} callback body gets the uploaded blueprint
 */
BlueprintsClient.prototype.upload = function( blueprint_path , blueprint_id, callback ){
    logger.trace('uploading blueprint');
    throw new Error('this function is not implemented');
};

/**
 *
 * @description
 * downloads aa previously uploaded blueprint from cloudify's manager.
 *
 * @param {string} blueprint_id
 * @param {string} output_file
 * @param {ApiCallback} callback body gets the path of downloaded  blueprint
 */
BlueprintsClient.prototype.download = function( blueprint_id, output_file, callback  ){
    logger.trace('downloading blueprint');
    throw new Error('this function is not implemented');
};

module.exports = BlueprintsClient;<commit_msg>Added blueprint validate call<commit_after>'use strict';

var logger = require('log4js').getLogger('cloudify.blueprints');
/**
 * @typedef {object} Blueprint
 *
 * @property {string} id The identifier of the blueprint
 * @property {number} created_at timestamp of blueprint creation
 * @property {object} the contents of the blueprint. plan Gets the plan the blueprints represents: nodes, relationships etc..
 */

/**
 * @description
 * collection of API calls for blueprints
 * @class BlueprintsClient
 * @param {ClientConfig} config
 * @constructor
 */
function BlueprintsClient( config ){
    this.config = config;
}

/**
 * @param {IncludeParam} [_include] list of fields to include in response
 * @param {ApiCallback} callback body gets a list of blueprints
 */
BlueprintsClient.prototype.list = function( _include, callback ){
    logger.trace('listing blueprints');
    var qs = {};
    if ( !!_include ){
        qs._include = _include;
    }
    return this.config.request( {
        'method' : 'GET',
        'url' : this.config.endpoint + '/blueprints',
        'qs' : qs
    }, callback );
};

/**
 * @description
 * Gets  a bluprint by its id.
 * @param {string} blueprint_id Blueprint's id to get
 * @param {IncludeParam} [_include] List of fields to include in response
 * @param {ApiCallback} callback body gets the blueprint
 */
BlueprintsClient.prototype.get = function (blueprint_id, _include, callback) {
    logger.trace('getting blueprint by id');
    var qs = {};
    if (!!_include) {
        qs._include = _include;
    }

    return this.config.request({
            'method': 'GET',
            'url': String.format(this.config.endpoint + '/blueprints/{0}', blueprint_id ),
            'qs': qs
        }, callback );
};

/**
 * @description
 * Gets  a bluprint by its id.
 * @param {string} blueprint_id Blueprint's id to validate
 * @param {IncludeParam} [_include] List of fields to include in response
 * @param {ApiCallback} callback body gets the blueprint validation result
 */
BlueprintsClient.prototype.validate = function (blueprint_id, _include, callback) {
    logger.trace('validating blueprint by id');
    var qs = {};
    if (!!_include) {
        qs._include = _include;
    }

    return this.config.request({
        'method': 'GET',
        'url': String.format(this.config.endpoint + '/blueprints/{0}/validate', blueprint_id ),
        'qs': qs
    }, callback );
};

/**
 * @description Deltes the blueprint whose id matches the provided blueprint id.
 * @param {string} blueprint_id the id of the blueprint to be deleted
 * @param {ApiCallback} callback body gets the deleted blueprint
 */
BlueprintsClient.prototype.delete = function(blueprint_id, callback ){
    logger.trace('deleting blueprint');
    return this.config.request({
        'method' : 'DELETE',
        'url' : String.format(this.config.endpoint + '/blueprints/{0}', blueprint_id )
    }, callback );
};

///// ONLY ADD FUNCTION THAT MIGHT NOT BE IMPLEMENTED FROM THIS POINT ON..

// ignore undefined variables.
/* jshint unused: false */
/**
 *
 * @description
 * uploads a blueprint to cloudify's manager.
 *
 * @exception error if function is not implemented. not all clients implement this function.
 *
 * @param {string} [blueprint_path] main blueprint yaml file path.
 * @param {string} blueprint_id id of the uploaded blueprint
 * @param {ApiCallback} callback body gets the uploaded blueprint
 */
BlueprintsClient.prototype.upload = function( blueprint_path , blueprint_id, callback ){
    logger.trace('uploading blueprint');
    throw new Error('this function is not implemented');
};

/**
 *
 * @description
 * downloads aa previously uploaded blueprint from cloudify's manager.
 *
 * @param {string} blueprint_id
 * @param {string} output_file
 * @param {ApiCallback} callback body gets the path of downloaded  blueprint
 */
BlueprintsClient.prototype.download = function( blueprint_id, output_file, callback  ){
    logger.trace('downloading blueprint');
    throw new Error('this function is not implemented');
};

module.exports = BlueprintsClient;<|endoftext|>


<commit_before>/**
 * Map functionality. This file should be refactored, currently it is
 * a bunch of functionality thrown together without much coherence.
 */

function touchHandler(event)
{
    var touches = event.changedTouches,
        first = touches[0],
        type = "";

         switch(event.type)
    {
        case "touchstart": type = "mousedown"; break;
        case "touchmove":  type="mousemove"; break;
        case "touchend":   type="mouseup"; break;
        default: return;
    }

             //initMouseEvent(type, canBubble, cancelable, view, clickCount,
    //           screenX, screenY, clientX, clientY, ctrlKey,
    //           altKey, shiftKey, metaKey, button, relatedTarget);

    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1,
                              first.screenX, first.screenY,
                              first.clientX, first.clientY, false,
                              false, false, false, 0/*left*/, null);

                                                                                first.target.dispatchEvent(simulatedEvent);
//    event.preventDefault();
}

document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);

$(function()
{
    var filtersShowing = true;

    function showFilterTool() {
        filtersShowing = true;
        $(".filtertool-contents").show();
        $("#apply-btn").show();
        $("#hide-btn").text("Hide");
    }

    function hideFilterTool() {
        $(".filtertool-contents").hide();
        $("#apply-btn").hide();
        $("#hide-btn").text("Show");
        filtersShowing = false;
    }

    $("#hide-btn").click(
        function()
        {
            filtersShowing ? hideFilterTool() : showFilterTool();
        });

    var allSources = ['twitter', 'instagram', 'vbdb'];

    var hashToState = function(hash) {
        return JSON.parse(decodeURIComponent(hash.substr(1)));
    };
    var stateToHash = function(state) {
        return encodeURIComponent(JSON.stringify(state));
    };

    var ItemMapping = {
        'twitter': function(item)
        {
            this.fullName = function() {
                return this.data.original.user.name;
            };
            this.markerImage = function() {
                return "/img/blue.png";
            };
            return this;
        },
        'instagram': function() {
            this.fullName = function() {
                return this.data.original.user.full_name;
            };
            this.markerImage = function() {
                return "/img/red.png";
            };
            return this;
        },
        'vbdb': function() {
            this.fullName = function() {
                return 'Verbeter de Buurt';
            };
            this.markerImage = function() {
                return "/img/green.png";
            };
            return this;
        }
    };
    var ItemFactory = function(item) {
        var inst = new ItemMapping[item.source]();
        inst.data = item;
        var s = item.location.split(",");
        inst.latlng = new google.maps.LatLng(parseFloat(s[0]), parseFloat(s[1]));
        inst.marker = new google.maps.Marker({position: inst.latlng, icon: inst.markerImage()});
        return inst;
    };

    $(".do_timebar:first").timebar();
    var timebar = $(".do_timebar:first").data('timebar');

    var myOptions = {
        center: new google.maps.LatLng(52.310550, 4.957151),
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map"),
                                  myOptions);

    var getState = function() {
        var c = map.getCenter();
        var sources = [];
        $("input.source:checked").each(function() { sources.push($(this).attr("id").substr(4));});
        return [c.lat(), c.lng(), map.getZoom(),sources, view, timebar.getBracket()];
    };
    var applyState = function(state) {
        map.setCenter(new google.maps.LatLng(state[0], state[1]));
        map.setZoom(state[2]);
        $("input.source").each(function(){$(this).removeAttr("checked"); if ($.inArray($(this).attr("id").substr(4), state[3])>=0) $(this).attr("checked", "checked");});
        view = state[4];
        $("input.view").removeAttr("checked");
        $("#view-" + view).attr("checked", "checked");
        timebar.setBracket(state[5][0], state[5][1]);
    };

    var allItems = {};
    var loading = false;
    var lastLoad = null;
    var lastNumResults = 0;
    var view = 'items';

    if (document.location.hash) {
        try {
            var state = hashToState(document.location.hash);
            applyState(state);
        } catch (x) {
        }
    }

    function linkURLS(text) {
        var linkWithProtocol = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
        text = text.replace(linkWithProtocol, '$1');

        var linkWithoutProtocol = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
        text = text.replace(linkWithoutProtocol, '$1$2');

        var linkEmail = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
        text = text.replace(linkEmail, '$1');

        return text;
    }

    var infowindow = new google.maps.InfoWindow({disableAutoPan: true});

    function showInfoWindow(item)
    {
        var showitem = function(detail) {
            $.extend(item.data, detail);
            var html = "";
            html += "
" + item.fullName() + " @ " + detail.date + "
";
            if (detail.thumbnail) html +="

";
            if (detail.text) html +="
"+linkURLS(detail.text)+"
";
            infowindow.setContent(html);
            infowindow.setPosition(item.latlng);
            infowindow.open(map);
        };

        $.ajax({url: '/item?id=' + encodeURIComponent(item.data.id),
                success: showitem
               });
    }
    google.maps.event.addListener(map, 'click', function(){infowindow.close();});

    function loadData(incremental)
    {
        document.location = "#" + stateToHash(getState());

        if (loading) return;
        $("#loader").show();
        loading = true;

        var b = map.getBounds();

        var c = b.getCenter();
        var r = google.maps.geometry.spherical.computeDistanceBetween(
            new google.maps.LatLng(c.lat(), b.getSouthWest().lng()),
            c);

        var srci = $("#src-instagram:checked").length > 0;
        var srct = $("#src-twitter:checked").length > 0;

        var sources = "";
        $("input.source:checked").each(function() { sources += " source: " + $(this).attr("id").substr(4);});
        if (sources)
            sources = "+(" + sources + ")";

        var v = $("#q").val().trim();
        var txt = v ? (" +alltext:"+v) : "";
        var args = {'from': Util.ISODateString(incremental ? lastLoad : timebar.timeLeft),
                    'to': Util.ISODateString(timebar.timeRight),
                    'start': Util.ISODateString(timebar.timeStart),
                    'end': Util.ISODateString(timebar.timeEnd),
                    'lat': c.lat(),
                    'lon': c.lng(),
                    'radius': Math.ceil(r/1000),
                    'facet': !incremental,
                    'q': sources + txt
                   };

        $.ajax({url: '/query?' + $.param(args),
                success: function(r) {
                    lastLoad = new Date();
                    lastNumResults = incremental ? (lastNumResults + r.response.numFound) : r.response.numFound;
                    var html = "";
                    html += "
Results: " + lastNumResults + "
";
                    $("#stats").html(html);

                    if (r.facet_counts) {
                        var data = r.facet_counts.facet_dates.date;
                        delete data.gap; delete data.start; delete data.end;
                        timebar.setData(r.facet_counts.facet_dates.date);
                    }

                    var hit = {};
                    var numnew = 0;
                    var lastnew = null;
                    var lastnewdist = null;

                    $(r.response.docs).each(function() {
                                                var el = this;
                                                hit[el.id] = true;
                                                if (el.id in allItems) {
                                                    if (view == 'items') allItems[el.id].marker.setVisible(true);
                                                    return;
                                                }
                                                var item = ItemFactory(el);
                                                google.maps.event.addListener(item.marker, 'click', function(){showInfoWindow(item);});
                                                numnew++;
                                                if (numnew < 2) {
                                                    item.marker.setAnimation(google.maps.Animation.DROP);
                                                    var r = google.maps.geometry.spherical.computeDistanceBetween(item.latlng, c);
                                                    if (lastnewdist === null || r < lastnewdist)
                                                        lastnew = item;
                                                }
                                                allItems[item.data.id] = item;
                                                if (view != 'items') allItems[el.id].marker.setVisible(false);
                                                item.marker.setMap(map);
                                            });
                    if (view == 'heatmap') {
                        for (var i in allItems) allItems[i].marker.setVisible(false);
                    }
                    hoverlay.heatmap.setVisible(view == 'heatmap');
                    if (!incremental) {
                        for (var id in allItems) if (!hit[id]) allItems[id].marker.setVisible(false);
                        if (view == 'heatmap') refreshHeatmap(r);
                    }
                    if (lastnew && view == 'items')
                        showInfoWindow(lastnew);
                    $("#loader").hide();
                    loading = false;
                },
                error: function() {
                    $("#loader").hide();
                    loading = false;
                }
               });
    }

    // heatmap
    var hoverlay = new HeatmapOverlay(map, {"radius":50, "visible":true, "opacity":80});

    function refreshHeatmap(r) {
        var dataset = {data: [], max: 1};

        r = r.facet_counts.facet_fields.geohash_8;

        for (var i=0; i< r.length; i+= 2) {
            var hash = r[i].substr(1);
            var c = r[i+1];
            var h = decodeGeoHash(hash);

            var lat = h.latitude[2];
            var lng = h.longitude[2];

            dataset.data.push({lat: lat, lng: lng, count: c});
            dataset.max = Math.max(dataset.max, c);
        }
/*
        for (var id in allItems) {
            if (!allItems[id].marker.getVisible()) continue;
            var p = allItems[id].latlng;
            dataset.data.push({lat: p.lat(), lng: p.lng(), count: 1});
        }
*/
        hoverlay.setDataSet(dataset);
    }

    var mapChangeTimer = Util.IdleTimer(1000, loadData);
    google.maps.event.addListener(map, 'bounds_changed', function() {
                                      mapChangeTimer.bump();
                                  });

    Util.PubSub.subscribe('timebar-change', function(timebar) {
                              loadData(timebar);
                          });

    setInterval(function() {
                    if(timebar.timeRight > new Date()) {
                        // poll when we're in "realtime" mode
                        loadData(true);
                    }
                }, 5000);

    $("#filter-form").submit(
        function(e) {
            e.preventDefault();
            loadData();
        });

    var geocoder = new google.maps.Geocoder();

    $("#location-form").submit(
        function(e) {
            e.preventDefault();
            var address = $("#location").val();
            geocoder.geocode({
                                 address: address,
                                 region: 'nl'},
                             function(results, status) {
                                 if (status == google.maps.GeocoderStatus.OK) {
                                     map.setCenter(results[0].geometry.location);
                                 } else {
                                     alert("Geocode was not successful for the following reason: " + status);
                                 }
                            });
        });

    $("input.view").change(
        function() {
            view = $("input.view:checked").val();
            mapChangeTimer.bump();
        });
});<commit_msg>added links to user profiles. Cannot find documentation for vbdb API — how do you call username and/or link to profile?<commit_after>/**
 * Map functionality. This file should be refactored, currently it is
 * a bunch of functionality thrown together without much coherence.
 */

function touchHandler(event)
{
    var touches = event.changedTouches,
        first = touches[0],
        type = "";

         switch(event.type)
    {
        case "touchstart": type = "mousedown"; break;
        case "touchmove":  type="mousemove"; break;
        case "touchend":   type="mouseup"; break;
        default: return;
    }

             //initMouseEvent(type, canBubble, cancelable, view, clickCount,
    //           screenX, screenY, clientX, clientY, ctrlKey,
    //           altKey, shiftKey, metaKey, button, relatedTarget);

    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1,
                              first.screenX, first.screenY,
                              first.clientX, first.clientY, false,
                              false, false, false, 0/*left*/, null);

                                                                                first.target.dispatchEvent(simulatedEvent);
//    event.preventDefault();
}

document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);

$(function()
{
    var filtersShowing = true;

    function showFilterTool() {
        filtersShowing = true;
        $(".filtertool-contents").show();
        $("#apply-btn").show();
        $("#hide-btn").text("Hide");
    }

    function hideFilterTool() {
        $(".filtertool-contents").hide();
        $("#apply-btn").hide();
        $("#hide-btn").text("Show");
        filtersShowing = false;
    }

    $("#hide-btn").click(
        function()
        {
            filtersShowing ? hideFilterTool() : showFilterTool();
        });

    var allSources = ['twitter', 'instagram', 'vbdb'];

    var hashToState = function(hash) {
        return JSON.parse(decodeURIComponent(hash.substr(1)));
    };
    var stateToHash = function(state) {
        return encodeURIComponent(JSON.stringify(state));
    };

    var ItemMapping = {
        'twitter': function(item)
        {
            this.fullName = function() {
                return this.data.original.user.name;
            };
            this.userURL = function() {
                return "http://www.twitter.com/#!/" + this.data.original.user.screen_name;
            };
            this.markerImage = function() {
                return "/img/blue.png";
            };
            return this;
        },
        'instagram': function() {
            this.fullName = function() {
                return this.data.original.user.full_name;
            };
            this.userURL = function() {
                return this.data.original.link;
            };
            this.markerImage = function() {
                return "/img/red.png";
            };
            return this;
        },
        'vbdb': function() {
            this.fullName = function() {
                return 'Verbeter de Buurt';
            };
            this.userURL = function() {
                return "";
            };
            this.markerImage = function() {
                return "/img/green.png";
            };
            return this;
        }
    };
    var ItemFactory = function(item) {
        var inst = new ItemMapping[item.source]();
        inst.data = item;
        var s = item.location.split(",");
        inst.latlng = new google.maps.LatLng(parseFloat(s[0]), parseFloat(s[1]));
        inst.marker = new google.maps.Marker({position: inst.latlng, icon: inst.markerImage()});
        return inst;
    };

    $(".do_timebar:first").timebar();
    var timebar = $(".do_timebar:first").data('timebar');

    var myOptions = {
        center: new google.maps.LatLng(52.310550, 4.957151),
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map"),
                                  myOptions);

    var getState = function() {
        var c = map.getCenter();
        var sources = [];
        $("input.source:checked").each(function() { sources.push($(this).attr("id").substr(4));});
        return [c.lat(), c.lng(), map.getZoom(),sources, view, timebar.getBracket()];
    };
    var applyState = function(state) {
        map.setCenter(new google.maps.LatLng(state[0], state[1]));
        map.setZoom(state[2]);
        $("input.source").each(function(){$(this).removeAttr("checked"); if ($.inArray($(this).attr("id").substr(4), state[3])>=0) $(this).attr("checked", "checked");});
        view = state[4];
        $("input.view").removeAttr("checked");
        $("#view-" + view).attr("checked", "checked");
        timebar.setBracket(state[5][0], state[5][1]);
    };

    var allItems = {};
    var loading = false;
    var lastLoad = null;
    var lastNumResults = 0;
    var view = 'items';

    if (document.location.hash) {
        try {
            var state = hashToState(document.location.hash);
            applyState(state);
        } catch (x) {
        }
    }

    function linkURLS(text) {
        var linkWithProtocol = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
        text = text.replace(linkWithProtocol, '$1');

        var linkWithoutProtocol = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
        text = text.replace(linkWithoutProtocol, '$1$2');

        var linkEmail = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
        text = text.replace(linkEmail, '$1');

        return text;
    }

    var infowindow = new google.maps.InfoWindow({disableAutoPan: true});

    function showInfoWindow(item)
    {
        var showitem = function(detail) {
            $.extend(item.data, detail);
            var html = "";
            html += "
" item.fullName() + "" " @ " + detail.date + "
";
            if (detail.thumbnail) html +="

";
            if (detail.text) html +="
"+linkURLS(detail.text)+"
";
            infowindow.setContent(html);
            infowindow.setPosition(item.latlng);
            infowindow.open(map);
        };

        $.ajax({url: '/item?id=' + encodeURIComponent(item.data.id),
                success: showitem
               });
    }
    google.maps.event.addListener(map, 'click', function(){infowindow.close();});

    function loadData(incremental)
    {
        document.location = "#" + stateToHash(getState());

        if (loading) return;
        $("#loader").show();
        loading = true;

        var b = map.getBounds();

        var c = b.getCenter();
        var r = google.maps.geometry.spherical.computeDistanceBetween(
            new google.maps.LatLng(c.lat(), b.getSouthWest().lng()),
            c);

        var srci = $("#src-instagram:checked").length > 0;
        var srct = $("#src-twitter:checked").length > 0;

        var sources = "";
        $("input.source:checked").each(function() { sources += " source: " + $(this).attr("id").substr(4);});
        if (sources)
            sources = "+(" + sources + ")";

        var v = $("#q").val().trim();
        var txt = v ? (" +alltext:"+v) : "";
        var args = {'from': Util.ISODateString(incremental ? lastLoad : timebar.timeLeft),
                    'to': Util.ISODateString(timebar.timeRight),
                    'start': Util.ISODateString(timebar.timeStart),
                    'end': Util.ISODateString(timebar.timeEnd),
                    'lat': c.lat(),
                    'lon': c.lng(),
                    'radius': Math.ceil(r/1000),
                    'facet': !incremental,
                    'q': sources + txt
                   };

        $.ajax({url: '/query?' + $.param(args),
                success: function(r) {
                    lastLoad = new Date();
                    lastNumResults = incremental ? (lastNumResults + r.response.numFound) : r.response.numFound;
                    var html = "";
                    html += "
Results: " + lastNumResults + "
";
                    $("#stats").html(html);

                    if (r.facet_counts) {
                        var data = r.facet_counts.facet_dates.date;
                        delete data.gap; delete data.start; delete data.end;
                        timebar.setData(r.facet_counts.facet_dates.date);
                    }

                    var hit = {};
                    var numnew = 0;
                    var lastnew = null;
                    var lastnewdist = null;

                    $(r.response.docs).each(function() {
                                                var el = this;
                                                hit[el.id] = true;
                                                if (el.id in allItems) {
                                                    if (view == 'items') allItems[el.id].marker.setVisible(true);
                                                    return;
                                                }
                                                var item = ItemFactory(el);
                                                google.maps.event.addListener(item.marker, 'click', function(){showInfoWindow(item);});
                                                numnew++;
                                                if (numnew < 2) {
                                                    item.marker.setAnimation(google.maps.Animation.DROP);
                                                    var r = google.maps.geometry.spherical.computeDistanceBetween(item.latlng, c);
                                                    if (lastnewdist === null || r < lastnewdist)
                                                        lastnew = item;
                                                }
                                                allItems[item.data.id] = item;
                                                if (view != 'items') allItems[el.id].marker.setVisible(false);
                                                item.marker.setMap(map);
                                            });
                    if (view == 'heatmap') {
                        for (var i in allItems) allItems[i].marker.setVisible(false);
                    }
                    hoverlay.heatmap.setVisible(view == 'heatmap');
                    if (!incremental) {
                        for (var id in allItems) if (!hit[id]) allItems[id].marker.setVisible(false);
                        if (view == 'heatmap') refreshHeatmap(r);
                    }
                    if (lastnew && view == 'items')
                        showInfoWindow(lastnew);
                    $("#loader").hide();
                    loading = false;
                },
                error: function() {
                    $("#loader").hide();
                    loading = false;
                }
               });
    }

    // heatmap
    var hoverlay = new HeatmapOverlay(map, {"radius":50, "visible":true, "opacity":80});

    function refreshHeatmap(r) {
        var dataset = {data: [], max: 1};

        r = r.facet_counts.facet_fields.geohash_8;

        for (var i=0; i< r.length; i+= 2) {
            var hash = r[i].substr(1);
            var c = r[i+1];
            var h = decodeGeoHash(hash);

            var lat = h.latitude[2];
            var lng = h.longitude[2];

            dataset.data.push({lat: lat, lng: lng, count: c});
            dataset.max = Math.max(dataset.max, c);
        }
/*
        for (var id in allItems) {
            if (!allItems[id].marker.getVisible()) continue;
            var p = allItems[id].latlng;
            dataset.data.push({lat: p.lat(), lng: p.lng(), count: 1});
        }
*/
        hoverlay.setDataSet(dataset);
    }

    var mapChangeTimer = Util.IdleTimer(1000, loadData);
    google.maps.event.addListener(map, 'bounds_changed', function() {
                                      mapChangeTimer.bump();
                                  });

    Util.PubSub.subscribe('timebar-change', function(timebar) {
                              loadData(timebar);
                          });

    setInterval(function() {
                    if(timebar.timeRight > new Date()) {
                        // poll when we're in "realtime" mode
                        loadData(true);
                    }
                }, 5000);

    $("#filter-form").submit(
        function(e) {
            e.preventDefault();
            loadData();
        });

    var geocoder = new google.maps.Geocoder();

    $("#location-form").submit(
        function(e) {
            e.preventDefault();
            var address = $("#location").val();
            geocoder.geocode({
                                 address: address,
                                 region: 'nl'},
                             function(results, status) {
                                 if (status == google.maps.GeocoderStatus.OK) {
                                     map.setCenter(results[0].geometry.location);
                                 } else {
                                     alert("Geocode was not successful for the following reason: " + status);
                                 }
                            });
        });

    $("input.view").change(
        function() {
            view = $("input.view:checked").val();
            mapChangeTimer.bump();
        });
});<|endoftext|>


<commit_before>"use strict";

var path = require( 'path' ),
    util = require('util'),
    _ = require('lodash'),
    logger = null,
    rocambole = require("rocambole"),
    rocamboleToken = require("rocambole-token");

// function that allows you iterate and also break out of the iteration
var _eachTokenInBetween = function(startToken, endToken, iterator) {
  var last = endToken && endToken.next;
  while (startToken && startToken !== last) {
    var ret = iterator(startToken);
    if(!ret) {
      break;
    }
    startToken = startToken.next;
  }
};

var _stripTagsFromFeatureText = function(featureText) {
 return featureText.replace(':start', '').replace(':end', '').replace(':file', '');
};

var _commentOutEntireFile = function(ast, tokensToRemove) {
  // Remove comment tokens that have been previously added
  if(tokensToRemove) {
    tokensToRemove.forEach(function(token) {
      rocamboleToken.remove(token);
    });
  }

  rocamboleToken.eachInBetween(ast.startToken, ast.endToken, function(token) {
    // Block comments could have newline chars, so we need to comment those out too.
    if(token.type === 'BlockComment') {
      token.raw = token.raw.replace(/\n/g, "\n//");
    }

    if(rocamboleToken.isBr(token.next)) {
      var newToken = {
        type : 'Custom', // can be anything (not used internally)
        value : '// '
      };
      rocamboleToken.after(token.next, newToken);
    }
  });
};

var _commentOutExcludedFeatures = function(ast, includedFeatures, excludedFeatures) {
    // Keeps track of whether a particular feature should be commented out or not as we iterate
    // over all the tokens
    var featureStatusList = [];
    var shouldCommentOutEntireFile = false;
    var newCommentTokens = [];
    _eachTokenInBetween(ast.startToken, ast.endToken, function(token) {
      // Find all of the block comments in the file
      if(token.type === 'BlockComment') {
        var comment = token.value;
        var isFeatureComment = comment.match(/ feature .*?/) !== null;
        if(isFeatureComment) {
          var fNameString = comment.replace('feature', '').trim();
          var fNameList = fNameString.split(',');
          var containsIncludedFeature = _.filter(fNameList, function(fName) {
            return includedFeatures.indexOf(_stripTagsFromFeatureText(fName)) !== -1;
          }).length > 0;

          // Iterate over all of the features that are mentioned in the comment
          for (var i = 0; i < fNameList.length; i++) {
            var fName = fNameList[i];
            var shouldExcludeFeature = excludedFeatures.indexOf(_stripTagsFromFeatureText(fName)) !== -1 &&
                                      !containsIncludedFeature;

            // Only comment out feature if it's in the exludedFeatures array AND the comment doesn't mention any features that
            // are in the includedFeatures array
            if(shouldExcludeFeature) {
              var cleanFName;
              var featureStatus;
              var existingFeatureStatus;
              if(fName.indexOf(":file") !== -1) {
                shouldCommentOutEntireFile = true;
                // Break out of loop
                return false;
              } else if(fName.indexOf(":start") !== -1) {
                // Start commenting out a :start feature
                cleanFName = fName.replace(":start", "");
                existingFeatureStatus = _.findWhere(featureStatusList, {name:cleanFName, type:"multiLine"});
                if(existingFeatureStatus) {
                  existingFeatureStatus.comment = true;
                } else {
                  featureStatus = {
                    type: "multiLine",
                    name: cleanFName,
                    comment: true
                  };
                  featureStatusList.push(featureStatus);
                }
              } else if(fName.indexOf(":end") !== -1) {
                // Stop commenting out the closest matching :start feature
                cleanFName = fName.replace(":end", "");
                var startingFeature = _.findWhere(featureStatusList, {name:cleanFName, type:"multiLine"});
                if(startingFeature) {
                  startingFeature.comment = false;
                }
              } else {
                // Start commenting out a single line feature
                cleanFName = fName;
                existingFeatureStatus = _.findWhere(featureStatusList, {name:cleanFName, type:"singleLine"});
                if(existingFeatureStatus) {
                  existingFeatureStatus.comment = true;
                } else {
                  featureStatus = {
                    type: "singleLine",
                    name: cleanFName,
                    comment: true
                  };
                  featureStatusList.push(featureStatus);
                }
              }
            }

          }
        }
      }

      // Actually comment out the line
      var shouldComment = shouldCommentOutEntireFile || _.where(featureStatusList, {comment:true}).length > 0;
      if(shouldComment) {
        // Block comments could have newline chars, so we need to comment those out too.
        if(token.type === 'BlockComment') {
          token.raw = token.raw.replace(/\n/g, "\n//");
        }
        if(rocamboleToken.isBr(token.next)) {
          var newToken = {
            type : 'Custom', // can be anything (not used internally)
            value : '// '
          };
          rocamboleToken.after(token.next, newToken);
          newCommentTokens.push(newToken);

          // Stop commenting single line features
          var singleLineFeatureStatusList = _.where(featureStatusList, {type: "singleLine"});
          singleLineFeatureStatusList.forEach(function(f) {
            f.comment = false;
          });
        }
      }

      return true;
    });

    if(shouldCommentOutEntireFile) {
      _commentOutEntireFile(ast, newCommentTokens);
    }
};

var _defeature = function( mimosaConfig, options, next ) {
  if ( !options.isVendor && options.files && options.files.length ) {
    options.files.forEach( function( file ) {
      var includedFeatures = mimosaConfig.defeature.includedFeatures;
      var excludedFeatures = mimosaConfig.defeature.excludedFeatures;
      // Do a quick check to see if the file has any feature comments before
      // doing any heavy processing
      var shouldDefeatureFile = false;
      for (var i = 0; i < excludedFeatures.length; i++) {
        var featureName = excludedFeatures[i];
        var featureMatcher = new RegExp("/\\* feature .*?"+ featureName + ".*? \\*/", "g");
        if(featureMatcher.test(file.inputFileText)) {
          shouldDefeatureFile = true;
          break;
        }
      }

      if(shouldDefeatureFile) {
        try {
          var ast = rocambole.parse(file.inputFileText);
          _commentOutExcludedFeatures(ast, includedFeatures, excludedFeatures);
          file.inputFileText = ast.toString();
        } catch(error) {
          logger.error("Unable to defeature file [[ " + file.outputFileName + " ]] due to parsing errors ", error);
        }
      }

    });
  }

  next();
};

exports.registration = function( mimosaConfig, register ) {
  logger = mimosaConfig.log;
  var exts = mimosaConfig.extensions.javascript;
  register(
    ['add', 'update', 'remove', 'buildFile'],
    'afterRead',
    _defeature,
    exts
  );
};<commit_msg>removing white space at end of blank lines<commit_after>"use strict";

var path = require( 'path' ),
    util = require('util'),
    _ = require('lodash'),
    logger = null,
    rocambole = require("rocambole"),
    rocamboleToken = require("rocambole-token");

// function that allows you iterate and also break out of the iteration
var _eachTokenInBetween = function(startToken, endToken, iterator) {
  var last = endToken && endToken.next;
  while (startToken && startToken !== last) {
    var ret = iterator(startToken);
    if(!ret) {
      break;
    }
    startToken = startToken.next;
  }
};

var _stripTagsFromFeatureText = function(featureText) {
 return featureText.replace(':start', '').replace(':end', '').replace(':file', '');
};

var _processBrToken = function(token) {
  var newTokenValue = '// ';
  // No trailing whitespace on last line
  // or on any empty lines
  if (!token.next.next || rocamboleToken.isBr(token.next.next)) {
    newTokenValue = '//';
  }
  var newToken = {
    type : 'Custom', // can be anything (not used internally)
    value : newTokenValue
  };
  rocamboleToken.after(token.next, newToken);

  return newToken;
};

var _commentOutEntireFile = function(ast, tokensToRemove) {
  // Remove comment tokens that have been previously added
  if(tokensToRemove) {
    tokensToRemove.forEach(function(token) {
      rocamboleToken.remove(token);
    });
  }

  rocamboleToken.eachInBetween(ast.startToken, ast.endToken, function(token) {
    // Block comments could have newline chars, so we need to comment those out too.
    if(token.type === 'BlockComment') {
      token.raw = token.raw.replace(/\n/g, "\n//");
    }

    if(rocamboleToken.isBr(token.next)) {
      _processBrToken(token);
    }
  });
};

var _commentOutExcludedFeatures = function(ast, includedFeatures, excludedFeatures) {
    // Keeps track of whether a particular feature should be commented out or not as we iterate
    // over all the tokens
    var featureStatusList = [];
    var shouldCommentOutEntireFile = false;
    var newCommentTokens = [];
    _eachTokenInBetween(ast.startToken, ast.endToken, function(token) {
      // Find all of the block comments in the file
      if(token.type === 'BlockComment') {
        var comment = token.value;
        var isFeatureComment = comment.match(/ feature .*?/) !== null;
        if(isFeatureComment) {
          var fNameString = comment.replace('feature', '').trim();
          var fNameList = fNameString.split(',');
          var containsIncludedFeature = _.filter(fNameList, function(fName) {
            return includedFeatures.indexOf(_stripTagsFromFeatureText(fName)) !== -1;
          }).length > 0;

          // Iterate over all of the features that are mentioned in the comment
          for (var i = 0; i < fNameList.length; i++) {
            var fName = fNameList[i];
            var shouldExcludeFeature = excludedFeatures.indexOf(_stripTagsFromFeatureText(fName)) !== -1 &&
                                      !containsIncludedFeature;

            // Only comment out feature if it's in the exludedFeatures array AND the comment doesn't mention any features that
            // are in the includedFeatures array
            if(shouldExcludeFeature) {
              var cleanFName;
              var featureStatus;
              var existingFeatureStatus;
              if(fName.indexOf(":file") !== -1) {
                shouldCommentOutEntireFile = true;
                // Break out of loop
                return false;
              } else if(fName.indexOf(":start") !== -1) {
                // Start commenting out a :start feature
                cleanFName = fName.replace(":start", "");
                existingFeatureStatus = _.findWhere(featureStatusList, {name:cleanFName, type:"multiLine"});
                if(existingFeatureStatus) {
                  existingFeatureStatus.comment = true;
                } else {
                  featureStatus = {
                    type: "multiLine",
                    name: cleanFName,
                    comment: true
                  };
                  featureStatusList.push(featureStatus);
                }
              } else if(fName.indexOf(":end") !== -1) {
                // Stop commenting out the closest matching :start feature
                cleanFName = fName.replace(":end", "");
                var startingFeature = _.findWhere(featureStatusList, {name:cleanFName, type:"multiLine"});
                if(startingFeature) {
                  startingFeature.comment = false;
                }
              } else {
                // Start commenting out a single line feature
                cleanFName = fName;
                existingFeatureStatus = _.findWhere(featureStatusList, {name:cleanFName, type:"singleLine"});
                if(existingFeatureStatus) {
                  existingFeatureStatus.comment = true;
                } else {
                  featureStatus = {
                    type: "singleLine",
                    name: cleanFName,
                    comment: true
                  };
                  featureStatusList.push(featureStatus);
                }
              }
            }

          }
        }
      }

      // Actually comment out the line
      var shouldComment = shouldCommentOutEntireFile || _.where(featureStatusList, {comment:true}).length > 0;
      if(shouldComment) {
        // Block comments could have newline chars, so we need to comment those out too.
        if(token.type === 'BlockComment') {
          token.raw = token.raw.replace(/\n/g, "\n//");
        }
        if(rocamboleToken.isBr(token.next)) {
          var newToken = _processBrToken(token);
          newCommentTokens.push(newToken);

          // Stop commenting single line features
          var singleLineFeatureStatusList = _.where(featureStatusList, {type: "singleLine"});
          singleLineFeatureStatusList.forEach(function(f) {
            f.comment = false;
          });
        }
      }

      return true;
    });

    if(shouldCommentOutEntireFile) {
      _commentOutEntireFile(ast, newCommentTokens);
    }
};

var _defeature = function( mimosaConfig, options, next ) {
  if ( !options.isVendor && options.files && options.files.length ) {
    options.files.forEach( function( file ) {
      var includedFeatures = mimosaConfig.defeature.includedFeatures;
      var excludedFeatures = mimosaConfig.defeature.excludedFeatures;
      // Do a quick check to see if the file has any feature comments before
      // doing any heavy processing
      var shouldDefeatureFile = false;
      for (var i = 0; i < excludedFeatures.length; i++) {
        var featureName = excludedFeatures[i];
        var featureMatcher = new RegExp("/\\* feature .*?"+ featureName + ".*? \\*/", "g");
        if(featureMatcher.test(file.inputFileText)) {
          shouldDefeatureFile = true;
          break;
        }
      }

      if(shouldDefeatureFile) {
        try {
          var ast = rocambole.parse(file.inputFileText);
          _commentOutExcludedFeatures(ast, includedFeatures, excludedFeatures);
          file.inputFileText = ast.toString();
        } catch(error) {
          logger.error("Unable to defeature file [[ " + file.outputFileName + " ]] due to parsing errors ", error);
        }
      }

    });
  }

  next();
};

exports.registration = function( mimosaConfig, register ) {
  logger = mimosaConfig.log;
  var exts = mimosaConfig.extensions.javascript;
  register(
    ['add', 'update', 'remove', 'buildFile'],
    'afterRead',
    _defeature,
    exts
  );
};<|endoftext|>


<commit_before>var $ = require('jQuery');
var onReady = require('kwf/on-ready');
var historyState = require('kwf/history-state');
var getKwcRenderUrl = require('kwf/get-kwc-render-url');
var statistics = require('kwf/statistics');
var formRegistry = require('kwf/frontend-form/form-registry');

var byComponentId = {};
var byDirectoryViewComponentId = {};

var uniqueIdCnt = 0;
function getUniqueIdForFilterLink(el) {
    if (!el.id) {
        uniqueIdCnt++;
        el.id = 'filterLink'+uniqueIdCnt;
    }
    return el.id;
}

$(document).on('click', 'a', function(event) {
    var a = $(event.currentTarget);
    if (a.data('kwc-view-ajax-filter')) {
        var config = a.data('kwc-view-ajax-filter');

        var view = byDirectoryViewComponentId[config.viewComponentId];
        if (!view) return;
        view.loadView({
            filterComponentId: config.componentId
        });
        if (view._getState().viewFilter != config.componentId) {
            view._getState().viewFilter = config.componentId;
            view._getState().menuLinkId = getUniqueIdForFilterLink(this);
            historyState.pushState(document.title, this.href);
        }

        $('a[kwc-view-ajax-filter]').each(function() {
            var config = $(this).data('kwc-view-ajax-filter');
            if (config.viewComponentId == view.componentId) {
                $(this).removeClass('current');
            }
        });
        $(this).addClass('current');

        event.preventDefault();

    }

});

//if there is no viewAjax that can handle the changed state reload current page
//this can happen if a reload has been between state navigations
historyState.on('popstate', function() {
    if (historyState.currentState.viewAjax) {
        var found = false;
        for (var componentId in historyState.currentState.viewAjax) {
            if (byComponentId[componentId]) {
                found = true;
            }
        }
        if (!found) {
            location.href = location.href;
        }
    }
}, this);

var ViewAjax = function(config) {
    $.extend(this, config);
    this.init();
};

ViewAjax.prototype = {

    controllerUrl: null,
    loadMoreBufferPx: 700,
    limit: 10,
    initialPageSize: null,
    minimumCharactersForFilter: 3,
    checkLastViewScrollPosition: false,

    addHistoryEntryTimer: 0,

    init: function() {
        this.$el = $(this.el);
        byComponentId[this.componentId] = this;
        if (this.directoryViewComponentId) {
            byDirectoryViewComponentId[this.directoryViewComponentId] = this;
        }
        this.baseParams = {
            componentId: this.componentId
        };
        if (typeof Kwf != 'undefined' && Kwf.sessionToken) {
            this.baseParams.kwfSessionToken = Kwf.sessionToken;
        }

        if (this.searchFormComponentId) {
            this.searchForm = formRegistry.getFormByComponentId(this.searchFormComponentId);
        }

        if (this.searchForm) {

            $.extend(this.baseParams, this.searchForm.getValues());

            this.searchForm.on('fieldChange', function(ev, f) {
                if (f.el.find('input[type=text]').length && f.getValue().length < this.minimumCharactersForFilter) return; //minimum length

                var values = this.searchForm.getValues();
                var diffFound = false;
                for (var i in values) {
                    if (values[i] != this.baseParams[i]) {
                        diffFound = true;
                        break;
                    }
                }
                if (diffFound) {
                    $.extend(this.baseParams, values);
                    this.load();
                    clearTimeout(this.addHistoryEntryTimer);
                    this.addHistoryEntryTimer = setTimeout(this.pushSearchFormHistoryState.bind(this), 2000);
                }
            }, this, { buffer: 500 });

            this.searchForm.on('beforeSubmit', function(f) {
                var values = this.searchForm.getValues();
                $.extend(this.baseParams, values);
                this.load();
                this.pushSearchFormHistoryState();
                return false;
            }, this);
        }

        if (!historyState.currentState.viewAjax) historyState.currentState.viewAjax = {};
        historyState.currentState.viewAjax[this.componentId] = {};

        if (this.searchForm) {
            this._getState().searchFormValues = this.searchForm.getValues();
        }

        //set menuLinkId to link that is current, be be able to set current again
        $('a[kwc-view-ajax-filter]').each((function(index, linkEl) {
            var config = $(linkEl).data('kwc-view-ajax-filter');
            if (config.viewComponentId == this.componentId) {
                if ($(linkEl).hasClass('current')) {
                    this._getState().menuLinkId = getUniqueIdForFilterLink(linkEl);
                }
            }
        }).bind(this));

        if (this.filterComponentId) {
            this._getState().viewFilter = this.filterComponentId;
            this.baseParams.filterComponentId = this.filterComponentId;
            delete this.filterComponentId;
        }

        historyState.updateState();

        historyState.on('popstate', function() {
            if (!this._getState()) return;
            if (this.searchForm) {
                this.searchForm.setValues(this._getState().searchFormValues);
            }
            if (this._getState().viewDetail) {
                this.showDetail(this._getState().viewDetail);
            } else if (this._getState().viewFilter) {
                this.loadView({
                    filterComponentId: this._getState().viewFilter
                });
            } else {
                this.loadView({
                    filterComponentId: null
                });
            }

            if (this.checkLastViewScrollPosition && !this.visibleDetail && this._lastViewScrollPosition) {
                $(window).scrollTop(this._lastViewScrollPosition);
            }
            if (this._getState().menuLinkId) {
                $('a[kwc-view-ajax-filter]').each((function(i, el) {
                    var config = $(el).data('kwc-view-ajax-filter');
                    if (config.viewComponentId == this.componentId) {
                        $(el).removeClass('current');
                    }
                }).bind(this));

                var el = $('#'+this._getState().menuLinkId);
                if (el) {
                    el.addClass('current');
                }
            }
        }, this);

        if (this.loadMoreBufferPx) {
            var timer = 0;
            $(window).scroll((function() {
                clearTimeout(timer);
                timer = setTimeout((function() {
                    var height = this.$el.offset().top+this.$el.height();
                    height -= $(window).height();
                    height = height - $(window).scrollTop();
                    if (height < this.loadMoreBufferPx) {
                        this.loadMore();
                    }
                }).bind(this), 50);
            }).bind(this));
        }

        if (this.loadDetailAjax) {
            this.$el.click((function(ev) {
                var a = $(ev.target).closest('a');
                if (!a.length) return;
                if (!a.data('kwc-detail')) return;
                var config = a.data('kwc-detail');
                if (!config.directoryComponentId) return;
                if (this.directoryComponentId) {
                    if (config.directoryComponentId != this.directoryComponentId) return;
                } else {
                    if (config.directoryComponentClass != this.directoryComponentClass) return;
                }

                ev.preventDefault();
                //more... Link clicked
                if (this.checkLastViewScrollPosition) this._lastViewScrollPosition = $(window).scrollTop();
                this.showDetail(a.attr('href'));

            }).bind(this));
        }

        this.kwfMainContent = this.$el.closest('.kwfUp-kwfMainContent');
    },

    showView: function() {
        if (!this.visibleDetail) return;
        this.visibleDetail = null;

        this.hideDetail();

        this.kwfMainContent.show();
    },

    pushSearchFormHistoryState: function()
    {
        clearTimeout(this.addHistoryEntryTimer);
        this.addHistoryEntryTimer = 0;
        if (this.visibleDetail) return;
        this._getState().searchFormValues = this.searchForm.getValues();
        var url = location.protocol+'//'+location.host+this.viewUrl+'?'+$.param(this.searchForm.getValuesIncludingPost());
        historyState.pushState(document.title, url);
    },

    _getState: function()
    {
        if (!historyState.currentState.viewAjax) historyState.currentState.viewAjax = {};
        if (!historyState.currentState.viewAjax[this.componentId]) historyState.currentState.viewAjax[this.componentId] = {};
        return historyState.currentState.viewAjax[this.componentId];
    },

    loadView: function(params)
    {
        if (!params) params = {};
        if (this.searchForm) {
            $.extend(params, this.searchForm.getValues());
        }
        var diffFound = false;
        for (var i in params) {
            if (params[i] != this.baseParams[i]) {
                diffFound = true;
                break;
            }
        }
        if (diffFound) {
            for (var i in params) this.baseParams[i] = params[i];
            this.load();
        }
        this.showView();
    },

    loadMore: function()
    {
        if (this.$el.find('.kwfUp-kwfViewAjaxItem').length<this.initialPageSize || this.loadingMore || this.visibleDetail) return;

        this.loadingMore = true;
        this.$el.addClass('kwfUp-loadingMore');
        var params = $.extend({
            start: this.$el.find('.kwfUp-kwfViewAjaxItem').length,
            limit: this.limit
        }, this.baseParams);
        $.ajax({
            data: params,
            url: this.controllerUrl+'/json-data',
            dataType: 'json'
        }).done((function(data) {
            this.$el.removeClass('kwfUp-loadingMore');
            if (data.rows.length) { //wenn nichts geladen sind wir bereits am ende
                this.loadingMore = false;
            }
            for (var i=0; i<data.rows.length; i++) {
                this.$el.append("
"+data.rows[i].content+"
");
            }
            onReady.callOnContentReady(this.$el, { action: 'render' });
        }).bind(this));
    },

    load : function(params) {
        if (!params) params = {};
        if (!params.start) {
            params.start = 0;
        }
        if (!params.limit) {
            params.limit = this.initialPageSize;
        }
        $.extend(params, this.baseParams);

        this.$el.addClass('loading');
        $.ajax({
            data: params,
            url: this.controllerUrl+'/json-data',
            dataType: 'json'
        }).done((function(data) {
            this.$el.removeClass('loading');
            var html = '';
            if (!data.rows.length) {
                html = ''+this.placeholder.noEntriesFound+'';
            } else {
                html += this._renderAjaxItems(data);
            }
            this.$el.html(html);
            this.$el.trigger('load', data);
            onReady.callOnContentReady(this.$el, { action: 'render' });
        }).bind(this));
    },

    _renderAjaxItems: function(data)
    {
        var html = '';
        for (var i=0; i<data.rows.length; i++) {
            html += "
"+data.rows[i].content+"
";
        }
        return html;
    },

    hideDetail: function()
    {
        if (this.detailEl) {
            this.detailEl.hide();
            onReady.callOnContentReady(this.detailEl, {action: 'hide'});
            this.detailEl.remove();
            this.detailEl = null;
        }
    },

    showDetail: function(href)
    {
        if (this.visibleDetail == href) return;
        this.visibleDetail = href;

        if (this._getState().viewDetail != href) {
            this._getState().viewDetail = href;
            historyState.pushState(document.title, href);
        }
        this.hideDetail();

        var classNames = this.$el.closest('.kwcDirectoriesListViewAjax').attr('class');

        this.kwfMainContent.hide();

            //style: 'width: ' + this.kwfMainContent.getStyle('width'),
        this.detailEl = $('

');
        this.kwfMainContent.after(this.detailEl);

        $.ajax({
            url: getKwcRenderUrl(),
            data: { url: 'http://'+location.host+href, type: 'json' },
            dataType: 'json'
        }).done((function(response) {
            if (!this.detailEl) return;
            injectAssets(response.assets);
            this.detailEl.removeClass('kwfUp-loadingContent '+classNames);
            this.detailEl.html(response.content);
            statistics.trackView(href);

            var directoryUrl = href.match(/(.*)\/[^/]+/)[1];
            this.detailEl.find('a').each((function(index, el) {
                if ($(el).attr('href') == directoryUrl) {
                    $(el).click((function(ev) {
                        if (history.length > 1) {
                            if (Kwf.Utils.HistoryState.entries > 0 || document.referrer.indexOf(document.domain) >= 0) {
                                ev.preventDefault();
                                ev.stopPropagation();
                                history.back(); //keeps scroll position
                            }
                        } else {
                            this.showView();
                        }
                    }).bind(this));
                }
            }).bind(this));

            onReady.callOnContentReady(this.detailEl, {newRender: true});
            $(window).scrollTop(0);

        }).bind(this));
    }
};

module.exports = ViewAjax;
<commit_msg>add missing dependency(inject-assets) for ajax view<commit_after>var $ = require('jQuery');
var onReady = require('kwf/on-ready');
var historyState = require('kwf/history-state');
var getKwcRenderUrl = require('kwf/get-kwc-render-url');
var statistics = require('kwf/statistics');
var formRegistry = require('kwf/frontend-form/form-registry');
var injectAssets = require('kwf/inject-assets');

var byComponentId = {};
var byDirectoryViewComponentId = {};

var uniqueIdCnt = 0;
function getUniqueIdForFilterLink(el) {
    if (!el.id) {
        uniqueIdCnt++;
        el.id = 'filterLink'+uniqueIdCnt;
    }
    return el.id;
}

$(document).on('click', 'a', function(event) {
    var a = $(event.currentTarget);
    if (a.data('kwc-view-ajax-filter')) {
        var config = a.data('kwc-view-ajax-filter');

        var view = byDirectoryViewComponentId[config.viewComponentId];
        if (!view) return;
        view.loadView({
            filterComponentId: config.componentId
        });
        if (view._getState().viewFilter != config.componentId) {
            view._getState().viewFilter = config.componentId;
            view._getState().menuLinkId = getUniqueIdForFilterLink(this);
            historyState.pushState(document.title, this.href);
        }

        $('a[kwc-view-ajax-filter]').each(function() {
            var config = $(this).data('kwc-view-ajax-filter');
            if (config.viewComponentId == view.componentId) {
                $(this).removeClass('current');
            }
        });
        $(this).addClass('current');

        event.preventDefault();

    }

});

//if there is no viewAjax that can handle the changed state reload current page
//this can happen if a reload has been between state navigations
historyState.on('popstate', function() {
    if (historyState.currentState.viewAjax) {
        var found = false;
        for (var componentId in historyState.currentState.viewAjax) {
            if (byComponentId[componentId]) {
                found = true;
            }
        }
        if (!found) {
            location.href = location.href;
        }
    }
}, this);

var ViewAjax = function(config) {
    $.extend(this, config);
    this.init();
};

ViewAjax.prototype = {

    controllerUrl: null,
    loadMoreBufferPx: 700,
    limit: 10,
    initialPageSize: null,
    minimumCharactersForFilter: 3,
    checkLastViewScrollPosition: false,

    addHistoryEntryTimer: 0,

    init: function() {
        this.$el = $(this.el);
        byComponentId[this.componentId] = this;
        if (this.directoryViewComponentId) {
            byDirectoryViewComponentId[this.directoryViewComponentId] = this;
        }
        this.baseParams = {
            componentId: this.componentId
        };
        if (typeof Kwf != 'undefined' && Kwf.sessionToken) {
            this.baseParams.kwfSessionToken = Kwf.sessionToken;
        }

        if (this.searchFormComponentId) {
            this.searchForm = formRegistry.getFormByComponentId(this.searchFormComponentId);
        }

        if (this.searchForm) {

            $.extend(this.baseParams, this.searchForm.getValues());

            this.searchForm.on('fieldChange', function(ev, f) {
                if (f.el.find('input[type=text]').length && f.getValue().length < this.minimumCharactersForFilter) return; //minimum length

                var values = this.searchForm.getValues();
                var diffFound = false;
                for (var i in values) {
                    if (values[i] != this.baseParams[i]) {
                        diffFound = true;
                        break;
                    }
                }
                if (diffFound) {
                    $.extend(this.baseParams, values);
                    this.load();
                    clearTimeout(this.addHistoryEntryTimer);
                    this.addHistoryEntryTimer = setTimeout(this.pushSearchFormHistoryState.bind(this), 2000);
                }
            }, this, { buffer: 500 });

            this.searchForm.on('beforeSubmit', function(f) {
                var values = this.searchForm.getValues();
                $.extend(this.baseParams, values);
                this.load();
                this.pushSearchFormHistoryState();
                return false;
            }, this);
        }

        if (!historyState.currentState.viewAjax) historyState.currentState.viewAjax = {};
        historyState.currentState.viewAjax[this.componentId] = {};

        if (this.searchForm) {
            this._getState().searchFormValues = this.searchForm.getValues();
        }

        //set menuLinkId to link that is current, be be able to set current again
        $('a[kwc-view-ajax-filter]').each((function(index, linkEl) {
            var config = $(linkEl).data('kwc-view-ajax-filter');
            if (config.viewComponentId == this.componentId) {
                if ($(linkEl).hasClass('current')) {
                    this._getState().menuLinkId = getUniqueIdForFilterLink(linkEl);
                }
            }
        }).bind(this));

        if (this.filterComponentId) {
            this._getState().viewFilter = this.filterComponentId;
            this.baseParams.filterComponentId = this.filterComponentId;
            delete this.filterComponentId;
        }

        historyState.updateState();

        historyState.on('popstate', function() {
            if (!this._getState()) return;
            if (this.searchForm) {
                this.searchForm.setValues(this._getState().searchFormValues);
            }
            if (this._getState().viewDetail) {
                this.showDetail(this._getState().viewDetail);
            } else if (this._getState().viewFilter) {
                this.loadView({
                    filterComponentId: this._getState().viewFilter
                });
            } else {
                this.loadView({
                    filterComponentId: null
                });
            }

            if (this.checkLastViewScrollPosition && !this.visibleDetail && this._lastViewScrollPosition) {
                $(window).scrollTop(this._lastViewScrollPosition);
            }
            if (this._getState().menuLinkId) {
                $('a[kwc-view-ajax-filter]').each((function(i, el) {
                    var config = $(el).data('kwc-view-ajax-filter');
                    if (config.viewComponentId == this.componentId) {
                        $(el).removeClass('current');
                    }
                }).bind(this));

                var el = $('#'+this._getState().menuLinkId);
                if (el) {
                    el.addClass('current');
                }
            }
        }, this);

        if (this.loadMoreBufferPx) {
            var timer = 0;
            $(window).scroll((function() {
                clearTimeout(timer);
                timer = setTimeout((function() {
                    var height = this.$el.offset().top+this.$el.height();
                    height -= $(window).height();
                    height = height - $(window).scrollTop();
                    if (height < this.loadMoreBufferPx) {
                        this.loadMore();
                    }
                }).bind(this), 50);
            }).bind(this));
        }

        if (this.loadDetailAjax) {
            this.$el.click((function(ev) {
                var a = $(ev.target).closest('a');
                if (!a.length) return;
                if (!a.data('kwc-detail')) return;
                var config = a.data('kwc-detail');
                if (!config.directoryComponentId) return;
                if (this.directoryComponentId) {
                    if (config.directoryComponentId != this.directoryComponentId) return;
                } else {
                    if (config.directoryComponentClass != this.directoryComponentClass) return;
                }

                ev.preventDefault();
                //more... Link clicked
                if (this.checkLastViewScrollPosition) this._lastViewScrollPosition = $(window).scrollTop();
                this.showDetail(a.attr('href'));

            }).bind(this));
        }

        this.kwfMainContent = this.$el.closest('.kwfUp-kwfMainContent');
    },

    showView: function() {
        if (!this.visibleDetail) return;
        this.visibleDetail = null;

        this.hideDetail();

        this.kwfMainContent.show();
    },

    pushSearchFormHistoryState: function()
    {
        clearTimeout(this.addHistoryEntryTimer);
        this.addHistoryEntryTimer = 0;
        if (this.visibleDetail) return;
        this._getState().searchFormValues = this.searchForm.getValues();
        var url = location.protocol+'//'+location.host+this.viewUrl+'?'+$.param(this.searchForm.getValuesIncludingPost());
        historyState.pushState(document.title, url);
    },

    _getState: function()
    {
        if (!historyState.currentState.viewAjax) historyState.currentState.viewAjax = {};
        if (!historyState.currentState.viewAjax[this.componentId]) historyState.currentState.viewAjax[this.componentId] = {};
        return historyState.currentState.viewAjax[this.componentId];
    },

    loadView: function(params)
    {
        if (!params) params = {};
        if (this.searchForm) {
            $.extend(params, this.searchForm.getValues());
        }
        var diffFound = false;
        for (var i in params) {
            if (params[i] != this.baseParams[i]) {
                diffFound = true;
                break;
            }
        }
        if (diffFound) {
            for (var i in params) this.baseParams[i] = params[i];
            this.load();
        }
        this.showView();
    },

    loadMore: function()
    {
        if (this.$el.find('.kwfUp-kwfViewAjaxItem').length<this.initialPageSize || this.loadingMore || this.visibleDetail) return;

        this.loadingMore = true;
        this.$el.addClass('kwfUp-loadingMore');
        var params = $.extend({
            start: this.$el.find('.kwfUp-kwfViewAjaxItem').length,
            limit: this.limit
        }, this.baseParams);
        $.ajax({
            data: params,
            url: this.controllerUrl+'/json-data',
            dataType: 'json'
        }).done((function(data) {
            this.$el.removeClass('kwfUp-loadingMore');
            if (data.rows.length) { //wenn nichts geladen sind wir bereits am ende
                this.loadingMore = false;
            }
            for (var i=0; i<data.rows.length; i++) {
                this.$el.append("
"+data.rows[i].content+"
");
            }
            onReady.callOnContentReady(this.$el, { action: 'render' });
        }).bind(this));
    },

    load : function(params) {
        if (!params) params = {};
        if (!params.start) {
            params.start = 0;
        }
        if (!params.limit) {
            params.limit = this.initialPageSize;
        }
        $.extend(params, this.baseParams);

        this.$el.addClass('loading');
        $.ajax({
            data: params,
            url: this.controllerUrl+'/json-data',
            dataType: 'json'
        }).done((function(data) {
            this.$el.removeClass('loading');
            var html = '';
            if (!data.rows.length) {
                html = ''+this.placeholder.noEntriesFound+'';
            } else {
                html += this._renderAjaxItems(data);
            }
            this.$el.html(html);
            this.$el.trigger('load', data);
            onReady.callOnContentReady(this.$el, { action: 'render' });
        }).bind(this));
    },

    _renderAjaxItems: function(data)
    {
        var html = '';
        for (var i=0; i<data.rows.length; i++) {
            html += "
"+data.rows[i].content+"
";
        }
        return html;
    },

    hideDetail: function()
    {
        if (this.detailEl) {
            this.detailEl.hide();
            onReady.callOnContentReady(this.detailEl, {action: 'hide'});
            this.detailEl.remove();
            this.detailEl = null;
        }
    },

    showDetail: function(href)
    {
        if (this.visibleDetail == href) return;
        this.visibleDetail = href;

        if (this._getState().viewDetail != href) {
            this._getState().viewDetail = href;
            historyState.pushState(document.title, href);
        }
        this.hideDetail();

        var classNames = this.$el.closest('.kwcDirectoriesListViewAjax').attr('class');

        this.kwfMainContent.hide();

            //style: 'width: ' + this.kwfMainContent.getStyle('width'),
        this.detailEl = $('

');
        this.kwfMainContent.after(this.detailEl);

        $.ajax({
            url: getKwcRenderUrl(),
            data: { url: 'http://'+location.host+href, type: 'json' },
            dataType: 'json'
        }).done((function(response) {
            if (!this.detailEl) return;
            injectAssets(response.assets);
            this.detailEl.removeClass('kwfUp-loadingContent '+classNames);
            this.detailEl.html(response.content);
            statistics.trackView(href);

            var directoryUrl = href.match(/(.*)\/[^/]+/)[1];
            this.detailEl.find('a').each((function(index, el) {
                if ($(el).attr('href') == directoryUrl) {
                    $(el).click((function(ev) {
                        if (history.length > 1) {
                            if (Kwf.Utils.HistoryState.entries > 0 || document.referrer.indexOf(document.domain) >= 0) {
                                ev.preventDefault();
                                ev.stopPropagation();
                                history.back(); //keeps scroll position
                            }
                        } else {
                            this.showView();
                        }
                    }).bind(this));
                }
            }).bind(this));

            onReady.callOnContentReady(this.detailEl, {newRender: true});
            $(window).scrollTop(0);

        }).bind(this));
    }
};

module.exports = ViewAjax;
<|endoftext|>


<commit_before>// roguelike dungeon generating code
// 2010 no copyright -- mariofag
// free software is our future

function Dungeon(level) {
	function TreeGrid(startX, startY, endX, endY) {
		this.startX = startX;
		this.startY = startY;
		this.endX = endX;
		this.endY = endY;
	}
	function Walker(dun, x, y) {
		this.x = x;
		this.y = y;
		this.dead = false;
		this.moveTo = function (dir, i, limit, xMin, xMax, yMin, yMax, check) {
			var tempX = this.x + xOff[dir];
			var tempY = this.y + yOff[dir];
			if (tempX > xMax || tempY > yMax || tempX < xMin || tempY < yMin || (check && dun[tempX][tempY].pass)) {
				if (i < limit) {
					this.moveTo((dir + 1) % 5, i+1, limit, xMin, xMax, yMin, yMax, check);
				}
			} else {
				this.x = tempX;
				this.y = tempY;
			}
		}
	}
	function diffFill(dun, cell) {
		var x = 0;
		dun[Math.round((cell.endX + cell.startX)/2)][Math.round((cell.endY + cell.startY)/2)] = new DungeonTile(1, true, 0);
		while (x < ((cell.endX-cell.startX)*(cell.endY-cell.startY))/2) {
			var walkers = new Array();
			for (var i = 0; i < 5; i++) {
				walkers[i] = new Walker(dun, rand(cell.startX+1, cell.endX-1), rand(cell.startY+1, cell.endY-1));
			}
			var cont = true;
			while (cont) {
				cont = false;
				for(var i = 0; i < 5; i++) {
					if (!walkers[i].dead) {
						walkers[i].moveTo(rand(1,4), 0, 4, cell.startX+1, cell.endX-1, cell.startY+1, cell.endY-1, true);
						if (dun[walkers[i].x-1][walkers[i].y].pass || dun[walkers[i].x+1][walkers[i].y].pass || dun[walkers[i].x][walkers[i].y-1].pass || dun[walkers[i].x][walkers[i].y+1].pass) {
							dun[walkers[i].x][walkers[i].y].pass = true;
							dun[walkers[i].x][walkers[i].y].tile = 1;
							walkers[i].dead = true;
							x++;
						}
					}
				}
				if (x > ((cell.endX-cell.startX)*(cell.endY-cell.startY))/2) break;
			}
		}
	}
	function connect(dun, from, to) {
		function rand2(a,b) {
			var choice = new Array(a,b);
			return choice[rand(0,1)];
		}
		var w = new Walker(dun, Math.round((from.endX + from.startX)/2), Math.round((from.endY + from.startY)/2));
		var toX = Math.round((to.endX + to.startX)/2);
		var toY = Math.round((to.endY + to.startY)/2);

		while ((w.x != toX) || (w.y != toY)) {
			w.moveTo((w.x > toX) ? (w.y > toY ? rand2(1,4) : rand2(3,4)) : (w.y > toY ? rand2(1,2) : rand2(2,3))
			, 0, 4, 1, 50, 1, 50, false);
			dun[w.x][w.y].tile = 1;
			dun[w.x][w.y].pass = true;
		}
	}
	var tree = new Array();
	tree[1] = new TreeGrid(1, 1, 50, 50);

	for (var i = 2; i <= 31; i += 2) {
		if (rand(0,1)) {
			tree[i] = new TreeGrid(tree[Math.floor(i/2)].startX,
				tree[Math.floor(i/2)].startY,
				Math.floor(tree[Math.floor(i/2)].startX + ((tree[Math.floor(i/2)].endX - tree[Math.floor(i/2)].startX + 1)* (rand(45,55)/100))),
				tree[Math.floor(i/2)].endY);
			tree[i+1] = new TreeGrid(tree[i].endX, tree[i].startY, tree[Math.floor(i/2)].endX, tree[Math.floor(i/2)].endY);
		} else {
			tree[i] = new TreeGrid(tree[Math.floor(i/2)].startX,
				tree[Math.floor(i/2)].startY,
				tree[Math.floor(i/2)].endX,
				Math.floor(tree[Math.floor(i/2)].startY + ((tree[Math.floor(i/2)].endY - tree[Math.floor(i/2)].startY + 1)* (rand(45,55)/100))));
			tree[i+1] = new TreeGrid(tree[i].startX, tree[i].endY, tree[Math.floor(i/2)].endX, tree[Math.floor(i/2)].endY);
		}
	}

	for (var i=0; i <= 51; i++) {
		this[i] = new Array();
		for (var j=0; j <= 51; j++) {
			this[i][j] = new DungeonTile(2, false, 0);
		}
	}

	for (var i = 16; i <= 31; i++)
    diffFill(this, tree[i]);
	for (var i = 4; i >= 0; i--) {
		for (var j = Math.pow(2, i); j <= Math.pow(2, i+1)-1; j += 2)
      connect(this, tree[j], tree[j+1]);
	}
	var playerCell = rand(16, 31); // placing player
	player.x = Math.floor((tree[playerCell].startX + tree[playerCell].endX) / 2);
	player.y = Math.floor((tree[playerCell].startY + tree[playerCell].endY) / 2);
	for (var i = (player.x-10 < 1 ? 1 : player.x-10); i <= (player.x+10 > 50 ? 50 : player.x+10); i++) {
		for (var j = (player.y-7 < 1 ? 1 : player.y-7); j <= (player.y+7 > 50 ? 50 : player.y+7); j++) {
			this[i][j].known = true;
		}
	}
	j = 1;
	for (var i = rand(16,18); i <= 31; i += rand(1,3)) { // placing monsters
		if (i != playerCell) {
			monsters[j] = new Monster(j, rand(1, monsterTypes.length-1), rand(level == 1 ? 1 : level - 1, level + 1), Math.floor((tree[i].startX + tree[i].endX)/2), Math.floor((tree[i].startY + tree[i].endY)/2), 3);
			this[Math.floor((tree[i].startX + tree[i].endX)/2)][Math.floor((tree[i].startY + tree[i].endY)/2)].monster = j;
			j++;
		}
	}
	i = rand(16, 31); // placing exit
	if (i == playerCell || this[Math.floor((tree[i].startX + tree[i].endX)/2)][Math.floor((tree[i].startY + tree[i].endY)/2)].monster) { // if there's a monster/player in the centre of that room
		do {
			var x = rand(tree[i].startX, tree[i].endX);
			var y = rand(tree[i].startY, tree[i].endY);
		} while ((!this[x][y].pass) || (this[x][y].monster));
		this[x][y] = new DungeonTile(T_EXIT, false, 0, 0)
	} else { // if there's no monster
		this[Math.floor((tree[i].startX + tree[i].endX)/2)][Math.floor((tree[i].startY + tree[i].endY)/2)].tile = T_EXIT;
		this[Math.floor((tree[i].startX + tree[i].endX)/2)][Math.floor((tree[i].startY + tree[i].endY)/2)].pass = false;
	}
	for (i=1; i<=50; i++) {
		for (j=1; j<=50; j++) {
			if (this[i][j].tile == 2 && (this[i][j+1] == undefined || this[i][j+1].tile != 2)) {
				this[i][j].tile = 4;
			}
		}
	}
	this.level = level;
}
<commit_msg>+ fixed issue #1<commit_after>// roguelike dungeon generating code
// 2010 no copyright -- mariofag
// free software is our future

function Dungeon(level) {
	function TreeGrid(startX, startY, endX, endY) {
		this.startX = startX;
		this.startY = startY;
		this.endX = endX;
		this.endY = endY;
	}
	function Walker(dun, x, y) {
		this.x = x;
		this.y = y;
		this.dead = false;
		this.moveTo = function (dir, i, limit, xMin, xMax, yMin, yMax, check) {
			var tempX = this.x + xOff[dir];
			var tempY = this.y + yOff[dir];
			if (tempX > xMax || tempY > yMax || tempX < xMin || tempY < yMin || (check && dun[tempX][tempY].pass)) {
				if (i < limit) {
					this.moveTo((dir + 1) % 5, i+1, limit, xMin, xMax, yMin, yMax, check);
				}
			} else {
				this.x = tempX;
				this.y = tempY;
			}
		}
	}
	function diffFill(dun, cell) {
		var x = 0;
		dun[Math.round((cell.endX + cell.startX)/2)][Math.round((cell.endY + cell.startY)/2)] = new DungeonTile(1, true, 0);
		while (x < ((cell.endX-cell.startX)*(cell.endY-cell.startY))/2) {
			var walkers = new Array();
			for (var i = 0; i < 5; i++) {
				walkers[i] = new Walker(dun, rand(cell.startX+1, cell.endX-1), rand(cell.startY+1, cell.endY-1));
			}
			var cont = true;
			while (cont) {
				cont = false;
				for(var i = 0; i < 5; i++) {
					if (!walkers[i].dead) {
						walkers[i].moveTo(rand(1,4), 0, 4, cell.startX+1, cell.endX-1, cell.startY+1, cell.endY-1, true);
						if (dun[walkers[i].x-1][walkers[i].y].pass || dun[walkers[i].x+1][walkers[i].y].pass || dun[walkers[i].x][walkers[i].y-1].pass || dun[walkers[i].x][walkers[i].y+1].pass) {
							dun[walkers[i].x][walkers[i].y].pass = true;
							dun[walkers[i].x][walkers[i].y].tile = 1;
							walkers[i].dead = true;
							x++;
						}
					}
				}
				if (x > ((cell.endX-cell.startX)*(cell.endY-cell.startY))/2) break;
			}
		}
	}
	function connect(dun, from, to) {
		function rand2(a,b) {
			var choice = new Array(a,b);
			return choice[rand(0,1)];
		}
		var w = new Walker(dun, Math.round((from.endX + from.startX)/2), Math.round((from.endY + from.startY)/2));
		var toX = Math.round((to.endX + to.startX)/2);
		var toY = Math.round((to.endY + to.startY)/2);

		while ((w.x != toX) || (w.y != toY)) {
			w.moveTo((w.x > toX) ? (w.y > toY ? rand2(1,4) : rand2(3,4)) : (w.y > toY ? rand2(1,2) : rand2(2,3))
			, 0, 4, 1, 50, 1, 50, false);
			dun[w.x][w.y].tile = 1;
			dun[w.x][w.y].pass = true;
		}
	}

	var tree = new Array();
	tree[1] = new TreeGrid(1, 1, 50, 50);

	for (var i = 2; i <= 31; i += 2) {
		if (rand(0,1)) {
			tree[i] = new TreeGrid(tree[Math.floor(i/2)].startX,
				tree[Math.floor(i/2)].startY,
				Math.floor(tree[Math.floor(i/2)].startX + ((tree[Math.floor(i/2)].endX - tree[Math.floor(i/2)].startX + 1)* (rand(45,55)/100))),
				tree[Math.floor(i/2)].endY);
			tree[i+1] = new TreeGrid(tree[i].endX, tree[i].startY, tree[Math.floor(i/2)].endX, tree[Math.floor(i/2)].endY);
		} else {
			tree[i] = new TreeGrid(tree[Math.floor(i/2)].startX,
				tree[Math.floor(i/2)].startY,
				tree[Math.floor(i/2)].endX,
				Math.floor(tree[Math.floor(i/2)].startY + ((tree[Math.floor(i/2)].endY - tree[Math.floor(i/2)].startY + 1)* (rand(45,55)/100))));
			tree[i+1] = new TreeGrid(tree[i].startX, tree[i].endY, tree[Math.floor(i/2)].endX, tree[Math.floor(i/2)].endY);
		}
	}

	for (var i=0; i <= 51; i++) {
		this[i] = new Array();
		for (var j=0; j <= 51; j++) {
			this[i][j] = new DungeonTile(2, false, 0);
		}
	}

	for (var i = 16; i <= 31; i++)
    diffFill(this, tree[i]);
	for (var i = 4; i >= 0; i--) {
		for (var j = Math.pow(2, i); j <= Math.pow(2, i+1)-1; j += 2)
      connect(this, tree[j], tree[j+1]);
	}
	var playerCell = rand(16, 31); // placing player
	player.x = Math.floor((tree[playerCell].startX + tree[playerCell].endX) / 2);
	player.y = Math.floor((tree[playerCell].startY + tree[playerCell].endY) / 2);
	for (var i = (player.x-10 < 1 ? 1 : player.x-10); i <= (player.x+10 > 50 ? 50 : player.x+10); i++) {
		for (var j = (player.y-7 < 1 ? 1 : player.y-7); j <= (player.y+7 > 50 ? 50 : player.y+7); j++) {
			this[i][j].known = true;
		}
	}
	j = 1;
	for (var i = rand(16,18); i <= 31; i += rand(1,3)) { // placing monsters
		if (i != playerCell) {
			monsters[j] = new Monster(j, rand(1, monsterTypes.length-1), rand(level == 1 ? 1 : level - 1, level + 1), Math.floor((tree[i].startX + tree[i].endX)/2), Math.floor((tree[i].startY + tree[i].endY)/2), 3);
			this[Math.floor((tree[i].startX + tree[i].endX)/2)][Math.floor((tree[i].startY + tree[i].endY)/2)].monster = j;
			j++;
		}
	}
	do { // placing exit
    i = rand(16, 31);
  } while (i == playerCell);
  w = new Walker(this, Math.floor((tree[i].startX + tree[i].endX)/2), Math.floor((tree[i].startY + tree[i].endY)/2));
  while (this[w.x][w.y].pass) {
    w.moveTo(rand(1, 4), 0, 4, 1, 50, 1, 50, false);
  }
  this[w.x][w.y].tile = T_EXIT;
	for (i=1; i<=50; i++) {
		for (j=1; j<=50; j++) {
			if (this[i][j].tile == 2 && (this[i][j+1] == undefined || this[i][j+1].tile != 2)) {
				this[i][j].tile = 4;
			}
		}
	}
	this.level = level;
}
<|endoftext|>


<commit_before>#!/usr/bin/env phantomjs

// This script looks at the HTML files in the offline folder
// and isolates the markdown section in each page.

var page = require('webpage').create();
var fs = require('fs');

page.onConsoleMessage = function (msg) { console.log(msg); };

// code executed inside page
function fixPage() {

  // set title to first header text
  // (replace any redundant mentions of ClojureScript)
  var header = document.querySelector('h1') || document.querySelector('h2');
  document.title = header.innerText.replace('ClojureScript','').trim();

  // replace everything with .file box (markdown view)
  var file = document.querySelector('.file');
  file.style.marginTop = "0";
  document.body.innerHTML = file.outerHTML;

  // remove the file header
  document.querySelector('.file-header').innerHTML = "";

  // set width to tame formatting
  document.body.style.width = "900px";

  // make anchor links work
  var links = document.querySelectorAll('a');
  var i, link;
  for (i=0, len=links.length; i<len; i++) {
    link = links[i];
    if (link.id) {
      link.id = link.id.replace("user-content-", "");
    }
  };

  // TODO: add table of contents for history, unported, readme
}

function handlePage(file) {
  console.log("\n\nCLEANING", file);
  page.open(file, function () {
      page.evaluate(fixPage);
      fs.write(file, page.content, 'w');
      nextPage();
  });
}

function getHtmlFiles(path) {
  return fs.list(path)
           .filter(function(x) { return /\.html/.test(x); })
           .map(function (x) { return path + x; });
}

var rootPath = "offline/github.com/cljsinfo/api-refs/blob/catalog/";
var refsPath = rootPath + "refs/";
var pages = getHtmlFiles(rootPath)
             .concat(getHtmlFiles(refsPath));

function nextPage() {
  var file = pages.shift();
  if (!file) { phantom.exit() }
  handlePage(file);
}

nextPage();
<commit_msg>fix title setter for docset<commit_after>#!/usr/bin/env phantomjs

// This script looks at the HTML files in the offline folder
// and isolates the markdown section in each page.

var page = require('webpage').create();
var fs = require('fs');

page.onConsoleMessage = function (msg) { console.log(msg); };

// code executed inside page
function fixPage() {

  // replace everything with .file box (markdown view)
  var file = document.querySelector('.file');
  file.style.marginTop = "0";
  document.body.innerHTML = file.outerHTML;

  // remove the file header
  document.querySelector('.file-header').innerHTML = "";

  // set title to first header text
  // (replace any redundant mentions of ClojureScript)
  var header = document.querySelector('h1') || document.querySelector('h2');
  document.title = header.innerText.replace('ClojureScript','').trim();

  // set width to tame formatting
  document.body.style.width = "900px";

  // make anchor links work
  var links = document.querySelectorAll('a');
  var i, link;
  for (i=0, len=links.length; i<len; i++) {
    link = links[i];
    if (link.id) {
      link.id = link.id.replace("user-content-", "");
    }
  };

  // TODO: add table of contents for history, unported, readme
}

function handlePage(file) {
  console.log("\n\nCLEANING", file);
  page.open(file, function () {
      page.evaluate(fixPage);
      fs.write(file, page.content, 'w');
      nextPage();
  });
}

function getHtmlFiles(path) {
  return fs.list(path)
           .filter(function(x) { return /\.html/.test(x); })
           .map(function (x) { return path + x; });
}

var rootPath = "offline/github.com/cljsinfo/api-refs/blob/catalog/";
var refsPath = rootPath + "refs/";
var pages = getHtmlFiles(rootPath)
             .concat(getHtmlFiles(refsPath));

function nextPage() {
  var file = pages.shift();
  if (!file) { phantom.exit() }
  handlePage(file);
}

nextPage();
<|endoftext|>


<commit_before>app.controller('DomainsCtrl', ['$scope', 'Domains',
    function($scope, Domains) {
        $scope.domains = Domains.query();
    }
]);

<commit_msg>Make $log available within our DomainsCtrl<commit_after>app.controller('DomainsCtrl', ['$scope', '$log', 'Domains',
    function($scope, $log, Domains) {
        $scope.domains = Domains.query();
    }
]);

<|endoftext|>