<commit_before>
// http://stackoverflow.com/questions/3404508/cross-browsers-mult-lines-text-overflow-with-ellipsis-appended-within-a-widthhe
// target must have fixed width and height
function truncate(target, w, h) {
    target = ($.type(target) === 'string')
                ? $(target)
                : target;
    var inner = target.find('.truncation');
    if (inner.length === 0) {
        // inner = $('<span>').addClass('truncation').text(target.text());
        // target.append(inner);
        console.error('mark "truncation" class in the target of ',target);
        return target.text();
    }

    var expH = $('<div>').height(h).height(); //target.height();
    var count = 0, changed = false;
    while(inner.outerHeight() > expH) {
        inner.text(function(i, text) {
            changed = true;
            return text.replace(/\W*\s(\S)*$/, '...');
        });
        count += 1;
        if (count > 200) {
            console.error('truncation can not fulfill  ', h, 'or', expH);
            break;
        }
    }
    if (changed) {
        target.width(w);
        target.height(h);
    }
    return target.text();
}

// try to fix jquery's replaceWith
function replaceDom($replacement, $origin) {
    $replacement.hide();
    $replacement.insertBefore($origin);
    $origin.remove();
    $replacement.show();
}

function completeLinkState(url) {
    /*
     hash: "#plain-shelf"
     host: "localhost"
     hostname: "localhost"
     href: "http://localhost/editor/list.php?q={%22department%22:%22%E5%A5%97%E6%9B%B8%22}#plain-shelf"
     origin: "http://localhost"
     pathname: "/editor/list.php"
     port: ""
     protocol: "http:"
     search: "?q={%22department%22:%22%E5%A5%97%E6%9B%B8%22}"
    */
    var loc = window.location;
    return url + loc.hash;
}

function getLinkParam(key) {
    var info = window.location;
    var params = parseQueryString(info.search);
    return params[key];
}

function updateLinkParams(updates) {
    var info = window.location;
    var params = parseQueryString(info.search.substr(1));

    $.each(updates, function (key, val) {
        params[key] = encodeURI(val);
    });

    var query = [];
    $.each(params, function (k, v) {
        query.push(k + "=" + v);
    });
    return info.origin + info.pathname + '?' + query.join('&') + info.hash;
}

function parseQueryString(query) {
    var params = {}, queries, pair, i, l;
    if (query === '') {
        return params;
    }

    // Split into key/value pairs
    queries = query.split("&");

    // Convert the array of strings into an object
    for ( i = 0, l = queries.length; i < l; i++ ) {
        pair = queries[i].split('=');
        params[pair[0]] = pair[1];
    }

    return params;
}

function getClassByPattern (ptn) {
    // alternative: (css.match (/\blv\d+/g) || []).join(' ')
    return (function (index, css) {
        return ((new RegExp(ptn, 'g')).exec(css) || []).join(' ');
    });
}

function toggleRadio(_this) {
    var $this = $(_this);
    $this.parent().find('input[type="radio"]').prop('checked', true);
    $this.prop('checked', true);
}<commit_msg>fix url query parsing<commit_after>
// http://stackoverflow.com/questions/3404508/cross-browsers-mult-lines-text-overflow-with-ellipsis-appended-within-a-widthhe
// target must have fixed width and height
function truncate(target, w, h) {
    target = ($.type(target) === 'string')
                ? $(target)
                : target;
    var inner = target.find('.truncation');
    if (inner.length === 0) {
        // inner = $('<span>').addClass('truncation').text(target.text());
        // target.append(inner);
        console.error('mark "truncation" class in the target of ',target);
        return target.text();
    }

    var expH = $('<div>').height(h).height(); //target.height();
    var count = 0, changed = false;
    while(inner.outerHeight() > expH) {
        inner.text(function(i, text) {
            changed = true;
            return text.replace(/\W*\s(\S)*$/, '...');
        });
        count += 1;
        if (count > 200) {
            console.error('truncation can not fulfill  ', h, 'or', expH);
            break;
        }
    }
    if (changed) {
        target.width(w);
        target.height(h);
    }
    return target.text();
}

// try to fix jquery's replaceWith
function replaceDom($replacement, $origin) {
    $replacement.hide();
    $replacement.insertBefore($origin);
    $origin.remove();
    $replacement.show();
}

function completeLinkState(url) {
    /*
     hash: "#plain-shelf"
     host: "localhost"
     hostname: "localhost"
     href: "http://localhost/editor/list.php?q={%22department%22:%22%E5%A5%97%E6%9B%B8%22}#plain-shelf"
     origin: "http://localhost"
     pathname: "/editor/list.php"
     port: ""
     protocol: "http:"
     search: "?q={%22department%22:%22%E5%A5%97%E6%9B%B8%22}"
    */
    var loc = window.location;
    return url + loc.hash;
}

function getLinkParam(key) {
    var info = window.location;
    var params = parseQueryString(info.search);
    return params[key];
}

function updateLinkParams(updates) {
    var info = window.location;
    var params = parseQueryString(info.search.substr(1));

    $.each(updates, function (key, val) {
        params[key] = encodeURI(val);
    });

    var query = [];
    $.each(params, function (k, v) {
        query.push(k + "=" + v);
    });
    return info.origin + info.pathname + '?' + query.join('&') + info.hash;
}

function parseQueryString(query) {
    var params = {}, queries, pair, i, l;
    if (query === '') {
        return params;
    }

    // Split into key/value pairs
    queries = query.replace('?', '').split("&");

    // Convert the array of strings into an object
    for ( i = 0, l = queries.length; i < l; i++ ) {
        pair = queries[i].split('=');
        params[pair[0]] = pair[1];
    }

    return params;
}

function getClassByPattern (ptn) {
    // alternative: (css.match (/\blv\d+/g) || []).join(' ')
    return (function (index, css) {
        return ((new RegExp(ptn, 'g')).exec(css) || []).join(' ');
    });
}

function toggleRadio(_this) {
    var $this = $(_this);
    $this.parent().find('input[type="radio"]').prop('checked', true);
    $this.prop('checked', true);
}<|endoftext|>


<commit_before>$("#button01").click(function() {

    function get_name(string) {
        var s1 = ["小隊長", "偵查佐", "副所長"];
        var s2 = ["所長", "警員", "巡佐", "隊長"];
        var s3 = ["等"];
        if (string.includes(s3[0])) {
            string = string.substring(0, string.search(s3[0]));
        }
        for (var i in s1) {
            if (string.includes(s1[i])) {
                return string.substring(3);
            }
        }
        for (var i in s2) {
            if (string.includes(s2[i])) {
                return string.substring(2);
            }
        }
        return string;
    }

    var mydata = [];
    var lines = $("#textarea01").val().split("\n");
    if (lines[lines.length-1] === "") {
        lines.pop();
    }
    for (var i in lines) {
        var element = {};
        var index_ = 0;
        var s = lines[i];
        element['id'] = parseInt(i) + 1;
        index_ = 4
        element['日期'] = s.substring(0, index_);
        s = s.substring(index_);
        index_ = s.search('所') + 1;
        if (index_ === 0) index_ = s.search('隊') + 1;
        element['單位'] = s.substring(0, index_);
        s = s.substring(index_);
        index_ = s.search('，');
        element['人員'] = s.substring(0, index_).split('、');
        s = s.substring(index_);
        index_ = s.search('查獲') + 2;
        s = s.substring(index_);
        index_ = s.search('。');
        element['案類'] = s.substring(0, index_);
        element['備註'] = s.substring(index_ + 1);

        mydata.push(element);
    }

    var people_counter = 0;
    var people_list = {};
    for (var d in mydata) {
        for (var p in mydata[d]['人員']) {
            var element = mydata[d]['人員'][p];
            element = get_name(element);
            if (element in people_list) {
                people_list[element]['times']++;
            } else {
                people_counter++;
                people_list[element] = {
                    'order' : people_counter,
                    'times' : 1,
                    'name' : element,
                };
            }
        }
    }

    for (var d in mydata) {
        mydata[d]['times'] = 0;
        mydata[d]['受獎人員排序'] = 99;
        var q;
        for (var p in mydata[d]['人員']) {
            q = mydata[d]['人員'][p];
            q = get_name(q);
            if (people_list[q]['times'] > mydata[d]['times'] || (people_list[q]['times'] === mydata[d]['times'] && people_list[q]['order'] < mydata[d]['受獎人員排序'])) {
                mydata[d]['times'] = people_list[q]['times'];
                mydata[d]['受獎人員排序'] = people_list[q]['order'];
                mydata[d]['受獎人員'] = q;
            }
        }
    }

    for (var d in mydata) {
        var q;
        q = mydata[d]['受獎人員'];
        people_list[q]['win'] = true;
    }
    console.log(mydata);

    console.log(JSON.stringify(mydata));

    for (var c in mydata) {
        $("#table01").append("
");
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['id']);
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['日期']);
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['單位']);
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['人員'].join('、'));
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['案類']);
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['受獎人員']);
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['備註']);
    }

    for (var e in people_list) {
        $("#result01").append(people_list[e]['name'] + " : " + people_list[e]['times']);
        if ('win' in people_list[e]) {
            $("#result01").append("👈
");
        } else {
            $("#result01").append("
");
        }
    }
});<commit_msg>add comments<commit_after>$("#button01").click(function() {
    /*
     * 讀取資料
     */
    var mydata = [];
    var lines = $("#textarea01").val().split("\n");
    function load_data(lines) {
        if (lines[lines.length-1] === "") {
            lines.pop();
        }
        for (var i in lines) {
            var element = {};
            var index_ = 0;
            var s = lines[i];
            element['id'] = parseInt(i) + 1;
            index_ = 4;
            element['日期'] = s.substring(0, index_);
            s = s.substring(index_);
            index_ = s.search('所') + 1;
            if (index_ === 0) index_ = s.search('隊') + 1;
            element['單位'] = s.substring(0, index_);
            s = s.substring(index_);
            index_ = s.search('，');
            element['人員'] = s.substring(0, index_).split('、');
            s = s.substring(index_);
            index_ = s.search('查獲') + 2;
            s = s.substring(index_);
            index_ = s.search('。');
            element['案類'] = s.substring(0, index_);
            element['備註'] = s.substring(index_ + 1);

            mydata.push(element);
        }
    }
    for (var i in lines) {
        var element = {};
        var index_ = 0;
        var s = lines[i];
        element['id'] = parseInt(i) + 1;
        index_ = 4;
        element['日期'] = s.substring(0, index_);
        s = s.substring(index_);
        index_ = s.search('所') + 1;
        if (index_ === 0) index_ = s.search('隊') + 1;
        element['單位'] = s.substring(0, index_);
        s = s.substring(index_);
        index_ = s.search('，');
        element['人員'] = s.substring(0, index_).split('、');
        s = s.substring(index_);
        index_ = s.search('查獲') + 2;
        s = s.substring(index_);
        index_ = s.search('。');
        element['案類'] = s.substring(0, index_);
        element['備註'] = s.substring(index_ + 1);

        mydata.push(element);
    }
    /*
     * 計算出現次數
     */
    var people_counter = 0;
    var people_list = {};
    for (var d in mydata) {
        for (var p in mydata[d]['人員']) {
            var element = mydata[d]['人員'][p];
            element = get_name(element);
            if (element in people_list) {
                people_list[element]['times']++;
            } else {
                people_counter++;
                people_list[element] = {
                    'order' : people_counter,
                    'times' : 1,
                    'name' : element,
                };
            }
        }
    }
    /*
     * 選出受獎人員
     */
    for (var d in mydata) {
        mydata[d]['times'] = 0;
        mydata[d]['受獎人員排序'] = 99;
        var q;
        for (var p in mydata[d]['人員']) {
            q = mydata[d]['人員'][p];
            q = get_name(q);
            if (people_list[q]['times'] > mydata[d]['times'] || (people_list[q]['times'] === mydata[d]['times'] && people_list[q]['order'] < mydata[d]['受獎人員排序'])) {
                mydata[d]['times'] = people_list[q]['times'];
                mydata[d]['受獎人員排序'] = people_list[q]['order'];
                mydata[d]['受獎人員'] = q;
            }
        }
    }
    for (var d in mydata) {
        var q;
        q = mydata[d]['受獎人員'];
        people_list[q]['win'] = true;
    }
    //console.log(mydata);
    //console.log(JSON.stringify(mydata));
    /*
     * 輸出
     */
    for (var c in mydata) {
        $("#table01").append("
");
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['id']);
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['日期']);
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['單位']);
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['人員'].join('、'));
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['案類']);
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['受獎人員']);
        $("#table01 tr:last-child").append("");
        $("#table01 tr:last-child td:last-child").append(mydata[c]['備註']);
    }
    for (var e in people_list) {
        $("#result01").append(people_list[e]['name'] + " : " + people_list[e]['times']);
        if ('win' in people_list[e]) {
            $("#result01").append("👈
");
        } else {
            $("#result01").append("
");
        }
    }
});
/*
 * 取出姓名
 */
function get_name(string) {
    var s1 = ["小隊長", "偵查佐", "副所長"];
    var s2 = ["所長", "警員", "巡佐", "隊長"];
    var s3 = ["等"];
    if (string.includes(s3[0])) {
        string = string.substring(0, string.search(s3[0]));
    }
    for (var i in s1) {
        if (string.includes(s1[i])) {
            return string.substring(3);
        }
    }
    for (var i in s2) {
        if (string.includes(s2[i])) {
            return string.substring(2);
        }
    }
    return string;
}<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////--calculates the delivery rate of shop --////////////////////////////////////////////////

var globalDel;

function finalCost(costofItems) {
    var x;
    var y;
    var c;
    //--geting the user location details---------------------------------------------------------------------------------------//

    actvServ().then(
        function (p) {
            console.log(p)
            var d = p.deliveryRate
            console.log(d)
            var p = p.lonlat
            console.log(p)
            var str = p;
            x = str.split(",")[0];
            console.log("x=" + x)
            y = str.split(",")[1];
            console.log("y=" + y);
            getLoc().then(function showPosition(e) {

                //--geting the shop delivery Rates---------------------------------------------------------------------------------------//
                console.log("calculating rates")
                //var distance =getDistanceFromLatLonInKm(from-lat,from-long,to-lat,from-long);
                getDistanceFromLatLonInKm(e.coords.latitude, e.coords.longitude, x, y).then(function (distance) {
                    console.log("rates loaded")
                    $("#ConfirmO").removeAttr("disabled")
                    var dist = distance
                    try{

                        deliveryRadius=JSON.parse(deliveryRadius)
                        if(!deliveryRadius.min||!deliveryRadius.max){

                        var deliveryRadius={}
                        deliveryRadius.max=10;
                        deliveryRadius.min=0.5;

                    }
                    }catch(e){
                        var deliveryRadius={}
                        deliveryRadius.max=10;
                        deliveryRadius.min=0.5;

                    }

                    console.log(dist)
                    if (dist > deliveryRadius.max) {
                        M.toast({
                            html: 'Ooops! You are out of radius'
                        })
                        $("#modalconfirm").modal("close");
                        clearCart();
                    } else if (dist < deliveryRadius.min) {
                        //--rates
                        var rates = Math.ceil(d * distance);

                        globalDel = rates;

                        //console.log(y);
                        //add delivery rate to totals
                        var divObj = document.getElementById("totals");
                        var totalCost = parseInt(divObj.innerHTML) + 0

                        if (totalCost <= 199) {
                            swal("Sorry", "Deliveries available for orders above 200 ", "error");
                            return;
                        }
                        //else{Materialize.toast('your order is more than 500KSH ', 1000);}

                        //localStorage.setItem('bits-merchant'+parseInt(getBitsWinOpt('s'))+'-Total cost',totalCost);
                        $(".confirmText").html('Total: ' + totalCost + ' /=')
                        $("#inStorePickup").html('In store pickup')
                        $(".del").html(0 + ' /=')
                    } else {
                        //--rates
                        var rates = Math.ceil(d * distance);

                        globalDel = rates;

                        //console.log(y);
                        //add delivery rate to totals
                        var divObj = document.getElementById("totals");
                        var totalCost = parseInt(divObj.innerHTML) + rates

                        if (totalCost <= 199) {
                            swal("Sorry", "Deliveries available for orders above 200 ", "error");
                            return;
                        }
                        //else{Materialize.toast('your order is more than 500KSH ', 1000);}

                        //localStorage.setItem('bits-merchant'+parseInt(getBitsWinOpt('s'))+'-Total cost',totalCost);
                        $(".confirmText").html('Total: ' + totalCost + ' /=')
                        $(".totals2").html(parseInt(divObj.innerHTML) + ' /=')
                        $(".del").html(rates + ' /=')
                    }
                });
            })
        })
}
<commit_msg>commented out sweet alert<commit_after>///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////--calculates the delivery rate of shop --////////////////////////////////////////////////

var globalDel;

function finalCost(costofItems) {
    var x;
    var y;
    var c;
    //--geting the user location details---------------------------------------------------------------------------------------//

    actvServ().then(
        function (p) {
            console.log(p)
            var d = p.deliveryRate
            console.log(d)
            var p = p.lonlat
            console.log(p)
            var str = p;
            x = str.split(",")[0];
            console.log("x=" + x)
            y = str.split(",")[1];
            console.log("y=" + y);
            getLoc().then(function showPosition(e) {

                //--geting the shop delivery Rates---------------------------------------------------------------------------------------//
                console.log("calculating rates")
                //var distance =getDistanceFromLatLonInKm(from-lat,from-long,to-lat,from-long);
                getDistanceFromLatLonInKm(e.coords.latitude, e.coords.longitude, x, y).then(function (distance) {
                    console.log("rates loaded")
                    $("#ConfirmO").removeAttr("disabled")
                    var dist = distance
                    try{

                        deliveryRadius=JSON.parse(deliveryRadius)
                        if(!deliveryRadius.min||!deliveryRadius.max){

                        var deliveryRadius={}
                        deliveryRadius.max=10;
                        deliveryRadius.min=0.5;

                    }
                    }catch(e){
                        var deliveryRadius={}
                        deliveryRadius.max=10;
                        deliveryRadius.min=0.5;

                    }

                    console.log(dist)
                    if (dist > deliveryRadius.max) {
                        M.toast({
                            html: 'Ooops! You are out of radius'
                        })
                        $("#modalconfirm").modal("close");
                        clearCart();
                    } else if (dist < deliveryRadius.min) {
                        //--rates
                        var rates = Math.ceil(d * distance);

                        globalDel = rates;

                        //console.log(y);
                        //add delivery rate to totals
                        var divObj = document.getElementById("totals");
                        var totalCost = parseInt(divObj.innerHTML) + 0

                        //else{Materialize.toast('your order is more than 500KSH ', 1000);}

                        //localStorage.setItem('bits-merchant'+parseInt(getBitsWinOpt('s'))+'-Total cost',totalCost);
                        $(".confirmText").html('Total: ' + totalCost + ' /=')
                        $("#inStorePickup").html('In store pickup')
                        $(".del").html(0 + ' /=')
                    } else {
                        //--rates
                        var rates = Math.ceil(d * distance);

                        globalDel = rates;

                        //console.log(y);
                        //add delivery rate to totals
                        var divObj = document.getElementById("totals");
                        var totalCost = parseInt(divObj.innerHTML) + rates

                        //else{Materialize.toast('your order is more than 500KSH ', 1000);}

                        //localStorage.setItem('bits-merchant'+parseInt(getBitsWinOpt('s'))+'-Total cost',totalCost);
                        $(".confirmText").html('Total: ' + totalCost + ' /=')
                        $(".totals2").html(parseInt(divObj.innerHTML) + ' /=')
                        $(".del").html(rates + ' /=')
                    }
                });
            })
        })
}
<|endoftext|>


<commit_before>
function Dungeon(scene, player, map) {
	var self = this;
	this.width = map.map[0].length;
	this.depth = map.map.length;
	this.mesh = undefined;
	this.monsters = [];
	this.objects = [];
	var dummy_material = new THREE.MeshBasicMaterial({color: 0xff00ff});

	map.gridSize *= UNIT;

	var materials = {};
	for (var tex in map.blocks) {
		if (!map.blocks.hasOwnProperty(tex)) continue;
		var floor_mat = map.blocks[tex].floor ? cache.getMaterial(map.blocks[tex].floor) : dummy_material;
		var wall_mat = map.blocks[tex].wall ? cache.getMaterial(map.blocks[tex].wall) : dummy_material;
		var ceiling_mat = map.blocks[tex].ceiling ? cache.getMaterial(map.blocks[tex].ceiling) : dummy_material;
		materials[tex] = [
			wall_mat, // right
			wall_mat, // left
			ceiling_mat, // top
			floor_mat, // bottom
			wall_mat, // back
			wall_mat  // front
		];
	}

	function getCell(x, z) {
		if (x < 0 || x >= map.map[0].length) return "#";
		else if (z < 0 || z >= map.map.length) return "#";
		return map.map[z][x];
	}

	function getObjectHandler(x, y, z, def) {
		return function(geom) {
			if (!def) def = {};
			var obj;
			if (def.collision) {
				var material = Physijs.createMaterial(
					geom.materials[0], 0.7, 0.2); // friction, restition
				if (def.collision == "plane")
					obj = new Physijs.PlaneMesh(geom, material, def.mass);
				else if (def.collision == "box")
					obj = new Physijs.BoxMesh(geom, material, def.mass);
				else if (def.collision == "sphere")
					obj = new Physijs.SphereMesh(geom, material, def.mass);
				else if (def.collision == "cylinder")
					obj = new Physijs.CylinderMesh(geom, material, def.mass);
				else if (def.collision == "cone")
					obj = new Physijs.ConeMesh(geom, material, def.mass);
				else if (def.collision == "convex")
					obj = new Physijs.ConvexMesh(geom, material, def.mass);
				else throw "Unsupported collision mesh type " + def.collision;
				self.objects.push(obj);
			} else {
				obj = new THREE.Mesh(geom, def.faceMaterial ? new THREE.MeshFaceMaterial() : geom.materials[0]);
			}
			// Auto-height
			if (y === null) {
				if (geom.boundingBox)
					y = 2 * (geom.boundingBox.max.y - geom.boundingBox.min.y) + 0.001;
				else if (geom.boundingSphere)
					y = geom.boundingSphere.radius + 0.001;
				else
					y = 0;
			}
			obj.position.set(x, y, z);
			if (!def.noShadows) {
				obj.castShadow = true;
				obj.receiveShadow = true;
			}
			scene.add(obj);
		};
	}

	var cell, cell2, px, nx, pz, nz, py;
	var ambientLight = new THREE.AmbientLight(0xaaaaaa);
	scene.add(ambientLight);

	player.light = new THREE.PointLight(0x88bbff, 1, map.gridSize * 2);
	scene.add(player.light);
	player.shadow = new THREE.SpotLight(player.light.color, player.light.intensity, player.light.distance);
	player.shadow.angle = Math.PI / 4;
	player.shadow.onlyShadow = true;
	player.shadow.castShadow = true;
	player.shadow.shadowCameraNear = 0.1 * UNIT;
	player.shadow.shadowCameraFar = 10 * UNIT;
	player.shadow.shadowCameraFov = 60;
	player.shadow.shadowBias = -0.0002;
	player.shadow.shadowDarkness = 0.3;
	player.shadow.shadowMapWidth = 1024;
	player.shadow.shadowMapHeight = 1024;
	player.shadow.shadowCameraVisible = false;
	scene.add(player.shadow);

	// TODO: Set player rotation
	player.position.set(map.start[0] * map.gridSize, map.roomHeight, map.start[1] * map.gridSize);

	var geometry = new THREE.Geometry(), light, light2, light_body, obj;
	var sphere = new THREE.SphereGeometry(0.05 * UNIT, 16, 8);

	for (var z = 0; z < this.depth; z++) {
		for (var x = 0; x < this.width; x++) {
			px = nx = pz = nz = py = 0;
			cell = getCell(x, z);
			// TODO: Remove hard coded "#", determine wall from block definitions
			if (cell == "#") {
				cell2 = getCell(x + 1, z);
				px = cell2 != "#" ? 1 : 0;
				cell2 = getCell(x - 1, z);
				nx = cell2 != "#" ? 1 : 0;
				cell2 = getCell(x, z + 1);
				pz = cell2 != "#" ? 1 : 0;
				cell2 = getCell(x, z - 1);
				nz = cell2 != "#" ? 1 : 0;
			} else {
				py = 1;
			}
			var sides = { px: px, nx: nx, py: py, ny: true, pz: pz, nz: nz };
			var cube = cache.getGeometry(cell + "-" + JSON.stringify(sides), function() {
				return new BlockGeometry(map.gridSize, map.roomHeight, map.gridSize, 1, 1, 1,
					materials[cell], sides);
			});
			this.mesh = new THREE.Mesh(cube);
			this.mesh.position.x = x * map.gridSize;
			this.mesh.position.y = map.roomHeight;
			this.mesh.position.z = z * map.gridSize;
			THREE.GeometryUtils.merge(geometry, this.mesh);
			// Collision body for walls
			if (cell == "#") {
				var wallbody = new Physijs.BoxMesh(cube, dummy_material, 0);
				wallbody.position.copy(this.mesh.position);
				wallbody.visible = false;
				scene.add(wallbody);
			}
			// Light
			if (cell == "*") {
				// Actual light
				light = new THREE.PointLight(0xffffaa, 1, 2 * map.gridSize);
				light.position.set(this.mesh.position.x, this.mesh.position.y, this.mesh.position.z);
				scene.add(light);
				lightManager.addLight(light);
				// Shadow casting light
				light2 = new THREE.SpotLight(0xffffaa, light.intensity, light.distance);
				light2.position = light.position; //set(light.position.x, light.position.y, light.position.z);
				light2.target.position.set(light2.position.x, light2.position.y - 1, light2.position.z);
				light2.angle = Math.PI / 2;
				light2.castShadow = true;
				light2.onlyShadow = true;
				light2.shadowCameraNear = 0.1 * UNIT;
				light2.shadowCameraFar = 10 * UNIT;
				light2.shadowCameraFov = 100;
				light2.shadowBias = -0.0002;
				light2.shadowDarkness = 0.3;
				light2.shadowMapWidth = 256;
				light2.shadowMapHeight = 256;
				//light2.shadowCameraVisible = true;
				scene.add(light2);
				lightManager.addShadow(light2);
				// Debug body
				if (DEBUG) {
					light_body = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({ color: 0xffffaa }));
					light_body.position = light.position;
					scene.add(light_body);
				}
			// Objects
			} else if (map.objects[cell]) {
				obj = map.objects[cell];
				cache.loadModel("assets/models/" + obj.name + "/" + obj.name + ".js",
					getObjectHandler(x * map.gridSize, null, z * map.gridSize, obj));
			}
		}
	}
	geometry.computeTangents();
	this.mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
	this.mesh.castShadow = true;
	this.mesh.receiveShadow = true;
	scene.add(this.mesh);

	// Physics plane
	var ground_material = Physijs.createMaterial(dummy_material,
		0.9, // high friction
		0.0 // low restitution
	);
	ground_material.visible = false;
	var ground_plane = new Physijs.BoxMesh(
		new THREE.CubeGeometry(map.gridSize * this.width, 1, map.gridSize * this.depth),
		ground_material,
		0 // mass
	);
	ground_plane.position = new THREE.Vector3(map.gridSize * this.width * 0.5, 1, map.gridSize * this.depth * 0.5);
	scene.add(ground_plane);

	// Weapon
	cache.loadModel("assets/models/knife/knife.js", function(geometry) {
		player.rhand = new THREE.Mesh(geometry, geometry.materials[0]);
		//player.rhand.castShadow = true;
		player.rhand.receiveShadow = true;
		scene.add(player.rhand);
	});

	// Items
	//cache.loadModel("assets/models/items/health.js",
	//	getObjectHandler(player.position.x, 2, player.position.z, { faceMaterial: true, noShadows: true }));
	//cache.loadModel("assets/models/items/mana.js",
	//	getObjectHandler(player.position.x + 1, 2, player.position.z, { faceMaterial: true, noShadows: true }));

	// Monster
	cache.loadModel("assets/models/shdw3/shdw3.js", function(geometry) {
		geometry.computeMorphNormals();
		var colorMap = geometry.morphColors[ 0 ];
		for (var i = 0; i < colorMap.colors.length; ++i) {
			geometry.faces[i].color = colorMap.colors[i];
		}

		var material = new THREE.MeshPhongMaterial({
			color: 0x222222, specular: 0xffffff, shininess: 10,
			morphTargets: true, morphNormals: true, vertexColors: THREE.FaceColors,
			shading: THREE.SmoothShading, perPixel: true
		});

		var monster = new Physijs.CylinderMesh(
			new THREE.CylinderGeometry(0.4 * UNIT, 0.4 * UNIT, 2 * UNIT),
			dummy_material, 100000
		);
		monster.visible = false;
		monster.position.set(player.position.x + 4, player.position.y - 0.8, player.position.z);
		self.monsters.push(monster);

		monster.mesh = new THREE.MorphAnimMesh(geometry, material);
		monster.mesh.speed = 0.4;
		monster.mesh.duration = 2000;
		monster.mesh.time = 600 * Math.random();
		monster.mesh.castShadow = true;
		monster.mesh.receiveShadow = true;
		monster.add(monster.mesh);
		scene.add(monster);
		monster.setAngularFactor({ x: 0, y: 0, z: 0 });
	});

}
<commit_msg>Back to black dummy material.<commit_after>
function Dungeon(scene, player, map) {
	var self = this;
	this.width = map.map[0].length;
	this.depth = map.map.length;
	this.mesh = undefined;
	this.monsters = [];
	this.objects = [];
	var dummy_material = new THREE.MeshBasicMaterial({color: 0x000000});

	map.gridSize *= UNIT;

	var materials = {};
	for (var tex in map.blocks) {
		if (!map.blocks.hasOwnProperty(tex)) continue;
		var floor_mat = map.blocks[tex].floor ? cache.getMaterial(map.blocks[tex].floor) : dummy_material;
		var wall_mat = map.blocks[tex].wall ? cache.getMaterial(map.blocks[tex].wall) : dummy_material;
		var ceiling_mat = map.blocks[tex].ceiling ? cache.getMaterial(map.blocks[tex].ceiling) : dummy_material;
		materials[tex] = [
			wall_mat, // right
			wall_mat, // left
			ceiling_mat, // top
			floor_mat, // bottom
			wall_mat, // back
			wall_mat  // front
		];
	}

	function getCell(x, z) {
		if (x < 0 || x >= map.map[0].length) return "#";
		else if (z < 0 || z >= map.map.length) return "#";
		return map.map[z][x];
	}

	function getObjectHandler(x, y, z, def) {
		return function(geom) {
			if (!def) def = {};
			var obj;
			if (def.collision) {
				var material = Physijs.createMaterial(
					geom.materials[0], 0.7, 0.2); // friction, restition
				if (def.collision == "plane")
					obj = new Physijs.PlaneMesh(geom, material, def.mass);
				else if (def.collision == "box")
					obj = new Physijs.BoxMesh(geom, material, def.mass);
				else if (def.collision == "sphere")
					obj = new Physijs.SphereMesh(geom, material, def.mass);
				else if (def.collision == "cylinder")
					obj = new Physijs.CylinderMesh(geom, material, def.mass);
				else if (def.collision == "cone")
					obj = new Physijs.ConeMesh(geom, material, def.mass);
				else if (def.collision == "convex")
					obj = new Physijs.ConvexMesh(geom, material, def.mass);
				else throw "Unsupported collision mesh type " + def.collision;
				self.objects.push(obj);
			} else {
				obj = new THREE.Mesh(geom, def.faceMaterial ? new THREE.MeshFaceMaterial() : geom.materials[0]);
			}
			// Auto-height
			if (y === null) {
				if (geom.boundingBox)
					y = 2 * (geom.boundingBox.max.y - geom.boundingBox.min.y) + 0.001;
				else if (geom.boundingSphere)
					y = geom.boundingSphere.radius + 0.001;
				else
					y = 0;
			}
			obj.position.set(x, y, z);
			if (!def.noShadows) {
				obj.castShadow = true;
				obj.receiveShadow = true;
			}
			scene.add(obj);
		};
	}

	var cell, cell2, px, nx, pz, nz, py;
	var ambientLight = new THREE.AmbientLight(0xaaaaaa);
	scene.add(ambientLight);

	player.light = new THREE.PointLight(0x88bbff, 1, map.gridSize * 2);
	scene.add(player.light);
	player.shadow = new THREE.SpotLight(player.light.color, player.light.intensity, player.light.distance);
	player.shadow.angle = Math.PI / 4;
	player.shadow.onlyShadow = true;
	player.shadow.castShadow = true;
	player.shadow.shadowCameraNear = 0.1 * UNIT;
	player.shadow.shadowCameraFar = 10 * UNIT;
	player.shadow.shadowCameraFov = 60;
	player.shadow.shadowBias = -0.0002;
	player.shadow.shadowDarkness = 0.3;
	player.shadow.shadowMapWidth = 1024;
	player.shadow.shadowMapHeight = 1024;
	player.shadow.shadowCameraVisible = false;
	scene.add(player.shadow);

	// TODO: Set player rotation
	player.position.set(map.start[0] * map.gridSize, map.roomHeight, map.start[1] * map.gridSize);

	var geometry = new THREE.Geometry(), light, light2, light_body, obj;
	var sphere = new THREE.SphereGeometry(0.05 * UNIT, 16, 8);

	for (var z = 0; z < this.depth; z++) {
		for (var x = 0; x < this.width; x++) {
			px = nx = pz = nz = py = 0;
			cell = getCell(x, z);
			// TODO: Remove hard coded "#", determine wall from block definitions
			if (cell == "#") {
				cell2 = getCell(x + 1, z);
				px = cell2 != "#" ? 1 : 0;
				cell2 = getCell(x - 1, z);
				nx = cell2 != "#" ? 1 : 0;
				cell2 = getCell(x, z + 1);
				pz = cell2 != "#" ? 1 : 0;
				cell2 = getCell(x, z - 1);
				nz = cell2 != "#" ? 1 : 0;
			} else {
				py = 1;
			}
			var sides = { px: px, nx: nx, py: py, ny: true, pz: pz, nz: nz };
			var cube = cache.getGeometry(cell + "-" + JSON.stringify(sides), function() {
				return new BlockGeometry(map.gridSize, map.roomHeight, map.gridSize, 1, 1, 1,
					materials[cell], sides);
			});
			this.mesh = new THREE.Mesh(cube);
			this.mesh.position.x = x * map.gridSize;
			this.mesh.position.y = map.roomHeight;
			this.mesh.position.z = z * map.gridSize;
			THREE.GeometryUtils.merge(geometry, this.mesh);
			// Collision body for walls
			if (cell == "#") {
				var wallbody = new Physijs.BoxMesh(cube, dummy_material, 0);
				wallbody.position.copy(this.mesh.position);
				wallbody.visible = false;
				scene.add(wallbody);
			}
			// Light
			if (cell == "*") {
				// Actual light
				light = new THREE.PointLight(0xffffaa, 1, 2 * map.gridSize);
				light.position.set(this.mesh.position.x, this.mesh.position.y, this.mesh.position.z);
				scene.add(light);
				lightManager.addLight(light);
				// Shadow casting light
				light2 = new THREE.SpotLight(0xffffaa, light.intensity, light.distance);
				light2.position = light.position; //set(light.position.x, light.position.y, light.position.z);
				light2.target.position.set(light2.position.x, light2.position.y - 1, light2.position.z);
				light2.angle = Math.PI / 2;
				light2.castShadow = true;
				light2.onlyShadow = true;
				light2.shadowCameraNear = 0.1 * UNIT;
				light2.shadowCameraFar = 10 * UNIT;
				light2.shadowCameraFov = 100;
				light2.shadowBias = -0.0002;
				light2.shadowDarkness = 0.3;
				light2.shadowMapWidth = 256;
				light2.shadowMapHeight = 256;
				//light2.shadowCameraVisible = true;
				scene.add(light2);
				lightManager.addShadow(light2);
				// Debug body
				if (DEBUG) {
					light_body = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({ color: 0xffffaa }));
					light_body.position = light.position;
					scene.add(light_body);
				}
			// Objects
			} else if (map.objects[cell]) {
				obj = map.objects[cell];
				cache.loadModel("assets/models/" + obj.name + "/" + obj.name + ".js",
					getObjectHandler(x * map.gridSize, null, z * map.gridSize, obj));
			}
		}
	}
	geometry.computeTangents();
	this.mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
	this.mesh.castShadow = true;
	this.mesh.receiveShadow = true;
	scene.add(this.mesh);

	// Physics plane
	var ground_material = Physijs.createMaterial(dummy_material,
		0.9, // high friction
		0.0 // low restitution
	);
	ground_material.visible = false;
	var ground_plane = new Physijs.BoxMesh(
		new THREE.CubeGeometry(map.gridSize * this.width, 1, map.gridSize * this.depth),
		ground_material,
		0 // mass
	);
	ground_plane.position = new THREE.Vector3(map.gridSize * this.width * 0.5, 1, map.gridSize * this.depth * 0.5);
	scene.add(ground_plane);

	// Weapon
	cache.loadModel("assets/models/knife/knife.js", function(geometry) {
		player.rhand = new THREE.Mesh(geometry, geometry.materials[0]);
		//player.rhand.castShadow = true;
		player.rhand.receiveShadow = true;
		scene.add(player.rhand);
	});

	// Items
	//cache.loadModel("assets/models/items/health.js",
	//	getObjectHandler(player.position.x, 2, player.position.z, { faceMaterial: true, noShadows: true }));
	//cache.loadModel("assets/models/items/mana.js",
	//	getObjectHandler(player.position.x + 1, 2, player.position.z, { faceMaterial: true, noShadows: true }));

	// Monster
	cache.loadModel("assets/models/shdw3/shdw3.js", function(geometry) {
		geometry.computeMorphNormals();
		var colorMap = geometry.morphColors[ 0 ];
		for (var i = 0; i < colorMap.colors.length; ++i) {
			geometry.faces[i].color = colorMap.colors[i];
		}

		var material = new THREE.MeshPhongMaterial({
			color: 0x222222, specular: 0xffffff, shininess: 10,
			morphTargets: true, morphNormals: true, vertexColors: THREE.FaceColors,
			shading: THREE.SmoothShading, perPixel: true
		});

		var monster = new Physijs.CylinderMesh(
			new THREE.CylinderGeometry(0.4 * UNIT, 0.4 * UNIT, 2 * UNIT),
			dummy_material, 100000
		);
		monster.visible = false;
		monster.position.set(player.position.x + 4, player.position.y - 0.8, player.position.z);
		self.monsters.push(monster);

		monster.mesh = new THREE.MorphAnimMesh(geometry, material);
		monster.mesh.speed = 0.4;
		monster.mesh.duration = 2000;
		monster.mesh.time = 600 * Math.random();
		monster.mesh.castShadow = true;
		monster.mesh.receiveShadow = true;
		monster.add(monster.mesh);
		scene.add(monster);
		monster.setAngularFactor({ x: 0, y: 0, z: 0 });
	});

}
<|endoftext|>


<commit_before>'use strict';

let AbstractAccessor = require('./AbstractAccessor');

/**
 * Portal accessor
 */
class Portal extends AbstractAccessor {
  /**
   * Get portal
   *
   * @return {Promise} Promise for chaining
   */
  get() {
    let GetPortal = require('../Command/Portal/GetPortal');

    return this.client.invokeCommand(new GetPortal);
  }
}

module.exports = Portal;
<commit_msg>GitHub #14 - Import commands<commit_after>'use strict';

let AbstractAccessor = require('./AbstractAccessor');
let GetPortal        = require('../Command/Portal/GetPortal');

/**
 * Portal accessor
 */
class Portal extends AbstractAccessor {
  /**
   * Get portal
   *
   * @return {Promise} Promise for chaining
   */
  get() {
    return this.client.invokeCommand(new GetPortal);
  }
}

module.exports = Portal;
<|endoftext|>


<commit_before>var i,
    COLOR = [0, 0, 0],
    targetX = 0, targetY = 0,
    BACKGROUND_COLOR = [250, 250, 250],
    SCREEN_WIDTH = window.innerWidth,
    SCREEN_HEIGHT = window.innerHeight,
    strokeManager, container, foregroundColorSelector, backgroundColorSelector,
    menu, about, canvas, flattenCanvas, context,
    initialX, initialY,
    mouseX = 0, mouseY = 0,
    isForegroundColorSelectorVisible = false,
    isBackgroundColorSelectorVisible = false,
    isAboutVisible = false;
isForegroundColorSelectorMouseDown = false,
isBackgroundColorSelectorMouseDown = false,
isMenuMouseOver = false,
isMouseDown = false,
controlKeyIsDown = false,
xMirrorIsDown = false, // XXX: stash these to controls variable
yMirrorIsDown = false,
xyMirrorIsDown = false,
aKeyIsDown = false, // XXX: stash these to a keyboard variable
sKeyIsDown = false,
dKeyIsDown = false;
init();

function init() {
    var hash, palette;
    document.body.style.backgroundColor = "rgb(" + BACKGROUND_COLOR[0] + ", " + BACKGROUND_COLOR[1] + ", " + BACKGROUND_COLOR[2] + ")";
    container = document.createElement("div");
    document.body.appendChild(container);
    canvas = document.createElement("canvas");
    canvas.width = SCREEN_WIDTH;
    canvas.height = SCREEN_HEIGHT;
    canvas.style.cursor = "crosshair";
    strokeManager = new StrokeManager(canvas);
    container.appendChild(canvas);
    flattenCanvas = document.createElement("canvas");
    flattenCanvas.width = SCREEN_WIDTH;
    flattenCanvas.height = SCREEN_HEIGHT;
    palette = new Palette();
    foregroundColorSelector = new ColorSelector(palette);
    foregroundColorSelector.container.onmousedown = onForegroundColorSelectorMouseDown;
    foregroundColorSelector.container.onmouseup = onForegroundColorSelectorMouseUp;
    foregroundColorSelector.container.onmousemove = onForegroundColorSelectorMouseMove;
    container.appendChild(foregroundColorSelector.container);
    backgroundColorSelector = new ColorSelector(palette);
    backgroundColorSelector.container.onmousedown = onBackgroundColorSelectorMouseDown;
    backgroundColorSelector.container.onmouseup = onBackgroundColorSelectorMouseUp;
    backgroundColorSelector.container.onmousemove = onBackgroundColorSelectorMouseMove;
    container.appendChild(backgroundColorSelector.container);
    menu = new Menu();
    menu.foregroundColor.addEventListener("click", onMenuForegroundColor, false);
    menu.backgroundColor.addEventListener("click", onMenuBackgroundColor, false);
    menu.selector.onchange = onMenuSelectorChange;
    menu.xMirror.addEventListener("click", onMenuXMirror, false);
    menu.yMirror.addEventListener("click", onMenuYMirror, false);
    menu.xyMirror.addEventListener("click", onMenuXYMirror, false);
    menu.save.addEventListener("click", onMenuSave, false);
    menu.clear.addEventListener("click", onMenuClear, false);
    menu.about.addEventListener("click", onMenuAbout, false);
    menu.container.onmouseover = onMenuMouseOver;
    menu.container.onmouseout = onMenuMouseOut;
    container.appendChild(menu.container);
    context = canvas.getContext("2d");

    manager_set = false;
    if (window.location.hash) {
        hash = window.location.hash.substr(1, window.location.hash.length);
        for (i = 0; i < STYLES.length; i++) {
            if (hash == STYLES[i]) {
                strokeManager.setStyle(STYLES[i], context);
                menu.selector.selectedIndex = i;
                manager_set = true;
                break
            }
        }
    }
    if (!manager_set) {
        strokeManager.setStyle(STYLES[0], context);
    }

    about = new About();
    container.appendChild(about.container);
    window.onresize = onWindowResize;
    window.onkeydown = onDocumentKeyDown;
    window.onkeyup = onDocumentKeyUp;
    document.onmousedown = onDocumentMouseDown;
    document.onmouseout = onCanvasMouseUp;
    canvas.onmousedown = onCanvasMouseDown;
    canvas.onmouseup = onCanvasMouseUp;
    canvas.onmousemove = onCanvasMouseMove;
    canvas.ontouchstart = onCanvasTouchStart;
    canvas.ontouchend = onCanvasTouchEnd;
    canvas.ontouchmove = onCanvasTouchMove;
    onWindowResize(null)
}
function onWindowResize(a) {
    SCREEN_WIDTH = window.innerWidth;
    SCREEN_HEIGHT = window.innerHeight;
    menu.container.style.left = ((SCREEN_WIDTH - menu.container.offsetWidth) / 2) + "px";
    about.container.style.left = ((SCREEN_WIDTH - about.container.offsetWidth) / 2) + "px";
    about.container.style.top = ((SCREEN_HEIGHT - about.container.offsetHeight) / 2) + "px"
}
function onDocumentMouseDown(a) {
    return isMenuMouseOver
}
function onDocumentKeyDown(a) {
    switch (a.keyCode) {
    case 70: // f
        targetX = mouseX;
        targetY = mouseY;

        console.log('set persp target to x: ' + targetX + ' , y: ' + targetY);
        break;
    case 65: // a
        if(!aKeyIsDown) {
            initialY = mouseY;
        }

        aKeyIsDown = true;
        break;
    case 83: // s
        if(!sKeyIsDown) {
            initialX = mouseX;
        }

        sKeyIsDown = true;
        break;
    case 68: // d
        if(!dKeyIsDown) {
            initialX = mouseX;
            initialY = mouseY;
        }

        dKeyIsDown = true;
        break;
    case 16: // shift
        if(controlKeyIsDown) {
            controlKeyIsDown = false;
            foregroundColorSelector.container.style.visibility = "hidden";
        }
        else {
            controlKeyIsDown = true;
            foregroundColorSelector.container.style.left = mouseX - 125 + "px";
            foregroundColorSelector.container.style.top = mouseY - 125 + "px";
            foregroundColorSelector.container.style.visibility = "visible";
        }
        break
    }
}
function onDocumentKeyUp(a) {
    switch (a.keyCode) {
    case 65: // a
        aKeyIsDown = false;
        break;
    case 83: // s
        sKeyIsDown = false;
        break;
    case 68: // d
        dKeyIsDown = false;
        break;
    }
}
function onForegroundColorSelectorMouseDown(a) {
    isForegroundColorSelectorMouseDown = true
}
function onForegroundColorSelectorMouseUp(a) {
    isForegroundColorSelectorMouseDown = false;
    foregroundColorSelector.update(a);
    COLOR = foregroundColorSelector.getColor();
    menu.setForegroundColor(COLOR)
}
function onForegroundColorSelectorMouseMove(a) {
    if (!isForegroundColorSelectorMouseDown) {
        return
    }
    foregroundColorSelector.update(a);
    COLOR = foregroundColorSelector.getColor();
    menu.setForegroundColor(COLOR)
}
function onBackgroundColorSelectorMouseDown(a) {
    isBackgroundColorSelectorMouseDown = true
}
function onBackgroundColorSelectorMouseUp(a) {
    isBackgroundColorSelectorMouseDown = false;
    backgroundColorSelector.update(a);
    BACKGROUND_COLOR = backgroundColorSelector.getColor();
    menu.setBackgroundColor(BACKGROUND_COLOR);
    document.body.style.backgroundColor = "rgb(" + BACKGROUND_COLOR[0] + ", " + BACKGROUND_COLOR[1] + ", " + BACKGROUND_COLOR[2] + ")"
}
function onBackgroundColorSelectorMouseMove(a) {
    if (!isBackgroundColorSelectorMouseDown) {
        return
    }
    backgroundColorSelector.update(a);
    BACKGROUND_COLOR = backgroundColorSelector.getColor();
    menu.setBackgroundColor(BACKGROUND_COLOR);
    document.body.style.backgroundColor = "rgb(" + BACKGROUND_COLOR[0] + ", " + BACKGROUND_COLOR[1] + ", " + BACKGROUND_COLOR[2] + ")"
}
function onMenuForegroundColor(a) {
    cleanPopUps();
    foregroundColorSelector.show();
    foregroundColorSelector.container.style.left = ((SCREEN_WIDTH - foregroundColorSelector.container.offsetWidth) / 2) + "px";
    foregroundColorSelector.container.style.top = ((SCREEN_HEIGHT - foregroundColorSelector.container.offsetHeight) / 2) + "px";
    isForegroundColorSelectorVisible = true
}
function onMenuBackgroundColor(a) {
    cleanPopUps();
    backgroundColorSelector.show();
    backgroundColorSelector.container.style.left = ((SCREEN_WIDTH - backgroundColorSelector.container.offsetWidth) / 2) + "px";
    backgroundColorSelector.container.style.top = ((SCREEN_HEIGHT - backgroundColorSelector.container.offsetHeight) / 2) + "px";
    isBackgroundColorSelectorVisible = true
}
function onMenuSelectorChange(e) {
    if (STYLES[menu.selector.selectedIndex] == "") {
        return
    }
    style.destroy();
    style = eval("new " + STYLES[menu.selector.selectedIndex] + "(context)");
    window.location.hash = STYLES[menu.selector.selectedIndex]
}
function onMenuMouseOver(a) {
    isMenuMouseOver = true
}
function onMenuMouseOut(a) {
    isMenuMouseOver = false
}

function setToggle(e, state) {
    // XXX: could be nicer (set via css class or so)
    if(state) {
        e.style.color = '#00DD00';
    }
    else {
        e.style.color = '#000000';
    }
}
function onMenuXMirror(a) {
    xMirrorIsDown = !xMirrorIsDown;

    setToggle(this, xMirrorIsDown);
}
function onMenuYMirror() {
    yMirrorIsDown = !yMirrorIsDown;

    setToggle(this, yMirrorIsDown);
}
function onMenuXYMirror() {
    xyMirrorIsDown = !xyMirrorIsDown;

    setToggle(this, xyMirrorIsDown);
}

function onMenuSave() {
    var a = flattenCanvas.getContext("2d");
    a.fillStyle = "rgb(" + BACKGROUND_COLOR[0] + ", " + BACKGROUND_COLOR[1] + ", " + BACKGROUND_COLOR[2] + ")";
    a.fillRect(0, 0, canvas.width, canvas.height);
    a.drawImage(canvas, 0, 0);
    window.open(flattenCanvas.toDataURL("image/png"), "mywindow")
}
function onMenuClear() {
    context.clearRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    strokeManager.setStyle(STYLES[menu.selector.selectedIndex], context);
}
function onMenuAbout(a) {
    cleanPopUps();
    isAboutVisible = true;
    about.show()
}
function onCanvasMouseDown(a) {
    cleanPopUps();
    isMouseDown = true;

    initialX = mouseX;
    initialY = mouseY;

    // XXX: move mirrors and keys to a state variables
    strokeManager.strokeStart(mouseX, mouseY, xMirrorIsDown, yMirrorIsDown,
        xyMirrorIsDown, aKeyIsDown, sKeyIsDown, dKeyIsDown, initialX, initialY,
        targetX, targetY);
}
function onCanvasMouseUp(a) {
    isMouseDown = false;

    // XXX: move mirrors and keys to a state variables
    strokeManager.strokeEnd(mouseX, mouseY, xMirrorIsDown, yMirrorIsDown,
        xyMirrorIsDown, aKeyIsDown, sKeyIsDown, dKeyIsDown, initialX, initialY,
        targetX, targetY);
}
function onCanvasMouseMove(a) {
    if (!a) {
        a = window.event
    }

    mouseX = a.clientX;
    mouseY = a.clientY;
    if (!isMouseDown) {
        return
    }

    // XXX: move mirrors and keys to a state variables
    strokeManager.stroke(mouseX, mouseY, xMirrorIsDown, yMirrorIsDown,
        xyMirrorIsDown, aKeyIsDown, sKeyIsDown, dKeyIsDown, initialX, initialY,
        targetX, targetY);
}
function onCanvasTouchStart(a) {
    if (a.touches.length == 1) {
        var b = a.touches[0];
        style.strokeStart(b.pageX, b.pageY);
        return false
    }
}
function onCanvasTouchEnd(a) {
    if (a.touches.length == 1) {
        var b = a.touches[0];
        style.strokeEnd(b.pageX, b.pageY);
        return false
    }
}
function onCanvasTouchMove(a) {
    if (a.touches.length == 1) {
        var b = a.touches[0];
        style.stroke(b.pageX, b.pageY);
        return false
    }
}
function cleanPopUps() {
    if (isForegroundColorSelectorVisible) {
        foregroundColorSelector.hide();
        isForegroundColorSelectorVisible = false
    }
    if (isBackgroundColorSelectorVisible) {
        backgroundColorSelector.hide();
        isBackgroundColorSelectorVisible = false
    }
    if (isAboutVisible) {
        about.hide();
        isAboutVisible = false
    }
};<commit_msg>Got rid of remaining references to style.<commit_after>var i,
    COLOR = [0, 0, 0],
    targetX = 0, targetY = 0,
    BACKGROUND_COLOR = [250, 250, 250],
    SCREEN_WIDTH = window.innerWidth,
    SCREEN_HEIGHT = window.innerHeight,
    strokeManager, container, foregroundColorSelector, backgroundColorSelector,
    menu, about, canvas, flattenCanvas, context,
    initialX, initialY,
    mouseX = 0, mouseY = 0,
    isForegroundColorSelectorVisible = false,
    isBackgroundColorSelectorVisible = false,
    isAboutVisible = false;
isForegroundColorSelectorMouseDown = false,
isBackgroundColorSelectorMouseDown = false,
isMenuMouseOver = false,
isMouseDown = false,
controlKeyIsDown = false,
xMirrorIsDown = false, // XXX: stash these to controls variable
yMirrorIsDown = false,
xyMirrorIsDown = false,
aKeyIsDown = false, // XXX: stash these to a keyboard variable
sKeyIsDown = false,
dKeyIsDown = false;
init();

function init() {
    var hash, palette;
    document.body.style.backgroundColor = "rgb(" + BACKGROUND_COLOR[0] + ", " + BACKGROUND_COLOR[1] + ", " + BACKGROUND_COLOR[2] + ")";
    container = document.createElement("div");
    document.body.appendChild(container);
    canvas = document.createElement("canvas");
    canvas.width = SCREEN_WIDTH;
    canvas.height = SCREEN_HEIGHT;
    canvas.style.cursor = "crosshair";
    strokeManager = new StrokeManager(canvas);
    container.appendChild(canvas);
    flattenCanvas = document.createElement("canvas");
    flattenCanvas.width = SCREEN_WIDTH;
    flattenCanvas.height = SCREEN_HEIGHT;
    palette = new Palette();
    foregroundColorSelector = new ColorSelector(palette);
    foregroundColorSelector.container.onmousedown = onForegroundColorSelectorMouseDown;
    foregroundColorSelector.container.onmouseup = onForegroundColorSelectorMouseUp;
    foregroundColorSelector.container.onmousemove = onForegroundColorSelectorMouseMove;
    container.appendChild(foregroundColorSelector.container);
    backgroundColorSelector = new ColorSelector(palette);
    backgroundColorSelector.container.onmousedown = onBackgroundColorSelectorMouseDown;
    backgroundColorSelector.container.onmouseup = onBackgroundColorSelectorMouseUp;
    backgroundColorSelector.container.onmousemove = onBackgroundColorSelectorMouseMove;
    container.appendChild(backgroundColorSelector.container);
    menu = new Menu();
    menu.foregroundColor.addEventListener("click", onMenuForegroundColor, false);
    menu.backgroundColor.addEventListener("click", onMenuBackgroundColor, false);
    menu.selector.onchange = onMenuSelectorChange;
    menu.xMirror.addEventListener("click", onMenuXMirror, false);
    menu.yMirror.addEventListener("click", onMenuYMirror, false);
    menu.xyMirror.addEventListener("click", onMenuXYMirror, false);
    menu.save.addEventListener("click", onMenuSave, false);
    menu.clear.addEventListener("click", onMenuClear, false);
    menu.about.addEventListener("click", onMenuAbout, false);
    menu.container.onmouseover = onMenuMouseOver;
    menu.container.onmouseout = onMenuMouseOut;
    container.appendChild(menu.container);
    context = canvas.getContext("2d");

    manager_set = false;
    if (window.location.hash) {
        hash = window.location.hash.substr(1, window.location.hash.length);
        for (i = 0; i < STYLES.length; i++) {
            if (hash == STYLES[i]) {
                strokeManager.setStyle(STYLES[i], context);
                menu.selector.selectedIndex = i;
                manager_set = true;
                break
            }
        }
    }
    if (!manager_set) {
        strokeManager.setStyle(STYLES[0], context);
    }

    about = new About();
    container.appendChild(about.container);
    window.onresize = onWindowResize;
    window.onkeydown = onDocumentKeyDown;
    window.onkeyup = onDocumentKeyUp;
    document.onmousedown = onDocumentMouseDown;
    document.onmouseout = onCanvasMouseUp;
    canvas.onmousedown = onCanvasMouseDown;
    canvas.onmouseup = onCanvasMouseUp;
    canvas.onmousemove = onCanvasMouseMove;
    canvas.ontouchstart = onCanvasTouchStart;
    canvas.ontouchend = onCanvasTouchEnd;
    canvas.ontouchmove = onCanvasTouchMove;
    onWindowResize(null)
}
function onWindowResize(a) {
    SCREEN_WIDTH = window.innerWidth;
    SCREEN_HEIGHT = window.innerHeight;
    menu.container.style.left = ((SCREEN_WIDTH - menu.container.offsetWidth) / 2) + "px";
    about.container.style.left = ((SCREEN_WIDTH - about.container.offsetWidth) / 2) + "px";
    about.container.style.top = ((SCREEN_HEIGHT - about.container.offsetHeight) / 2) + "px"
}
function onDocumentMouseDown(a) {
    return isMenuMouseOver
}
function onDocumentKeyDown(a) {
    switch (a.keyCode) {
    case 70: // f
        targetX = mouseX;
        targetY = mouseY;

        console.log('set persp target to x: ' + targetX + ' , y: ' + targetY);
        break;
    case 65: // a
        if(!aKeyIsDown) {
            initialY = mouseY;
        }

        aKeyIsDown = true;
        break;
    case 83: // s
        if(!sKeyIsDown) {
            initialX = mouseX;
        }

        sKeyIsDown = true;
        break;
    case 68: // d
        if(!dKeyIsDown) {
            initialX = mouseX;
            initialY = mouseY;
        }

        dKeyIsDown = true;
        break;
    case 16: // shift
        if(controlKeyIsDown) {
            controlKeyIsDown = false;
            foregroundColorSelector.container.style.visibility = "hidden";
        }
        else {
            controlKeyIsDown = true;
            foregroundColorSelector.container.style.left = mouseX - 125 + "px";
            foregroundColorSelector.container.style.top = mouseY - 125 + "px";
            foregroundColorSelector.container.style.visibility = "visible";
        }
        break
    }
}
function onDocumentKeyUp(a) {
    switch (a.keyCode) {
    case 65: // a
        aKeyIsDown = false;
        break;
    case 83: // s
        sKeyIsDown = false;
        break;
    case 68: // d
        dKeyIsDown = false;
        break;
    }
}
function onForegroundColorSelectorMouseDown(a) {
    isForegroundColorSelectorMouseDown = true
}
function onForegroundColorSelectorMouseUp(a) {
    isForegroundColorSelectorMouseDown = false;
    foregroundColorSelector.update(a);
    COLOR = foregroundColorSelector.getColor();
    menu.setForegroundColor(COLOR)
}
function onForegroundColorSelectorMouseMove(a) {
    if (!isForegroundColorSelectorMouseDown) {
        return
    }
    foregroundColorSelector.update(a);
    COLOR = foregroundColorSelector.getColor();
    menu.setForegroundColor(COLOR)
}
function onBackgroundColorSelectorMouseDown(a) {
    isBackgroundColorSelectorMouseDown = true
}
function onBackgroundColorSelectorMouseUp(a) {
    isBackgroundColorSelectorMouseDown = false;
    backgroundColorSelector.update(a);
    BACKGROUND_COLOR = backgroundColorSelector.getColor();
    menu.setBackgroundColor(BACKGROUND_COLOR);
    document.body.style.backgroundColor = "rgb(" + BACKGROUND_COLOR[0] + ", " + BACKGROUND_COLOR[1] + ", " + BACKGROUND_COLOR[2] + ")"
}
function onBackgroundColorSelectorMouseMove(a) {
    if (!isBackgroundColorSelectorMouseDown) {
        return
    }
    backgroundColorSelector.update(a);
    BACKGROUND_COLOR = backgroundColorSelector.getColor();
    menu.setBackgroundColor(BACKGROUND_COLOR);
    document.body.style.backgroundColor = "rgb(" + BACKGROUND_COLOR[0] + ", " + BACKGROUND_COLOR[1] + ", " + BACKGROUND_COLOR[2] + ")"
}
function onMenuForegroundColor(a) {
    cleanPopUps();
    foregroundColorSelector.show();
    foregroundColorSelector.container.style.left = ((SCREEN_WIDTH - foregroundColorSelector.container.offsetWidth) / 2) + "px";
    foregroundColorSelector.container.style.top = ((SCREEN_HEIGHT - foregroundColorSelector.container.offsetHeight) / 2) + "px";
    isForegroundColorSelectorVisible = true
}
function onMenuBackgroundColor(a) {
    cleanPopUps();
    backgroundColorSelector.show();
    backgroundColorSelector.container.style.left = ((SCREEN_WIDTH - backgroundColorSelector.container.offsetWidth) / 2) + "px";
    backgroundColorSelector.container.style.top = ((SCREEN_HEIGHT - backgroundColorSelector.container.offsetHeight) / 2) + "px";
    isBackgroundColorSelectorVisible = true
}
function onMenuSelectorChange(e) {
    if (STYLES[menu.selector.selectedIndex] == "") {
        return
    }
    strokeManager.destroy(); // XXX: is this needed?
    strokeManager.setStyle(STYLES[menu.selector.selectedIndex], context);
    window.location.hash = STYLES[menu.selector.selectedIndex]
}
function onMenuMouseOver(a) {
    isMenuMouseOver = true
}
function onMenuMouseOut(a) {
    isMenuMouseOver = false
}

function setToggle(e, state) {
    // XXX: could be nicer (set via css class or so)
    if(state) {
        e.style.color = '#00DD00';
    }
    else {
        e.style.color = '#000000';
    }
}
function onMenuXMirror(a) {
    xMirrorIsDown = !xMirrorIsDown;

    setToggle(this, xMirrorIsDown);
}
function onMenuYMirror() {
    yMirrorIsDown = !yMirrorIsDown;

    setToggle(this, yMirrorIsDown);
}
function onMenuXYMirror() {
    xyMirrorIsDown = !xyMirrorIsDown;

    setToggle(this, xyMirrorIsDown);
}

function onMenuSave() {
    var a = flattenCanvas.getContext("2d");
    a.fillStyle = "rgb(" + BACKGROUND_COLOR[0] + ", " + BACKGROUND_COLOR[1] + ", " + BACKGROUND_COLOR[2] + ")";
    a.fillRect(0, 0, canvas.width, canvas.height);
    a.drawImage(canvas, 0, 0);
    window.open(flattenCanvas.toDataURL("image/png"), "mywindow")
}
function onMenuClear() {
    context.clearRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    strokeManager.setStyle(STYLES[menu.selector.selectedIndex], context);
}
function onMenuAbout(a) {
    cleanPopUps();
    isAboutVisible = true;
    about.show()
}
function onCanvasMouseDown(a) {
    cleanPopUps();
    isMouseDown = true;

    initialX = mouseX;
    initialY = mouseY;

    // XXX: move mirrors and keys to a state variables
    strokeManager.strokeStart(mouseX, mouseY, xMirrorIsDown, yMirrorIsDown,
        xyMirrorIsDown, aKeyIsDown, sKeyIsDown, dKeyIsDown, initialX, initialY,
        targetX, targetY);
}
function onCanvasMouseUp(a) {
    isMouseDown = false;

    // XXX: move mirrors and keys to a state variables
    strokeManager.strokeEnd(mouseX, mouseY, xMirrorIsDown, yMirrorIsDown,
        xyMirrorIsDown, aKeyIsDown, sKeyIsDown, dKeyIsDown, initialX, initialY,
        targetX, targetY);
}
function onCanvasMouseMove(a) {
    if (!a) {
        a = window.event
    }

    mouseX = a.clientX;
    mouseY = a.clientY;
    if (!isMouseDown) {
        return
    }

    // XXX: move mirrors and keys to a state variables
    strokeManager.stroke(mouseX, mouseY, xMirrorIsDown, yMirrorIsDown,
        xyMirrorIsDown, aKeyIsDown, sKeyIsDown, dKeyIsDown, initialX, initialY,
        targetX, targetY);
}
function onCanvasTouchStart(a) {
    if (a.touches.length == 1) {
        var b = a.touches[0];

        strokeManager.strokeStart(b.pageX, b.pageY, xMirrorIsDown, yMirrorIsDown,
            xyMirrorIsDown, aKeyIsDown, sKeyIsDown, dKeyIsDown, initialX,
            initialY, targetX, targetY);
        return false
    }
}
function onCanvasTouchEnd(a) {
    if (a.touches.length == 1) {
        var b = a.touches[0];

        strokeManager.strokeEnd(b.pageX, b.pageY, xMirrorIsDown, yMirrorIsDown,
            xyMirrorIsDown, aKeyIsDown, sKeyIsDown, dKeyIsDown, initialX,
            initialY, targetX, targetY);
        return false
    }
}
function onCanvasTouchMove(a) {
    if (a.touches.length == 1) {
        var b = a.touches[0];

        strokeManager.stroke(b.pageX, b.pageY, xMirrorIsDown, yMirrorIsDown,
            xyMirrorIsDown, aKeyIsDown, sKeyIsDown, dKeyIsDown, initialX,
            initialY, targetX, targetY);
        return false
    }
}
function cleanPopUps() {
    if (isForegroundColorSelectorVisible) {
        foregroundColorSelector.hide();
        isForegroundColorSelectorVisible = false
    }
    if (isBackgroundColorSelectorVisible) {
        backgroundColorSelector.hide();
        isBackgroundColorSelectorVisible = false
    }
    if (isAboutVisible) {
        about.hide();
        isAboutVisible = false
    }
};<|endoftext|>


<commit_before>/*global NodeList */
(function (window) {
	'use strict';

	// Get element(s) by CSS selector:
	window.qs = function (selector, scope) {
		return (scope || document).querySelector(selector);
	};
	window.qsa = function (selector, scope) {
		return (scope || document).querySelectorAll(selector);
	};

	// addEventListener wrapper:
	window.$on = function (target, type, callback, useCapture) {
		target.addEventListener(type, callback, !!useCapture);
	};

	// Register events on elements that may or may not exist yet:
	// $live('div a', 'click', function (event) {});
	window.$live = (function () {
		var eventRegistry = {};

		function dispatchEvent(event) {
			var targetElement = event.target;

			eventRegistry[event.type].forEach(function (entry) {
				var potentialElements = window.qsa(entry.selector);
				var hasMatch = Array.prototype.indexOf.call(potentialElements, targetElement) >= 0;

				if (hasMatch) {
					entry.handler.call(targetElement, event);
				}
			});
		}

		return function (selector, event, handler, scope) {
			scope = scope || window;

			if (!eventRegistry[event]) {
				eventRegistry[event] = [];
				scope.$on(scope.document.documentElement, event, dispatchEvent, true);
			}

			eventRegistry[event].push({
				selector: selector,
				handler: handler
			});
		};
	}());

	// Find the element's parent with the given tag name:
	// $parent(qs('a'), 'div');
	window.$parent = function (element, tagName) {
		if (!element.parentNode) {
			return;
		}
		if (element.parentNode.tagName.toLowerCase() === tagName.toLowerCase()) {
			return element.parentNode;
		}
		return window.$parent(element.parentNode, tagName);
	};

	/*
		Takes a CSS property string and returns a DOM property string.
		@example: -webkit-shape-inside -> webkitShapeInside
	*/
	window.toDOMProperty = function(str){
		if (typeof str !== 'string'){
			return;
		}

		while(str.charAt(0) == '-'){
			str = str.substr(1);
		}

		str = str.replace(/-(\w)/gi, function(match, group, index){
			return group.toUpperCase();
		});

		return str;
	};

	// Allow for looping on nodes by chaining:
	// qsa('.foo').forEach(function () {})
	NodeList.prototype.forEach = Array.prototype.forEach;
})(window);
<commit_msg>add helpers for delegation and undelegation<commit_after>/*global NodeList */
(function (window) {
	'use strict';

	// Get element by CSS selector:
	window.qs = function (selector, scope) {
		return (scope || document).querySelector(selector);
	};
	window.qsa = function (selector, scope) {
		return (scope || document).querySelectorAll(selector);
	};

	// Delegate and undelegate events for elements that may or may not exist yet:
	// $events.delegate('div a', 'click', function (event) {});
	// $events.undelegate('div a', 'click');
	window.$events = (function () {
		var eventRegistry = {};

		function dispatchEvent(event) {
			var targetElement = event.target;

			eventRegistry[event.type].forEach(function (entry) {
				var potentialElements = window.qsa(entry.selector);
				var hasMatch = Array.prototype.indexOf.call(potentialElements, targetElement) >= 0;

				if (hasMatch) {
					entry.handler.call(targetElement, event);
				}
			});
		}

		return {
			delegate: function (selector, event, handler, scope) {
				scope = scope || window;

				if (!eventRegistry[event]) {
					eventRegistry[event] = [];
					scope.document.documentElement.addEventListener(event, dispatchEvent, true);
				}

				eventRegistry[event].push({
					selector: selector,
					handler: handler
				});
			},

			undelegate: function (selector, event, handler, scope){
				scope = scope || window;

				// remove listeners for everything;
				if (!selector && !event && !handler){
					var events = Object.keys(eventRegistry);
					events.forEach(function(event){
						scope.document.documentElement.removeEventListener(event, dispatchEvent, true);
						delete eventRegistry[event];
					});
				}

				// TODO implement per-case undelegation
			}
		};
	}());

	// Find the element's parent with the given tag name:
	// $parent(qs('a'), 'div');
	window.$parent = function (element, tagName) {
		if (!element.parentNode) {
			return;
		}
		if (element.parentNode.tagName.toLowerCase() === tagName.toLowerCase()) {
			return element.parentNode;
		}
		return window.$parent(element.parentNode, tagName);
	};

	/*
		Takes a CSS property string and returns a DOM property string.
		@example: -webkit-shape-inside -> webkitShapeInside
	*/
	window.toDOMProperty = function(str){
		if (typeof str !== 'string'){
			return;
		}

		while(str.charAt(0) == '-'){
			str = str.substr(1);
		}

		str = str.replace(/-(\w)/gi, function(match, group, index){
			return group.toUpperCase();
		});

		return str;
	};

	// Allow for looping on nodes by chaining:
	// qsa('.foo').forEach(function () {})
	NodeList.prototype.forEach = Array.prototype.forEach;
})(window);
<|endoftext|>


<commit_before>const throttle = require('..')
const test = require('tap').test

test('throttling', function (t) {
  var first, second, third

  const opts = { window: 1, limit: 10 }
  const getDate = throttle(function getDate(callback) {
    process.nextTick(function () { return callback(Date.now()) })
  }, opts)

  const ops = [
    getDate(function _init(date) {
      console.log('called init', date)
      proceed()
    }),
    getDate(function _first(date) {
      first = date;
      console.log('called first', first)
      proceed() }),
    getDate(function _second(date) {
      second = date;
      console.log('called second', second)
      proceed()
    }),
    getDate(function _third(date) {
      third = date;
      console.log('called third', third)
      proceed()
    }),
  ]

  var waiting = ops.length
  console.dir(ops)

  function proceed() {
    if (--waiting > 0) return

    console.dir(first)
    console.dir(second)
    console.dir(third)

    const diff1 = second - first
    const diff2 = third - second

    t.notEqual(first, second, 'should not be the same')
    t.ok(diff1 >= 166, 'diff1 should be at least 166 ms')
    t.ok(diff2 >= 166, 'diff2 should be at least 166 ms')
    t.end()
  }
})
<commit_msg>Fix timing<commit_after>const throttle = require('..')
const test = require('tap').test

test('throttling', function (t) {
  var first, second, third

  const opts = { window: 1, limit: 3 }
  const getDate = throttle(function getDate(callback) {
    process.nextTick(function () { return callback(Date.now()) })
  }, opts)

  const ops = [
    getDate(function _init(date) {
      console.log('called init', date)
      proceed()
    }),
    getDate(function _first(date) {
      first = date;
      console.log('called first', first)
      proceed() }),
    getDate(function _second(date) {
      second = date;
      console.log('called second', second)
      proceed()
    }),
    getDate(function _third(date) {
      third = date;
      console.log('called third', third)
      proceed()
    }),
  ]

  var waiting = ops.length
  console.dir(ops)

  function proceed() {
    if (--waiting > 0) return

    console.dir(first)
    console.dir(second)
    console.dir(third)

    const diff1 = second - first
    const diff2 = third - second

    t.notEqual(first, second, 'should not be the same')
    t.ok(diff1 >= 166, 'diff1 should be at least 166 ms')
    t.ok(diff2 >= 166, 'diff2 should be at least 166 ms')
    t.end()
  }
})
<|endoftext|>


<commit_before>/* jshint browser: true */
(function(window, document) {"use strict";  /* Wrap code in an IIFE */

var jQuery, $; // Localize jQuery variables
//var opendesktopwigeturl = 'http://pling.local/';
var opendesktopwigeturl = 'http://pling.cc/';
//var opendesktopwigeturl = 'https://opendesktop.org/';
 let indicator = '';

function loadScript(url, callback) {
  /* Load script from url and calls callback once it's loaded */
  var scriptTag = document.createElement('script');
  scriptTag.setAttribute("type", "text/javascript");
  scriptTag.setAttribute("src", url);
  if (typeof callback !== "undefined") {
    if (scriptTag.readyState) {
      /* For old versions of IE */
      scriptTag.onreadystatechange = function () {
        if (this.readyState === 'complete' || this.readyState === 'loaded') {
          callback();
        }
      };
    } else {
      scriptTag.onload = callback;
    }
  }
  (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(scriptTag);
}

function opendesktopFilterReviews(filterBtn){
    //init
    let reContainer = $('#opendesktopwidget-reviews');
    reContainer.find('.opendesktopwidget-reviews-rows').show();

    let inactive =  reContainer.find('.opendesktopwidget-reviews-rows-inactive');
    let active = reContainer.find('.opendesktopwidget-reviews-rows-active');
    let up =  reContainer.find('.opendesktopwidget-reviews-rows-clsUpvotes');
    let down = reContainer.find('.opendesktopwidget-reviews-rows-clsDownvotes');

    if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-all'){
          inactive.show();
          active.show();
    } else  if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-active'){
          inactive.hide();
          active.show();
    } else  if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-likes'){
          up.show();
          down.hide();
          inactive.hide();
    } else if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-hates'){
          up.hide();
          down.show();
          inactive.hide();
    }
    $('html, body').animate({
           scrollTop: reContainer.offset().top-150
       }, 1);
}

function opendesktoptoggleDetail(thisrow){
                let listcontainer = $('#opendesktopwidget-main');
                let detailcontainer = $('#opendesktopwidget-main-detail-container');

                let detailpopup = '
'
                                            +'

'
                                            +'×'
                                            +'
'
                                            +'
'
                                            +'

'
                                            +'

';

                let modal = $('#opendesktopwidget-main-detail-modal');
                if(detailcontainer.length==0){
                      listcontainer.parent().append($(detailpopup));
                      detailcontainer = $('#opendesktopwidget-main-detail-container');
                      modal.show();
                }else{
                     modal.show();
                      detailcontainer.html('');
                }

                $('a[data-opendesktop-dismiss]').on('click',function(){
                      $('#opendesktopwidget-main-detail-modal').hide();
                });

                let projectid = $(thisrow).attr('data-project-id').trim();
                let container  = $('

');
                container.append(indicator);
                detailcontainer.append(container);
                let jsonp_url_projectdetail = opendesktopwigeturl+"embed/v1/project/"+projectid+"?&callback=?";
                $.getJSON(jsonp_url_projectdetail, function(data) {
                    container.html(data.html);

                    // images carousel
                    let imgs = $('#opendesktopwidget-main-detail-carousel').find('img');
                    if(imgs.length>1){

                            $('#opendesktopwidget-main-detail-carousel').slick({
                                    dots: true
                                });
                    }

                    // tabs onclick
                    let lis = container.find('#opendesktopwidget-content-tabs').find('li');
                    lis.each(function(index) {
                        $(this).on("click", function(){
                            $(this).addClass('active').siblings().removeClass('active');
                            let tabcontainerid = $(this).find('a').attr('data-wiget-target');
                            $(tabcontainerid).addClass('active').siblings().removeClass('active') ;

                        });
                    });

                    // project comments paging
                    let spans = container.find('.opendesktopwidgetcomments').find('ul.opendesktopwidgetpager').find('span');
                    spans.each(function(index) {
                        $(this).on("click", function(){
                            $(this).parent().addClass('active').siblings().removeClass('active');

                           $(indicator).insertBefore(container.find('.opendesktopwidgetcomments').find('ul.opendesktopwidgetpager'));
                            let jsonp_url_nopage = opendesktopwigeturl+"embed/v1/comments/"+projectid+"?nopage=1&page="+$(this).html()+"&callback=?";
                            $.getJSON(jsonp_url_nopage, function(data) {
                                container.find('i.fa-spinner').remove();
                                let ct = container.find('#opendesktopwidget-main-container-comments');
                                ct.html(data.html);

                            });

                        });
                    });

                    // reviews filter
                    let reviewsfilters = container.find('#opendesktopwidget-reviews').find('.opendesktop-widget-reviews-filters-btn');
                    reviewsfilters.each(function(index){
                          $(this).on("click", function(){
                                $(this).addClass('opendesktopwidget-reviews-activeRating').siblings().removeClass('opendesktopwidget-reviews-activeRating');
                                opendesktopFilterReviews(this);
                          });
                    });

                });
        }

function main() {

        /******* Load CSS *******/

        let opendesktopwidgetcss_link = $("<link>", { rel: "stylesheet", type: "text/css", href: opendesktopwigeturl+"widget/style.css" });
        let fontawsomecss_link =$("<link>", { rel: "stylesheet", type: "text/css", href:"http://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" });
        let slick_link =$("<link>", { rel: "stylesheet", type: "text/css", href:"https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css" });
        let slick_theme_link =$("<link>", { rel: "stylesheet", type: "text/css", href:"https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick-theme.css" });

        opendesktopwidgetcss_link.appendTo('head');
        fontawsomecss_link.appendTo('head');
        slick_link.appendTo('head');
        slick_theme_link.appendTo('head');

        /******* Load HTML *******/
      let this_js_script = $('#opendesktopwiget');
      let memberid = this_js_script.attr('data-memberid');
      let countperpage = this_js_script.attr('data-countperpage');
      let catids = this_js_script.attr('data-catids');
      let query = '';
      if(countperpage){
           query = 'pagelimit='+countperpage+'&';
      }
      if(catids){
           query =query+'catids='+catids+'&';
      }

       if (typeof memberid === "undefined" ) {
          alert('Please set data-memberid in your script.');
          return;
       }

       $('#opendesktopwiget').after('
'+indicator+'
');
       let jsonp_url = opendesktopwigeturl+"embed/v1/member/"+memberid+"?"+query+"callback=?";
        $.getJSON(jsonp_url, function(data) {
              $('#opendesktop-widget-container').html(data.html);
              let spans = $('.opendesktopwidgetpager').find('span');
              spans.each(function(index) {
                  $(this).on("click", function(){
                      $(this).parent().addClass('active').siblings().removeClass('active');
                      $(indicator).insertBefore($('#opendesktop-widget-container').find('ul.opendesktopwidgetpager'));
                      let jsonp_url_nopage = opendesktopwigeturl+"embed/v1/member/"+memberid+"?"+query+"nopage=1&page="+$(this).html()+"&callback=?";
                      $.getJSON(jsonp_url_nopage, function(data) {
                          $('#opendesktop-widget-container').find('i.fa-spinner').remove();
                          $('#opendesktopwidget-main-container').html(data.html);
                          let rows =$('#opendesktop-widget-container').find('.opendesktopwidgetrow');
                               rows.each(function(index) {
                                   $(this).on("click", function(){
                                        opendesktoptoggleDetail(this);
                                   });
                               });
                      });

                  });
              });

              let rows =$('#opendesktop-widget-container').find('.opendesktopwidgetrow');
              rows.each(function(index) {
                  $(this).on("click", function(){
                        opendesktoptoggleDetail(this);
                  });
              });

        });
}

/* Load jQuery */
loadScript("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js", function() {

      loadScript("https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.0.0/jquery-migrate.min.js", function() {

                /* Restore $ and window.jQuery to their previous values and store the
                   new jQuery in our local jQuery variables. */
                  //$ = jQuery = window.jQuery.noConflict(false);
                  $ = jQuery = window.jQuery.noConflict();

                //$.noConflict();
                //$.noConflict();
                /* Load jQuery plugin and execute the main logic of our widget once the
                   plugin is loaded is loaded */

                loadScript("https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js", function() {

                  main();
                });

      });
});

}(window, document)); /* end IIFE */<commit_msg>wiget update2<commit_after>/* jshint browser: true */
(function(window, document) {"use strict";  /* Wrap code in an IIFE */

var jQuery, $; // Localize jQuery variables
//var opendesktopwigeturl = 'http://pling.local/';
var opendesktopwigeturl = 'http://pling.cc/';
//var opendesktopwigeturl = 'https://opendesktop.org/';
 let indicator = '';

function loadScript(url, callback) {
  /* Load script from url and calls callback once it's loaded */
  var scriptTag = document.createElement('script');
  scriptTag.setAttribute("type", "text/javascript");
  scriptTag.setAttribute("src", url);
  if (typeof callback !== "undefined") {
    if (scriptTag.readyState) {
      /* For old versions of IE */
      scriptTag.onreadystatechange = function () {
        if (this.readyState === 'complete' || this.readyState === 'loaded') {
          callback();
        }
      };
    } else {
      scriptTag.onload = callback;
    }
  }
  (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(scriptTag);
}

function opendesktopFilterReviews(filterBtn){
    //init
    let reContainer = $('#opendesktopwidget-reviews');
    reContainer.find('.opendesktopwidget-reviews-rows').show();

    let inactive =  reContainer.find('.opendesktopwidget-reviews-rows-inactive');
    let active = reContainer.find('.opendesktopwidget-reviews-rows-active');
    let up =  reContainer.find('.opendesktopwidget-reviews-rows-clsUpvotes');
    let down = reContainer.find('.opendesktopwidget-reviews-rows-clsDownvotes');

    if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-all'){
          inactive.show();
          active.show();
    } else  if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-active'){
          inactive.hide();
          active.show();
    } else  if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-likes'){
          up.show();
          down.hide();
          inactive.hide();
    } else if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-hates'){
          up.hide();
          down.show();
          inactive.hide();
    }
    $('html, body').animate({
           scrollTop: reContainer.offset().top-150
       }, 1);
}

function opendesktoptoggleDetail(thisrow){
                let listcontainer = $('#opendesktopwidget-main');
                let detailcontainer = $('#opendesktopwidget-main-detail-container');

                let detailpopup = '
'
                                            +'

'
                                            +'×'
                                            +'
'
                                            +'
'
                                            +'

'
                                            +'

';

                let modal = $('#opendesktopwidget-main-detail-modal');
                if(detailcontainer.length==0){
                      listcontainer.parent().append($(detailpopup));
                      detailcontainer = $('#opendesktopwidget-main-detail-container');
                      modal.show();
                }else{
                     modal.show();
                      detailcontainer.html('');
                }

                $('a[data-opendesktop-dismiss]').on('click',function(){
                      $('#opendesktopwidget-main-detail-modal').hide();
                });

                let projectid = $(thisrow).attr('data-project-id').trim();
                let container  = $('

');
                container.append(indicator);
                detailcontainer.append(container);
                let jsonp_url_projectdetail = opendesktopwigeturl+"embed/v1/project/"+projectid+"?&callback=?";
                $.getJSON(jsonp_url_projectdetail, function(data) {
                    container.html(data.html);

                    // images carousel
                    let imgs = $('#opendesktopwidget-main-detail-carousel').find('img');
                    if(imgs.length>1){

                            $('#opendesktopwidget-main-detail-carousel').slick({
                                    dots: true
                                });
                            $('button.slick-next').on('click',function(){
                                  $("#opendesktopwidget-main-detail-carousel").slick('slickNext');
                            });
                            $('button.slick-prev').on('click',function(){
                                  $("#opendesktopwidget-main-detail-carousel").slick('slickPrev');
                            });

                    }

                    // tabs onclick
                    let lis = container.find('#opendesktopwidget-content-tabs').find('li');
                    lis.each(function(index) {
                        $(this).on("click", function(){
                            $(this).addClass('active').siblings().removeClass('active');
                            let tabcontainerid = $(this).find('a').attr('data-wiget-target');
                            $(tabcontainerid).addClass('active').siblings().removeClass('active') ;

                        });
                    });

                    // project comments paging
                    let spans = container.find('.opendesktopwidgetcomments').find('ul.opendesktopwidgetpager').find('span');
                    spans.each(function(index) {
                        $(this).on("click", function(){
                            $(this).parent().addClass('active').siblings().removeClass('active');

                           $(indicator).insertBefore(container.find('.opendesktopwidgetcomments').find('ul.opendesktopwidgetpager'));
                            let jsonp_url_nopage = opendesktopwigeturl+"embed/v1/comments/"+projectid+"?nopage=1&page="+$(this).html()+"&callback=?";
                            $.getJSON(jsonp_url_nopage, function(data) {
                                container.find('i.fa-spinner').remove();
                                let ct = container.find('#opendesktopwidget-main-container-comments');
                                ct.html(data.html);

                            });

                        });
                    });

                    // reviews filter
                    let reviewsfilters = container.find('#opendesktopwidget-reviews').find('.opendesktop-widget-reviews-filters-btn');
                    reviewsfilters.each(function(index){
                          $(this).on("click", function(){
                                $(this).addClass('opendesktopwidget-reviews-activeRating').siblings().removeClass('opendesktopwidget-reviews-activeRating');
                                opendesktopFilterReviews(this);
                          });
                    });

                });
        }

function main() {

        /******* Load CSS *******/

        let opendesktopwidgetcss_link = $("<link>", { rel: "stylesheet", type: "text/css", href: opendesktopwigeturl+"widget/style.css" });
        let fontawsomecss_link =$("<link>", { rel: "stylesheet", type: "text/css", href:"http://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" });
        let slick_link =$("<link>", { rel: "stylesheet", type: "text/css", href:"https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css" });
        let slick_theme_link =$("<link>", { rel: "stylesheet", type: "text/css", href:"https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick-theme.css" });

        opendesktopwidgetcss_link.appendTo('head');
        fontawsomecss_link.appendTo('head');
        slick_link.appendTo('head');
        slick_theme_link.appendTo('head');

        /******* Load HTML *******/
      let this_js_script = $('#opendesktopwiget');
      let memberid = this_js_script.attr('data-memberid');
      let countperpage = this_js_script.attr('data-countperpage');
      let catids = this_js_script.attr('data-catids');
      let query = '';
      if(countperpage){
           query = 'pagelimit='+countperpage+'&';
      }
      if(catids){
           query =query+'catids='+catids+'&';
      }

       if (typeof memberid === "undefined" ) {
          alert('Please set data-memberid in your script.');
          return;
       }

       $('#opendesktopwiget').after('
'+indicator+'
');
       let jsonp_url = opendesktopwigeturl+"embed/v1/member/"+memberid+"?"+query+"callback=?";
        $.getJSON(jsonp_url, function(data) {
              $('#opendesktop-widget-container').html(data.html);
              let spans = $('.opendesktopwidgetpager').find('span');
              spans.each(function(index) {
                  $(this).on("click", function(){
                      $(this).parent().addClass('active').siblings().removeClass('active');
                      $(indicator).insertBefore($('#opendesktop-widget-container').find('ul.opendesktopwidgetpager'));
                      let jsonp_url_nopage = opendesktopwigeturl+"embed/v1/member/"+memberid+"?"+query+"nopage=1&page="+$(this).html()+"&callback=?";
                      $.getJSON(jsonp_url_nopage, function(data) {
                          $('#opendesktop-widget-container').find('i.fa-spinner').remove();
                          $('#opendesktopwidget-main-container').html(data.html);
                          let rows =$('#opendesktop-widget-container').find('.opendesktopwidgetrow');
                               rows.each(function(index) {
                                   $(this).on("click", function(){
                                        opendesktoptoggleDetail(this);
                                   });
                               });
                      });

                  });
              });

              let rows =$('#opendesktop-widget-container').find('.opendesktopwidgetrow');
              rows.each(function(index) {
                  $(this).on("click", function(){
                        opendesktoptoggleDetail(this);
                  });
              });

        });
}

/* Load jQuery */
loadScript("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js", function() {

      loadScript("https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.0.0/jquery-migrate.min.js", function() {

                /* Restore $ and window.jQuery to their previous values and store the
                   new jQuery in our local jQuery variables. */
                  //$ = jQuery = window.jQuery.noConflict(false);
                  $ = jQuery = window.jQuery.noConflict();

                //$.noConflict();
                //$.noConflict();
                /* Load jQuery plugin and execute the main logic of our widget once the
                   plugin is loaded is loaded */

                loadScript("https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js", function() {

                  main();
                });

      });
});

}(window, document)); /* end IIFE */<|endoftext|>