<commit_before>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal) {

    $scope.selected = [];
    $scope.checkboxes = $("input[type=checkbox][name=feedid]");

    var update_selected = function(action, id) {

        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }

    }

    $scope.feedback_status = function(id, feed_status) {
        console.log(feed_status + " id: " + id);

        FeedbackSignal.set_status_message(feed_status)
        FeedbackSignal.set_feed_id(id);

        FeedbackControlService.change_status(id, feed_status);
    }

    $scope.reply_feedback = function(id) {
        console.log("reply id:" + id);
    }

    $scope.update_selection = function($event, feed) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        update_selected(action, feed);

        if(checkbox.checked) {
            $(checkbox).parents('.dashboard-feedback').css({'background-color': '#F1F1f1'});
        } else {
            $(checkbox).parents('.dashboard-feedback').css({'background-color': '#FFF'});
        }

    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < $scope.checkboxes.length; i++) {
            var entity = $($scope.checkboxes[i]);

            if(action == "add") {
                entity.prop("checked", true);
            } else {
                entity.prop("checked", false);
            }

            update_selected(action, parseInt(entity.val(), 10));
        }
    }

    $scope.is_selected = function(id) {
        return $scope.selected.indexOf(id) >= 0;
    }

    $scope.is_selected_all = function() {
        return $scope.selected.length === $scope.checkboxes.length;
    }
}

function CheckyBox($scope, FeedbackSignal) {

    $scope.status_selection;
    $scope.feed_id;

    $scope.undo = function() {
        console.log("Undo id: " + $scope.feed_id);
    }

    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.feed_status;
        $scope.feed_id = FeedbackSignal.feed_id;
    });
}
<commit_msg>oh yeas baby<commit_after>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal) {

    $scope.selected = [];
    $scope.checkboxes = $("input[type=checkbox][name=feedid]");

    var update_selected = function(action, id) {

        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }

    }

    $scope.feedback_status = function(id, feed_status) {
        console.log(feed_status + " id: " + id);

        FeedbackSignal.set_status_message(feed_status)
        FeedbackSignal.set_feed_id(id);

        FeedbackControlService.change_status(id, feed_status);
    }

    $scope.reply_feedback = function(id) {
        console.log("reply id:" + id);
    }

    $scope.update_selection = function($event, feed) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        update_selected(action, feed);

        if(checkbox.checked) {
            $(checkbox).parents('.dashboard-feedback').css({'background-color': '#F1F1f1'});
        } else {
            $(checkbox).parents('.dashboard-feedback').css({'background-color': '#FFF'});
        }

    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < $scope.checkboxes.length; i++) {
            var entity = $($scope.checkboxes[i]);

            if(action == "add") {
                entity.prop("checked", true);
            } else {
                entity.prop("checked", false);
            }

            update_selected(action, parseInt(entity.val(), 10));
        }
    }

    $scope.is_selected = function(id) {
        return $scope.selected.indexOf(id) >= 0;
    }

    $scope.is_selected_all = function() {
        return $scope.selected.length === $scope.checkboxes.length;
    }
}

function CheckyBox($scope, FeedbackSignal) {

    var status_selection;
    var feed_id;

    $scope.undo = function() {
        console.log("Undo id: " + feed_id);
    }

    $scope.$on('checkFeedbackStatus', function() {
        status_selection = FeedbackSignal.feed_status;
        feed_id = FeedbackSignal.feed_id;
    });
}
<|endoftext|>


<commit_before>/*! barometer v1.0.0 */
_='!e´ t(an¡) n¡;r=n¡={²:{id:a,ed:!1}; e¡.call(r,r,r,tr.ed¤r}n={}; t.m=¢.c=n,t.p="",t(0)}([¢,ne1)=Z@r2o6~n(7n(3n(8¯=¥,a=r,=r.,a=o,#=o.#@r3o1~¯="XXXXX",eW={¦s:{ers:{}=0e(=||0,++,",e)a,t=||[],.(t¦",¢)};i=¥;tWiK<100Kii=£n,5e3)n0Ko.¯iK(ii=¥~±;e(~n=o.¯;)(n,~else{u=new r.a;u.op("POST",n,!eu.£R*Header("C`tt-Type","applici`/js`"u.sd(u.timeout=4e3}}a=;u=["UNSENT","OPENED","HEADERS_RECEIVED","LOADING","DONE"];r"xhrQeo,t,na={¨:n}re)"_"r[0]K0e°K(a°=e°-t~ ait,n,r=i(¯u=o(FTimes,off£,¨)su)t="timing(n,u[s]~t="µs.(nt="size(n,(r*.µText©.)We=new a;try{±{n=op,o=sd;op=o,itry{s=;r(e,"readystec§",t[u[F]]=}r(e,"d",n i({:o,¯:i,FTimes:t,off£:s,¨:-s,r*:e})})}cc} n,sdW o}ci} e,n?(t,n,!1):K("`"+t,n)n=(e©$.^	-\\/~(t©.m/\\?/)K(n+=t$.slice(1)	-\\/)n},r,o,i@u4s7c2f=0,g=[];i.uWc(r,-a)i.sWc.(ªvisits")aKi.u(f++;e=,t=f,n=0,u=[9,9,9,9,9],l=!1,p=25,d=ªdynamic"vWwo¤a=,r=ªgagemt"~±125;c(d,-e-t)n=0;n<g.;n++)g[n]()w=£l¤1===f)for(e=0;e<g.;e++)g[e]()6e3mWe=;£a=,r=a-e-p;r>nK(n=r!ltf) v(~uu.(r)o=0,i=0;i<5;i++)o+=u[i]; o<5Kn>25?v():void £m,p)}p)};m()i.s( ?(u(,"popste",i.see±·;·W i.s(t}}( )):u(,"hashc§",i.sig.(e)i.#o) e(~±!1;i(t||(t¤e())})o{n=®;e=toJSON()ae)"®"aK0e¡K(t¡=e¡-n~ tri(ref,ash~"pageQt+"Qe	-)fW¢=.timing||{n=o(t)rn)e=r(ro(e,n°~i=(.Yi`||{}).¬Count||0;e=r("¬s"o(e,i)"object"==of K("complete"===documt.F?f():r(,"",f)),r@o6i2u=0,s=0;(e~tK³(¢)Z.rs;tfor(nro=0;o<t.;o++i=t[o];(!||m¶ph||r.mi.ph¶||===i.)) i.metrics} ¥}³,t"rsQ+".";a+=n)	_a+=".",a+)$	_)rtr=t°;o=e°;0oK("duri`"rK(o=s-oi(a+"Qr,o))}WKK(a=,o(s=-ae=(~u<;u++)(e[u])}))()}]~´(¢,n%avar windowreturn.²buffernew De	.[^a-z0-9.¦.performance.`PageC§dn=nam«/"a=),){r*.stut(++,Z.debugKc`sollog("Timeout(.apply(e,argumts)}count;for(},a.=n(=e]/gi,"_"ate.en#`cePageLoaded$«?")[0]%"use strict";*equest@=e={FreadySteK&&Q."+W=YnavigZ.barometer`on~);if(https?:\\/\\//i,"")esourceJSON.stringify(t)replace(/.ers[e]}@r4o2i5~addEvtListerlgthr.initialiseQ+"Qr+"Q.shift(Yor.sdBeac`.getEntries}¢%e,tSize±=n.join("/"r.handleR.XMLHttpR*loadpush in typech(clears[e]r.findRules,n=r(totachEvt.loci`.h!==tryType .history¡[a]¢e,t£set¤=!0,¥null¦gauge§hange¨total©||"")ªs.r("«.split("¬redirecti.domain®Yi`Start¯url°[r]±t=²exports³r.track´functi`µresp`se¶))K(!i.·Ste';for(Y in $='·¶µ´³²±°¯®¬«ª©¨§¦¥¤£¢¡ ~`ZYWQKF@*%$#	')with(_.split($[Y]))_=join(pop());eval(_)<commit_msg>v1.1.0<commit_after>/*! barometer v1.1.0 */
_='!e´ t(an¡) n¡;r=n¡={²:{id:a,ed:!1}; e¡.call(r,r,r,tr.ed¤r}n={}; t.m=¢.c=n,t.p="",t(0)}([¢,ne1)=Z@r2o6~n(7n(3n(8¯=¥,a=r,=r.,a=o,#=o.#@r3o1~¯="XXXXX",eW={¦s:{ers:{}=0e(=||0,++,",e)a,t=||[],.(t¦",¢)};i=¥;tWiK<100Kii=£n,5e3)n0Ko.¯iK(ii=¥~±;e(~n=o.¯;)(n,~else{u=new r.a;u.op("POST",n,!eu.£R*Header("C`tt-Type","applici`/js`"u.sd(u.timeout=4e3}}a=;u=["UNSENT","OPENED","HEADERS_RECEIVED","LOADING","DONE"];r"xhrQeo,t,na={¨:n}re)"_"r[0]K0e°K(a°=e°-t~ ait,n,r=i(¯u=o(FTimes,off£,¨)su)t="timing(n,u[s]~t="µs.(nt="size(n,(r*.µText©.)We=new a;try{±{n=op,o=sd;op=o,itry{s=;r(e,"readystec§",t[u[F]]=}r(e,"d",n i({:o,¯:i,FTimes:t,off£:s,¨:-s,r*:e})})}cc} n,sdW o}ci} e,n?(t,n,!1):K("`"+t,n)n=(e©$.^	-\\/~(t©.m/\\?/)K(n+=t$.slice(1)	-\\/)n},r,o,i@u4s7c2f=0,g=[];i.uWc(r,-a)i.sWc.(ªvisits")aKi.u(f++;e=,t=f,n=0,u=[9,9,9,9,9],l=!1,p=25,d=ªdynamic"vWwo¤a=,r=ªgagemt"~±125;c(d,-e-t)n=0;n<g.;n++)g[n]()w=£l¤1===f)for(e=0;e<g.;e++)g[e]()6e3mWe=;£a=,r=a-e-p;r>nK(n=r!ltf) v(~uu.(r)o=0,i=0;i<5;i++)o+=u[i]; o<5Kn>25?v():void £m,p)}p)};m()i.s( ?(u(,"popste",i.see±·;·W i.s(t}}( )):u(,"hashc§",i.sig.(e)i.#o) e(~±!1;i(t||(t¤e())})o{n=®;e=toJSON()ae)"®"aK0e¡K(t¡=e¡-n~ tri(ref,ash~"pageQt+"Qe	-)fW¢=.timing||{n=o(t)rn)e=r(ro(e,n°~i=(.Yi`||{}).¬Count||0;e=r("¬s"o(e,i)"object"==of K("complete"===documt.F?f():r(,"",f)),r@o6i2u=0,s=0;(e~tK³(¢)Z.rs;tfor(nro=0;o<t.;o++i=t[o];(!||m¶ph||r.mi.ph¶||===i.)) i.metrics} ¥}³,t"rsQ+".";a+=n)	_a+=".",a+)$	_)rtr=t°;o=e°;0oK("duri`"rK(o=s-oi(a+"Qr,o))}WKK(a=,o(s=-ae=(~u<;u++)(e[u])}))()}]~´(¢,n%avar windowreturn.²buffernew De	.[^a-z0-9.¦.performance.`PageC§dn=nam«/"a=),){r*.stut(++,Z.debugKc`sollog("Timeout(.apply(e,argumts)}count;for(},a.=n(=e]/gi,"_"ate.en#`cePageLoaded$«?")[0]%"use strict";*equest@=e={FreadySteK&&Q."+W=YnavigZ.barometer`on~);if(https?:\\/\\//i,"")esourceJSON.stringify(t)replace(/.ers[e]}@r4o2i5~addEvtListerlgthr.initialiseQ+"Qr+"Q.shift(Yor.sdBeac`.getEntries}¢%e,tSize±=n.join("/"r.handleR.XMLHttpR*loadpush in typech(clears[e]r.findRules,n=r(totachEvt.loci`.h!==tryType .history¡[a]¢e,t£set¤=!0,¥null¦gauge§hange¨total©||"")ªs.r("«.split("¬redirecti.domain®Yi`Start¯url°[r]±t=²exports³r.track´functi`µresp`se¶))K(!i.·Ste';for(Y in $='·¶µ´³²±°¯®¬«ª©¨§¦¥¤£¢¡ ~`ZYWQKF@*%$#	')with(_.split($[Y]))_=join(pop());eval(_)<|endoftext|>


<commit_before>gc2map.createSearch = function (me, komKode) {
    var type1, type2, gids = [], searchString;
    var placeStore = new geocloud.geoJsonStore({
        host: "http://eu1.mapcentia.com",
        db: "dk",
        sql: null,
        pointToLayer: null,
        onLoad: function () {
            var resultLayer = new L.FeatureGroup();
            me.map.addLayer(resultLayer);
            resultLayer.addLayer(this.layer);
            me.zoomToExtentOfgeoJsonStore(this);
            if (me.map.getZoom() > 18) {
                me.map.setZoom(18);
            }
        }
    });
    $("#custom-search-form").show();
    $('#custom-search').typeahead({
        highlight: false
    }, {
        name: 'adresse',
        displayKey: 'value',
        templates: {
            header: '
Adresser
'
        },
        source: function (query, cb) {
            if (query.match(/\d+/g) === null && query.match(/\s+/g) === null) {
                type1 = "vejnavn,bynavn";
            }
            if (query.match(/\d+/g) === null && query.match(/\s+/g) !== null) {
                type1 = "vejnavn_bynavn";
            }
            if (query.match(/\d+/g) !== null) {
                type1 = "adresse";
            }
            var names = [];

            (function ca() {
                $.ajax({
                    url: 'http://eu1.mapcentia.com/api/v1/elasticsearch/search/dk/aws4/' + type1,
                    data: '&q={"query":{"filtered":{"query":{"query_string":{"default_field":"string","query":"' + encodeURIComponent(query.toLowerCase().replace(",", "")) + '","default_operator":"AND"}},"filter":{"term":{"kommunekode":"0' + komKode + '"}}}}}',
                    contentType: "application/json; charset=utf-8",
                    scriptCharset: "utf-8",
                    dataType: 'jsonp',
                    jsonp: 'jsonp_callback',
                    success: function (response) {
                        $.each(response.hits.hits, function (i, hit) {
                            var str = hit._source.properties.string;
                            gids[str] = hit._source.properties.gid;
                            names.push({value: str});
                        });
                        if (names.length === 1 && (type1 === "vejnavn,bynavn" || type1 === "vejnavn_bynavn")) {
                            type1 = "adresse";
                            names = [];
                            gids = [];
                            ca();
                        } else {
                            cb(names);
                        }
                    }
                })
            })();
        }
    }, {
        name: 'matrikel',
        displayKey: 'value',
        templates: {
            header: '
Matrikel
'
        },
        source: function (query, cb) {
            var names = [];
            type2 = (query.match(/\d+/g) != null) ? "jordstykke" : "ejerlav";
            (function ca() {
                $.ajax({
                    url: 'http://eu1.mapcentia.com/api/v1/elasticsearch/search/dk/matrikel/' + type2,
                    data: '&q={"sort":[{"sort_string":"asc"}],"query":{"filtered":{"query":{"query_string":{"default_field":"string","query":"' + encodeURIComponent(query.toLowerCase()) + '","default_operator":"AND"}},"filter":{"term":{"komkode":"' + komKode + '"}}}}}',
                    contentType: "application/json; charset=utf-8",
                    scriptCharset: "utf-8",
                    dataType: 'jsonp',
                    jsonp: 'jsonp_callback',
                    success: function (response) {
                        $.each(response.hits.hits, function (i, hit) {
                            var str = hit._source.properties.string;
                            gids[str] = hit._source.properties.gid;
                            names.push({value: str});
                        });
                        if (names.length === 1 && (type2 === "ejerlav")) {
                            type2 = "jordstykke";
                            names = [];
                            gids = [];
                            ca();
                        } else {
                            cb(names);
                        }
                    }
                });
            }());
        }
    });
    $('#custom-search').bind('typeahead:selected', function (obj, datum, name) {
        if ((type1 === "adresse" && name === "adresse") || (type2 === "jordstykke" && name === "matrikel")) {
            placeStore.reset();

            if (name === "matrikel") {
                placeStore.sql = "SELECT gid,the_geom,ST_asgeojson(ST_transform(the_geom,4326)) as geojson FROM matrikel.jordstykke WHERE gid=" + gids[datum.value];
            }
            if (name === "adresse") {
                placeStore.sql = "SELECT gid,the_geom,ST_asgeojson(ST_transform(the_geom,4326)) as geojson FROM adresse.adgang4 WHERE gid=" + gids[datum.value];
            }
            searchString = datum.value;
            placeStore.load();
        } else {
            setTimeout(function () {
                $(".typeahead").val(datum.value + " ").trigger("paste").trigger("input");
            }, 100);
        }
    });
};
<commit_msg>no message<commit_after>gc2map.createSearch = function (me, komKode) {
    var type1, type2, gids = [], searchString;
    var placeStore = new geocloud.geoJsonStore({
        host: "//eu1.mapcentia.com",
        db: "dk",
        sql: null,
        pointToLayer: null,
        onLoad: function () {
            var resultLayer = new L.FeatureGroup();
            me.map.addLayer(resultLayer);
            resultLayer.addLayer(this.layer);
            me.zoomToExtentOfgeoJsonStore(this);
            if (me.map.getZoom() > 18) {
                me.map.setZoom(18);
            }
        }
    });
    $("#custom-search-form").show();
    $('#custom-search').typeahead({
        highlight: false
    }, {
        name: 'adresse',
        displayKey: 'value',
        templates: {
            header: '
Adresser
'
        },
        source: function (query, cb) {
            if (query.match(/\d+/g) === null && query.match(/\s+/g) === null) {
                type1 = "vejnavn,bynavn";
            }
            if (query.match(/\d+/g) === null && query.match(/\s+/g) !== null) {
                type1 = "vejnavn_bynavn";
            }
            if (query.match(/\d+/g) !== null) {
                type1 = "adresse";
            }
            var names = [];

            (function ca() {
                $.ajax({
                    url: '//eu1.mapcentia.com/api/v1/elasticsearch/search/dk/aws4/' + type1,
                    data: '&q={"query":{"filtered":{"query":{"query_string":{"default_field":"string","query":"' + encodeURIComponent(query.toLowerCase().replace(",", "")) + '","default_operator":"AND"}},"filter":{"term":{"kommunekode":"0' + komKode + '"}}}}}',
                    contentType: "application/json; charset=utf-8",
                    scriptCharset: "utf-8",
                    dataType: 'jsonp',
                    jsonp: 'jsonp_callback',
                    success: function (response) {
                        $.each(response.hits.hits, function (i, hit) {
                            var str = hit._source.properties.string;
                            gids[str] = hit._source.properties.gid;
                            names.push({value: str});
                        });
                        if (names.length === 1 && (type1 === "vejnavn,bynavn" || type1 === "vejnavn_bynavn")) {
                            type1 = "adresse";
                            names = [];
                            gids = [];
                            ca();
                        } else {
                            cb(names);
                        }
                    }
                })
            })();
        }
    }, {
        name: 'matrikel',
        displayKey: 'value',
        templates: {
            header: '
Matrikel
'
        },
        source: function (query, cb) {
            var names = [];
            type2 = (query.match(/\d+/g) != null) ? "jordstykke" : "ejerlav";
            (function ca() {
                $.ajax({
                    url: '//eu1.mapcentia.com/api/v1/elasticsearch/search/dk/matrikel/' + type2,
                    data: '&q={"sort":[{"sort_string":"asc"}],"query":{"filtered":{"query":{"query_string":{"default_field":"string","query":"' + encodeURIComponent(query.toLowerCase()) + '","default_operator":"AND"}},"filter":{"term":{"komkode":"' + komKode + '"}}}}}',
                    contentType: "application/json; charset=utf-8",
                    scriptCharset: "utf-8",
                    dataType: 'jsonp',
                    jsonp: 'jsonp_callback',
                    success: function (response) {
                        $.each(response.hits.hits, function (i, hit) {
                            var str = hit._source.properties.string;
                            gids[str] = hit._source.properties.gid;
                            names.push({value: str});
                        });
                        if (names.length === 1 && (type2 === "ejerlav")) {
                            type2 = "jordstykke";
                            names = [];
                            gids = [];
                            ca();
                        } else {
                            cb(names);
                        }
                    }
                });
            }());
        }
    });
    $('#custom-search').bind('typeahead:selected', function (obj, datum, name) {
        if ((type1 === "adresse" && name === "adresse") || (type2 === "jordstykke" && name === "matrikel")) {
            placeStore.reset();

            if (name === "matrikel") {
                placeStore.sql = "SELECT gid,the_geom,ST_asgeojson(ST_transform(the_geom,4326)) as geojson FROM matrikel.jordstykke WHERE gid=" + gids[datum.value];
            }
            if (name === "adresse") {
                placeStore.sql = "SELECT gid,the_geom,ST_asgeojson(ST_transform(the_geom,4326)) as geojson FROM adresse.adgang4 WHERE gid=" + gids[datum.value];
            }
            searchString = datum.value;
            placeStore.load();
        } else {
            setTimeout(function () {
                $(".typeahead").val(datum.value + " ").trigger("paste").trigger("input");
            }, 100);
        }
    });
};
<|endoftext|>


<commit_before>/* creep_factory.js
 *
 * Encapsulates the logic to determine creep spawning behavior.
 *
 */
'use strict';

var Globals = require('globals');
var UtilsCreep = require('utils.creep');

var exports = module.exports = {};

exports.run = function(room) {

    // determine current Room Control Level
    var rcl = room.controller.level;

    // determine population levels
    /*var harvesters = 0;
    var upgraders = 0;
    var builders = 0;

    switch (rcl) {
        case 0:
            harvesters = 1;
            upgraders = 1;
            builders = 1;
            break;

        default:
            harvesters = 1;
            upgraders = 1;
            builders = 1;
    }*/

    // determine total available energy (spawns + extensions)
    //var energyCap = room.energyCapacityAvailable;

    // determine number of sources in the room
    //var numSources = room.memory.sources.length;

    // total available mining spots
    var maxOccupancy = _.sum(room.memory.sources, 'maxOccupancy');

    // harvesters to build
    //var numHarvesters = Math.ceil(maxOccupancy / 2);

    //console.log("Max occ: " + maxOccupancy + ", build: " + numHarvesters);

    // get spawn
    var spawns = room.find(FIND_MY_SPAWNS);
    for (var s in spawns) {
        var spawn = spawns[s];
        if (spawn.spawning === null) {
            var body = null;
            var mem = null;

            // priority spawns
            //--------------------------
            if (room.memory.population.harvester.length < 1) {
                body = UtilsCreep.getBestBuildableCreepClass(room, 'harvester');
                mem = Globals.getCreepRoleMemory('harvester');
                if (spawn.canCreateCreep(body) == OK) {
                    spawn.createCreep(body, undefined, mem);
                }

            } else if (room.memory.population.upgrader.length < 1) {
                body = UtilsCreep.getBestPossibleCreepClass(room, 'upgrader');
                mem = Globals.getCreepRoleMemory('upgrader');
                if (spawn.canCreateCreep(body) == OK) {
                    spawn.createCreep(body, undefined, mem);
                }

            } else if (room.memory.population.builder.length < 1) {
                body = UtilsCreep.getBestPossibleCreepClass(room, 'builder');
                mem = Globals.getCreepRoleMemory('builder');
                if (spawn.canCreateCreep(body) == OK) {
                    spawn.createCreep(body, undefined, mem);
                }

            } else if (room.memory.population.distributor.length < 1) {
                body = UtilsCreep.getBestBuildableCreepClass(room, 'distributor');
                mem = Globals.getCreepRoleMemory('distributor');
                if (spawn.canCreateCreep(body) == OK) {
                    spawn.createCreep(body, undefined, mem);
                }

            } /*else if (!('soldier' in room.memory.population) || (room.memory.population['soldier'].length < 1)) {
                if (spawn.canCreateCreep(Globals.TYPE_S_CLASS_4) == OK) {
                    spawn.createCreep(Globals.TYPE_S_CLASS_4, undefined, Globals.MEM_TYPE_S);
                }

            } */else {

                // extra spawns
                //----------------------

            }
        }
    }

    /*

    // spawn harvesters
    var harvesterBody = Utils.getBestCreepClass(room, 'harvester');
    var harvesterMemory = Object.assign({}, Globals.CREEP_MEMORY);
    harvesterMemory.role = 'harvester';
    for (var s in spawns) {
        var spawn = spawns[s];
        if (spawn.spawning == null) {
            if (room.memory.population['harvester'].length < 3) {
                if (spawn.canCreateCreep(harvesterBody) == OK) {
                    spawn.createCreep(harvesterBody, undefined, harvesterMemory);
                }
            }
        }
    }

    // spawn upgrader
    var upgraderBody = Utils.getBestCreepClass(room, 'upgrader');
    var upgraderMemory = Object.assign({}, Globals.CREEP_MEMORY);
    upgraderMemory.role = 'upgrader';
    for (var s in spawns) {
        var spawn = spawns[s];
        if (spawn.spawning == null) {
            if (room.memory.population['upgrader'].length < 5) {
                if (spawn.canCreateCreep(upgraderBody) == OK) {
                    spawn.createCreep(upgraderBody, undefined, upgraderMemory);
                }
            }
        }
    }

    // spawn builder
    var builderBody = Utils.getBestCreepClass(room, 'builder');
    var builderMemory = Object.assign({}, Globals.CREEP_MEMORY);
    builderMemory.role = 'builder';
    for (var s in spawns) {
        var spawn = spawns[s];
        if (spawn.spawning == null) {
            if (room.memory.population['builder'].length < 2) {
                if (spawn.canCreateCreep(builderBody) == OK) {
                    spawn.createCreep(builderBody, undefined, builderMemory);
                }
            }
        }
    }

    */

};
<commit_msg>delete old code<commit_after><|endoftext|>


<commit_before>import {bindable, inject, processContent, ObserverLocator, customElement, skipContentProcessing } from 'aurelia-framework';
import {GridColumn} from './grid-column';
import {Compiler} from 'CharlesPockert/aurelia-compiler';
import './aurelia-bs-grid.css!';

@customElement('grid')
@skipContentProcessing()
@inject(Element, Compiler, ObserverLocator)
export class Grid {

	/* == Styling == */
	@bindable gridHeight = 0;

	/* == Options == */

	// Initial load flag (for client side)
	@bindable initialLoad = false;

	// Filtering
	@bindable showColumnFilters = false;
	@bindable serverFiltering = false;
	@bindable filterDebounce = 500;

	// Pagination
	@bindable serverPaging = false;
	@bindable pageable = true;
	@bindable pageSize = 10;
	@bindable page = 1;
	@bindable pagerSize = 10;

	@bindable showPageSizeBox = true;
	@bindable showPagingSummary = true;
	@bindable showFirstLastButtons = true;
	@bindable showJumpButtons = true;

	@bindable pageSizes = [10, 25, 50];

	firstVisibleItem = 0;
	lastVisibleItem = 0;

	pageNumber = 1;

	// Sortination
	@bindable serverSorting = false;
	@bindable sortable = true;
	sortProcessingOrder = []; // Represents which order to apply sorts to each column
	sorting = {};

	// Burnination?
	Trogdor = true;

	// Column defs
	@bindable autoGenerateColumns;
	@bindable showColumnHeaders = true;
	columnHeaders = [];
	columns = [];

	// Selection
	@bindable selectable = false;
	@bindable selectedItem = null;

	// Misc
	@bindable noRowsMessage = "";

	// Data ....
	@bindable autoLoad = true;
	loading = false;
	@bindable loadingMessage = "Loading...";

	// Read
	@bindable read = null;
	@bindable onReadError = null;

	// Tracking
	cache = [];
	data = [];
	count = 0;

	// Subscription handling
	unbinding = false;

	// Visual
	// TODO: calc scrollbar width using browser
	scrollBarWidth = 16;

	constructor(element, compiler, observerLocator) {
		this.element = element;
		this.compiler = compiler;
		this.observerLocator = observerLocator;

		// Grab user template from element
		this.processUserTemplate();
	}

	processUserTemplate() {

		// Get any col tags from the content
		var rowElement = this.element.querySelector("grid-row");
		var columnElements = Array.prototype.slice.call(rowElement.querySelectorAll("grid-col"));

		columnElements.forEach(c => {

			var attrs = Array.prototype.slice.call(c.attributes), colHash = {};
			attrs.forEach(a => colHash[a.name] = a.value);

			var col = new GridColumn(colHash, c.innerHTML);

			this.addColumn(col);
		});

		// Pull any row attrs into a hash object
		this.rowAttrs = {};
		var attrs = Array.prototype.slice.call(rowElement.attributes);
		attrs.forEach(a => this.rowAttrs[a.name] = a.value);

		// Remove all children
		while(this.element.childNodes.length > 0)
			this.element.removeChild(this.element.childNodes[0]);
	}

	/* === Lifecycle === */
	attached() {
		this.gridHeightChanged();

		if(this.autoLoad)
		    this.refresh();
	}

	bind(executionContext) {

		// Listen for window resize so we can re-flow the grid layout
		this.resizeListener = window.addEventListener('resize', this.syncColumnHeadersWithColumns.bind(this));

		this["$parent"] = executionContext;

		// Ensure the grid settings
		// If we can page on the server and we can't server sort, we can't sort locally
		if(this.serverPaging && !this.serverSorting)
			this.sortable = false;

		// Build the rows then dynamically compile the table
		// Get the table...
		var table = this.element.querySelector("table>tbody");
		var rowTemplate = table.querySelector("tr");

		// Create a fragment we will manipulate the DOM in
		var fragment = document.createDocumentFragment();

		// Move the row template to the fragment
		fragment.appendChild(rowTemplate);

		// Create the repeater
		rowTemplate.setAttribute("repeat.for", "$item of data");
		rowTemplate.setAttribute("class", "${ $item === $parent.selectedItem ? 'info' : '' }");

		// Copy any user specified row attributes to the row template
		for (var prop in this.rowAttrs) {
    		if (this.rowAttrs.hasOwnProperty(prop)) {
				rowTemplate.setAttribute(prop, this.rowAttrs[prop]);
        	}
		}

		// Create the columns
		this.columns.forEach(c => {
			var td = document.createElement("td");

			// Set attributes
			for (var prop in c) {
	    		if (c.hasOwnProperty(prop)) {

	    			if(prop == "template")
	    				td.innerHTML = c[prop];
	    			else
		    			td.setAttribute(prop, c[prop]);
	        	}
			}

			rowTemplate.appendChild(td);
		});

		// Compile
		this.compiler.compile(table, this, undefined, fragment);

		// HACK: why is the change handler not firing for noRowsMessage?
		this.noRowsMessageChanged();
	}

	unbind() {
		this.unbinding = true;
		window.removeEventListener('resize', this.resizeListener);
		this.dontWatchForChanges();
	}

	/* === Column handling === */
	addColumn(col) {

		// No-sort if grid is not sortable
		if(!this.sortable)
			col.nosort = true;

		this.columns.push(col);
	}

	/* === Paging === */
	pageChanged(page, oldValue) {

		if(page === oldValue) return;

		this.pageNumber = Number(page);
		this.refresh();
	}

	pageSizeChanged(newValue, oldValue) {

		if(newValue === oldValue) return;

		//this.pageChanged(1);
		this.updatePager();
	}

	filterSortPage(data) {
		// Applies filter, sort then page
		// 1. First filter the data down to the set we want, if we are using local data
		var tempData = data;

		if(this.showColumnFilters && !this.serverFiltering)
			tempData = this.applyFilter(tempData);

		// Count the data now before the sort/page
		this.count = tempData.length;

		// 2. Now sort the data
		if(this.sortable && !this.serverSorting)
			tempData = this.applySort(tempData);

		// 3. Now apply paging
		if(this.pageable && !this.serverPaging)
			tempData = this.applyPage(tempData);

		this.data = tempData;

		this.updatePager();

		this.watchForChanges();

		setTimeout(this.syncColumnHeadersWithColumns.bind(this), 0);
	}

	applyPage(data) {
		var start = (Number(this.pageNumber) - 1) * Number(this.pageSize);
		data = data.slice(start, start + Number(this.pageSize));

		return data;
	}

	updatePager() {
		if(this.pager)
			this.pager.update(this.pageNumber, Number(this.pageSize), Number(this.count));

		this.firstVisibleItem = (this.pageNumber - 1) * Number(this.pageSize) + 1;
		this.lastVisibleItem = Math.min((this.pageNumber) * Number(this.pageSize), this.count);
	}

	/* === Sorting === */
	fieldSorter(fields) {
	    return function (a, b) {
	        return fields
	            .map(function (o) {
	                var dir = 1;
	                if (o[0] === '-') {
	                   dir = -1;
	                   o = o.substring(1);
	                }
	                if (a[o] > b[o]) return dir;
	                if (a[o] < b[o]) return -(dir);
	                return 0;
	            })
	            .reduce(function firstNonZeroValue (p,n) {
	                return p ? p : n;
	            }, 0);
	    };
	}

	pageSizesChanged() {
		this.refresh();
	}

	sortChanged(field) {

		// Determine new sort
		var newSort = undefined;

		// Figure out which way this field should be sorting
	    switch(this.sorting[field]) {
	    	case "asc":
	    			newSort = "desc";
	    		break;
	    		case "desc":
	    			newSort = "";
	    		break;
	    		default:
	    			newSort = "asc";
	    		break;
	    }

	    this.sorting[field] = newSort;

	    // If the sort is present in the sort stack, slice it to the back of the stack, otherwise just add it
	    var pos = this.sortProcessingOrder.indexOf(field);

	    if(pos > -1)
	    	this.sortProcessingOrder.splice(pos, 1);

		this.sortProcessingOrder.push(field);

	    // Apply the new sort
		this.refresh();
	}

	applySort(data) {

		// Format the sort fields
		var fields = [];

		// Get the fields in the "sortingORder"
		for (var i = 0; i < this.sortProcessingOrder.length; i++) {
			var sort = this.sortProcessingOrder[i];

			for(var prop in this.sorting) {
				if(sort == prop && this.sorting[prop] !== "")
					fields.push(this.sorting[prop] === "asc" ? (prop) : ("-" + prop));
			}
		};

		// If server sort, just refresh
		data = data.sort(this.fieldSorter(fields));

		return data;
	}

	/* === Filtering === */
	applyFilter(data) {
		return data.filter((row) => {
			var include = true;

			for (var i = this.columns.length - 1; i >= 0; i--) {
				var col = this.columns[i];

				if(col.filterValue !== "" && row[col.field].toString().indexOf(col.filterValue) === -1) {
					include = false;
				}
			}

			return include;
		});
	}

	getFilterColumns() {
		var cols = {};

		for (var i = this.columns.length - 1; i >= 0; i--) {
			var col = this.columns[i];

			if(col.filterValue !== "")
				cols[col.field] = col.filterValue;
		}

		return cols;
	}

	debounce(func, wait) {
	    var timeout;

	    // the debounced function
	    return function() {

	        var context = this,
	            args = arguments;

	        // nulls out timer and calls original function
	        var later = function() {
	            timeout = null;
	            func.apply(context, args);
	        };

	        // restart the timer to call last function
	        clearTimeout(timeout);
	        timeout = setTimeout(later, wait);
	    };
	}

	updateFilters() {
		// Debounce

		if(!this.debouncedUpdateFilters) {
			this.debouncedUpdateFilters = this.debounce(this.refresh.bind(this), this.filterDebounce || 100);
		}

		this.debouncedUpdateFilters();
	}

	/* === Data === */
	refresh() {

		// If we have any server side stuff we need to get the data first
		this.dontWatchForChanges();

		if(this.serverPaging || this.serverSorting || this.serverFiltering || !this.initialLoad)
			this.getData();
		else
			this.filterSortPage(this.cache);

	}

	getData() {
		if(!this.read)
			throw new Error("No read method specified for grid");

		this.initialLoad = true;

		// TODO: Implement progress indicator
		this.loading = true;

		// Try to read from the data adapter
		this.read({
			sorting: this.sorting,
			paging: { page: this.pageNumber, size: Number(this.pageSize) },
			filtering: this.getFilterColumns()
		})
		.then((result) => {

			// Data should be in the result so grab it and assign it to the data property
			this.handleResult(result);

			this.loading = false;
		}, (result) => {
			// Something went terribly wrong, notify the consumer
			if(this.onReadError)
				this.onReadError(result);

			this.loading = false;
		});
	}

	handleResult(result) {

		// TODO: Check valid stuff was returned
		var data = result.data;

		// Is the data being paginated on the client side?
		// TODO: Work out when we should we use the cache... ever? If it's local data
		if(this.pageable && !this.serverPaging && !this.serverSorting && !this.serverFiltering) {
			// Cache the data
			this.cache = result.data;
			this.filterSortPage(this.cache);
		} else {
			this.data = result.data;
			this.filterSortPage(this.data);
		}

	    this.count = result.count;

	    // Update the pager - maybe the grid options should contain an update callback instead of reffing the
	    // pager into the current VM?
	    this.updatePager();
	}

	watchForChanges() {

		this.dontWatchForChanges();

		// Guard against data refresh events hitting after the user does anything that unloads the grid
		if(!this.unbinding)
		    // We can update the pager automagically
		    this.subscription = this.observerLocator
		        .getArrayObserver(this.cache)
		        .subscribe((splices) => {
					this.refresh();
		        });
	}

	dontWatchForChanges() {
		if(this.subscription)
			this.subscription();
	}

	/* === Selection === */

	select(item) {
		if(this.selectable)
			this.selectedItem = item;

		return true;
	}

	/* === Change handlers === */
	noRowsMessageChanged() {
		this.showNoRowsMessage = this.noRowsMessage !== "";
	}

	gridHeightChanged() {

		// TODO: Make this a one off
		var cont = this.element.querySelector(".grid-content-container");

		if(this.gridHeight > 0) {
			cont.setAttribute("style", "height:" + this.gridHeight + "px");
		} else {
			cont.removeAttribute("style");
		}
	}

	/* === Visual === */
	syncColumnHeadersWithColumns() {
		// Get the header row
		var headers = this.element.querySelectorAll("table>thead>tr:first-child>th");
		var filters = this.element.querySelectorAll("table>thead>tr:last-child>th");

		// Get the first row from the data if there is one...
		var cells = this.element.querySelectorAll("table>tbody>tr:first-child>td");

		for (var i = headers.length - 1; i >= 0; i--) {
			var header = headers[i];
			var filter = filters[i];
			var cell = cells[i];

			if(cell && header && filter) {
				var overflow = this.isBodyOverflowing();
				var tgtWidth = cell.offsetWidth + (i == headers.length - 1 && overflow ? this.scrollBarWidth : 0);

				// Make the header the same width as the cell...
				header.setAttribute("style", "width: " + tgtWidth + "px");
				filter.setAttribute("style", "width: " + tgtWidth + "px");
			}
		};
	}

	isBodyOverflowing() {
		var body = this.element.querySelector(".grid-content-container");
		return body.offsetHeight < body.scrollHeight || body.offsetWidth < body.scrollWidth;
	}
}

<commit_msg>Update grid.js<commit_after>import {bindable, inject, processContent, ObserverLocator, customElement, skipContentProcessing } from 'aurelia-framework';
import {GridColumn} from './grid-column';
import {Compiler} from 'charlespockert/aurelia-compiler';
import './aurelia-bs-grid.css!';

@customElement('grid')
@skipContentProcessing()
@inject(Element, Compiler, ObserverLocator)
export class Grid {

	/* == Styling == */
	@bindable gridHeight = 0;

	/* == Options == */

	// Initial load flag (for client side)
	@bindable initialLoad = false;

	// Filtering
	@bindable showColumnFilters = false;
	@bindable serverFiltering = false;
	@bindable filterDebounce = 500;

	// Pagination
	@bindable serverPaging = false;
	@bindable pageable = true;
	@bindable pageSize = 10;
	@bindable page = 1;
	@bindable pagerSize = 10;

	@bindable showPageSizeBox = true;
	@bindable showPagingSummary = true;
	@bindable showFirstLastButtons = true;
	@bindable showJumpButtons = true;

	@bindable pageSizes = [10, 25, 50];

	firstVisibleItem = 0;
	lastVisibleItem = 0;

	pageNumber = 1;

	// Sortination
	@bindable serverSorting = false;
	@bindable sortable = true;
	sortProcessingOrder = []; // Represents which order to apply sorts to each column
	sorting = {};

	// Burnination?
	Trogdor = true;

	// Column defs
	@bindable autoGenerateColumns;
	@bindable showColumnHeaders = true;
	columnHeaders = [];
	columns = [];

	// Selection
	@bindable selectable = false;
	@bindable selectedItem = null;

	// Misc
	@bindable noRowsMessage = "";

	// Data ....
	@bindable autoLoad = true;
	loading = false;
	@bindable loadingMessage = "Loading...";

	// Read
	@bindable read = null;
	@bindable onReadError = null;

	// Tracking
	cache = [];
	data = [];
	count = 0;

	// Subscription handling
	unbinding = false;

	// Visual
	// TODO: calc scrollbar width using browser
	scrollBarWidth = 16;

	constructor(element, compiler, observerLocator) {
		this.element = element;
		this.compiler = compiler;
		this.observerLocator = observerLocator;

		// Grab user template from element
		this.processUserTemplate();
	}

	processUserTemplate() {

		// Get any col tags from the content
		var rowElement = this.element.querySelector("grid-row");
		var columnElements = Array.prototype.slice.call(rowElement.querySelectorAll("grid-col"));

		columnElements.forEach(c => {

			var attrs = Array.prototype.slice.call(c.attributes), colHash = {};
			attrs.forEach(a => colHash[a.name] = a.value);

			var col = new GridColumn(colHash, c.innerHTML);

			this.addColumn(col);
		});

		// Pull any row attrs into a hash object
		this.rowAttrs = {};
		var attrs = Array.prototype.slice.call(rowElement.attributes);
		attrs.forEach(a => this.rowAttrs[a.name] = a.value);

		// Remove all children
		while(this.element.childNodes.length > 0)
			this.element.removeChild(this.element.childNodes[0]);
	}

	/* === Lifecycle === */
	attached() {
		this.gridHeightChanged();

		if(this.autoLoad)
		    this.refresh();
	}

	bind(executionContext) {

		// Listen for window resize so we can re-flow the grid layout
		this.resizeListener = window.addEventListener('resize', this.syncColumnHeadersWithColumns.bind(this));

		this["$parent"] = executionContext;

		// Ensure the grid settings
		// If we can page on the server and we can't server sort, we can't sort locally
		if(this.serverPaging && !this.serverSorting)
			this.sortable = false;

		// Build the rows then dynamically compile the table
		// Get the table...
		var table = this.element.querySelector("table>tbody");
		var rowTemplate = table.querySelector("tr");

		// Create a fragment we will manipulate the DOM in
		var fragment = document.createDocumentFragment();

		// Move the row template to the fragment
		fragment.appendChild(rowTemplate);

		// Create the repeater
		rowTemplate.setAttribute("repeat.for", "$item of data");
		rowTemplate.setAttribute("class", "${ $item === $parent.selectedItem ? 'info' : '' }");

		// Copy any user specified row attributes to the row template
		for (var prop in this.rowAttrs) {
    		if (this.rowAttrs.hasOwnProperty(prop)) {
				rowTemplate.setAttribute(prop, this.rowAttrs[prop]);
        	}
		}

		// Create the columns
		this.columns.forEach(c => {
			var td = document.createElement("td");

			// Set attributes
			for (var prop in c) {
	    		if (c.hasOwnProperty(prop)) {

	    			if(prop == "template")
	    				td.innerHTML = c[prop];
	    			else
		    			td.setAttribute(prop, c[prop]);
	        	}
			}

			rowTemplate.appendChild(td);
		});

		// Compile
		this.compiler.compile(table, this, undefined, fragment);

		// HACK: why is the change handler not firing for noRowsMessage?
		this.noRowsMessageChanged();
	}

	unbind() {
		this.unbinding = true;
		window.removeEventListener('resize', this.resizeListener);
		this.dontWatchForChanges();
	}

	/* === Column handling === */
	addColumn(col) {

		// No-sort if grid is not sortable
		if(!this.sortable)
			col.nosort = true;

		this.columns.push(col);
	}

	/* === Paging === */
	pageChanged(page, oldValue) {

		if(page === oldValue) return;

		this.pageNumber = Number(page);
		this.refresh();
	}

	pageSizeChanged(newValue, oldValue) {

		if(newValue === oldValue) return;

		//this.pageChanged(1);
		this.updatePager();
	}

	filterSortPage(data) {
		// Applies filter, sort then page
		// 1. First filter the data down to the set we want, if we are using local data
		var tempData = data;

		if(this.showColumnFilters && !this.serverFiltering)
			tempData = this.applyFilter(tempData);

		// Count the data now before the sort/page
		this.count = tempData.length;

		// 2. Now sort the data
		if(this.sortable && !this.serverSorting)
			tempData = this.applySort(tempData);

		// 3. Now apply paging
		if(this.pageable && !this.serverPaging)
			tempData = this.applyPage(tempData);

		this.data = tempData;

		this.updatePager();

		this.watchForChanges();

		setTimeout(this.syncColumnHeadersWithColumns.bind(this), 0);
	}

	applyPage(data) {
		var start = (Number(this.pageNumber) - 1) * Number(this.pageSize);
		data = data.slice(start, start + Number(this.pageSize));

		return data;
	}

	updatePager() {
		if(this.pager)
			this.pager.update(this.pageNumber, Number(this.pageSize), Number(this.count));

		this.firstVisibleItem = (this.pageNumber - 1) * Number(this.pageSize) + 1;
		this.lastVisibleItem = Math.min((this.pageNumber) * Number(this.pageSize), this.count);
	}

	/* === Sorting === */
	fieldSorter(fields) {
	    return function (a, b) {
	        return fields
	            .map(function (o) {
	                var dir = 1;
	                if (o[0] === '-') {
	                   dir = -1;
	                   o = o.substring(1);
	                }
	                if (a[o] > b[o]) return dir;
	                if (a[o] < b[o]) return -(dir);
	                return 0;
	            })
	            .reduce(function firstNonZeroValue (p,n) {
	                return p ? p : n;
	            }, 0);
	    };
	}

	pageSizesChanged() {
		this.refresh();
	}

	sortChanged(field) {

		// Determine new sort
		var newSort = undefined;

		// Figure out which way this field should be sorting
	    switch(this.sorting[field]) {
	    	case "asc":
	    			newSort = "desc";
	    		break;
	    		case "desc":
	    			newSort = "";
	    		break;
	    		default:
	    			newSort = "asc";
	    		break;
	    }

	    this.sorting[field] = newSort;

	    // If the sort is present in the sort stack, slice it to the back of the stack, otherwise just add it
	    var pos = this.sortProcessingOrder.indexOf(field);

	    if(pos > -1)
	    	this.sortProcessingOrder.splice(pos, 1);

		this.sortProcessingOrder.push(field);

	    // Apply the new sort
		this.refresh();
	}

	applySort(data) {

		// Format the sort fields
		var fields = [];

		// Get the fields in the "sortingORder"
		for (var i = 0; i < this.sortProcessingOrder.length; i++) {
			var sort = this.sortProcessingOrder[i];

			for(var prop in this.sorting) {
				if(sort == prop && this.sorting[prop] !== "")
					fields.push(this.sorting[prop] === "asc" ? (prop) : ("-" + prop));
			}
		};

		// If server sort, just refresh
		data = data.sort(this.fieldSorter(fields));

		return data;
	}

	/* === Filtering === */
	applyFilter(data) {
		return data.filter((row) => {
			var include = true;

			for (var i = this.columns.length - 1; i >= 0; i--) {
				var col = this.columns[i];

				if(col.filterValue !== "" && row[col.field].toString().indexOf(col.filterValue) === -1) {
					include = false;
				}
			}

			return include;
		});
	}

	getFilterColumns() {
		var cols = {};

		for (var i = this.columns.length - 1; i >= 0; i--) {
			var col = this.columns[i];

			if(col.filterValue !== "")
				cols[col.field] = col.filterValue;
		}

		return cols;
	}

	debounce(func, wait) {
	    var timeout;

	    // the debounced function
	    return function() {

	        var context = this,
	            args = arguments;

	        // nulls out timer and calls original function
	        var later = function() {
	            timeout = null;
	            func.apply(context, args);
	        };

	        // restart the timer to call last function
	        clearTimeout(timeout);
	        timeout = setTimeout(later, wait);
	    };
	}

	updateFilters() {
		// Debounce

		if(!this.debouncedUpdateFilters) {
			this.debouncedUpdateFilters = this.debounce(this.refresh.bind(this), this.filterDebounce || 100);
		}

		this.debouncedUpdateFilters();
	}

	/* === Data === */
	refresh() {

		// If we have any server side stuff we need to get the data first
		this.dontWatchForChanges();

		if(this.serverPaging || this.serverSorting || this.serverFiltering || !this.initialLoad)
			this.getData();
		else
			this.filterSortPage(this.cache);

	}

	getData() {
		if(!this.read)
			throw new Error("No read method specified for grid");

		this.initialLoad = true;

		// TODO: Implement progress indicator
		this.loading = true;

		// Try to read from the data adapter
		this.read({
			sorting: this.sorting,
			paging: { page: this.pageNumber, size: Number(this.pageSize) },
			filtering: this.getFilterColumns()
		})
		.then((result) => {

			// Data should be in the result so grab it and assign it to the data property
			this.handleResult(result);

			this.loading = false;
		}, (result) => {
			// Something went terribly wrong, notify the consumer
			if(this.onReadError)
				this.onReadError(result);

			this.loading = false;
		});
	}

	handleResult(result) {

		// TODO: Check valid stuff was returned
		var data = result.data;

		// Is the data being paginated on the client side?
		// TODO: Work out when we should we use the cache... ever? If it's local data
		if(this.pageable && !this.serverPaging && !this.serverSorting && !this.serverFiltering) {
			// Cache the data
			this.cache = result.data;
			this.filterSortPage(this.cache);
		} else {
			this.data = result.data;
			this.filterSortPage(this.data);
		}

	    this.count = result.count;

	    // Update the pager - maybe the grid options should contain an update callback instead of reffing the
	    // pager into the current VM?
	    this.updatePager();
	}

	watchForChanges() {

		this.dontWatchForChanges();

		// Guard against data refresh events hitting after the user does anything that unloads the grid
		if(!this.unbinding)
		    // We can update the pager automagically
		    this.subscription = this.observerLocator
		        .getArrayObserver(this.cache)
		        .subscribe((splices) => {
					this.refresh();
		        });
	}

	dontWatchForChanges() {
		if(this.subscription)
			this.subscription();
	}

	/* === Selection === */

	select(item) {
		if(this.selectable)
			this.selectedItem = item;

		return true;
	}

	/* === Change handlers === */
	noRowsMessageChanged() {
		this.showNoRowsMessage = this.noRowsMessage !== "";
	}

	gridHeightChanged() {

		// TODO: Make this a one off
		var cont = this.element.querySelector(".grid-content-container");

		if(this.gridHeight > 0) {
			cont.setAttribute("style", "height:" + this.gridHeight + "px");
		} else {
			cont.removeAttribute("style");
		}
	}

	/* === Visual === */
	syncColumnHeadersWithColumns() {
		// Get the header row
		var headers = this.element.querySelectorAll("table>thead>tr:first-child>th");
		var filters = this.element.querySelectorAll("table>thead>tr:last-child>th");

		// Get the first row from the data if there is one...
		var cells = this.element.querySelectorAll("table>tbody>tr:first-child>td");

		for (var i = headers.length - 1; i >= 0; i--) {
			var header = headers[i];
			var filter = filters[i];
			var cell = cells[i];

			if(cell && header && filter) {
				var overflow = this.isBodyOverflowing();
				var tgtWidth = cell.offsetWidth + (i == headers.length - 1 && overflow ? this.scrollBarWidth : 0);

				// Make the header the same width as the cell...
				header.setAttribute("style", "width: " + tgtWidth + "px");
				filter.setAttribute("style", "width: " + tgtWidth + "px");
			}
		};
	}

	isBodyOverflowing() {
		var body = this.element.querySelector(".grid-content-container");
		return body.offsetHeight < body.scrollHeight || body.offsetWidth < body.scrollWidth;
	}
}

<|endoftext|>


<commit_before><commit_msg>preload images during page load<commit_after><|endoftext|>


<commit_before><commit_msg>Remove user-profile.js script.<commit_after><|endoftext|>


<commit_before><commit_msg>Add expression prefix regex code completion optimization feature<commit_after><|endoftext|>


<commit_before>function ConstraintManipulator(host){
    this.id = "mdConstraints";
    this.title = "Constraints";

    this.width = 224;
    this.height = 290;
    this.posx = 800;
    this.posy = 312;

    this.host = host;

	this.constraints = {};
}

ConstraintManipulator.method("getInitContent", function(){
	var ret = '<form id="SaveConstraints" enctype="multipart/form-data" method="post" action="/Constraint" style="display: block">';
	ret += '<input type="hidden" id="windowKey" name="windowKey" value="' + this.host.key + '">';
	ret += '<input type="hidden" id="constraintCont" name="constraints" value="' + this.host.key + '">';
	ret += '<input type="hidden" id="instanceName" name="instName" value="' + this.host.key + '">';
	ret += '<input type="submit" class="inputButton" id="Save" value="Save New Constraints"></form>';
	ret += '<text id="constraintDisplay" style="white-space: pre;"></text>';
	return ret;

});

ConstraintManipulator.method("onInitRendered", function(){
    var that = this;
    $("#Save").click(function(){
    	$("#constraintCont").val(that.getClaferConstraints(false));
    	$("#instanceName").val(that.instanceProcessor.getInstanceName().replace(/c[0-9]_/, "") + " : " + that.instanceProcessor.getInstanceSuperClafer().replace(/c[0-9]_/, ""));
    });
});

ConstraintManipulator.method("onDataLoaded", function(data){
	this.Processor = new ClaferProcessor(data.claferXML);
	this.instanceProcessor = new InstanceProcessor(data.instancesXML);

	this.constraints = {};
	this.updateContent();
});

ConstraintManipulator.method("addConstraint", function(feature, require){
	this.constraints[feature] = require;
	this.updateContent();
});

ConstraintManipulator.method("removeConstraint", function(feature){
	delete this.constraints[feature];
	this.updateContent();
});

ConstraintManipulator.method("getConstraints", function(){
	var array = [];
	for(var constraint in this.constraints){
		array.push(constraint);
	}
	return array;
})

ConstraintManipulator.method("getClaferConstraints", function(includeOriginalConstraints){
	var ret = "";

	if(includeOriginalConstraints){ //pull from original model
		var list = this.Processor.getConstraints();
		for (var i=0; i<list.length; i++){
			ret += "\n" + list[i];
		}
	}

	var constraints = this.getConstraints();
	for (i=0; i<constraints.length; i++){
		ret += "\n[";
		if (!this.constraints[constraints[i]]){
			ret += "!";
		}
		ret += constraints[i];
		ret += "]";
	}
	console.log(ret)
	return ret;
});

ConstraintManipulator.method("updateContent", function(){
	var content = this.getClaferConstraints(true);
	$("#constraintDisplay").text(content);
});<commit_msg>Regex typo<commit_after>function ConstraintManipulator(host){
    this.id = "mdConstraints";
    this.title = "Constraints";

    this.width = 224;
    this.height = 290;
    this.posx = 800;
    this.posy = 312;

    this.host = host;

	this.constraints = {};
}

ConstraintManipulator.method("getInitContent", function(){
	var ret = '<form id="SaveConstraints" enctype="multipart/form-data" method="post" action="/Constraint" style="display: block">';
	ret += '<input type="hidden" id="windowKey" name="windowKey" value="' + this.host.key + '">';
	ret += '<input type="hidden" id="constraintCont" name="constraints" value="' + this.host.key + '">';
	ret += '<input type="hidden" id="instanceName" name="instName" value="' + this.host.key + '">';
	ret += '<input type="submit" class="inputButton" id="Save" value="Save New Constraints"></form>';
	ret += '<text id="constraintDisplay" style="white-space: pre;"></text>';
	return ret;

});

ConstraintManipulator.method("onInitRendered", function(){
    var that = this;
    $("#Save").click(function(){
    	$("#constraintCont").val(that.getClaferConstraints(false));
    	$("#instanceName").val(that.instanceProcessor.getInstanceName().replace(/c[0-9]_/g, "") + " : " + that.instanceProcessor.getInstanceSuperClafer().replace(/c[0-9]_/g ""));
    });
});

ConstraintManipulator.method("onDataLoaded", function(data){
	this.Processor = new ClaferProcessor(data.claferXML);
	this.instanceProcessor = new InstanceProcessor(data.instancesXML);

	this.constraints = {};
	this.updateContent();
});

ConstraintManipulator.method("addConstraint", function(feature, require){
	this.constraints[feature] = require;
	this.updateContent();
});

ConstraintManipulator.method("removeConstraint", function(feature){
	delete this.constraints[feature];
	this.updateContent();
});

ConstraintManipulator.method("getConstraints", function(){
	var array = [];
	for(var constraint in this.constraints){
		array.push(constraint);
	}
	return array;
})

ConstraintManipulator.method("getClaferConstraints", function(includeOriginalConstraints){
	var ret = "";

	if(includeOriginalConstraints){ //pull from original model
		var list = this.Processor.getConstraints();
		for (var i=0; i<list.length; i++){
			ret += "\n" + list[i];
		}
	}

	var constraints = this.getConstraints();
	for (i=0; i<constraints.length; i++){
		ret += "\n[";
		if (!this.constraints[constraints[i]]){
			ret += "!";
		}
		ret += constraints[i];
		ret += "]";
	}
	console.log(ret)
	return ret;
});

ConstraintManipulator.method("updateContent", function(){
	var content = this.getClaferConstraints(true);
	$("#constraintDisplay").text(content);
});<|endoftext|>


<commit_before>/// <reference path="globals.ts"/>
define(["require", "exports", "Framework/Signum.Web/Signum/Scripts/Entities", "Framework/Signum.Web/Signum/Scripts/Validator", "Framework/Signum.Web/Signum/Scripts/Navigator", "Framework/Signum.Web/Signum/Scripts/Finder"], function(require, exports, Entities, Validator, Navigator, Finder) {
    function executeDefault(options) {
        options = $.extend({
            avoidValidate: false,
            validationOptions: {},
            isLite: false
        }, options);

        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        return exports.entityIsValidOrLite(options).then(function () {
            return exports.executeAjax(options).then(function (eHtml) {
                Navigator.reload(eHtml);
                exports.notifyExecuted();
            });
        });
    }
    exports.executeDefault = executeDefault;

    function executeAjax(options) {
        options = $.extend({
            controllerUrl: SF.Urls.operationExecute,
            isLite: false,
            isNavigatePopup: Navigator.isNavigatePopup(options.prefix)
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.entityRequestData(options) }).then(function (result) {
            Validator.assertModelStateErrors(result, options.prefix);
            return Entities.EntityHtml.fromHtml(options.prefix, result);
        });
    }
    exports.executeAjax = executeAjax;

    function executeDefaultContextual(options) {
        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        return exports.executeAjaxContextual(options).then(function (result) {
            if (result)
                exports.markCells(options.prefix);
        });
    }
    exports.executeDefaultContextual = executeDefaultContextual;

    function executeAjaxContextual(options, runtimeInfo) {
        options = $.extend({
            controllerUrl: SF.Urls.operationExecute,
            avoidReturnView: true,
            isLite: true
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.contextualRequestData(options, null, runtimeInfo) }).then(SF.isEmpty);
    }
    exports.executeAjaxContextual = executeAjaxContextual;

    function constructFromDefault(options, openNewWindowOrEvent) {
        options = $.extend({
            avoidValidate: false,
            validationOptions: {},
            isLite: true
        }, options);

        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        return exports.entityIsValidOrLite(options).then(function () {
            if (Navigator.isOpenNewWindow(openNewWindowOrEvent))
                exports.constructFromSubmit(options);
            else
                return exports.constructFromAjax(options, exports.getNewPrefix(options)).then(function (eHtml) {
                    return exports.openPopup(eHtml);
                });
        });
    }
    exports.constructFromDefault = constructFromDefault;

    function constructFromAjax(options, newPrefix) {
        options = $.extend({
            controllerUrl: SF.Urls.operationConstructFrom,
            isLite: true
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.entityRequestData(options, newPrefix) }).then(function (html) {
            return Entities.EntityHtml.fromHtml(newPrefix, html);
        });
    }
    exports.constructFromAjax = constructFromAjax;

    function constructFromSubmit(options) {
        options = $.extend({
            controllerUrl: SF.Urls.operationConstructFrom,
            isLite: true
        }, options);

        SF.submitOnly(options.controllerUrl, exports.entityRequestData(options, ""), true);
    }
    exports.constructFromSubmit = constructFromSubmit;

    function constructFromDefaultContextual(options, openNewWindowOrEvent) {
        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        if (Navigator.isOpenNewWindow(openNewWindowOrEvent)) {
            exports.markCells(options.prefix);
            exports.constructFromSubmitContextual(options);
        } else {
            return exports.constructFromAjaxContextual(options, exports.getNewPrefix(options)).then(function (eHtml) {
                exports.markCells(options.prefix);
                return exports.openPopup(eHtml);
            });
        }
    }
    exports.constructFromDefaultContextual = constructFromDefaultContextual;

    function constructFromAjaxContextual(options, newPrefix, runtimeInfo) {
        options = $.extend({
            controllerUrl: SF.Urls.operationConstructFrom,
            isLite: true
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.contextualRequestData(options, newPrefix, runtimeInfo) }).then(function (html) {
            return Entities.EntityHtml.fromHtml(newPrefix, html);
        });
    }
    exports.constructFromAjaxContextual = constructFromAjaxContextual;

    function constructFromSubmitContextual(options, runtimeInfo) {
        options = $.extend({
            controllerUrl: SF.Urls.operationConstructFrom,
            isLite: true
        }, options);

        SF.submitOnly(options.controllerUrl, exports.contextualRequestData(options, "", runtimeInfo), true);
    }
    exports.constructFromSubmitContextual = constructFromSubmitContextual;

    function deleteDefault(options) {
        options = $.extend({
            avoidValidate: true,
            isLite: true
        }, options);

        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        return exports.entityIsValidOrLite(options).then(function () {
            return exports.deleteAjax(options);
        }).then(function () {
            //ajax prefilter will take redirect
            if (options.prefix) {
                Navigator.closePopup(options.prefix);
            }
        });
    }
    exports.deleteDefault = deleteDefault;

    function deleteAjax(options) {
        options = $.extend({
            controllerUrl: SF.Urls.operationDelete,
            avoidReturnRedirect: !!options.prefix,
            isLite: true
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.entityRequestData(options) });
    }
    exports.deleteAjax = deleteAjax;

    function deleteDefaultContextual(options) {
        options = $.extend({
            isLite: true
        }, options);

        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        return exports.deleteAjaxContextual(options).then(function (result) {
            exports.markCells(options.prefix);
        });
    }
    exports.deleteDefaultContextual = deleteDefaultContextual;

    function deleteAjaxContextual(options, runtimeInfo) {
        options = $.extend({
            controllerUrl: SF.Urls.operationDelete,
            avoidReturnRedirect: true,
            isLite: true
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.contextualRequestData(options, null, runtimeInfo) });
    }
    exports.deleteAjaxContextual = deleteAjaxContextual;

    function constructFromManyDefault(options, openNewWindowOrEvent) {
        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        if (Navigator.isOpenNewWindow(openNewWindowOrEvent)) {
            exports.markCells(options.prefix);
            exports.constructFromManySubmit(options);
        } else {
            return exports.constructFromManyAjax(options, exports.getNewPrefix(options)).then(function (eHtml) {
                exports.markCells(options.prefix);
                return exports.openPopup(eHtml);
            });
        }
    }
    exports.constructFromManyDefault = constructFromManyDefault;

    function constructFromManyAjax(options, newPrefix) {
        options = $.extend({
            isLite: true,
            controllerUrl: SF.Urls.operationConstructFromMany
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.constructFromManyRequestData(options, newPrefix) }).then(function (html) {
            return Entities.EntityHtml.fromHtml(newPrefix, html);
        });
    }
    exports.constructFromManyAjax = constructFromManyAjax;

    function constructFromManySubmit(options) {
        options = $.extend({
            isLite: true,
            controllerUrl: SF.Urls.operationConstructFromMany
        }, options);

        SF.submitOnly(options.controllerUrl, exports.constructFromManyRequestData(options, ""), true);
    }
    exports.constructFromManySubmit = constructFromManySubmit;

    function confirmIfNecessary(options) {
        return !options.confirmMessage || confirm(options.confirmMessage);
    }
    exports.confirmIfNecessary = confirmIfNecessary;

    function openPopup(entityHtml) {
        exports.notifyExecuted();
        return Navigator.navigatePopup(entityHtml);
    }
    exports.openPopup = openPopup;

    function markCells(prefix) {
        $("tr.active").addClass("sf-entity-ctxmenu-success");
        exports.notifyExecuted();
    }
    exports.markCells = markCells;

    function notifyExecuted() {
        SF.Notify.info(lang.signum.executed, 2000);
    }
    exports.notifyExecuted = notifyExecuted;

    function getNewPrefix(options) {
        return options.prefix.child("New");
    }
    exports.getNewPrefix = getNewPrefix;

    function entityRequestData(options, newPrefix) {
        var result = exports.baseRequestData(options, newPrefix);

        var formValues = options.isLite ? Validator.getFormValuesLite(options.prefix) : Validator.getFormValues(options.prefix);

        formValues[Entities.Keys.viewMode] = options.isNavigatePopup ? "Navigate" : "View";

        return $.extend(result, formValues);
    }
    exports.entityRequestData = entityRequestData;

    function constructFromManyRequestData(options, newPrefix, liteKey) {
        var result = exports.baseRequestData(options, newPrefix);

        if (!liteKey) {
            var items = Finder.SearchControl.getSelectedItems(options.prefix);
            liteKey = items.map(function (i) {
                return i.runtimeInfo.key();
            });
        }

        result["liteKeys"] = liteKey.join(",");

        return result;
    }
    exports.constructFromManyRequestData = constructFromManyRequestData;

    function contextualRequestData(options, newPrefix, runtimeInfo) {
        var result = exports.baseRequestData(options, newPrefix);

        if (!runtimeInfo) {
            var items = Finder.SearchControl.getSelectedItems(options.prefix);

            if (items.length > 1)
                throw new Error("just one entity should have been selected");

            runtimeInfo = items[0].runtimeInfo;
        }

        result[options.prefix.child(Entities.Keys.runtimeInfo)] = runtimeInfo.toString();

        return result;
    }
    exports.contextualRequestData = contextualRequestData;

    function baseRequestData(options, newPrefix) {
        var formValues = Validator.getFormBasics();

        formValues = $.extend({
            isLite: options.isLite,
            operationFullKey: options.operationKey,
            newprefix: newPrefix,
            prefix: options.prefix
        }, formValues);

        if (options.avoidReturnRedirect)
            formValues["sfAvoidReturnRedirect"] = true;

        if (options.avoidReturnView)
            formValues["sfAvoidReturnView"] = true;

        return $.extend(formValues, options.requestExtraJsonData);
    }
    exports.baseRequestData = baseRequestData;

    function entityIsValidOrLite(options) {
        if (options.isLite || options.avoidValidate)
            return Promise.resolve(null);

        var valOptions = $.extend({ prefix: options.prefix }, options.validationOptions);

        return Validator.entityIsValid(valOptions);
    }
    exports.entityIsValidOrLite = entityIsValidOrLite;

    function validateAndSubmit(options) {
        if (exports.entityIsValidOrLite(options))
            exports.submit(options);
    }
    exports.validateAndSubmit = validateAndSubmit;

    function submit(options) {
        var mainControl = options.prefix ? $("#{0}_divMainControl".format(options.prefix)) : $("#divMainControl");

        var $form = mainControl.closest("form");
        $form.append(SF.hiddenInput('isLite', options.isLite) + SF.hiddenInput('operationFullKey', options.operationKey) + SF.hiddenInput("prefix", options.prefix));

        if (!SF.isEmpty(options.prefix)) {
            //Check runtimeInfo present => if it's a popup from a LineControl it will not be
            var myRuntimeInfoKey = options.prefix.child(Entities.Keys.runtimeInfo);
            if (myRuntimeInfoKey.tryGet().length == 0) {
                SF.hiddenInput(myRuntimeInfoKey, mainControl.data("runtimeinfo"));
            }
        }

        SF.submit(options.controllerUrl, options.requestExtraJsonData, $form);

        return false;
    }
    exports.submit = submit;
});
//# sourceMappingURL=Operations.js.map
<commit_msg>fix Operations.js compilation<commit_after>/// <reference path="globals.ts"/>
define(["require", "exports", "Framework/Signum.Web/Signum/Scripts/Entities", "Framework/Signum.Web/Signum/Scripts/Validator", "Framework/Signum.Web/Signum/Scripts/Navigator", "Framework/Signum.Web/Signum/Scripts/Finder"], function(require, exports, Entities, Validator, Navigator, Finder) {
    function executeDefault(options) {
        options = $.extend({
            avoidValidate: false,
            validationOptions: {},
            isLite: false
        }, options);

        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        return exports.entityIsValidOrLite(options).then(function () {
            return exports.executeAjax(options).then(function (eHtml) {
                Navigator.reload(eHtml);
                exports.notifyExecuted();
            });
        });
    }
    exports.executeDefault = executeDefault;

    function executeAjax(options) {
        options = $.extend({
            controllerUrl: SF.Urls.operationExecute,
            isLite: false,
            isNavigatePopup: Navigator.isNavigatePopup(options.prefix)
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.entityRequestData(options) }).then(function (result) {
            Validator.assertModelStateErrors(result, options.prefix);
            return Entities.EntityHtml.fromHtml(options.prefix, result);
        });
    }
    exports.executeAjax = executeAjax;

    function executeDefaultContextual(options) {
        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        return exports.executeAjaxContextual(options).then(function (result) {
            if (result)
                exports.markCells(options.prefix);
        });
    }
    exports.executeDefaultContextual = executeDefaultContextual;

    function executeAjaxContextual(options, runtimeInfo) {
        options = $.extend({
            controllerUrl: SF.Urls.operationExecute,
            avoidReturnView: true,
            isLite: true
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.contextualRequestData(options, null, runtimeInfo) }).then(SF.isEmpty);
    }
    exports.executeAjaxContextual = executeAjaxContextual;

    function constructFromDefault(options, openNewWindowOrEvent) {
        options = $.extend({
            avoidValidate: false,
            validationOptions: {},
            isLite: true
        }, options);

        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        return exports.entityIsValidOrLite(options).then(function () {
            if (Navigator.isOpenNewWindow(openNewWindowOrEvent))
                exports.constructFromSubmit(options);
            else
                return exports.constructFromAjax(options, exports.getNewPrefix(options)).then(function (eHtml) {
                    return exports.openPopup(eHtml);
                });
        });
    }
    exports.constructFromDefault = constructFromDefault;

    function constructFromAjax(options, newPrefix) {
        options = $.extend({
            controllerUrl: SF.Urls.operationConstructFrom,
            isLite: true
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.entityRequestData(options, newPrefix) }).then(function (html) {
            return Entities.EntityHtml.fromHtml(newPrefix, html);
        });
    }
    exports.constructFromAjax = constructFromAjax;

    function constructFromSubmit(options) {
        options = $.extend({
            controllerUrl: SF.Urls.operationConstructFrom,
            isLite: true
        }, options);

        SF.submitOnly(options.controllerUrl, exports.entityRequestData(options, ""), true);
    }
    exports.constructFromSubmit = constructFromSubmit;

    function constructFromDefaultContextual(options, openNewWindowOrEvent) {
        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        if (Navigator.isOpenNewWindow(openNewWindowOrEvent)) {
            exports.markCells(options.prefix);
            exports.constructFromSubmitContextual(options);
        } else {
            return exports.constructFromAjaxContextual(options, exports.getNewPrefix(options)).then(function (eHtml) {
                exports.markCells(options.prefix);
                return exports.openPopup(eHtml);
            });
        }
    }
    exports.constructFromDefaultContextual = constructFromDefaultContextual;

    function constructFromAjaxContextual(options, newPrefix, runtimeInfo) {
        options = $.extend({
            controllerUrl: SF.Urls.operationConstructFrom,
            isLite: true
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.contextualRequestData(options, newPrefix, runtimeInfo) }).then(function (html) {
            return Entities.EntityHtml.fromHtml(newPrefix, html);
        });
    }
    exports.constructFromAjaxContextual = constructFromAjaxContextual;

    function constructFromSubmitContextual(options, runtimeInfo) {
        options = $.extend({
            controllerUrl: SF.Urls.operationConstructFrom,
            isLite: true
        }, options);

        SF.submitOnly(options.controllerUrl, exports.contextualRequestData(options, "", runtimeInfo), true);
    }
    exports.constructFromSubmitContextual = constructFromSubmitContextual;

    function deleteDefault(options) {
        options = $.extend({
            avoidValidate: true,
            isLite: true
        }, options);

        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        return exports.entityIsValidOrLite(options).then(function () {
            return exports.deleteAjax(options);
        }).then(function () {
            //ajax prefilter will take redirect
            if (options.prefix) {
                Navigator.closePopup(options.prefix);
            }
        });
    }
    exports.deleteDefault = deleteDefault;

    function deleteAjax(options) {
        options = $.extend({
            controllerUrl: SF.Urls.operationDelete,
            avoidReturnRedirect: !!options.prefix,
            isLite: true
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.entityRequestData(options) });
    }
    exports.deleteAjax = deleteAjax;

    function deleteDefaultContextual(options) {
        options = $.extend({
            isLite: true
        }, options);

        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        return exports.deleteAjaxContextual(options).then(function (result) {
            exports.markCells(options.prefix);
        });
    }
    exports.deleteDefaultContextual = deleteDefaultContextual;

    function deleteAjaxContextual(options, runtimeInfo) {
        options = $.extend({
            controllerUrl: SF.Urls.operationDelete,
            avoidReturnRedirect: true,
            isLite: true
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.contextualRequestData(options, null, runtimeInfo) });
    }
    exports.deleteAjaxContextual = deleteAjaxContextual;

    function constructFromManyDefault(options, openNewWindowOrEvent) {
        if (!exports.confirmIfNecessary(options))
            return Promise.reject("confirmation");

        if (Navigator.isOpenNewWindow(openNewWindowOrEvent)) {
            exports.markCells(options.prefix);
            exports.constructFromManySubmit(options);
        } else {
            return exports.constructFromManyAjax(options, exports.getNewPrefix(options)).then(function (eHtml) {
                exports.markCells(options.prefix);
                return exports.openPopup(eHtml);
            });
        }
    }
    exports.constructFromManyDefault = constructFromManyDefault;

    function constructFromManyAjax(options, newPrefix) {
        options = $.extend({
            isLite: true,
            controllerUrl: SF.Urls.operationConstructFromMany
        }, options);

        return SF.ajaxPost({ url: options.controllerUrl, data: exports.constructFromManyRequestData(options, newPrefix) }).then(function (html) {
            return Entities.EntityHtml.fromHtml(newPrefix, html);
        });
    }
    exports.constructFromManyAjax = constructFromManyAjax;

    function constructFromManySubmit(options) {
        options = $.extend({
            isLite: true,
            controllerUrl: SF.Urls.operationConstructFromMany
        }, options);

        SF.submitOnly(options.controllerUrl, exports.constructFromManyRequestData(options, ""), true);
    }
    exports.constructFromManySubmit = constructFromManySubmit;

    function confirmIfNecessary(options) {
        return !options.confirmMessage || confirm(options.confirmMessage);
    }
    exports.confirmIfNecessary = confirmIfNecessary;

    function openPopup(entityHtml) {
        exports.notifyExecuted();
        return Navigator.navigatePopup(entityHtml);
    }
    exports.openPopup = openPopup;

    function markCells(prefix) {
        $("tr.active").addClass("sf-entity-ctxmenu-success");
        exports.notifyExecuted();
    }
    exports.markCells = markCells;

    function notifyExecuted() {
        SF.Notify.info(lang.signum.executed, 2000);
    }
    exports.notifyExecuted = notifyExecuted;

    function getNewPrefix(options) {
        return options.prefix.child("New");
    }
    exports.getNewPrefix = getNewPrefix;

    function entityRequestData(options, newPrefix) {
        var result = exports.baseRequestData(options, newPrefix);

        var formValues = options.isLite ? Validator.getFormValuesLite(options.prefix) : Validator.getFormValues(options.prefix);

        formValues[Entities.Keys.viewMode] = options.isNavigatePopup ? "Navigate" : "View";

        return $.extend(result, formValues);
    }
    exports.entityRequestData = entityRequestData;

    function constructFromManyRequestData(options, newPrefix, liteKey) {
        var result = exports.baseRequestData(options, newPrefix);

        if (!liteKey) {
            var items = Finder.SearchControl.getSelectedItems(options.prefix);
            liteKey = items.map(function (i) {
                return i.key();
            });
        }

        result["liteKeys"] = liteKey.join(",");

        return result;
    }
    exports.constructFromManyRequestData = constructFromManyRequestData;

    function contextualRequestData(options, newPrefix, runtimeInfo) {
        var result = exports.baseRequestData(options, newPrefix);

        if (!runtimeInfo) {
            var items = Finder.SearchControl.getSelectedItems(options.prefix);

            if (items.length > 1)
                throw new Error("just one entity should have been selected");

            runtimeInfo = items[0].runtimeInfo;
        }

        result[options.prefix.child(Entities.Keys.runtimeInfo)] = runtimeInfo.toString();

        return result;
    }
    exports.contextualRequestData = contextualRequestData;

    function baseRequestData(options, newPrefix) {
        var formValues = Validator.getFormBasics();

        formValues = $.extend({
            isLite: options.isLite,
            operationFullKey: options.operationKey,
            newprefix: newPrefix,
            prefix: options.prefix
        }, formValues);

        if (options.avoidReturnRedirect)
            formValues["sfAvoidReturnRedirect"] = true;

        if (options.avoidReturnView)
            formValues["sfAvoidReturnView"] = true;

        return $.extend(formValues, options.requestExtraJsonData);
    }
    exports.baseRequestData = baseRequestData;

    function entityIsValidOrLite(options) {
        if (options.isLite || options.avoidValidate)
            return Promise.resolve(null);

        var valOptions = $.extend({ prefix: options.prefix }, options.validationOptions);

        return Validator.entityIsValid(valOptions);
    }
    exports.entityIsValidOrLite = entityIsValidOrLite;

    function validateAndSubmit(options) {
        if (exports.entityIsValidOrLite(options))
            exports.submit(options);
    }
    exports.validateAndSubmit = validateAndSubmit;

    function submit(options) {
        var mainControl = options.prefix ? $("#{0}_divMainControl".format(options.prefix)) : $("#divMainControl");

        var $form = mainControl.closest("form");
        $form.append(SF.hiddenInput('isLite', options.isLite) + SF.hiddenInput('operationFullKey', options.operationKey) + SF.hiddenInput("prefix", options.prefix));

        if (!SF.isEmpty(options.prefix)) {
            //Check runtimeInfo present => if it's a popup from a LineControl it will not be
            var myRuntimeInfoKey = options.prefix.child(Entities.Keys.runtimeInfo);
            if (myRuntimeInfoKey.tryGet().length == 0) {
                SF.hiddenInput(myRuntimeInfoKey, mainControl.data("runtimeinfo"));
            }
        }

        SF.submit(options.controllerUrl, options.requestExtraJsonData, $form);

        return false;
    }
    exports.submit = submit;
});
//# sourceMappingURL=Operations.js.map
<|endoftext|>