ganttMaster_wev8.js 39.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 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
function GanttMaster() {
  this.tasks = [];
  this.deletedTaskIds = [];
  this.links = [];

  this.editor; //element for editor
  this.gantt; //element for gantt
  this.splitter; //element for splitter
  this.element;

  this.resources; //list of resources
  this.roles;  //list of roles

  this.minEditableDate = 0;
  this.maxEditableDate = Infinity;

  this.canWriteOnParent = true;
  this.canWrite = true;

  this.firstDayOfWeek = Date.firstDayOfWeek;

  this.currentTask; // task currently selected;

  this.resourceUrl = 'res/'; // URL to resources (images etc.)
  this.__currentTransaction;  // a transaction object holds previous state during changes
  this.__undoStack = [];
  this.__redoStack = [];
  this.__inUndoRedo = false; // a control flag to avoid Undo/Redo stacks reset when needed

  var self = this;
}

GanttMaster.prototype.init = function (place) {
  this.element = place;
  var self = this;
  //load templates
  $("#gantEditorTemplates").loadTemplates().remove();

  //create editor
  this.editor = new GridEditor(this);
  place.append(this.editor.gridified);

  //create gantt
  this.gantt = new Ganttalendar("m", new Date().getTime() - 3600000 * 24 * 2, new Date().getTime() + 3600000 * 24 * 15, this, place.width() * .6);

  //setup splitter
  self.splitter = $.splittify.init(place, this.editor.gridified, this.gantt.element, 60);
  self.splitter.firstBoxMinWidth=30;

  //prepend buttons
  place.before($.JST.createFromTemplate({}, "GANTBUTTONS"));

  //bindings
  place.bind("refreshTasks.gantt",function () {
    self.redrawTasks();
  }).bind("refreshTask.gantt",function (e, task) {
      self.drawTask(task);
    }).bind("deleteCurrentTask.gantt",function (e) {
      self.deleteCurrentTask();
    }).bind("addAboveCurrentTask.gantt",function () {
      self.addAboveCurrentTask();
    }).bind("addBelowCurrentTask.gantt",function () {
      self.addBelowCurrentTask();
    }).bind("indentCurrentTask.gantt",function () {
      self.indentCurrentTask();
    }).bind("outdentCurrentTask.gantt",function () {
      self.outdentCurrentTask();

    }).bind("moveUpCurrentTask.gantt",function () {
      self.moveUpCurrentTask();

    }).bind("moveDownCurrentTask.gantt",function () {
      self.moveDownCurrentTask();

    }).bind("zoomPlus.gantt",function () {
      self.gantt.zoomGantt(true);
    }).bind("zoomMinus.gantt",function () {
      self.gantt.zoomGantt(false);
    }).bind("zoomChange",function () {
      self.gantt.zoomGantt1();
    }).bind("undo.gantt",function () {
      if(!self.canWrite)
        return;
      self.undo();
    }).bind("redo.gantt", function () {
      if(!self.canWrite)
        return;
      self.redo();
    }).bind("resize.gantt", function () {
      self.resize();
    });

    //keyboard management bindings
  $("body").bind("keydown.body", function (e) {
    //console.debug(e.keyCode+ " "+e.target.nodeName)

    //manage only events for body -> not from inputs
    if (e.target.nodeName.toLowerCase() == "body" || e.target.nodeName.toLowerCase() == "svg") { // chrome,ff receive "body" ie "svg"
      //something focused?
      //console.debug(e.keyCode, e.ctrlKey)
      var eventManaged=true;
      switch (e.keyCode) {
        case 46: //del
        case 8: //backspace
          var focused = self.gantt.element.find(".focused.focused");// orrible hack for chrome that seems to keep in memory a cached object
          if (focused.is(".taskBox")) { // remove task
            self.deleteCurrentTask();
          } else if (focused.is(".linkGroup")) {
            self.removeLink(focused.data("from"), focused.data("to"));
          }
          break;

        case 38: //up
          if (self.currentTask) {
            if (self.currentTask.ganttElement.is(".focused")) {
              self.moveUpCurrentTask();
              self.gantt.element.oneTime(100, function () {self.currentTask.ganttElement.addClass("focused");});

            } else {
              self.currentTask.rowElement.prev().click();
            }
          }
          break;

        case 40: //down
          if (self.currentTask) {
            if (self.currentTask.ganttElement.is(".focused")) {
              self.moveDownCurrentTask();
              self.gantt.element.oneTime(100, function () {self.currentTask.ganttElement.addClass("focused");});
            } else {
              self.currentTask.rowElement.next().click();
            }
          }
          break;

        case 39: //right
          if (self.currentTask) {
            if (self.currentTask.ganttElement.is(".focused")) {
              self.indentCurrentTask();
              self.gantt.element.oneTime(100, function () {self.currentTask.ganttElement.addClass("focused");});
            }
          }
          break;

        case 37: //left
          if (self.currentTask) {
            if (self.currentTask.ganttElement.is(".focused")) {
              self.outdentCurrentTask();
              self.gantt.element.oneTime(100, function () {self.currentTask.ganttElement.addClass("focused");});
            }
          }
          break;


        case 89: //Y
          if (e.ctrlKey) {
            self.redo();
          }
          break;

        case 90: //Z
          if (e.ctrlKey) {
            self.undo();
          }
          break;

        default :{
          eventManaged=false;
        }

      }
      if (eventManaged){
        e.preventDefault();
        e.stopPropagation();
      }
    }
  });
};

GanttMaster.messages = {
  "CANNOT_WRITE":"CANNOT_WRITE",
  "CHANGE_OUT_OF_SCOPE":"NO_RIGHTS_FOR_UPDATE_PARENTS_OUT_OF_EDITOR_SCOPE",
  "START_IS_MILESTONE":"START_IS_MILESTONE",
  "END_IS_MILESTONE":"END_IS_MILESTONE",
  "TASK_HAS_CONSTRAINTS":"TASK_HAS_CONSTRAINTS",
  "GANTT_ERROR_DEPENDS_ON_OPEN_TASK":"GANTT_ERROR_DEPENDS_ON_OPEN_TASK",
  "GANTT_ERROR_DESCENDANT_OF_CLOSED_TASK":"GANTT_ERROR_DESCENDANT_OF_CLOSED_TASK",
  "TASK_HAS_EXTERNAL_DEPS":"TASK_HAS_EXTERNAL_DEPS",
  "GANTT_ERROR_LOADING_DATA_TASK_REMOVED":"GANTT_ERROR_LOADING_DATA_TASK_REMOVED",
  "CIRCULAR_REFERENCE":"CIRCULAR_REFERENCE",
  "ERROR_SETTING_DATES":"ERROR_SETTING_DATES",
  "CANNOT_DEPENDS_ON_ANCESTORS":"CANNOT_DEPENDS_ON_ANCESTORS",
  "CANNOT_DEPENDS_ON_DESCENDANTS":"CANNOT_DEPENDS_ON_DESCENDANTS",
  "INVALID_DATE_FORMAT":"INVALID_DATE_FORMAT",
  "GANTT_QUARTER_SHORT": "GANTT_QUARTER_SHORT",
  "GANTT_SEMESTER_SHORT":"GANTT_SEMESTER_SHORT",
  "CANNOT_CLOSE_TASK_IF_OPEN_ISSUE":"CANNOT_CLOSE_TASK_IF_OPEN_ISSUE",
  "Message1":"Message1",
  "Message2":"Message2",
  "Message3":"Message3",
  "Message4":"Message4",
  "Message5":"Message5",
  "Message6":"Message6",
  "Message7":"Message7",
  "Message8":"Message8"
};


GanttMaster.prototype.createTask = function (id, name, code, level, start, duration) {
  var factory = new TaskFactory();
  return factory.build(id, name, code, level, start, duration);
};


GanttMaster.prototype.createResource = function (id, name) {
  var res = new Resource(id, name);
  return res;
};


//update depends strings
GanttMaster.prototype.updateDependsStrings = function () {
  //remove all deps
  for (var i = 0; i < this.tasks.length; i++) {
    this.tasks[i].depends = "";
  }

  for (var i = 0; i < this.links.length; i++) {
    var link = this.links[i];
    var dep = link.to.depends;
    link.to.depends = link.to.depends + (link.to.depends == "" ? "" : ",") + (link.from.getRow() + 1) + (link.lag ? ":" + link.lag : "");
  }

};

GanttMaster.prototype.removeLink = function (fromTask,toTask) {
  if (!this.canWrite || (!fromTask.canWrite && !toTask.canWrite))
    return;

  this.beginTransaction();
  var found = false;
  for (var i = 0; i < this.links.length; i++) {
    if (this.links[i].from == fromTask && this.links[i].to == toTask) {
      this.links.splice(i, 1);
      found = true;
      break;
    }
  }

  if (found) {
    this.updateDependsStrings();
    if (this.updateLinks(toTask))
      //fake change to force date recomputation from dependencies
      this.changeTaskDates(toTask, toTask.start, toTask.end,toTask.starttime,toTask.endtime,toTask.passnoworktime); 
  }
  this.endTransaction();
};

GanttMaster.prototype.removeAllLinks = function (task,openTrans) {
  //console.debug("removeLink");
  if (!this.canWrite || (!task.canWrite && !task.canWrite))
    return;

  if (openTrans)
    this.beginTransaction();
  var found = false;
  for (var i = 0; i < this.links.length; i++) {
    if (this.links[i].from == task || this.links[i].to == task) {
      this.links.splice(i, 1);
      found = true;
    }
  }

  if (found) {
    this.updateDependsStrings();
  }
  if (openTrans)
    this.endTransaction();
};

GanttMaster.prototype.b_onChange = function(task,value){
	//结束日期不能小于开始日期
	 var taskid = task.id;
	  //开始日期不能大于结束日期
	  var enddate_v = $("#enddate_"+taskid).val();
	  if(enddate_v&&value>enddate_v){
		  //alert("开始日期不能大于结束日期");
		  alert(GanttMaster.messages["Message7"]);
		  setTimeout(
			  function timer() {
				$(".begindateDiv_"+taskid+"_e9").find(".text").html(enddate_v);
				$("#begindateDiv_"+taskid+"_e9Name").val(enddate_v);
			  },100);
		$("#begindate_"+taskid).val(enddate_v);
	  }else{
		$("#begindate_"+taskid).val(value);
	  }
	  
		  var self = task;
	      var inp = $("#begindate_"+taskid);  
	      if (inp.isValueChanged()) {
	        if (!Date.isValid(inp.val())) {
	        	//alert(GanttMaster.messages["INVALID_DATE_FORMAT"]);
	        	setTimeout(
					  function timer() {
						$(".begindateDiv_"+taskid+"_e9").find(".text").html(inp.getOldValue())
						$("#begindateDiv_"+taskid+"_e9Name").val(inp.getOldValue());
					  },100);
	        	inp.val(inp.getOldValue());
	        } else {
	          var date = Date.parseString(inp.val());
	          var row = inp.closest("tr");
	          var lstart = task.start;
	          var lend = task.end;
	          var lstarttime = task.starttime;
	          var lendtime = task.endtime;
	          var passnoworktime = task.passnoworktime;

	          if (inp.attr("name") == "start") {
  	            lstart = date.getTime();
  	            self.master.beginTransaction();
  	            self.master.changeTaskDates(task, lstart, lend,lstarttime,lendtime,passnoworktime);
  	            self.master.endTransaction();
	          } else {
  	            lend = date.getTime();
  	            if (lstart >= lend) {
  	              lend=lstart;
  	            }
  	            lend=lend+3600000*20; // this 20 hours are mandatory to reach the correct day end (snap to grid)

  	            //update task from editor
  	            self.master.beginTransaction();
  	            self.master.changeTaskDates(task, lstart, lend,lstarttime,lendtime,passnoworktime);
  	            self.master.endTransaction();
	          }
	          inp.updateOldValue(); //in order to avoid multiple call if nothing changed
	        }
	      }
  }
GanttMaster.prototype.e_onChange = function(task,value){
  	  var taskid = task.id;
	  //结束日期不能小于开始日期
	  var begindate_v = $("#begindate_"+taskid).val();
	  if(begindate_v&&value<begindate_v){
		  //alert("结束日期不能小于开始日期");
		  alert(GanttMaster.messages["Message8"]);
		  setTimeout(
			  function timer() {
				$(".enddateDiv_"+taskid+"_e9").find(".text").html(begindate_v);
				$("#enddateDiv_"+taskid+"_e9Name").val(begindate_v);
			  },100);
		$("#enddate_"+taskid).val(begindate_v);
	  }else{
		$("#enddate_"+taskid).val(value);
	  }
	  var self = task;
      var inp = $("#enddate_"+taskid);  
      if (inp.isValueChanged()) {
        if (!Date.isValid(inp.val())) {
        	setTimeout(
				  function timer() {
					$(".enddateDiv_"+taskid+"_e9").find(".text").html(inp.getOldValue());
					$("#enddateDiv_"+taskid+"_e9Name").val(inp.getOldValue());
				  },100);
          inp.val(inp.getOldValue());

        } else {
          var date = Date.parseString(inp.val());
          var row = inp.closest("tr");
          var taskId = row.attr("taskId");
          var lstart = task.start;
          var lend = task.end;
          var lstarttime = task.starttime;
          var lendtime = task.endtime;
          var passnoworktime = task.passnoworktime;

          if (inp.attr("name") == "start") {
            lstart = date.getTime();
            //update task from editor
            self.master.beginTransaction();
           // self.master.moveTask(task, lstart); 这个move不符合逻辑 换成 self.master.changeTaskDates
            self.master.changeTaskDates(task, lstart, lend,lstarttime,lendtime,passnoworktime);
            self.master.endTransaction();
          } else {
            lend = date.getTime();
            if (lstart >= lend) {
              lend=lstart;
            }
            lend=lend+3600000*20; // this 20 hours are mandatory to reach the correct day end (snap to grid)
            //update task from editor
            self.master.beginTransaction();
            self.master.changeTaskDates(task, lstart, lend,lstarttime,lendtime,passnoworktime);
            self.master.endTransaction();
          }
          inp.updateOldValue(); //in order to avoid multiple call if nothing changed
        }
      }
  }

GanttMaster.prototype.m_onChange = function(task,ids,names,datas){
	  var taskindex = task.index;
	  $("#txtManager_"+taskindex).val(ids);
}


//------- ADD TASK ------
GanttMaster.prototype.addTask = function (task, row) {
   //alert('GanttMaster.prototype.addTask');
   
   task.master = this; // in order to access controller from task
  // alert('task.master='+ task.master);

  //replace if already exists
  var pos = -1;
  for (var i = 0; i < this.tasks.length; i++) {
    if (task.id == this.tasks[i].id) {
      pos = i;
      break;
    }
  }
   //alert('task.id='+ task.id);
  //alert('pos'+pos >= 0);
  if (pos >= 0) {
    this.tasks.splice(pos, 1);
    row = parseInt(pos);
  }
   
   if(typeof(row) == 'undefined'){ //直接点空白行增加任务为undefined
	  task.level = 0; 
	  //task.name = '任务'+(this.tasks.length+1); 
   }
   
  //add task in collection
  if (typeof(row) != "number") {	
    this.tasks.push(task);
  } else {
    this.tasks.splice(row, 0, task);
    //recompute depends string
    this.updateDependsStrings();
  }

  //add Link collection in memory
  var linkLoops = !this.updateLinks(task);

  //set the status according to parent
  //alert("是否有父任务="+task.getParent());
  if (task.getParent())
    task.status = task.getParent().status;
  else
    task.status = "STATUS_ACTIVE";
   //新加的任务加个临时索引  
   task.index=this.tasks.length;
  var ret = task;
  if (linkLoops || !task.setPeriod1(task.start, task.end,task.starttime,task.endtime,task.passnoworktime)) {
    //remove task from in-memory collection
    //console.debug("removing task from memory",task);
    this.tasks.splice(task.getRow(), 1);
    ret = undefined;
  } else {
    //append task to editor
    this.editor.addTask(task, row);
    //append task to gantt
    this.gantt.addTask(task);
  }
  //E9单独解析
  var taskindex = task.index;
  var taskid = task.id;
  var nowdate = dateFormat_1(task.start);
  
  //开始日期
  var b_onChange = this.b_onChange;
  ReactDOM.render(React.createElement('div',{className:'begindateDiv_'+taskid+'_e9'},
		  React.createElement(ecCom.WeaDatePicker, {
			  		fieldName:'begindateDiv_'+taskid+'_e9Name',
			  		noInput:true,
			  		viewAttr:2,
			  		value:nowdate,
			  		onChange:b_onChange.bind(this,task)
			  	})
			) , document.getElementById('begindateDiv_'+taskid)
		);
  
  //结束日期
  var e_onChange = this.e_onChange;
  ReactDOM.render(React.createElement('div',{className:'enddateDiv_'+taskid+'_e9'},
		  React.createElement(ecCom.WeaDatePicker, {
			  		fieldName:'enddateDiv_'+taskid+'_e9Name',
			  		noInput:true,
			  		viewAttr:2,
			  		value:nowdate,
			  		onChange:e_onChange.bind(this,task)
			  	})
			) , document.getElementById('enddateDiv_'+taskid)
		);
  
  //人力资源浏览框
  var m_onChange = this.m_onChange;
  ReactDOM.render(React.createElement('div',{className:'txtManagerSpan_'+taskindex+'_e9'},
				  React.createElement(ecCom.WeaBrowser, {
					  		type:'17', 
					  		viewAttr:2,
					  		onChange:m_onChange.bind(this,task), 
					  		isSingle:false})
					) , document.getElementById('txtManagerSpan_'+taskindex)
				);
  return ret;
};


/**
 * a project contais tasks, resources, roles, and info about permisions
 * @param project
 */
GanttMaster.prototype.loadProject = function (project) {
  //alert(JSON.stringify(project));
  this.beginTransaction();
  this.resources = project.resources;
  this.roles = project.roles;
  this.canWrite = project.canWrite;
  this.canWriteOnParent = project.canWriteOnParent;
  this.cannotCloseTaskIfIssueOpen = project.cannotCloseTaskIfIssueOpen;

  if (project.minEditableDate)
    this.minEditableDate = computeStart(project.minEditableDate);
  else
    this.minEditableDate = -Infinity;

  if (project.maxEditableDate)
    this.maxEditableDate = computeEnd(project.maxEditableDate);
  else
    this.maxEditableDate = Infinity;

  this.loadTasks(project.tasks, project.selectedRow);
  
  this.deletedTaskIds = [];
  
  //recover saved splitter position
  if (project.splitterPosition)
    this.splitter.resize(project.splitterPosition);

  //recover saved zoom level
  if (project.zoom)
    this.gantt.zoom=project.zoom;

  this.endTransaction();
  var self = this;
  this.gantt.element.oneTime(200, function () {});
};

//加载数据,并且开始日期、结束日期、任务负责人绑定事件
GanttMaster.prototype.loadTasks = function (tasks, selectedRow) {
  var factory = new TaskFactory();
  //reset
  this.reset();
  
  for (var i = 0; i < tasks.length; i++) {
    var task = tasks[i];
    
    if (!(task instanceof Task)) {
      var t = factory.build(task.id, task.name, task.code, task.level, task.start,task.end,task.starttime,task.endtime,task.duration, task.collapsed);
      for (var key in task) {
      //这一行重新计算了时间注释掉
      // if (key != "end" && key != "start")
    	  //alert(task[key]);
          t[key] = task[key]; //copy all properties
      }
      task = t;
    }
    task.master = this; // in order to access controller from task
    this.tasks.push(task);  //append task at the end
  }

  //var prof=new Profiler("gm_loadTasks_addTaskLoop");
  for (var i = 0; i < this.tasks.length; i++) {
    var task = this.tasks[i];
    
    var numOfError=this.__currentTransaction&&this.__currentTransaction.errors?this.__currentTransaction.errors.length:0;
    //add Link collection in memory
    while (!this.updateLinks(task)){  // error on update links while loading can be considered as "warning". Can be displayed and removed in order to let transaction commits.
      if (this.__currentTransaction && numOfError!=this.__currentTransaction.errors.length){
        var msg = "";
        while (numOfError<this.__currentTransaction.errors.length) {
          var err = this.__currentTransaction.errors.pop();
          msg = msg + err.msg + "\n\n";
        }
        alert(msg);
      }
      this.removeAllLinks(task,false);
    }
      
    if (!task.setPeriod1(task.start,task.end,task.starttime,task.endtime,task.passnoworktime)) {
     //if (false) {
      alert(GanttMaster.messages.GANNT_ERROR_LOADING_DATA_TASK_REMOVED + "\n" + task.name + "\n" +GanttMaster.messages.ERROR_SETTING_DATES);
        //remove task from in-memory collection
      this.tasks.splice(task.getRow(), 1);
    } else {
      //append task to editor
      this.editor.addTask(task, null, true);
      //append task to gantt
      
      this.gantt.addTask(task);
    }
    
  }

  this.editor.fillEmptyLines();
  //prof.stop();

  // re-select old row if tasks is not empty
  if (this.tasks && this.tasks.length > 0) {
    selectedRow = selectedRow ? selectedRow : 0;
    this.tasks[selectedRow].rowElement.click();
  }
  
  for (var i = 0; i < this.tasks.length; i++) {
	  var task = this.tasks[i];
	  var taskid = task.id;
	  var taskindex = task.index;
	  var manager_viewAttr = $("#txtManagerSpan_"+taskindex).attr("isedit");
	  var begindate_viewAttr = $("#begindate_"+taskid).attr("isedit");
	  var enddate_viewAttr = $("#enddate_"+taskid).attr("isedit");
	  
	  var ids = task.hrmid;
	  var names = task.managername;
	  var begindate = dateFormat_1(task.start);
	  var enddate = dateFormat_1(task.end);
	 
	  var replaceDatas = new Array();
	  if(ids&&ids.length>0){
		  var id_array = ids.split(',');
		  var name_arrry = names.split(',');
		  if(id_array.length>1){
			  for(var j=0;j<id_array.length;j++){
				  replaceDatas[j] = {id:id_array[j],name:name_arrry[j]};
			  }
		  }else {
			  if(ids.length>0){
				  replaceDatas[0] = {id:ids,name:names};
			  }
		  }
	  }
	  
	  //开始日期
	  var b_onChange = this.b_onChange;
	  ReactDOM.render(React.createElement('div',{className:'begindateDiv_'+taskid+'_e9'},
			  React.createElement(ecCom.WeaDatePicker, {
				  		fieldName:'begindateDiv_'+taskid+'_e9Name',
				  		noInput:true,
				  		viewAttr:begindate_viewAttr,
				  		value:begindate,
				  		onChange:b_onChange.bind(this,task)
				  	})
				) , document.getElementById('begindateDiv_'+taskid)
			);
	  
	  //结束日期
	  var e_onChange = this.e_onChange;
	  ReactDOM.render(React.createElement('div',{className:'enddateDiv_'+taskid+'_e9'},
			  React.createElement(ecCom.WeaDatePicker, {
				  		fieldName:'enddateDiv_'+taskid+'_e9Name',
				  		noInput:true,
				  		viewAttr:begindate_viewAttr,
				  		value:enddate,
				  		onChange:e_onChange.bind(this,task)
				  		})
				) , document.getElementById('enddateDiv_'+taskid)
			);
	  var m_onChange = this.m_onChange;
	  //人力资源浏览框
	  ReactDOM.render(React.createElement('div',{className:'txtManagerSpan_'+taskindex+'_e9'},
					  React.createElement(ecCom.WeaBrowser, {
						  		type:'17', 
						  		replaceDatas:replaceDatas,
						  		viewAttr:manager_viewAttr,
						  		onChange:m_onChange.bind(this,task), 
						  		isSingle:false})
						) , document.getElementById('txtManagerSpan_'+taskindex)
					);
  	}
  
};


GanttMaster.prototype.getTask = function (taskId) {
  var ret;
  for (var i = 0; i < this.tasks.length; i++) {
    var tsk = this.tasks[i];
    if (tsk.id == taskId) {
      ret = tsk;
      break;
    }
  }
  return ret;
};


GanttMaster.prototype.getResource = function (resId) {
  var ret;
  for (var i = 0; i < this.resources.length; i++) {
    var res = this.resources[i];
    if (res.id == resId) {
      ret = res;
      break;
    }
  }
  return ret;
};

//结束日期change event
GanttMaster.prototype.changeTaskDates = function (task, start,end,starttime,endtime,passnoworktime) {  
    //alert("GanttMaster.prototype.changeTaskDates"+start);   
	var changeTaskDates = '1';
	return task.setPeriod1(start,end,starttime,endtime,passnoworktime,changeTaskDates);
};

//开始日期change event 这个计算不准确,换成了GanttMaster.prototype.changeTaskDates
GanttMaster.prototype.moveTask = function (task, newStart) {
  return task.moveTo(newStart, true);
};


GanttMaster.prototype.taskIsChanged = function () {
  //console.debug("taskIsChanged");
  var master = this;

  //refresh is executed only once every 50ms
  this.element.stopTime("gnnttaskIsChanged");
  //var profilerext = new Profiler("gm_taskIsChangedRequest");
  this.element.oneTime(50, "gnnttaskIsChanged", function () {
    //console.debug("task Is Changed real call to redraw");
    //var profiler = new Profiler("gm_taskIsChangedReal");
    master.editor.redraw();
    master.gantt.refreshGantt();
    //profiler.stop();
  });
  //profilerext.stop();
};


GanttMaster.prototype.redraw = function () {
  this.editor.redraw();
  this.gantt.refreshGantt();
};

GanttMaster.prototype.reset = function () {
  this.tasks = [];
  this.links = [];
  this.deletedTaskIds = [];
  if (!this.__inUndoRedo) {
    this.__undoStack = [];
    this.__redoStack = [];
  } else { // don't reset the stacks if we're in an Undo/Redo, but restart the inUndoRedo control
    this.__inUndoRedo = false;
  }
  delete this.currentTask;

  this.editor.reset();
  this.gantt.reset();
};


//弹出编辑框
/*GanttMaster.prototype.showTaskEditor = function (taskId) {
  var task = this.getTask(taskId);
  task.rowElement.find(".edit").click();
};*/

GanttMaster.prototype.saveProject = function () {
  return this.saveGantt(false);
};

GanttMaster.prototype.saveGantt = function (forTransaction) {
  var saved = [];
  for (var i = 0; i < this.tasks.length; i++) {
    var task = this.tasks[i];   
    //获取父任务行号
    var parentwxp = task.getParent();
    if(parentwxp){
    	  //alert(parentwxp.getRow());
    	  //task.parentrow = parentwxp.getRow();
    	task.parentrow = parentwxp.index;
    }else{
    	task.parentrow = 'oot_1';
    }
    var cloned = task.clone();
    delete cloned.master;
    delete cloned.rowElement;
    delete cloned.ganttElement;

    saved.push(cloned);
  }

  var ret = {tasks:saved};
  if (this.currentTask) {
    ret.selectedRow = this.currentTask.getRow();
  }
   //this must be consistent with transactions and undo
  ret.deletedTaskIds = this.deletedTaskIds; 

  if (!forTransaction) {
    ret.resources = this.resources;
    ret.roles = this.roles;
    ret.canWrite = this.canWrite;
    ret.canWriteOnParent = this.canWriteOnParent;
    ret.splitterPosition=this.splitter.perc;
    ret.zoom=this.gantt.zoom;
  }
 // alert("saveGantt"+JSON.stringify(ret));
  return ret;
};


GanttMaster.prototype.updateLinks = function (task) {
  // defines isLoop function
  function isLoop(task, target, visited) {
    if (target == task) {
      return true;
    }

    var sups = task.getSuperiors();
    
    //my parent' superiors are my superiors too
    var p= task.getParent();
    while (p){
      sups=sups.concat(p.getSuperiors());
      p= p.getParent();
    }

    //my children superiors are my superiors too
    var chs=task.getChildren();
    for (var i=0;i<chs.length;i++){
      sups=sups.concat(chs[i].getSuperiors());
    }

    var loop = false;
    //check superiors
    for (var i = 0; i < sups.length; i++) {
      var supLink = sups[i];
      if (supLink.from == target) {
        loop = true;
        break;
      } else {
        if (visited.indexOf(supLink.from.id+"x"+target.id) <= 0) {
          visited.push(supLink.from.id+"x"+target.id);
          if (isLoop(supLink.from, target, visited)) {
            loop = true;
            break;
          }
        }
      }
    }

    //check target parent
    var tpar=target.getParent();
    if (tpar ){
      if (visited.indexOf(task.id+"x"+tpar.id) <= 0) {
        visited.push(task.id+"x"+tpar.id);
        if (isLoop(task,tpar, visited)) {
          loop = true;
        }
      }
    }

    return loop;
  }

  //remove my depends
  this.links = this.links.filter(function (link) {
    return link.to != task;
  });

  var todoOk = true;
  if (task.depends) {

    //cannot depend from an ancestor
    var parents = task.getParents();
    //cannot depend from descendants
    var descendants = task.getDescendant();

    var deps = task.depends.split(",");
    var newDepsString = "";

    var visited = [];
    for (var j = 0; j < deps.length; j++) {
      var dep = deps[j]; // in the form of row(lag) e.g. 2:3,3:4,5
      var par = dep.split(":");
      var lag = 0;

      if (par.length > 1) {
        lag = parseInt(par[1]);
      }

      var sup = this.tasks[parseInt(par[0] - 1)];

      /*if (sup) {
        if (parents && parents.indexOf(sup) >= 0) {
          this.setErrorOnTransaction(task.name + "\n" + GanttMaster.messages.CANNOT_DEPENDS_ON_ANCESTORS + "\n" + sup.name);
          todoOk = false;

        } else if (descendants && descendants.indexOf(sup) >= 0) {
          this.setErrorOnTransaction(task.name + "\n" + GanttMaster.messages.CANNOT_DEPENDS_ON_DESCENDANTS + "\n" + sup.name);
          todoOk = false;

        } else if (isLoop(sup, task, visited)) {
          todoOk = false;
          this.setErrorOnTransaction(GanttMaster.messages.CIRCULAR_REFERENCE + "\n" + task.name + " -> " + sup.name);
        } else {
          this.links.push(new Link(sup, task, lag));
          newDepsString = newDepsString + (newDepsString.length > 0 ? "," : "") + dep;
        }
      }*/
    }
     this.links.push(new Link(sup, task, lag));
          newDepsString = newDepsString + (newDepsString.length > 0 ? "," : "") + dep;
    task.depends = newDepsString;

  }

  return todoOk;
};


GanttMaster.prototype.moveUpCurrentTask=function(){
  var self=this;
  if(!self.canWrite )
    return;

  if (self.currentTask) {
    self.beginTransaction();
    self.currentTask.moveUp();
    self.endTransaction();
  }
};

GanttMaster.prototype.moveDownCurrentTask=function(){
  var self=this;
  if(!self.canWrite)
    return;

  if (self.currentTask) {
    self.beginTransaction();
    self.currentTask.moveDown();
    self.endTransaction();
  }
};

GanttMaster.prototype.outdentCurrentTask=function(){
  var self=this;
  if(!self.canWrite|| !self.currentTask.canWrite)
    return;

  if (self.currentTask) {
    var par = self.currentTask.getParent();

    self.beginTransaction();
    self.currentTask.outdent();
    self.endTransaction();

    //[expand]
   if(par) self.editor.refreshExpandStatus(par);
  }
};

GanttMaster.prototype.indentCurrentTask=function(){
  var self=this;
  if (!self.canWrite|| !self.currentTask.canWrite)
    return;

  if (self.currentTask) {
    self.beginTransaction();
    self.currentTask.indent();
    self.endTransaction();
  }
};

GanttMaster.prototype.addBelowCurrentTask=function(){
  var self=this;
  if (!self.canWrite)
    return;

  var factory = new TaskFactory();
  self.beginTransaction();
  var ch;
  var row = 0;
  if (self.currentTask) {
    ch = factory.build("tmp_" + new Date().getTime(), "", "", self.currentTask.level + 1, self.currentTask.start, 1);
    row = self.currentTask.getRow() + 1;
  } else {
    ch = factory.build("tmp_" + new Date().getTime(), "", "", 0, new Date().getTime(), 1);
  }
  var task = self.addTask(ch, row);
  if (task) {
    task.rowElement.click();
    task.rowElement.find("[name=name]").focus();
  }
  self.endTransaction();
};

GanttMaster.prototype.addAboveCurrentTask=function(){
  var self=this;
  if (!self.canWrite)
    return;
  var factory = new TaskFactory();

  var ch;
  var row = 0;
  if (self.currentTask) {
    //cannot add brothers to root
  //  if (self.currentTask.level <= 0){}
     // return;

    ch = factory.build("tmp_" + new Date().getTime(), "", "", self.currentTask.level, self.currentTask.start, 1);
    row = self.currentTask.getRow();
  } else {
    ch = factory.build("tmp_" + new Date().getTime(), "", "", 0, new Date().getTime(), 1);
  }
  self.beginTransaction();
  var task = self.addTask(ch, row);
  if (task) {
    task.rowElement.click();
    task.rowElement.find("[name=name]").focus();
  }
  self.endTransaction();
};

GanttMaster.prototype.deleteCurrentTask=function(){
  if(window.confirm(SystemEnv.getHtmlNoteName(4686))){//该任务及其子任务都会被删除,您确认要删除吗?
  var self=this;
  if (!self.currentTask || !self.canWrite || !self.currentTask.canWrite)
    return;
  var row = self.currentTask.getRow();
  //if (self.currentTask && (row > 0 || self.currentTask.isNew())) { 这导致第一条任务不能删除
  if (self.currentTask ){
    var par = self.currentTask.getParent();
    self.beginTransaction();
    self.currentTask.deleteTask();
    self.currentTask = undefined;

    //recompute depends string
    self.updateDependsStrings();
    // $('#ganttDelbt').onclick();
     //$("#ganttSavebt").trigger("click");
     saveGanttOnServer(1);

    //redraw
    self.redraw();
  
    //[expand]
    if(par) self.editor.refreshExpandStatus(par);


    //focus next row
    row = row > self.tasks.length - 1 ? self.tasks.length - 1 : row;
    if (row >= 0) {
      self.currentTask = self.tasks[row];
      self.currentTask.rowElement.click();
      self.currentTask.rowElement.find("[name=name]").focus();
    }
    self.endTransaction();
  }
}

};

//<%--TRANSACTION MANAGEMENT --%>
GanttMaster.prototype.beginTransaction = function () {
  if (!this.__currentTransaction) {
    this.__currentTransaction = {
      snapshot:JSON.stringify(this.saveGantt(true)),
      errors:  []
    };
  } else {
    console.error("Cannot open twice a transaction");
  }
  return this.__currentTransaction;
};

//拖动开始、结束日期动作
GanttMaster.prototype.endTransaction = function () {
  if (!this.__currentTransaction) {
    console.error("Transaction never started.");
    return true;
  }

  var ret = true;

  //no error -> commit
  if (this.__currentTransaction.errors.length <= 0) {
    //put snapshot in undo
    this.__undoStack.push(this.__currentTransaction.snapshot);
    //clear redo stack
    this.__redoStack = [];

    //shrink gantt bundaries
    this.gantt.originalStartMillis = Infinity;
    this.gantt.originalEndMillis = -Infinity;
    for (var i = 0; i < this.tasks.length; i++) {
      var task = this.tasks[i];
      if (this.gantt.originalStartMillis > task.start)
        this.gantt.originalStartMillis = task.start;
      if (this.gantt.originalEndMillis < task.end)
        this.gantt.originalEndMillis = task.end;

    }
    this.taskIsChanged(); //enqueue for gantt refresh

    //error -> rollback
  } else {
    ret = false;
    //try to restore changed tasks
    var oldTasks = JSON.parse(this.__currentTransaction.snapshot);
    this.deletedTaskIds = oldTasks.deletedTaskIds;
    this.loadTasks(oldTasks.tasks, oldTasks.selectedRow);
    this.redraw();

    //compose error message
    var msg = "";
    for (var i = 0; i < this.__currentTransaction.errors.length; i++) {
      var err = this.__currentTransaction.errors[i];
      msg = msg + err.msg + "\n\n";
    }
    alert(msg);
  }
  //reset transaction
  this.__currentTransaction = undefined;

  //[expand]
  this.editor.refreshExpandStatus(this.currentTask);
  //修改开始、结束日期
  if(this.currentTask){
	  var begindate = dateFormat_1(this.currentTask.start);
	  var enddate = dateFormat_1(this.currentTask.end);
	  $(".begindateDiv_"+this.currentTask.id+"_e9").find(".text").html(begindate);
	  $("#begindateDiv_"+this.currentTask.id+"_e9Name").val(begindate);
	  $(".enddateDiv_"+this.currentTask.id+"_e9").find(".text").html(enddate);
	  $("#enddateDiv_"+this.currentTask.id+"_e9Name").val(enddate);
  }
  return ret;
};

//this function notify an error to a transaction -> transaction will rollback
GanttMaster.prototype.setErrorOnTransaction = function (errorMessage, task) {
  if (this.__currentTransaction) {
    this.__currentTransaction.errors.push({msg:errorMessage, task:task});
  } else {
    console.error(errorMessage);
  }
};

// inhibit undo-redo
GanttMaster.prototype.checkpoint = function () {
  this.__undoStack = [];
  this.__redoStack = [];
};

//---- UNDO/REDO MANAGEMENT ----%>

GanttMaster.prototype.undo = function () {
  //console.debug("undo before:",this.__undoStack,this.__redoStack);
  if (this.__undoStack.length > 0) {
    var his = this.__undoStack.pop();
    this.__redoStack.push(JSON.stringify(this.saveGantt()));
    var oldTasks = JSON.parse(his);
    this.deletedTaskIds = oldTasks.deletedTaskIds;
    this.__inUndoRedo = true; // avoid Undo/Redo stacks reset
    this.loadTasks(oldTasks.tasks, oldTasks.selectedRow);
    this.redraw();
  }
};

GanttMaster.prototype.redo = function () {
  if (this.__redoStack.length > 0) {
    var his = this.__redoStack.pop();
    this.__undoStack.push(JSON.stringify(this.saveGantt()));
    var oldTasks = JSON.parse(his);
    this.deletedTaskIds = oldTasks.deletedTaskIds;
    this.__inUndoRedo = true; // avoid Undo/Redo stacks reset
    this.loadTasks(oldTasks.tasks, oldTasks.selectedRow);
    this.redraw();
    //console.debug("redo after:",undoStack,redoStack);
  }
};


GanttMaster.prototype.resize = function () {
  //console.debug("GanttMaster.resize")
  this.splitter.resize();
};

GanttMaster.prototype.getCollapsedDescendant = function(){
    var allTasks = this.tasks;
    var collapsedDescendant = [];
    for (var i = 0; i < allTasks.length; i++) {
       var task = allTasks[i];
       if(collapsedDescendant.indexOf(task) >= 0) continue;
       if(task.collapsed) collapsedDescendant = collapsedDescendant.concat(task.getDescendant());
    }
    return collapsedDescendant;
}

/**
 * Compute the critical path using Backflow algorithm.
 * Translated from Java code supplied by M. Jessup here http://stackoverflow.com/questions/2985317/critical-path-method-algorithm
 *
 * For each task computes:
 * earlyStart, earlyFinish, latestStart, latestFinish, criticalCost
 *
 * A task on the critical path has isCritical=true
 * A task not in critical path can float by latestStart-earlyStart days
 *
 * If you use critical path avoid usage of dependencies between different levels of tasks
 *
 * WARNNG: It ignore milestones!!!!
 * @return {*}
 */
GanttMaster.prototype.computeCriticalPath = function () {

  if (!this.tasks)
    return false;

  // do not consider grouping tasks
  var tasks = this.tasks.filter(function (t) {
    //return !t.isParent()
    return (t.getRow()  > 0) && (!t.isParent() || (t.isParent() && !t.isDependent()));
  });

  // reset values
  for (var i = 0; i < tasks.length; i++) {
    var t = tasks[i];
    t.earlyStart = -1;
    t.earlyFinish = -1;
    t.latestStart = -1;
    t.latestFinish = -1;
    t.criticalCost = -1;
    t.isCritical=false;
  }

  // tasks whose critical cost has been calculated
  var completed = [];
  // tasks whose critical cost needs to be calculated
  var remaining = tasks.concat(); // put all tasks in remaining


  // Backflow algorithm
  // while there are tasks whose critical cost isn't calculated.
  while (remaining.length > 0) {
    var progress = false;

    // find a new task to calculate
    for (var i = 0; i < remaining.length; i++) {
      var task = remaining[i];
      var inferiorTasks = task.getInferiorTasks();

      if (containsAll(completed, inferiorTasks)) {
        // all dependencies calculated, critical cost is max dependency critical cost, plus our cost
        var critical = 0;
        for (var j = 0; j < inferiorTasks.length; j++) {
          var t = inferiorTasks[j];
          if (t.criticalCost > critical) {
            critical = t.criticalCost;
          }
        }
        task.criticalCost = critical + task.duration;
        // set task as calculated an remove
        completed.push(task);
        remaining.splice(i, 1);

        // note we are making progress
        progress = true;
      }
    }
    // If we haven't made any progress then a cycle must exist in
    // the graph and we wont be able to calculate the critical path
    if (!progress) {
      console.error("Cyclic dependency, algorithm stopped!");
      return false;
    }
  }

  // set earlyStart, earlyFinish, latestStart, latestFinish
  computeMaxCost(tasks);
  var initialNodes = initials(tasks);
  calculateEarly(initialNodes);
  calculateCritical(tasks);



/*
  for (var i = 0; i < tasks.length; i++) {
    var t = tasks[i];
    console.debug("Task ", t.name, t.duration, t.earlyStart, t.earlyFinish, t.latestStart, t.latestFinish, t.latestStart - t.earlyStart, t.earlyStart == t.latestStart)
  }*/

  return tasks;


  function containsAll(set, targets) {
    for (var i = 0; i < targets.length; i++) {
      if (set.indexOf(targets[i]) < 0)
        return false;
    }
    return true;
  }

  function computeMaxCost(tasks) {
    var max = -1;
    for (var i = 0; i < tasks.length; i++) {
      var t = tasks[i];

      if (t.criticalCost > max)
        max = t.criticalCost;
    }
    //console.debug("Critical path length (cost): " + max);
    for (var i = 0; i < tasks.length; i++) {
      var t = tasks[i];
      t.setLatest(max);
    }
  }

  function initials(tasks) {
    var initials = [];
    for (var i = 0; i < tasks.length; i++) {      
      if (!tasks[i].depends || tasks[i].depends == "")
        initials.push(tasks[i]);
    }
    return initials;
  }

  function calculateEarly(initials) {
    for (var i = 0; i < initials.length; i++) {
      var initial = initials[i];
      initial.earlyStart = 0;
      initial.earlyFinish = initial.duration;
      setEarly(initial);
    }
  }

  function setEarly(initial) {
    var completionTime = initial.earlyFinish;
    var inferiorTasks = initial.getInferiorTasks();
    for (var i = 0; i < inferiorTasks.length; i++) {
      var t = inferiorTasks[i];
      if (completionTime >= t.earlyStart) {
        t.earlyStart = completionTime;
        t.earlyFinish = completionTime + t.duration;
      }
      setEarly(t);
    }
  }

  function calculateCritical(tasks) {
    for (var i = 0; i < tasks.length; i++) {
      var t = tasks[i];
      t.isCritical=(t.earlyStart == t.latestStart)
    }
  }


};