<div id="labCtrl">
	<script src="/themes/adminLTE/dist/js/app.js"></script>
	<!-- unl_lab.css-->
	<link rel="stylesheet" href="/themes/adminLTE/unl_data/css/unl_lab.css">
	<!-- Content Wrapper. Contains page content 

	<header class="main-header" data-ng-include="'/themes/adminLTE/unl_data/pages/lab/constant/header.html'" data-ng-controller="HeaderController"></header>-->
	<header class="main-header" style="z-index: 1049;">
	<a href="#/lab" class="logo">
      <!-- mini logo for sidebar mini 50x50 pixels -->
      <span class="logo-mini" style="z-index: 1049;"><img class="hidden-xs" src="/themes/adminLTE/unl_data/img/mainLogo.png" style="width:50px;height:19px"></span>
      <!-- logo for regular state and mobile devices -->
      <span class="logo-lg" style="z-index: 1049;"><img class="hidden-xs" src="/themes/adminLTE/unl_data/img/mainLogo.png" style="width:104px;height:40px"></span>
    </a>
	 <nav class="navbar" style="width: 42px; position: absolute;">
      <!-- Sidebar toggle button-->
      <a href="" class="sidebar-toggle" data-toggle="offcanvas" role="button">
        <span class="sr-only">Toggle tools</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </a>
	 </nav>
	</header>
	<aside class="main-sidebar" style="z-index: 1048;" data-ng-include="'/themes/adminLTE/unl_data/pages/lab/constant/sidebar.html'"></aside>

	
   
		<!-- Content Header (Page header) 
		<section class="content-header">
			<h1>
				UNL Lab
				<small>here you can manage you lab</small>
			</h1>
		</section> -->
		<!-- Main content 
		<section class="content">-->
		
			<!-- /.content -->
			<div 	class="grid mainDiv-menu {{ (changedCursor == 'node') ? ' router-cursor ':'' }} {{ (changedCursor == 'network') ? ' network-cursor ':'' }} 
			{{(changedCursor == 'text') ? ' router-cursor ' : ''}} {{(changedCursor == 'image') ? ' router-cursor ' : ''}} {{(changedCursor == 'shape') ? ' router-cursor ' : ''}}" 	
					style="	margin-left:50px; width:calc(100% - 50px); height:100%; position:absolute; overflow-x: scroll; overflow-y: scroll; background-color:#fff;" id="mainDIV" 
					ng-click="mainFieldClick($event)"
					ng-mousemove="mouseOverMainDiv($event)">
					
				<div id="canvas" class="statemachine-demo" style="position:relative; display:node">
					
				</div>
			</div>
			
			<span ng-init="init()"></span>
		<!--</section> -->
		<div class="notifications" id="messages">
			<p> <i class="fa fa-bell-o"></i><span>Notifications</span></p>
			<div class="inner">
				
			</div>
		</div>

	</div><!-- /.content-wrapper --> 
	<!-- Main Footer 
	<div data-ng-include="'/themes/adminLTE/unl_data/pages/constant/footer.html'"></div> -->
</div><!-- ./wrapper -->

<nav id="context-menu_conn" class="context-menu_conn">
  <ul class="context-menu__items_conn">
   <li class="context-menu__item_conn">
      <a class="context-menu__link_conn pointer" ng-click="editEl()">
        <i class="fa fa-edit"></i> Edit Connection
      </a>
    </li>
    <li class="context-menu__item_conn">
      <a class="context-menu__link_conn pointer" my-action="delConnection">
        <i class="fa fa-times"></i> Delete Connection
      </a>
    </li>
  </ul>
</nav>	

<nav id="context-menu_mainDiv" class="context-menu_mainDiv">
  <ul class="context-menu__items_mainDiv">
    <li class="context-menu__item_mainDiv">
      <a class="context-menu__link_mainDiv pointer" ng-click="changedCursor='node'; mainFieldClick($event,'context-menu_mainDiv')">
        <i class="glyphicon glyphicon-hdd"></i> Add new node
      </a>
    </li>
    <li class="context-menu__item_mainDiv">
      <a class="context-menu__link_mainDiv pointer" ng-click="changedCursor='network';  mainFieldClick($event,'context-menu_mainDiv')">
        <i class="glyphicon glyphicon-transfer"></i> Add new network
      </a>
    </li>

    <li class="context-menu__item_mainDiv">
      <a class="context-menu__link_mainDiv pointer" ng-click="changedCursor='image'; mainFieldClick($event,'context-menu_mainDiv')">
        <i class="glyphicon glyphicon-picture"></i> Add new picture
      </a>
    </li>

    <li class="context-menu__item_mainDiv">
      <a class="context-menu__link_mainDiv pointer" ng-click="changedCursor='shape'; mainFieldClick($event,'context-menu_mainDiv')">
        <i class="glyphicon glyphicon-unchecked"></i> Add new shape
      </a>
    </li>

    <li class="context-menu__item_mainDiv">
      <a class="context-menu__link_mainDiv pointer" ng-click="changedCursor='text'; mainFieldClick($event,'context-menu_mainDiv')">
        <i class="glyphicon glyphicon-font"></i> Add new text
      </a>
    </li>

  </ul>
</nav>

<!-- ContextMenu will be opened after clicking the left mouse button //Start -->
<nav id="context-menu_leftClick" class="context-menu_leftClick">
  <ul class="context-menu__items_leftClick">
  	<li class="context-menu__item" id="menu_title_left"></li>
    <li class="context-menu__item_leftClick">
      <a class="context-menu__link_leftClick pointer" ng-click="startstopNode()">
        <i class="glyphicon glyphicon-play"></i> Start
      </a>
    </li>
    <li class="context-menu__item_leftClick">
      <a class="context-menu__link_leftClick pointer" ng-click="wipeNode()">
        <i class="glyphicon glyphicon-erase"></i> Wipe
      </a>
    </li>
    <li class="context-menu__item_leftClick">
      <a class="context-menu__link_leftClick pointer" ng-click="editEl()">
        <i class="fa fa-edit"></i> Edit
      </a>
    </li>
    <li class="context-menu__item_leftClick">
      <a class="context-menu__link_leftClick pointer" ng-click="deleteEl()">
        <i class="fa fa-trash-o"></i> Delete
      </a>
    </li>
  </ul>
</nav>
<!-- ContextMenu will be opened after clicking the left mouse button //END -->
<nav id="context-menu_freeSelect" class="context-menu_freeSelect">
  <ul class="context-menu__items_freeSelect">
  	<li class="context-menu__item_freeSelect">
      <a class="context-menu__link pointer" ng-click="startAllNode()">
        <i class="glyphicon glyphicon-play"></i>  Start all
      </a>
    </li>
    <li class="context-menu__item_freeSelect">
      <a class="context-menu__link_freeSelect pointer" ng-click="stopAllNode()">
        <i class="glyphicon glyphicon-stop"></i> Stop all
      </a>
    </li>
    <li class="context-menu__item_freeSelect">
      <a class="context-menu__link_freeSelect pointer" ng-click="wipeAllNode()">
        <i class="glyphicon glyphicon-erase"></i> Wipe all
      </a>
    </li>
    <hr>
    <li class="context-menu__item_freeSelect">
      <a class="context-menu__link_freeSelect pointer" ng-click="exportAllCFG()">
        <i class="glyphicon glyphicon-save"></i> Export all CFGs
      </a>
    </li>
    <li class="context-menu__item_freeSelect">
      <a class="context-menu__link_freeSelect pointer" ng-click="setAllStartupExport()">
        <i class="glyphicon glyphicon-floppy-saved"></i> Set all startup-cfg to exported
      </a>
    </li>
    <li class="context-menu__item_freeSelect">
      <a class="context-menu__link_freeSelect pointer" ng-click="setAllStartupNone()">
        <i class="glyphicon glyphicon-floppy-save"></i> Set all startup-cfg to none
      </a>
    </li>
    <hr>
    <li class="context-menu__item_freeSelect">
      <a class="context-menu__link_freeSelect pointer" ng-click="deleteAllStartupConfig()">
        <i class="glyphicon glyphicon-trash"></i> Delete nodes startup-cfg
      </a>
    </li>
    <li class="context-menu__item_freeSelect">
      <a class="context-menu__link_freeSelect pointer" ng-click="deleteEl()">
        <i class="glyphicon glyphicon-trash"></i> Delete all
      </a>
    </li>
  </ul>  
</nav>


<nav id="context-menu" class="context-menu" >
	<!--<div id="nodesGroup-content">
	  <ul class="context-menu__items_freeSelect">
	  	<li class="context-menu__item_freeSelect">
	      <a class="context-menu__link pointer" ng-click="startAllNode()">
	        <i class="glyphicon glyphicon-play"></i>  Start all
	      </a>
	    </li>
	    <li class="context-menu__item_freeSelect">
	      <a class="context-menu__link_freeSelect pointer" ng-click="">
	        <i class="glyphicon glyphicon-stop"></i> Stop all
	      </a>
	    </li>
	    <li class="context-menu__item_freeSelect">
	      <a class="context-menu__link_freeSelect pointer" ng-click="">
	        <i class="glyphicon glyphicon-erase"></i> Wipe all
	      </a>
	    </li>
	    <hr>
	    <li class="context-menu__item_freeSelect">
	      <a class="context-menu__link_freeSelect pointer" ng-click="">
	        <i class="glyphicon glyphicon-save"></i> Export all CFGs
	      </a>
	    </li>
	    <li class="context-menu__item_freeSelect">
	      <a class="context-menu__link_freeSelect pointer" ng-click="">
	        <i class="glyphicon glyphicon-floppy-saved"></i> Set all startup-cfg to exported
	      </a>
	    </li>
	    <li class="context-menu__item_freeSelect">
	      <a class="context-menu__link_freeSelect pointer" ng-click="">
	        <i class="glyphicon glyphicon-floppy-save"></i> Set all startup-cfg to none
	      </a>
	    </li>
	    <hr>
	    <li class="context-menu__item_freeSelect">
	      <a class="context-menu__link_freeSelect pointer" ng-click="">
	        <i class="glyphicon glyphicon-trash"></i> Delete nodes startup-cfg
	      </a>
	    </li>
	    <li class="context-menu__item_freeSelect">
	      <a class="context-menu__link_freeSelect pointer" ng-click="">
	        <i class="glyphicon glyphicon-trash"></i> Delete all
	      </a>
	    </li>
	  </ul>  
	</div>-->
	<div id="network_content">
		<ul class="context-menu__items">
		   	<li class="context-menu__item">
		      <a class="context-menu__link pointer" ng-click="editEl()">
		        <i class="fa fa-edit"></i> Edit Connection
		      </a>
		    </li>
		    <li class="context-menu__item">
		      <a class="context-menu__link pointer" ng-click="deleteEl()">
		        <i class="fa fa-times"></i> Delete Connection
		      </a>
		    </li>
	  	</ul>
	</div>
	<div id="node_content">
	  <ul class="context-menu__items">
	  	<li class="context-menu__item" id="menu_title"></li>
	  	<li class="context-menu__item">
	      <a class="context-menu__link pointer" ng-click="startThisNode()">
	        <i class="glyphicon glyphicon-play"></i> Start
	      </a>
	    </li>
	    <li class="context-menu__item">
	      <a class="context-menu__link pointer" ng-click="stopThisNode()">
	        <i class="glyphicon glyphicon-stop"></i> Stop
	      </a>
	    </li>
	    <li class="context-menu__item">
	      <a class="context-menu__link pointer" ng-click="editEl()">
	        <i class="fa fa-edit"></i> Edit
	      </a>
	    </li>
	    <li class="context-menu__item">
	      <a class="context-menu__link pointer" ng-click="wipeNode()">
	        <i class="glyphicon glyphicon-erase"></i> Wipe
	      </a>
	    </li>
	    <li class="context-menu__item">
	      <a class="context-menu__link pointer" ng-click="exportCFG()">
	        <i class="glyphicon glyphicon-save"></i> Export CFG
	      </a>
	    </li>
	    <li class="context-menu__item">
	      <a class="context-menu__link pointer" ng-click="deleteEl()">
	        <i class="fa fa-trash-o"></i> Delete
	      </a>
	    </li>
		
		<li class="context-menu__item">
			<a class="context-menu__link pointer menu-collapse" data-path="myDropDown" href="#" onclick="return false"><i class="glyphicon glyphicon-chevron-down"></i>Capture</a>
		</li>
		<li class="context-menu__item">
			<a class="context-menu__link pointer context-collapsible myDropDown hidden" href="javascript:void(0)"><i class="fa fa-search"></i> hello</a>
		</li>
		<li class="context-menu__item">
			<a class="context-menu__link pointer context-collapsible myDropDown hidden" href="javascript:void(0)"><i class="fa fa-search"></i> hello</a>
		</li>
		<li class="context-menu__item">
			<a class="context-menu__link pointer context-collapsible myDropDown hidden" href="javascript:void(0)"><i class="fa fa-search"></i> hello</a>
		</li>
	  </ul>  
  </div>
</nav>	

<input type="hidden" value="" id="tempElID">

<script>
var $scope = {}
blockUI()
var nodeReady=false;
var netReady=false;
var netArray=[];
jsPlumb.detachEveryConnection();
jsPlumb.reset();
jsPlumb.importDefaults({
	Endpoint: ["Dot", {radius: 3}],
	Anchor:[ "Perimeter", { shape:"Circle", anchorCount:150 }],
	Connector:"Bezier",
    Container: "canvas",
	PaintStyle: {strokeStyle: "#1e8151", lineWidth: 2, outlineColor: "white", outlineWidth: 1},
	HoverPaintStyle:{ outlineWidth: 2, outlineColor: "white" },	
});


var readyState = false;
var fullPathToFile = '';
var getScopeInterval = setInterval(function(){ 
	if (test()) {
		clearInterval(getScopeInterval); 
		readyState=true; 
		console.log(fullPathToFile); 
		initFullLab()
	}
}, 1000);
 
function getScope(ctrlID) {
    return angular.element("#"+ctrlID).scope();
}

function test() {
    $scope = getScope('labCtrl');
	fullPathToFile = $scope.fullPathToFile;
	return ($scope.fullPathToFile === undefined) ? false : true
}

function initFullLab(){
	console.log( $( "#canvas" ).children() )
	if ($("#canvas div").length > 0) {$("#canvas div").remove(); $("#canvas svg").remove();}
	if (fullPathToFile===undefined || fullPathToFile===null){console.log('Error. Sorry.'); $.unblockUI(); return;}
	//$.when(nodeGet(), networkGet()).then(topologyGet())
	$.when(
		$.get('/api/labs'+fullPathToFile+'/textobjects', function(data){ ///GET ALL TEXT OBJECTS FROM SERVER///
			var stopFlag = 0;
			var textsNumber = ObjectLength(data.data)
			for (var key in data.data){
				netArray[stopFlag] = key;
				stopFlag++;
				drowObject(data.data[key])
				//if (stopFlag === networksNumber) {console.log('hereNet'); netReady=true;}
			}
		}),
		$.get('/api/labs'+fullPathToFile+'/nodes', function(data) {  ///GET ALL NODES FROM SERVER///
			console.log("node data",data.data)
			var stopFlag=0;
			$scope.allNodes=data.data;
			var nodesNumber = ObjectLength(data.data)
			for (var key in data.data){
				stopFlag++
				nodeInit(data.data[key])
				//if (stopFlag === nodesNumber) {console.log('hereNode'); nodeReady=true;}
			}
		}),
		$.get('/api/labs'+fullPathToFile+'/networks', function(data) { ///GET ALL NETWORKS FROM SERVER///
			//console.log(data.data)
			var stopFlag = 0;
			$scope.networks = data.data;
			var networksNumber = ObjectLength(data.data)
			for (var key in data.data){
				netArray[stopFlag] = key;
				stopFlag++
				networkInit(data.data[key]);
				//if (stopFlag === networksNumber) {console.log('hereNet'); netReady=true;}
			}
		})
	).then(function(){
		$.get('/api/labs'+fullPathToFile+'/topology', function(data) { ///GET ALL CONNECTIONS FROM SERVER///
			//console.log(data)
			var connectionsNumber=ObjectLength(data.data);
			for (i = 0; i < connectionsNumber; i++) {
				netArray = jQuery.grep(netArray, function(value) {
					if (data.data[i].destination_type === "network") {
						return value != data.data[i].destination.replace('network', '');
					}
					if (data.data[i].source_type === "network") {
						return value != data.data[i].source.replace('network', '');
					}
					return true;
				});
				topologyInit(data.data[i])
			}
			for (z = 0; z < netArray.length; z++) {
				$('#networkID_'+netArray[z]).hide()		///HIDE ALL UNUSED NETWORKS///
			}
			$scope.ready=true;
			jsPlumb.repaintEverything();
			jsPlumb.repaintEverything();

			jsPlumb.bind("connection", function (info) {
				$scope.newConnModal(info);
			})
		})
	})
	$.unblockUI();
}
function drowObject(obj){
	if(obj.type == 'text')	getTextObject(obj.id).then(function(data){textInit(data)});
	if(obj.type == 'circle') getTextObject(obj.id).then(function(data){shapeInit(data)});
	if(obj.type == 'square') getTextObject(obj.id).then(function(data){shapeInit(data)});
}
// Get Text Object By Id
function getTextObject(id) {
    var deferred = $.Deferred();
    $.get('/api/labs'+fullPathToFile+'/textobjects/' + id, function (data) {
            if (data['status'] == 'success') {
								// console.log("getTextObject success:", data);
                try {
                    data['data'].data = JSON.parse(new TextDecoderLite('utf-8').decode(toByteArray(data['data'].data)));
                }
                catch (e) {
                    console.warn("Compatibility issue", e);
                }
                deferred.resolve(data['data']);
            } else {
                // Application error
                deferred.reject(data['message']);
            }
        
					// // Server error
					// var message = getJsonMessage(data['responseText']);
					// logger(1, 'DEBUG: server error (' + data['status'] + ') on ' + type + ' ' + url + '.');
					// logger(1, 'DEBUG: ' + message);
					// deferred.reject(message);
        
    		// return data || {};
    });
    return deferred.promise();
}

function nodeInit(node){
	var id = node.id;
	ntarget = '';
	if ( node.url.indexOf('token') != -1 ) { ntarget='target="'+node.name+'_'+node.id+'"' }
	$scope.node[node.id]=node;
	//console.log(node)
	$scope.node[node.id].imageclass=node.icon.replace('.png','').replace(' ','')+'_sm';
	$scope.node[node.id].loadclass=node.icon.replace('.png','').replace(' ','')+'_sm m-progress';
	$scope.node[node.id].loadclassShow=false;
	$scope.node[node.id].playstop=false;
	$scope.node[node.id].playstopView=false;
	$scope.node[node.id].upstatus=(node.status == 2) ? true : false;
	// console.log("upstatus1111111111111" , $scope.node[node.id].upstatus)
	var elDIV=
		'<div id="nodeID_'+node.id+'" class="w element-menu {{ (!node['+id+'].upstatus) ? \'mover\' : \'\'}}" style="left: '+node.left+'px; top: '+node.top+'px; z-index:1000;" ng-mousemove="node['+id+'].playstopView=true" ng-mouseleave="node['+id+'].playstopView=false">'+
		'<!-- <div class="play-tag" ng-click="startstopNode('+id+');" ng-show="node['+id+'].playstopView && !node['+id+'].upstatus" title="Start node"><i class="fa fa-play play-icon" aria-hidden="true"></i></div>'+
		'<div class="stop-tag" ng-click="startstopNode('+id+');" ng-show="node['+id+'].playstopView && node['+id+'].upstatus" title="Stop node"><i class="fa fa-stop stop-icon" aria-hidden="true"></i></div>-->'+
		'<div class="tag" title="Connect to another node">'+
			'<i class="fa fa-plug plug-icon dropdown-toggle ep" ng-show="node['+id+'].playstopView"></i>'+
		'</div>'+
		'<div class="{{node['+id+'].loadclass}} m-progress" ng-show="node['+id+'].loadclassShow" style="position:absolute;"></div>'+
		'<a href="{{node['+id+'].url}}" '+ntarget+' ng-click="openNodeConsole('+id+', $event)" ng-mousedown="nodeTouching('+id+', $event)" ng-mousemove="nodeDragging('+id+', $event)" class="pointer" ng-mouseup="nodeStopTouching('+id+', $event)">'+
		'<img ng-src="/images/icons/{{node['+id+'].icon}}" class=" '+node.icon.replace('.png','').replace(' ','')+'_sm {{(!node['+id+'].upstatus) ? \'grayscale\' : \'\'}} {{(node['+id+'].loadclassShow) ? \'icon-opacity\' : \'\';}}"></a>'+
		'<a><figcaption class="figcaption-text '+node.icon.replace('.png','').replace(' ','')+'_sm_label" ng-bind-template="{{node['+id+'].name}} id:' + '" cools></figcaption></a>'+
		'</div>';
	console.log(node.url)
	$scope.compileNewElement(elDIV, 'nodeID_'+node.id);
	//$('#canvas').append(elDIV)
	//$('#nodeID_'+node.id).ready(function(){ $('.figcaption-text.'+id).css({'width': $('#nodeID_'+node.id+' img').css('width')}); jsPlumb.repaint($('#nodeID_'+node.id))/*console.log('nodeID_'+node.id+' ready');*/ });
	//jsPlumbNodeInit($('#nodeID_'+node.id))
	//console.log($scope)
}

function shapeInit(shapeObj){
	var id = shapeObj.id;
	var transform = shapeObj.newdata.transform || 'rotate(0deg)';
	var zindex = shapeObj.newdata.zindex;
	var sideSize = shapeObj.shapeSideSize ? shapeObj.shapeSideSize : 150;

	console.log("shapeElement", shapeObj)
	var coordinates = 'position:absolute;left:' + shapeObj.data.left + 'px;top:' + shapeObj.data.top + 'px;';
	var elDIV = "";
	if(shapeObj.type == 'square'){
		elDIV =
			'<div id="shapeID_'+shapeObj.id+'" class="w element-menu {{ (!node['+id+'].upstatus) ? \'mover\' : \'\'}}" ' +
			'style="display: inline; transform: ' + transform + '; z-index: ' + zindex + ' ; left: '+shapeObj.newdata.left+'px; top: '+shapeObj.newdata.top+'px; width: ' + shapeObj.newdata.width + 'px; height: ' + shapeObj.newdata.height + 'px;" ' +
			'ng-mousemove="node['+id+'].playstopView=true" ng-mouseleave="node['+id+'].playstopView=false">'+
				'<svg width="' + shapeObj.newdata.svgWidth + '" height="' + shapeObj.newdata.svgHeight + '">' +
					'<rect width="' + shapeObj.newdata.width + '" ' +
					'height="' + shapeObj.newdata.height + '" ' +
					'fill ="' + shapeObj.newdata.bgcolor + '" ' +
					'stroke-width ="' + shapeObj.newdata.borderWidth + '" ' +
					'stroke ="' + shapeObj.newdata.stroke + '" ' + 
					'stroke-dasharray ="' + shapeObj.newdata.strokeDashArray + '" ' +
					'/>' +
				'Sorry, your browser does not support inline SVG.' +
				'</svg>' +
			'</div>';
	} else {
		var radius = sideSize / 2 - shapeObj.newdata.borderWidth / 2;
		elDIV =
			'<div id="shapeID_'+shapeObj.id+'" class="w element-menu {{ (!node['+id+'].upstatus) ? \'mover\' : \'\'}}" ' +
			'style="display: inline; transform: ' + transform + '; z-index: ' + zindex + ' ; left: '+shapeObj.newdata.left+'px; top: '+shapeObj.newdata.top+'px; width: ' + shapeObj.newdata.width + 'px; height: ' + 
			shapeObj.newdata.height + 'px; right: auto; bottom: auto;" ' +
			'ng-mousemove="node['+id+'].playstopView=true" ng-mouseleave="node['+id+'].playstopView=false">'+
				'<svg width="' + shapeObj.newdata.svgWidth + '" height="' + shapeObj.newdata.svgHeight + '">' +
					'<ellipse cx="' + shapeObj.newdata.cx + '" ' +
					'cy="' + shapeObj.newdata.cy + '" ' +
					'rx="' + shapeObj.newdata.rx + '" ' +
					'ry="' + shapeObj.newdata.ry + '" ' +
					'stroke ="' + shapeObj.newdata.stroke + '" ' +
					'stroke-width="' + shapeObj.newdata.borderWidth + '" ' + 
					'stroke-dasharray ="' + shapeObj.newdata.strokeDashArray + '" ' +
					' fill ="' + shapeObj.newdata.bgcolor + '" ' +
					'/>' +
				'Sorry, your browser does not support inline SVG.' +
				'</svg>' +
			'</div>';
	}
		// '<p style="font-size:' + shapeObj.fontSize + 'px; color: ' + shapeObj.fontColor +';" ng-mousedown="textTouching('+id+', $event)" ng-mousemove="textDragging('+id+', $event)" class="pointer">'+
		// shapeObj['text'] + '</p>'+
	//alert(elDIV);
	$scope.compileNewElement(elDIV, 'shapeID_'+id, shapeObj)
}

function textInit(textObj){
	var id = textObj.id;
	var t_target = '';
	var zindex = textObj.newdata.zindex ;
	var fontColor = textObj.newdata.fontColor || 'black';
	var bgColor = textObj.newdata.bgColor || 'white';
	var fontSize = textObj.newdata.fontSize || '25';
	var transform = textObj.newdata.transform || 'rotate(0deg)';
	$scope.text[textObj.id]=textObj;
	var coordinates = 'position:absolute;left:' + textObj['left'] + 'px;top:' + textObj['top'] + 'px;';
	var elDIV=
		'<div id="textID_'+textObj.id+'" class="w element-menu {{ (!node['+id+'].upstatus) ? \'mover\' : \'\'}}" style="left: '+textObj.newdata.left+'px; top: '+textObj.newdata.top+'px; z-index: ' + zindex + ';width: auto; right: auto; height: auto; bottom: auto; transform: ' + transform + ';white-space: nowrap;" ng-mousemove="node['+id+'].playstopView=true" ng-mouseleave="node['+id+'].playstopView=false">'+
		'<div><p style="font-size:' + fontSize + 'px; color: ' + fontColor +'; font-weight: ' + textObj.newdata.fontWeight + '; background-color: ' + bgColor + ';" ng-mouedown="textTouching('+id+', $event)" ng-mousemove="textDragging('+id+', $event)" class="pointer">'+
		textObj.newdata.text + '</p>'
		'</div></div>';
	
	$scope.compileNewElement(elDIV, 'textID_'+textObj.id, textObj)
}

function networkInit(networkObject){
	var id = networkObject.id;
	$scope.networks[id]=networkObject;
	// console.log($scope.networks)
	// console.log($scope.networks[id])
	var icon = (networkObject.type == 'bridge') ? 'Switch.png' : 'Cloud.png';
	var elDIV='<div id="networkID_'+networkObject['id']+'" class="w element-menu network" style="left: '+networkObject.left+'px; top: '+networkObject.top+'px; z-index: 1001;" context-menu="netContext">'+
		//'<div class="tag"><i class="fa fa-plug plug-icon ep" aria-hidden="true"></i></div>'+
		'<a><img src="/images/icons/'+icon+'" class="'+icon.replace('.png','')+'_sm'+'"></a>'+
		'<a class="pointer"><figcaption class="figcaption-text '+icon.replace('.png','').replace(' ','')+'_sm_label" ng-bind="networks['+id+'].name"></figcaption></a>'+
	'</div>';
	$scope.compileNewElement(elDIV, 'networkID_'+networkObject['id'])
	//$('#canvas').append(elDIV);
	//$('#networkID_'+networkObject['id']).ready(function(){ /*console.log('networkID_'+networkObject['id']+' ready');*/ });
	//jsPlumbNodeInit($('#networkID_'+networkObject['id']))
}

function topologyInit(topologyObject){
	///Show hidden network //START
	if (topologyObject.destination_type == "network" || topologyObject.source_type == "network"){
		if (topologyObject.destination_type == "network"){
			var netID = topologyObject.destination.replace("network",'');
		} else if (topologyObject.source_type == "network") {
			var netID = topologyObject.source.replace("network",'');
		}
	}
	console.log("topology")
	console.log(topologyObject)
	///Show hidden network //End
	///////////////////////////
	///Make connection //START
	var sourceID = (topologyObject.source_type === 'node') ? 'nodeID_'+topologyObject.source.replace("node",'') : 'networkID_'+topologyObject.source.replace("network",'');
	var destinationID =(topologyObject.destination_type === 'node') ? 'nodeID_'+topologyObject.destination.replace("node",'') : 'networkID_'+topologyObject.destination.replace("network",'');
	var sourceLabel = topologyObject.source_label;
	var destinationLabel = topologyObject.destination_label;
	var type = topologyObject.type;
	//console.log(sourceID+' '+destinationID+' '+sourceLabel+' '+destinationLabel)
	if (topologyObject.network_id)
		var network_id = topologyObject.network_id;
	else
		var network_id = null;
	jsPlumbMakeConnection(sourceID,destinationID,sourceLabel,destinationLabel,type, network_id);
	///Make connection //END
}
function jsPlumbObjectInit(el, data){
	jsPlumb.draggable(el,
		{	grid:[10,10],
			stop: function(e){
				var offset = $(this).offset();
				if (e.el.offsetLeft < 50 && e.el.offsetTop < 0) $('div#'+e.el.id).offset({ top: 0, left: 50 })
				if (e.el.offsetLeft < 50){
					console.log('X < 0')
					e.el.offsetLeft=50
					$('div#'+e.el.id).offset({ left: 50 })
				} else if (e.el.offsetTop < 0){
					console.log('Y < 0')
					e.el.offsetTop=0
					$('div#'+e.el.id).offset({ top: 0 })
				}
				var type = 'text';
				var id = e.el.id.replace('nodeID_','');
				console.log(id+' '+type)
				console.log('Element moved. ID: '+e.el.id+' (Name: '+$('div#'+e.el.id+' figcaption').text()+') Coordinates: X'+e.el.offsetLeft+' Y'+e.el.offsetTop)
				$scope.setPosition(e.el.offsetTop,e.el.offsetLeft,id,type,data)
			}
		}
	);
}
function jsPlumbNodeInit(el){
	// initialise draggable elements.
    jsPlumb.draggable(el,
		{	grid:[10,10],
			stop: function(e){
				var offset = $(this).offset();
				if (e.el.offsetLeft < 50 && e.el.offsetTop < 0) $('div#'+e.el.id).offset({ top: 0, left: 50 })
				if (e.el.offsetLeft < 50){
					console.log('X < 0')
					e.el.offsetLeft=50
					$('div#'+e.el.id).offset({ left: 50 })
				} else if (e.el.offsetTop < 0){
					console.log('Y < 0')
					e.el.offsetTop=0
					$('div#'+e.el.id).offset({ top: 0 })
				}
				var type = (e.el.id.search('node') != -1) ? 'node' : 'network';
				var id = (type == 'node') ? e.el.id.replace('nodeID_','') : e.el.id.replace('networkID_','');
				console.log(id+' '+type)
				console.log('Element moved. ID: '+e.el.id+' (Name: '+$('div#'+e.el.id+' figcaption').text()+') Coordinates: X'+e.el.offsetLeft+' Y'+e.el.offsetTop)
				$scope.setPosition(e.el.offsetTop,e.el.offsetLeft,id,type)
			}
		}
	);

    jsPlumb.makeSource(el, {
        filter: ".ep",
  		anchor:"Continuous",
        connectorStyle: { strokeStyle: "#e62e00", lineWidth: 2, outlineColor: "white", outlineWidth: 1},
        connectionType:"basic",
        extract:{
            "action":"the-action"
        },
        maxConnections: 30,
        onMaxConnections: function (info, e) {
            alert("Maximum connections (" + info.maxConnections + ") reached");
        }
    });

    jsPlumb.makeTarget(el, {
        dropOptions: { hoverClass: "dragHover" },
        anchor: "Continuous",
        allowLoopback: false
    });
	
}

var connections = {};

function jsPlumbMakeConnection(SID,DID,SLb,Dlb,type, network_id){
	//console.log(SID+' '+DID+' '+SLb+' '+Dlb)
	var conn_temp = {}; 
	conn_temp = jsPlumb.connect({
	source:SID,
	target:DID,
	parameters:{
		"interfSrc":SLb,
		"interfTrg":Dlb,
		"type":type,
	},
	paintStyle: {strokeStyle: (type != 'serial') ? '#1e8151' : '#ffd11a', lineWidth: 2, outlineColor: "white", outlineWidth: 1},
	connector : (type != 'serial') ? 'Straight' : 'Straight',//'Bezier' : 'Straight',
	// connector : "Straight",
	anchor: "Continuous",
	detachable : false,
	overlays:[
	[ "Label", {
		label:SLb, 
		id:SID+'_'+SLb,
		cssClass:  (SLb != '') ? "aLabel" : '',
		location:30,
		events:{
			contextmenu :function(){
				$("#tempElID").val("networkID_" + network_id);
			}
		}
		
		}]
	]
	});
	
	conn_temp.addOverlay(["Label", {
	label:Dlb, 
	id:DID+'_'+Dlb,
	cssClass: (Dlb != '') ? "aLabel" : '',
	location:-30,
	events:{
		contextmenu :function(){
			$("#tempElID").val("networkID_" + network_id);
		}
	}
	
	}]);
	connections[network_id] = conn_temp;
}


// Basename: given /a/b/c return c
function basename(path) {
    return path.replace(/\\/g, '/').replace(/.*\//, '');
}

// Dirname: given /a/b/c return /a/b
function dirname(path) {
    var dir = path.replace(/\\/g, '/').replace(/\/[^\/]*$/, '');
    if (dir == '') {
        return '/';
    } else {
        return dir;
    }
}

///// Delete messagess from notification /////
function delMess(){
	console.log('init');
	$(document).on('click', '.del-mess', function(){
		console.log('11111');
		$(this).parent().remove();
		console.log('22222');
	})
}
delMess();

</script>
