seatmap.js 13.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
/*

Seatmap javascript library for Moya

*/

function placemap(opts)
{
    if ( opts.element === undefined )
    {
        throw "element is mandatory argument";
    }

    if ( opts.moyaurl === undefined )
    {
        throw "moyaurl is mandatory argument";
    }

    if ( opts.map_id === undefined )
    {
        throw "map_id is mandatory argument";
    }

    if (opts.onclick === undefined )
    {
        opts.onclick = function(x) {return false;};
    }

    if (opts.editclick === undefined )
    {
    	opts.editclick = function(x, y) {return false;};
    }

    if (opts.toggleaction === undefined )
    {
        opts.toggleaction = false;
    }
    
    if(opts.tooltip === undefined) {
        opts.tooltip = function(d) {
            return "<strong>" + d.name + "</strong>";
        };
    }
    if(opts.hilightUser === undefined) {
        opts.hilightUser = false;
    }
    
    // px is returned object

    var px = {
        element: d3.select(opts.element),
        moyaurl: opts.moyaurl,
        map_id: opts.map_id,
        onclick: opts.onclick,
        editclick: opts.editclick,
        clicked_place: undefined,
        locale: opts.locale || 'fi',
        toggleaction: opts.toggleaction,
        placeurl: opts.placeurl,
    };

    if (px.locale == "und") px.locale == "fi";

    px.locales = {};
    
    px.locales['fi'] = {
    		cannot_reserve: "Ei voitu varata paikkaa",
    		cannot_release: "Ei voitu vapauttaa paikkaa",
    		success_reserve: "Varattu paikka",
    		success_release: "Vapautettu paikka",
            leavemessage: "Et ole lukinnut paikkojasi, oletko varma että haluat poistua?"
    };
    px.locales['en'] = {
    		cannot_reserve: "Can't reserve place",
    		cannot_release: "Can't release place",
    		success_reserve: "Place reserved",
    		success_release: "Place released",
            leavemessage: "Forgot to lock your places, are you sure you want to leave?"
    };

    px.is_leave_message_on = false;
    px.selected_count = 0;
    
    
    var guide_layer = px.element.append("g").attr("id", "guides");
    // Create background
    px.element.selectAll("image").data([0]).enter().append("svg:image")
    .attr("xlink:href", "/MoyaWeb/rest/placemap/v1/" + px.map_id + "/background")
    .attr("x",0)
    .attr("y", 0)
    .attr("width", px.element.attr('width'))
    .attr("height", px.element.attr('height'));
    
    var background = px.element.append("rect")
        .attr("class", "background_2")
        .attr("width", px.element.attr('width'))
        .attr("height", px.element.attr('width'))
        .attr("opacity", 0);

    // Define layers to use
    var map_layer = px.element.append("g").attr("id", "places");

    var edit_layer = px.element.append("g").attr("id", "edit");

    var clicked = false;

    px.place_colors = {
        "F": "#cccccc",
        "L": "#535353",
        "R": "#B40100",
        "P": "#2FA525",
        "T": "#4342C1"
    };

    px.snap_threshold = {x: 5, y: 5};

    var clickpos = {x: 0, y: 0};

    var tip = d3.tip()
      .attr('class', 'place-tooltip')
      .offset([-10, 0])
      .html(opts.tooltip);

    // TODO: Fix this tip layout
    var tip_updown = d3.tip().direction("s")
      .attr('class', 'place-tooltip-upside')
      .offset([10, 0])
      .html(opts.tooltip);

    function draw_guides(x1, y1, x2, y2, fade)
    {
        var guide = guide_layer.append('line')
                .attr('x1', x1)
                .attr('y1', y1)
                .attr('x2', x2)
                .attr('y2', y2)
                .attr("stroke-width", 1)
                .attr("stroke", "#666");
        if (fade == true)
        {
                guide.transition()
                .duration(500)
                .remove();
        }
    }


    function clear_guides()
    {
        guide_layer.selectAll('line').remove();
    }

    function snap_to_edges(x, y, fade)
    {
        // TODO: if there is node in range, snap coordinates next to it

        if (clicked == true) return;

        var xmin = x - px.snap_threshold.x;
        var xmax = x + px.snap_threshold.x;
        var ymin = y - px.snap_threshold.y;
        var ymax = y + px.snap_threshold.y;
        var xnode, ynode;
        var left, top, right, bottom;
        map_layer.selectAll('rect').each(function(d) {
            left = d.x;
            top = d.y;
            right = d.x + d.w;
            bottom = d.y + d.h;
            if (d.x > xmin && d.x < xmax)
            {
                if (xnode === undefined || Math.abs(x - d.x) < Math.abs(x - xnode.x))
                {
                    x = d.x;
                    xnode = d;
                }
            }
            if (right > xmin && right < xmax)
            {
                if (xnode === undefined || Math.abs(x - right) < Math.abs(x - xnode.x - xnode.w))
                {
                    x = right;
                    xnode = d;
                }
            }
            if (d.y > ymin && d.y < ymax)
            {
                if (ynode === undefined || Math.abs(y - top) < Math.abs(y - ynode.y)) {
                    y = d.y;
                    ynode = d;
                }
            }
            if (bottom > ymin && bottom < ymax)
            {
                if (ynode === undefined || Math.abs(y - bottom) < Math.abs(y - ynode.y - ynode.h)) {
                    y = bottom;
                    ynode = d;
                }
            }
        });

        clear_guides();

        if (ynode !== undefined)
        {
            if (ynode.y == y) draw_guides(ynode.x, ynode.y, x, y, fade);
            else draw_guides(ynode.x, ynode.y + ynode.h, x, y, fade);
        }

        if (xnode !== undefined)
        {
            if (xnode.x == x) draw_guides(xnode.x, xnode.y, x, y, fade);
            else draw_guides(xnode.x + xnode.w, xnode.y, x, y, fade);
        }

        return [x, y]
    }


    function show_tooltip(d, i) {


        var object = {
            x: d3.select(this).attr('x'),
            y: d3.select(this).attr('y'),
            width: d3.select(this).attr('width'),
            height: d3.select(this).attr('height')
        };
        if  (object.y >= 40)
        {
            return tip.show(d, i);
        }
        else {
             return tip_updown.show(d, i);
        }
    }

    function hide_tooltip(d, i)
    {
        tip.hide(d, i);
        tip_updown.hide(d, i);
    }

    px.update_leavemessage = function() {

        if(px.is_leave_message_on) {
            if(px.selected_count <= 0) {
                px.selected_count = 0;
                px.is_leave_message_on = false
                $(window).unbind('beforeunload');
            }
        } else {
            if(px.selected_count > 0) {
                $(window).bind('beforeunload', function () {
                    return px.locales[px.locale].leavemessage;
                });
                px.is_leave_message_on = true;
            }

        }
    }

    function place_color(d, i)
    {
        if (Object.keys(px.place_colors).indexOf(d.state) != -1) return px.place_colors[d.state];
        return "#888";
    }


    function draw_places(data, full)
    {
        full_data = false;
        if (full === true || full === false) {
            full_data = full;
        }
        // TODO: update functionality!
        var places = map_layer.selectAll("rect")
            .data(data, function(d) { return d.id; });
        places.enter()
            .append("rect")
            .filter(function(d,i){ return d.state != "D"; })
            .attr("x", function(d, i) { return d.x; })
            .attr("y", function(d, i) { return d.y; })
            .attr("width", function(d, i) { return d.w;})
            .attr("height", function(d, i) { return d.h; })
            .attr("id", function(d) {return d.id; })
            .style("fill", place_color)
            .style('stroke', '#101010')
            .style('stroke-width', '1')
            .append("title", function(d, i) { return d.name; });

        places
        	.attr("x", function(d, i) { return d.x; })
            .attr("y", function(d, i) { return d.y; })
            .attr("width", function(d, i) { return d.w;})
            .attr("height", function(d, i) { return d.h; })
            .attr("id", function(d) {return d.id; })
            .style("fill", place_color)
            .style('stroke', '#101010')
            .style('stroke-width', '1');
        if (full_data == true) {
            places.exit().remove();
        }
        places.filter(function(d,i){ return d.state == "D"; }).remove();

        if (px.edit_enabled == false)
        {
            places
            .on('mouseover', show_tooltip)
            .on('mouseout', hide_tooltip);
            
            if( px.toggleaction ) {
            	places.on('click', function (d, i) {
            		svgElement = d3.select(this);
                    data = svgElement.data()[0];
                    px.toggleaction(data)
            	});
            }
        }
    }

    function edit_clicked(d, i) {
        c = d3.mouse(this);
        var pos = {x: c[0], y: c[1]};

        // Begin click action
        if (clicked == false)
        {

            //coords = snap_to_edges(pos.x, pos.y, true);
            clicked = true;
            pos.x = coords[0];
            pos.y = coords[1];
            clickpos = pos;
            edit_layer.append("circle")
                .attr("cx", pos.x)
                .attr("cy", pos.y)
                .attr("r", 2)
                .attr("width", 10)
                .attr("height", 10)
                .attr("fill", "#111");
            px.editclick(pos.x, pos.y);
        }
        else {
            edit_layer.selectAll("circle").remove();
            clicked = false;
            //tip_add_places.hide(d, i);
        }

    }
    px.edit_enabled = false;
    px.enable_edit = function()
    {
        map_layer.selectAll('rect')
            .on('click', null);
        background.on("click", edit_clicked);
        background.on("mousemove", function(){
            c = d3.mouse(this);
            var pos = {x: c[0], y: c[1]};
            coords = snap_to_edges(pos.x, pos.y, false);
        });
        px.edit_enabled = true;
    };

    function gen_row(x,y, width, height, direction, count)
    {
        var places = [];
        place = 1;
        for (var i = 0; i < count; i++)
        {
            places.push({x: x, y: y, w: width, h: height, name: "foo" + i + x + y, id: i*1000+y*100+x, state: "F"});
            place += 1;
            if (direction == "horizontal")
            {
                x += width;
            }
            else {
                y += height;
            }
        }
        return places;
    }

    px.update = function() {
    	
		var url = px.moyaurl + "/rest/placemap/v1/" + px.map_id + "/places";
    	if(px.placeurl){
    		url = px.moyaurl + px.placeurl;
    	} 

        if(opts.hilightUser) {
            url = px.moyaurl + "/rest/placemap/v1/" + px.map_id + "/hilightedPlaces/"+opts.hilightUser;
        }

        d3.json(url, function(data) {
            draw_places(data.places, true);
        });
    };

    px.toggle_place = function(place) {
    	if (place !== undefined )
    	{ 
    		d3.xhr(px.moyaurl + "/rest/placemap/v1/place/" + place.id)
    	    .header("Content-Type", "application/json")
    	    .post(
    	        JSON.stringify({}),
    	        function(err, rawData) {
    	        	console.log(rawData);
    	            var data = JSON.parse(rawData.response);
    	            draw_places(data.places);
    	            console.log(data.places[0]);
    	            if (data.places[0].state == place.state)
    	            {
    	            	if ( place.state == "F") PF("messages_growl").show([{"summary":px.locales[px.locale].cannot_reserve,
                            "detail":"",
                            "severity":"warn"}]);
    	            	if ( place.state == "T") PF("messages_growl").show([{"summary":px.locales[px.locale].cannot_release,
                            "detail":"",
                            "severity":"warn"}]);
    	            }
    	            else if (data.places[0].state == "T")
    	            {
                        // tän korjaus sotki ehkä jotain, otetaan poies
    	            	//PF("messages_growl").show([{"summary":px.locales[x.locale].success_reserve, "detail":"", "severity":"info"}]);
                        px.selected_count++;
    	            }
    	            else if (data.places[0].state == "F") {
                        //PF("messages_growl").show([{"summary":px.locales[px.locale].success_release, "detail":"", "severity":"info"}]);
                        if (px.selected_count > 0) {
                            px.selected_count--;
                        } else {
                            px.selected_count = 0;
                        }
    	            }
                    px.update_leavemessage();
    	        }
    	    );
    	}
    };
    
    px.update_placeobj = function (d) {
    	draw_places(d, false);    	
    }
    
    px.update_place = function (place_id)
    {
    	if (place_id === undefined) place_id = px.clicked_place;
    	if (place_id !== undefined ) {
	    	d3.json(px.moyaurl + "/rest/placemap/v1/place/" + place_id, function (data) {
	    		draw_places(data.places);
	    	});
    	}
    };
    
    px.init = function() {
        d3.json(px.moyaurl + "/rest/placemap/v1/" + px.map_id + "/", function(data){
            px.element.attr("id", data.map.id).attr("name", data.map.name);
            px.update();
        });
    };

    px.init();

    px.element.call(tip);
    px.element.call(tip_updown);


    px.add_places = function (width, height, count, direction){
        var width = parseInt(document.getElementById("place_add_width").value);
        var height = parseInt(document.getElementById("place_add_height").value);
        var count = parseInt(document.getElementById("place_add_count").value);
        var direction = document.getElementById("place_add_direction").value;
        draw_places(gen_row(clickpos.x,clickpos.y, width, height, direction, count));
        edit_layer.selectAll("circle").remove();
        clicked = false;
        clear_guides();
    };

    return px;
}