<commit_before>function siggyMap(options)
{

	this.defaults = {
			jumpTrackerEnabled: true,
			jumpTrackerShowNames: true,
			jumpTrackerShowTime: true,
            showActivesShips: false
	};


	this.settings = $.extend(this.defaults, options);


	this.systems = {};
	this.wormholes = {};
	
	this.drawnSystems = {};
	this.drawnConnections = [];
			
	this.baseUrl = '';
	this.container = null;
	this.siggymain = null;
	
	this.loadingMessage = null;
	this.editingMessage = null;
	this.deletingMessage = null;
	
	this.buttonsContainer = null;
	
	this.updated = false;
	
	//map editing
	this.editing = false;
	this.massDelete = false;
	
	//wheditor
	this.editorOpen = false;
	this.editorMode = '';
	this.editingHash = 0;
	
	this.lastUpdate = 0;
	
	
	if( getCookie('mapOpen') != null )
	{
		this.mapOpen = parseInt(getCookie('mapOpen'));
	}
	else
	{
		this.mapOpen = 0;
	}
	
	if( getCookie('broadcast') != null )
	{
		this.broadcast = parseInt(getCookie('broadcast'));
	}
	else
	{
		this.broadcast = 1;
	}
	
	//panning stuff
    
	
	
	this.massSelect = false;
	this.massSelectBox = null;
	
	
	this.selectedSystemRect = null;
	this.selectedSystemID = 0;
	this.infoicon = null;
	
	//systemeditor
	this.editingSystem = 0;

    this.selectionBox = $('<div>').addClass('selection-box');
    this.selectedSystemBox = $('<div>').addClass('selected-system');
}

siggyMap.prototype.showMessage = function(what)
{
	if( what == 'loading' )
	{
		this.loadingMessage.css({'top': this.container.height()/2, left: this.container.width()/2 - this.loadingMessage.width()/2});
		this.loadingMessage.show();
	}
	else if( what == 'editing' )
	{
		this.editingMessage.css({left: this.container.width()/2 - this.editingMessage.width()/2});
		this.editingMessage.show();
	}
	else if( what == 'deleting' )
	{
		this.deletingMessage.css({left: this.container.width()/2 - this.deletingMessage.width()/2});
		this.deletingMessage.show();
	}
}

siggyMap.prototype.hideMessage = function(what)
{	
	if( what == 'loading' )
	{
		this.loadingMessage.hide();
	}
	else if( what == 'editing' )
	{
		this.editingMessage.hide();
	}
	else if( what == 'deleting' )
	{
		this.deletingMessage.hide();
	}
}

siggyMap.prototype.updateMessagePositions = function() 
{
	
	if( this.loadingMessage.is(':visible') )
	{
		this.loadingMessage.css({'top': this.container.height()/2 - this.loadingMessage.height()/2, left: this.container.width()/2 - this.loadingMessage.width()/2});
	}
	if( this.editingMessage.is(':visible') )
	{
		this.editingMessage.css({left: this.container.width()/2 - this.editingMessage.width()/2});
	}
	if( this.deletingMessage.is(':visible') )
	{
		this.deletingMessage.css({left: this.container.width()/2 - this.deletingMessage.width()/2});
	}
}

siggyMap.prototype.centerButtons = function()
{
	var bottomOffset = 30;
	if( this.buttonsContainer != null )
	{
	//	if( $('#chainPanTrackX').is(':visible') )
		//{
		//	bottomOffset += 20;
		//}
	}
}

siggyMap.prototype.initialize = function()
{
		var that = this;
		this.container = $('#chain-map-container');
		
		
		this.loadingMessage = this.container.find('p.loading');
		this.editingMessage = this.container.find('p.editing');
		this.deletingMessage = this.container.find('p.deleting');
		
		this.buttonsContainer = this.container.find('div.buttons');
		
		this.showMessage('loading');
		
        $('#chain-map-add-wh').click( function() {
            that.resetWormholeEditor();
            that.openWHEditor('add');
        });
		
        $('#chain-map-edit').click( function() {
            that.editing = true;
            $('#chain-map-save').show();
            that.centerButtons();
            
            if( that.infoicon != null )
            {
                    that.infoicon.disabled = true;
            }
            
            $('div.map-system-blob').qtip('disable');
            
            jsPlumb.setDraggable($('.map-system-blob'), true);
            
            
            that.showMessage('editing');
            
            
        });
        
        $('#chain-map-delete-whs').click( function() {
            that.showMessage('deleting');
            that.massDelete = true;
            
            
            $('#chain-map-mass-delete-confirm').show();
            $('#chain-map-mass-delete-cancel').show();
            that.centerButtons();
        });
        
		
        this.registerEvents();
        this.initializeTabs();
        this.setupEditor();
        this.setupSystemEditor();
        
        $(window).bind('resize', function() 
		{
			that.updateMessagePositions();
			that.centerButtons();
		});
        
        var $container = $("#chain-map");
        $container.on('mousedown', function(e) {
            if( !that.massDelete || that.massSelect )
            {
                return;
            }
            that.massSelect = true;
            var click_y = e.pageY-110,
            click_x = e.pageX-20;
            that.selectionBox.css({
              'top':    click_y,
              'left':   click_x,
              'width':  0,
              'height': 0,
              'z-index': 9999
            });
            
            that.selectionBox.appendTo($container);
            
            $container.on('mousemove', function(e) { 
				if ( ( that.massSelect )  )
				{           
                    var move_x = e.pageX-20,
                      move_y = e.pageY-110,
                      width  = Math.abs(move_x - click_x),
                      height = Math.abs(move_y - click_y),
                      new_x, new_y;

                    new_x = (move_x < click_x) ? (click_x - width) : click_x;
                    new_y = (move_y < click_y) ? (click_y - height) : click_y;

                    that.selectionBox.css({
                    'width': width,
                    'height': height,
                    'top': new_y,
                    'left': new_x
                    });
              }
            }).on('mouseup', function(e) {
				if ( that.massSelect )
				{
					that.massSelect = false;
                    $container.off('mousemove');
                    
                    var bb = {
                         w: that.selectionBox.width(),
                         h: that.selectionBox.height(),
                         x: that.selectionBox.position().left,
                         y: that.selectionBox.position().top
                    };
					
					if( bb.w < 1 || bb.h < 1 )
						return;
                       
                    
                    that.selectionBox.remove();
                    
                    var connectionList = jsPlumb.getConnections(); 
                    for (i in connectionList)
                    {
                        var conn = connectionList[i];
                        var hash = conn.getParameter('hash');    
                        var ele = $( conn.id );
                        
                        var inside = false;              
                        var internalconn = conn.getConnector();
                        var compareBB = {
                            h: internalconn.h,
                            x: internalconn.x,
                            y: internalconn.y,
                            w: internalconn.w
                        };
                        inside = jsPlumbGeom.intersects( bb, compareBB );
                        
                        if( inside )
                        {
						
                            if( conn.getParameter('deleteMe') )
                            {
                                conn.setParameter('deleteMe', false);
                                conn.setPaintStyle( {
                                       lineWidth:6,
                                       strokeStyle: that.getMassColor(that.wormholes[hash].mass),
                                       outlineColor: that.getTimeColor(that.wormholes[hash].eol),
                                       outlineWidth:3
                                });
                            }
                            else
                            {
                                conn.setParameter('deleteMe', true);
                                conn.setPaintStyle( {
                                       lineWidth:6,
                                       strokeStyle: "#006AFE",
                                       outlineColor: "#006AFE",
                                       outlineWidth:3
                                });
                                this.deleteMe = true;
                            }
                        }
                    }
                }					
            });
        });        
        
        
        
		$(document).bind('siggy.switchSystem', function(e, systemID) {
            that.setSelectedSystem( systemID );
            e.stopPropagation();
		});
}

siggyMap.prototype.setSelectedSystem = function( systemID )
{
		if( this.selectedSystemID != systemID )
		{
				$( "#"+this.selectedSystemID ).removeClass('map-system-blob-selected');
                
				$("#"+systemID ).addClass('map-system-blob-selected');
				
				this.selectedSystemID = systemID;
		}
}

siggyMap.prototype.registerEvents = function()
{
    var that = this;
    

    $('#chain-map-container h2').click( function() {
        if( that.mapOpen == 1 )
        {
            that.mapOpen = 0;
            $('#chain-map-inner').hide();
            $('#chain-map-ec').text('Click to show');
            $('#chainPanTrackX').hide();
            that.lastUpdate = 0;
            setCookie('mapOpen', 0, 365);
        }
        else
        {
            that.mapOpen = 1;
            $('#chain-map-inner').show();
            $('#chain-map-ec').text('Click to hide');
            setCookie('mapOpen', 1, 365);
            that.showMessage('loading');
        }
    } );
        
    $('#chain-map-save').click( function() {
        var saveSystemData = [];
        for (var i in that.systems) 
        {
            var sysID = that.systems[i].systemID;
        
            var saveSystem = {};
            saveSystem.id = parseInt(sysID);
            
            
            var offset = $( '#'+sysID ).position();
            saveSystem.x = offset.left;
            saveSystem.y = offset.top;
            
            saveSystemData.push(saveSystem);
        }
        
        $.post(that.baseUrl + 'dochainMapSave', {
            systemData: JSON.stringify(saveSystemData)
        });
        
        that.editing = false;
        $(this).hide();
        that.hideMessage('editing');
        if( that.infoicon != null )
        {
                that.infoicon.disabled = false;
        }
        $('div.map-system-blob').qtip('enable');
        
    } );
    

    $('#chain-map-mass-delete-confirm').click( function() {
        var deleteHashes = [];
        
        
        var connectionList = jsPlumb.getConnections(); 
        for (i in connectionList)
        {
            var conn = connectionList[i];
            
            if( conn.getParameter('deleteMe') == true )
            {
                deleteHashes.push( conn.getParameter('hash') );
                jsPlumb.detach(conn);
            }
        }
        
        if( deleteHashes.length > 0 )
        {
            $.post(that.baseUrl + 'dochainMapWHMassDelete', { hashes: JSON.stringify(deleteHashes) }, 
                function() {
                that.siggymain.updateNow();
            });
        }
        
        that.hideMessage('deleting');
        that.massDelete = false;
        
        
        $(this).hide();
        $('#chain-map-mass-delete-cancel').hide();
        
    });
    
    $('#chain-map-mass-delete-cancel').click( function() {

        var connectionList = jsPlumb.getConnections(); 
        for (i in connectionList)
        {
            var conn = connectionList[i];
            var hash = conn.getParameter('hash');    
            
            conn.setParameter('deleteMe', false);
            conn.setPaintStyle( {
                   lineWidth:6,
                   strokeStyle: that.getMassColor(that.wormholes[hash].mass),
                   outlineColor: that.getTimeColor(that.wormholes[hash].eol),
                   outlineWidth:3
            });
        }
        
        that.hideMessage('deleting');
        that.massDelete = false;
        
        $(this).hide();
        $('#chain-map-mass-delete-confirm').hide();
    });
}


siggyMap.prototype.update = function(timestamp, systems, wormholes)
{
	if( this.editing || this.massDelete )
	{
		return;
	}
	
	this.lastUpdate = parseInt(timestamp);
	
	this.systems = systems;
	this.wormholes = wormholes;
    
    
	this.draw();
	
	this.hideMessage('loading');
}

siggyMap.prototype.updateActives = function( activesData )
{
	if(  typeof( activesData ) == 'undefined' )
	{
		return;
	}
    
    for( var i in this.systems )
    {
        var sysID = this.systems[i].systemID;

        var ele =  $('#' + sysID + ' p.map-system-blob-actives');
        ele.empty();
        
        var fullActives = $("#fullactives"+sysID);
        fullActives.empty();
        
        if( typeof(activesData[sysID]) != 'undefined' )
        {
            var actives = activesData[sysID];
            var text = '';
            
            
            //setup our lengths
            //TBH, make the max length configurable
            var maxDisplayLen = 7;
            var len = actives.length;
            var displayLen = len > maxDisplayLen ? maxDisplayLen : len;
            
            var fullText = '';
            for(var j in actives)
            {
                var person = actives[j];
                
                if( j < displayLen )
                {
                    text += actives[j].name + '<br \>';
                }
                
                if( this.settings.showActivesShips )
                {
                    fullText += actives[j].name + " - " + actives[j].ship +'<br \>';
                }
                else
                {
                    fullText += actives[j].name + '<br \>';
                }
            }
            
            if( len > displayLen )
            {
                text += ' +' + (len-displayLen) + ' other...<br \>';
            }
            
            
            ele.html(text);
            fullActives.html(fullText);
        }
        else
        {
            fullActives.html("No actives");
        }
    }
	
}

siggyMap.prototype.isMapOpen = function()
{
	return this.mapOpen;
}


siggyMap.prototype.draw = function()
{
    var that = this;
    
    $('div.map-system-blob').qtip('destroy');
    $('div.map-system-blob').destroyContextMenu();
    $('div.map-full-actives').remove();
    jsPlumb.deleteEveryEndpoint();
    $('#chain-map').empty();
    
    for( var i in this.systems )
    {
        //local variable assignment
        var systemData = this.systems[i];
        
        var sysBlob = $("<div>").addClass('map-system-blob').offset({ top: systemData.y, left: systemData.x}).attr("id", systemData.systemID);
        
        //blob time for the title 
        var systemName = $("<span>").text(systemData.displayName == "" ? systemData.name : systemData.displayName).addClass('map-system-blob-sysname');
        
        var titleClassBit = "";
        if( systemData.sysClass >= 7 || ( systemData.sysClass < 7 && systemData.displayName == "") )
        {
            titleClassBit = $("<span>").addClass('map-system-blob-class').addClass( this.getClassColor( parseInt(systemData.sysClass) ) ).text( this.getClassText( parseInt(systemData.sysClass) ) );
        }
        
        //effect stuff
        var effectBit = $("<span>");
        var effectClass = this.getEffectColor( parseInt(systemData.effect) );
        if(effectClass != "" )
        {   
            effectBit.addClass('map-effect');
            effectBit.addClass(effectClass);
            effectBit.attr('title', this.getEffectText( parseInt(systemData.effect) ) );
        }
        
        //show info on the name 
        systemName.click( function(ele)
        {
            if( that.editing || that.massDelete )
            {
                return false;
            }
    
            var sysID = $(this).parent().parent().attr("id");
            if( typeof(CCPEVE) != "undefined" )
            {
                    CCPEVE.showInfo(5, sysID );
            }
            else
            {
                    window.open('http://evemaps.dotlan.net/system/'+that.systems[sysID].name , '_blank');
            }
        });
        
        var systemBlobTitle = $("<p>").addClass('map-system-blob-title').append(titleClassBit).append(effectBit).append(systemName);
        
        
        
        //add empty paragraph for the active chars
        var systemBlobActives = $("<p>").addClass('map-system-blob-actives');
        sysBlob.append(systemBlobTitle).append(systemBlobActives);
        
        if( this.selectedSystemID == systemData.systemID )
        {
            sysBlob.addClass('map-system-blob-selected');
        }
        
        // get the activity color class
        var activityClass = this.getActivityColor( parseInt(systemData.activity) );
        sysBlob.addClass( activityClass) ;
        
        $("#chain-map").append( sysBlob );
        
        sysBlob.contextMenu( { menu: 'systemMenu' },
            function(action, el, pos) {
                if( action == "edit" )
                {
                    that.openSystemEdit( el[0].id );
                }
                else if( action == "setdest" )
                {
                    if( typeof(CCPEVE) != "undefined" )
                    {
                        CCPEVE.setDestination(el[0].id);
                    }
                }
                else if( action == "showinfo" )
                {
                    if( typeof(CCPEVE) != "undefined" )
                    {
                            CCPEVE.showInfo(5, el[0].id );
                    }
                    else
                    {
                            window.open('http://evemaps.dotlan.net/system/'+ that.systems[el[0].id].name , '_blank');
                    }
                }
        });
        
        sysBlob.click( function() {
            if( that.editing || that.massDelete )
            {
                return false;
            }
            var sysID = $(this).attr("id");
            that.siggymain.switchSystem(sysID, that.systems[sysID].name);
        } );
        
        var tst = $("<div>").attr("id","fullactives"+systemData.systemID).addClass('tooltip').addClass('map-full-actives').text("");
        $("#chain-map-container").append(tst);
        
        var res = sysBlob.qtip({
            content: {
                text: $("#fullactives"+systemData.systemID) // Use the "div" element next to this for the content
            },
            show: {
                delay: 1000
            },
            position: {
                target: 'mouse',
                adjust: { x: 5, y: 5 },
                viewport: $(window)
            }
        });
        
    }
    
    var _listeners = function(e) {
        e.bind("mouseenter", function(c) { 
            if( that.editing || that.massDelete )
            {
                return false;
            }
            c.showOverlay("label");
        });
        e.bind("mouseexit", function(c) { 
            c.hideOverlay("label");
        });        
    };    
    
    for( var w in this.wormholes )
    {
        //local variable to make code smaller
        var wormhole = this.wormholes[w];

        var connectionOptions = { source: wormhole.from, 
                            target: wormhole.to,
                            anchor:"Continuous",
                            endpointsOnTop:false, 
                            endpoint:"Blank",		
                            detachable:false,
                            connector:["StateMachine", { curviness:0.001 }],
                            connectorTooltip: "aSDASDA",
                            tooltip: "aSDASDA",
                            anchor:[ "Perimeter", { shape:"Ellipse" } ],

                            paintStyle:{ 
                               lineWidth:6,
                               strokeStyle: this.getMassColor(wormhole.mass),
                               outlineColor: this.getTimeColor(wormhole.eol),
                               outlineWidth:3
                            },			   	
                            endpointStyle:{ fillStyle:"#a7b04b" },
                            parameters: { hash: wormhole.hash, deleteMe: false }

                        };
                        
        wormhole.eolToggled = parseInt(wormhole.eolToggled);
        if( wormhole.eolToggled != 0 )
        {
            connectionOptions.overlays = [
											["Label", {													   					
												cssClass:"map-eol-overlay",
												label : 'EOL set at: '+ siggymain.displayTimeStamp(wormhole.eolToggled),
												location:0.5,
												id:"label"
											}]
                                        ];
        }
            
        var connection = jsPlumb.connect(connectionOptions);     

        if( wormhole.eolToggled != 0 )
        {
            _listeners(connection);            
        }
        
        connection.bind("click", function(conn)
        {
            var hash = conn.getParameter('hash');    
            if( that.massDelete )
            {
                if( conn.getParameter('deleteMe') )
                {
                    conn.setPaintStyle( {
                           lineWidth:6,
                           strokeStyle: that.getMassColor(that.wormholes[hash].mass),
                           outlineColor: that.getTimeColor(that.wormholes[hash].eol),
                           outlineWidth:3
                    });
                    conn.setParameter('deleteMe', false);
                }
                else
                {
                    conn.setPaintStyle( {
                           lineWidth:6,
                           strokeStyle: "#006AFE",
                           outlineColor: "#006AFE",
                           outlineWidth:3
                    });
                    conn.setParameter('deleteMe', true);
                }
            }
            else
            {
                that.editWormhole(hash);
            }
			return false;
        });
            
    }
         
            
    jsPlumb.draggable($('.map-system-blob'), {
      containment: 'parent',
      stack: "div"
    });
    
    jsPlumb.setDraggable($('.map-system-blob'), false);
}

siggyMap.prototype.openSystemEdit = function( sysID )
{
	this.editingSystem = sysID;
	
	$('#chain-map-container').block({
		message: $('#system-options-popup'),
		css: { <commit_msg>Fixed empty map causing JS error.<commit_after>
function siggyMap(options)
{

	this.defaults = {
			jumpTrackerEnabled: true,
			jumpTrackerShowNames: true,
			jumpTrackerShowTime: true,
            showActivesShips: false
	};


	this.settings = $.extend(this.defaults, options);


	this.systems = {};
	this.wormholes = {};
	
	this.drawnSystems = {};
	this.drawnConnections = [];
			
	this.baseUrl = '';
	this.container = null;
	this.siggymain = null;
	
	this.loadingMessage = null;
	this.editingMessage = null;
	this.deletingMessage = null;
	
	this.buttonsContainer = null;
	
	this.updated = false;
	
	//map editing
	this.editing = false;
	this.massDelete = false;
	
	//wheditor
	this.editorOpen = false;
	this.editorMode = '';
	this.editingHash = 0;
	
	this.lastUpdate = 0;
	
	
	if( getCookie('mapOpen') != null )
	{
		this.mapOpen = parseInt(getCookie('mapOpen'));
	}
	else
	{
		this.mapOpen = 0;
	}
	
	if( getCookie('broadcast') != null )
	{
		this.broadcast = parseInt(getCookie('broadcast'));
	}
	else
	{
		this.broadcast = 1;
	}
	
	//panning stuff
    
	
	
	this.massSelect = false;
	this.massSelectBox = null;
	
	
	this.selectedSystemRect = null;
	this.selectedSystemID = 0;
	this.infoicon = null;
	
	//systemeditor
	this.editingSystem = 0;

    this.selectionBox = $('<div>').addClass('selection-box');
    this.selectedSystemBox = $('<div>').addClass('selected-system');
}

siggyMap.prototype.showMessage = function(what)
{
	if( what == 'loading' )
	{
		this.loadingMessage.css({'top': this.container.height()/2, left: this.container.width()/2 - this.loadingMessage.width()/2});
		this.loadingMessage.show();
	}
	else if( what == 'editing' )
	{
		this.editingMessage.css({left: this.container.width()/2 - this.editingMessage.width()/2});
		this.editingMessage.show();
	}
	else if( what == 'deleting' )
	{
		this.deletingMessage.css({left: this.container.width()/2 - this.deletingMessage.width()/2});
		this.deletingMessage.show();
	}
}

siggyMap.prototype.hideMessage = function(what)
{	
	if( what == 'loading' )
	{
		this.loadingMessage.hide();
	}
	else if( what == 'editing' )
	{
		this.editingMessage.hide();
	}
	else if( what == 'deleting' )
	{
		this.deletingMessage.hide();
	}
}

siggyMap.prototype.updateMessagePositions = function() 
{
	
	if( this.loadingMessage.is(':visible') )
	{
		this.loadingMessage.css({'top': this.container.height()/2 - this.loadingMessage.height()/2, left: this.container.width()/2 - this.loadingMessage.width()/2});
	}
	if( this.editingMessage.is(':visible') )
	{
		this.editingMessage.css({left: this.container.width()/2 - this.editingMessage.width()/2});
	}
	if( this.deletingMessage.is(':visible') )
	{
		this.deletingMessage.css({left: this.container.width()/2 - this.deletingMessage.width()/2});
	}
}

siggyMap.prototype.centerButtons = function()
{
	var bottomOffset = 30;
	if( this.buttonsContainer != null )
	{
	//	if( $('#chainPanTrackX').is(':visible') )
		//{
		//	bottomOffset += 20;
		//}
	}
}

siggyMap.prototype.initialize = function()
{
		var that = this;
		this.container = $('#chain-map-container');
		
		
		this.loadingMessage = this.container.find('p.loading');
		this.editingMessage = this.container.find('p.editing');
		this.deletingMessage = this.container.find('p.deleting');
		
		this.buttonsContainer = this.container.find('div.buttons');
		
		this.showMessage('loading');
		
        $('#chain-map-add-wh').click( function() {
            that.resetWormholeEditor();
            that.openWHEditor('add');
        });
		
        $('#chain-map-edit').click( function() {
            that.editing = true;
            $('#chain-map-save').show();
            that.centerButtons();
            
            if( that.infoicon != null )
            {
                    that.infoicon.disabled = true;
            }
            
            $('div.map-system-blob').qtip('disable');
            
            jsPlumb.setDraggable($('.map-system-blob'), true);
            
            
            that.showMessage('editing');
            
            
        });
        
        $('#chain-map-delete-whs').click( function() {
            that.showMessage('deleting');
            that.massDelete = true;
            
            
            $('#chain-map-mass-delete-confirm').show();
            $('#chain-map-mass-delete-cancel').show();
            that.centerButtons();
        });
        
		
        this.registerEvents();
        this.initializeTabs();
        this.setupEditor();
        this.setupSystemEditor();
        
        $(window).bind('resize', function() 
		{
			that.updateMessagePositions();
			that.centerButtons();
		});
        
        var $container = $("#chain-map");
        $container.on('mousedown', function(e) {
            if( !that.massDelete || that.massSelect )
            {
                return;
            }
            that.massSelect = true;
            var click_y = e.pageY-110,
            click_x = e.pageX-20;
            that.selectionBox.css({
              'top':    click_y,
              'left':   click_x,
              'width':  0,
              'height': 0,
              'z-index': 9999
            });
            
            that.selectionBox.appendTo($container);
            
            $container.on('mousemove', function(e) { 
				if ( ( that.massSelect )  )
				{           
                    var move_x = e.pageX-20,
                      move_y = e.pageY-110,
                      width  = Math.abs(move_x - click_x),
                      height = Math.abs(move_y - click_y),
                      new_x, new_y;

                    new_x = (move_x < click_x) ? (click_x - width) : click_x;
                    new_y = (move_y < click_y) ? (click_y - height) : click_y;

                    that.selectionBox.css({
                    'width': width,
                    'height': height,
                    'top': new_y,
                    'left': new_x
                    });
              }
            }).on('mouseup', function(e) {
				if ( that.massSelect )
				{
					that.massSelect = false;
                    $container.off('mousemove');
                    
                    var bb = {
                         w: that.selectionBox.width(),
                         h: that.selectionBox.height(),
                         x: that.selectionBox.position().left,
                         y: that.selectionBox.position().top
                    };
					
					if( bb.w < 1 || bb.h < 1 )
						return;
                       
                    
                    that.selectionBox.remove();
                    
                    var connectionList = jsPlumb.getConnections(); 
                    for (i in connectionList)
                    {
                        var conn = connectionList[i];
                        var hash = conn.getParameter('hash');    
                        var ele = $( conn.id );
                        
                        var inside = false;              
                        var internalconn = conn.getConnector();
                        var compareBB = {
                            h: internalconn.h,
                            x: internalconn.x,
                            y: internalconn.y,
                            w: internalconn.w
                        };
                        inside = jsPlumbGeom.intersects( bb, compareBB );
                        
                        if( inside )
                        {
						
                            if( conn.getParameter('deleteMe') )
                            {
                                conn.setParameter('deleteMe', false);
                                conn.setPaintStyle( {
                                       lineWidth:6,
                                       strokeStyle: that.getMassColor(that.wormholes[hash].mass),
                                       outlineColor: that.getTimeColor(that.wormholes[hash].eol),
                                       outlineWidth:3
                                });
                            }
                            else
                            {
                                conn.setParameter('deleteMe', true);
                                conn.setPaintStyle( {
                                       lineWidth:6,
                                       strokeStyle: "#006AFE",
                                       outlineColor: "#006AFE",
                                       outlineWidth:3
                                });
                                this.deleteMe = true;
                            }
                        }
                    }
                }					
            });
        });        
        
        
        
		$(document).bind('siggy.switchSystem', function(e, systemID) {
            that.setSelectedSystem( systemID );
            e.stopPropagation();
		});
}

siggyMap.prototype.setSelectedSystem = function( systemID )
{
		if( this.selectedSystemID != systemID )
		{
				$( "#"+this.selectedSystemID ).removeClass('map-system-blob-selected');
                
				$("#"+systemID ).addClass('map-system-blob-selected');
				
				this.selectedSystemID = systemID;
		}
}

siggyMap.prototype.registerEvents = function()
{
    var that = this;
    

    $('#chain-map-container h2').click( function() {
        if( that.mapOpen == 1 )
        {
            that.mapOpen = 0;
            $('#chain-map-inner').hide();
            $('#chain-map-ec').text('Click to show');
            $('#chainPanTrackX').hide();
            that.lastUpdate = 0;
            setCookie('mapOpen', 0, 365);
        }
        else
        {
            that.mapOpen = 1;
            $('#chain-map-inner').show();
            $('#chain-map-ec').text('Click to hide');
            setCookie('mapOpen', 1, 365);
            that.showMessage('loading');
        }
    } );
        
    $('#chain-map-save').click( function() {
        var saveSystemData = [];
        for (var i in that.systems) 
        {
            var sysID = that.systems[i].systemID;
        
            var saveSystem = {};
            saveSystem.id = parseInt(sysID);
            
            
            var offset = $( '#'+sysID ).position();
            saveSystem.x = offset.left;
            saveSystem.y = offset.top;
            
            saveSystemData.push(saveSystem);
        }
        
        $.post(that.baseUrl + 'dochainMapSave', {
            systemData: JSON.stringify(saveSystemData)
        });
        
        that.editing = false;
        $(this).hide();
        that.hideMessage('editing');
        if( that.infoicon != null )
        {
                that.infoicon.disabled = false;
        }
        $('div.map-system-blob').qtip('enable');
        
    } );
    

    $('#chain-map-mass-delete-confirm').click( function() {
        var deleteHashes = [];
        
        
        var connectionList = jsPlumb.getConnections(); 
        for (i in connectionList)
        {
            var conn = connectionList[i];
            
            if( conn.getParameter('deleteMe') == true )
            {
                deleteHashes.push( conn.getParameter('hash') );
                jsPlumb.detach(conn);
            }
        }
        
        if( deleteHashes.length > 0 )
        {
            $.post(that.baseUrl + 'dochainMapWHMassDelete', { hashes: JSON.stringify(deleteHashes) }, 
                function() {
                that.siggymain.updateNow();
            });
        }
        
        that.hideMessage('deleting');
        that.massDelete = false;
        
        
        $(this).hide();
        $('#chain-map-mass-delete-cancel').hide();
        
    });
    
    $('#chain-map-mass-delete-cancel').click( function() {

        var connectionList = jsPlumb.getConnections(); 
        for (i in connectionList)
        {
            var conn = connectionList[i];
            var hash = conn.getParameter('hash');    
            
            conn.setParameter('deleteMe', false);
            conn.setPaintStyle( {
                   lineWidth:6,
                   strokeStyle: that.getMassColor(that.wormholes[hash].mass),
                   outlineColor: that.getTimeColor(that.wormholes[hash].eol),
                   outlineWidth:3
            });
        }
        
        that.hideMessage('deleting');
        that.massDelete = false;
        
        $(this).hide();
        $('#chain-map-mass-delete-confirm').hide();
    });
}


siggyMap.prototype.update = function(timestamp, systems, wormholes)
{
	if( this.editing || this.massDelete )
	{
		return;
	}
	
	this.lastUpdate = parseInt(timestamp);
	
	this.systems = systems;
	this.wormholes = wormholes;
    
    
	this.draw();
	
	this.hideMessage('loading');
}

siggyMap.prototype.updateActives = function( activesData )
{
	if(  typeof( activesData ) == 'undefined' )
	{
		return;
	}
    
    for( var i in this.systems )
    {
        var sysID = this.systems[i].systemID;

        var ele =  $('#' + sysID + ' p.map-system-blob-actives');
        ele.empty();
        
        var fullActives = $("#fullactives"+sysID);
        fullActives.empty();
        
        if( typeof(activesData[sysID]) != 'undefined' )
        {
            var actives = activesData[sysID];
            var text = '';
            
            
            //setup our lengths
            //TBH, make the max length configurable
            var maxDisplayLen = 7;
            var len = actives.length;
            var displayLen = len > maxDisplayLen ? maxDisplayLen : len;
            
            var fullText = '';
            for(var j in actives)
            {
                var person = actives[j];
                
                if( j < displayLen )
                {
                    text += actives[j].name + '<br \>';
                }
                
                if( this.settings.showActivesShips )
                {
                    fullText += actives[j].name + " - " + actives[j].ship +'<br \>';
                }
                else
                {
                    fullText += actives[j].name + '<br \>';
                }
            }
            
            if( len > displayLen )
            {
                text += ' +' + (len-displayLen) + ' other...<br \>';
            }
            
            
            ele.html(text);
            fullActives.html(fullText);
        }
        else
        {
            fullActives.html("No actives");
        }
    }
	
}

siggyMap.prototype.isMapOpen = function()
{
	return this.mapOpen;
}


siggyMap.prototype.draw = function()
{
    var that = this;
    
    $('div.map-system-blob').qtip('destroy');
    $('div.map-system-blob').destroyContextMenu();
    $('div.map-full-actives').remove();
    jsPlumb.deleteEveryEndpoint();
    $('#chain-map').empty();
    
    for( var i in this.systems )
    {
        //local variable assignment
        var systemData = this.systems[i];
        
        var sysBlob = $("<div>").addClass('map-system-blob').offset({ top: systemData.y, left: systemData.x}).attr("id", systemData.systemID);
        
        //blob time for the title 
        var systemName = $("<span>").text(systemData.displayName == "" ? systemData.name : systemData.displayName).addClass('map-system-blob-sysname');
        
        var titleClassBit = "";
        if( systemData.sysClass >= 7 || ( systemData.sysClass < 7 && systemData.displayName == "") )
        {
            titleClassBit = $("<span>").addClass('map-system-blob-class').addClass( this.getClassColor( parseInt(systemData.sysClass) ) ).text( this.getClassText( parseInt(systemData.sysClass) ) );
        }
        
        //effect stuff
        var effectBit = $("<span>");
        var effectClass = this.getEffectColor( parseInt(systemData.effect) );
        if(effectClass != "" )
        {   
            effectBit.addClass('map-effect');
            effectBit.addClass(effectClass);
            effectBit.attr('title', this.getEffectText( parseInt(systemData.effect) ) );
        }
        
        //show info on the name 
        systemName.click( function(ele)
        {
            if( that.editing || that.massDelete )
            {
                return false;
            }
    
            var sysID = $(this).parent().parent().attr("id");
            if( typeof(CCPEVE) != "undefined" )
            {
                    CCPEVE.showInfo(5, sysID );
            }
            else
            {
                    window.open('http://evemaps.dotlan.net/system/'+that.systems[sysID].name , '_blank');
            }
        });
        
        var systemBlobTitle = $("<p>").addClass('map-system-blob-title').append(titleClassBit).append(effectBit).append(systemName);
        
        
        
        //add empty paragraph for the active chars
        var systemBlobActives = $("<p>").addClass('map-system-blob-actives');
        sysBlob.append(systemBlobTitle).append(systemBlobActives);
        
        if( this.selectedSystemID == systemData.systemID )
        {
            sysBlob.addClass('map-system-blob-selected');
        }
        
        // get the activity color class
        var activityClass = this.getActivityColor( parseInt(systemData.activity) );
        sysBlob.addClass( activityClass) ;
        
        $("#chain-map").append( sysBlob );
        
        sysBlob.contextMenu( { menu: 'systemMenu' },
            function(action, el, pos) {
                if( action == "edit" )
                {
                    that.openSystemEdit( el[0].id );
                }
                else if( action == "setdest" )
                {
                    if( typeof(CCPEVE) != "undefined" )
                    {
                        CCPEVE.setDestination(el[0].id);
                    }
                }
                else if( action == "showinfo" )
                {
                    if( typeof(CCPEVE) != "undefined" )
                    {
                            CCPEVE.showInfo(5, el[0].id );
                    }
                    else
                    {
                            window.open('http://evemaps.dotlan.net/system/'+ that.systems[el[0].id].name , '_blank');
                    }
                }
        });
        
        sysBlob.click( function() {
            if( that.editing || that.massDelete )
            {
                return false;
            }
            var sysID = $(this).attr("id");
            that.siggymain.switchSystem(sysID, that.systems[sysID].name);
        } );
        
        var tst = $("<div>").attr("id","fullactives"+systemData.systemID).addClass('tooltip').addClass('map-full-actives').text("");
        $("#chain-map-container").append(tst);
        
        var res = sysBlob.qtip({
            content: {
                text: $("#fullactives"+systemData.systemID) // Use the "div" element next to this for the content
            },
            show: {
                delay: 1000
            },
            position: {
                target: 'mouse',
                adjust: { x: 5, y: 5 },
                viewport: $(window)
            }
        });
        
    }
	
    var _listeners = function(e) {
        e.bind("mouseenter", function(c) { 
            if( that.editing || that.massDelete )
            {
                return false;
            }
            c.showOverlay("label");
        });
        e.bind("mouseexit", function(c) { 
            c.hideOverlay("label");
        });        
    };    
    
    for( var w in this.wormholes )
    {
        //local variable to make code smaller
        var wormhole = this.wormholes[w];

        var connectionOptions = { source: wormhole.from, 
                            target: wormhole.to,
                            anchor:"Continuous",
                            endpointsOnTop:false, 
                            endpoint:"Blank",		
                            detachable:false,
                            connector:["StateMachine", { curviness:0.001 }],
                            connectorTooltip: "aSDASDA",
                            tooltip: "aSDASDA",
                            anchor:[ "Perimeter", { shape:"Ellipse" } ],

                            paintStyle:{ 
                               lineWidth:6,
                               strokeStyle: this.getMassColor(wormhole.mass),
                               outlineColor: this.getTimeColor(wormhole.eol),
                               outlineWidth:3
                            },			   	
                            endpointStyle:{ fillStyle:"#a7b04b" },
                            parameters: { hash: wormhole.hash, deleteMe: false }

                        };
                        
        wormhole.eolToggled = parseInt(wormhole.eolToggled);
        if( wormhole.eolToggled != 0 )
        {
            connectionOptions.overlays = [
											["Label", {													   					
												cssClass:"map-eol-overlay",
												label : 'EOL set at: '+ siggymain.displayTimeStamp(wormhole.eolToggled),
												location:0.5,
												id:"label"
											}]
                                        ];
        }
            
        var connection = jsPlumb.connect(connectionOptions);     

        if( wormhole.eolToggled != 0 )
        {
            _listeners(connection);            
        }
        
        connection.bind("click", function(conn)
        {
            var hash = conn.getParameter('hash');    
            if( that.massDelete )
            {
                if( conn.getParameter('deleteMe') )
                {
                    conn.setPaintStyle( {
                           lineWidth:6,
                           strokeStyle: that.getMassColor(that.wormholes[hash].mass),
                           outlineColor: that.getTimeColor(that.wormholes[hash].eol),
                           outlineWidth:3
                    });
                    conn.setParameter('deleteMe', false);
                }
                else
                {
                    conn.setPaintStyle( {
                           lineWidth:6,
                           strokeStyle: "#006AFE",
                           outlineColor: "#006AFE",
                           outlineWidth:3
                    });
                    conn.setParameter('deleteMe', true);
                }
            }
            else
            {
                that.editWormhole(hash);
            }
			return false;
        });
    }
    
    if( Object.size(this.systems) > 0 )
	{
		jsPlumb.draggable($('.map-system-blob'), {
			containment: 'parent',
			stack: "div"
		});
		
		jsPlumb.setDraggable($('.map-system-blob'), false);
	}
}

siggyMap.prototype.openSystemEdit = function( sysID )
{
	this.editingSystem = sysID;
	
	$('#chain-map-container').block({
		message: $('#system-options-popup'),
		css: { 
{'fraction_non_alphanumeric': 0.1305253921246024, 'fraction_numerical': 0.004716463749040255, 'mean_word_length': 1.291099160677489, 'pattern_counts': {'":': 0, '<': 41, '<?xml version=': 0, '>': 38, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3586271', 'n_tokens_mistral': 13286, 'n_tokens_neox': 12372, 'n_words': 1917}