ganttTask_wev8.js 37.6 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
/**
 * A method to instantiate valid task models from
 * raw data.
*/
function TaskFactory() {

  /**
   * Build a new Task 新建项目
   */
  this.build = function(id, name, code, level, start,end,starttime,endtime,duration, collapsed) {
    // Set at beginning of day
     var adjusted_start = computeStart(start);
     
    //原来是通过开始时间和工期计算结束时间,现在直接有值传进来,不必计算
    // var calculated_end = computeEndByDuration(adjusted_start, duration);
    
    if(end ==1){ //新建任务时,开始日期默认是当天的,而end 则是1,这边判断一下
    	end = start
    }
    var calculated_end =  computeEnd(end);

    return new Task(id, name, code, level, adjusted_start, calculated_end,starttime,endtime, duration, collapsed);
  };

}

function Task(id, name, code, level, start, end,starttime,endtime, duration, collapsed,hrmid) {
  this.id = id;
  this.name = name;
  this.progress=0;
  this.description = "";
  this.code = code;
  this.level = level;
  this.status = "STATUS_UNDEFINED";
  this.depends="";
  this.canWrite=true; // by default all tasks are writeable

  this.start = start
  this.duration = duration;
  this.end = end;
  
  //add by wxp
  this.starttime= starttime;
  this.endtime = endtime;
  
  this.startIsMilestone = false;
  this.endIsMilestone = false;

  this.collapsed = collapsed;
  
  this.rowElement; //row editor html element
  this.ganttElement; //gantt html element
  this.master;

  this.assigs = [];
}

Task.prototype.clone = function () {
  var ret = {};
  for (var key in this) {
    if (typeof(this[key]) != "function") {
      ret[key] = this[key];
    }
  }
  return ret;
};

Task.prototype.getAssigsString = function () {
  var ret = "";
  for (var i=0;i<this.assigs.length;i++) {
    var ass = this.assigs[i];
    var res = this.master.getResource(ass.resourceId);
    if (res) {
      ret = ret + (ret == "" ? "" : ", ") + res.name;
    }
  }
  return ret;
};

Task.prototype.createAssignment = function (id, resourceId, roleId, effort) {
  var assig = new Assignment(id, resourceId, roleId, effort);
  this.assigs.push(assig);
  return assig;
};


//<%------ SET PERIOD 原来的时间运算 目前废弃 用 setPeriod1--------%>
Task.prototype.setPeriod = function (start, end) {
  if (start instanceof Date) {
    start = start.getTime();
  }
  if (end instanceof Date) {
    end = end.getTime();
  }

  var originalPeriod = {
    start: this.start,
    end:  this.end,
    duration: this.duration
  };

  //console.debug("setStart",date,date instanceof Date);
  var wantedStartMillis = start;

  //cannot start after end
  if (start > end) {
    start = end;
  }

  //set a legal start
  start = computeStart(start);

  //if depends -> start is set to max end + lag of superior 初始化后置任务的开始时间为前置任务的结束时间,没必要 注释by wxp
 /* var sups = this.getSuperiors();
  if (sups && sups.length > 0) {
    var supEnd = 0;
    for (var i=0;i<sups.length;i++) {
      var link = sups[i];
      supEnd = Math.max(supEnd, incrementDateByWorkingDays(link.from.end, link.lag));
    }
    if changed by depends move it    if (computeStart(supEnd) != start) {
      return this.moveTo(supEnd + 1, false);
    }
  }*/

  var somethingChanged = false;

  //move date to closest day
  var date = new Date(start);

  if (this.start != start || this.start != wantedStartMillis) {
    this.start = start;
    somethingChanged = true;
  }

  //set end
  var wantedEndMillis = end;
  end = computeEnd(end);

  if (this.end != end || this.end != wantedEndMillis) {
    this.end = end;
    somethingChanged = true;
  }

  this.duration = recomputeDuration(this.start, this.end);

  //profilerSetPer.stop();

  //nothing changed exit
  if (!somethingChanged)
    return true;

  //cannot write exit
  if(!this.canWrite){
    this.master.setErrorOnTransaction(GanttMaster.messages["CANNOT_WRITE"] + "\n" + this.name, this);
    return false;
  }

  //external dependencies: exit with error
  if (this.hasExternalDep) {
    this.master.setErrorOnTransaction(GanttMaster.messages["TASK_HAS_EXTERNAL_DEPS"] + "\n" + this.name, this);
    return false;
  }

  var todoOk = true;

  //I'm restricting
  var deltaPeriod = originalPeriod.duration - this.duration;
  var restricting = deltaPeriod > 0;
  var restrictingStart = restricting && (originalPeriod.start < this.start);
  var restrictingEnd = restricting && (originalPeriod.end > this.end);

  //console.debug( " originalPeriod.duration "+ originalPeriod.duration +" deltaPeriod "+deltaPeriod+" "+"restricting "+restricting);
  if (restricting) {
    //loops children to get boundaries
    var children = this.getChildren();
    var bs = Infinity;
    var be = 0;
    for (var i=0;i<children.length;i++) {

      ch = children[i];
      //console.debug("restricting: test child "+ch.name+" "+ch.end)
      if (restrictingEnd) {
        be = Math.max(be, ch.end);
      } else {
        bs = Math.min(bs, ch.start);
      }
    }

    if (restrictingEnd) {
      //console.debug("restricting end ",be, this.end);
      this.end = Math.max(be, this.end);
    } else {
      //console.debug("restricting start");
      this.start = Math.min(bs, this.start);
    }

     this.duration = recomputeDuration(this.start, this.end);
  } else {

    //check global boundaries
    if (this.start < this.master.minEditableDate || this.end > this.master.maxEditableDate) {
      this.master.setErrorOnTransaction(GanttMaster.messages["CHANGE_OUT_OF_SCOPE"], this);
      todoOk = false;
    }

    //console.debug("set period: somethingChanged",this);
   // if (todoOk && !updateTree(this)) {
    if (todoOk && !updateTree(this)) {
      todoOk = false;
    }
  }
  //alert('todoOk'+todoOk);
  if (todoOk) {
    //and now propagate to inferiors
    var infs = this.getInferiors();
    //alert('4444'+infs.length);
    if (infs && infs.length > 0) {
      for (var i=0;i<infs.length;i++) {
        var link = infs[i];
        if (!link.to.canWrite){
          this.master.setErrorOnTransaction(GanttMaster.messages["CANNOT_WRITE"] + "\n" + link.to.name, link.to);
          break;
        }
        todoOk = link.to.moveTo(end, false); //this is not the right date but moveTo checks start
       // alert('todoOk1'+todoOk);
        if (!todoOk)
          break;
      }
    }
  }

  return todoOk;
};


//<%------ SETPERIOD1 修改后的时间运算 add by wxp--------%> 
//changeTaskDates 这个参数作为后面修改时间传参数  
Task.prototype.setPeriod1 = function (start,end,starttime,endtime,passnoworktime,changeTaskDates) {

  if (start instanceof Date) { //前台可以直接传标准时间格式过来,也可以为时间戳
    start = start.getTime();
  }
 
  if (end instanceof Date) {
    end = end.getTime();
  }

   if(changeTaskDates == '1'){//手动调整时间时判断
	   
	   var start2 = new Date(start);
           start2 = start2.format("yyyy-MM-dd");
  
       var end2 = new Date(end);
           end2 = end2.format("yyyy-MM-dd");
  
	   if(start > end){
		  this.master.setErrorOnTransaction(GanttMaster.messages["Message1"], this);
    	  return false; 
	   } else if(new Date(start2+' '+starttime).getTime() > new Date(end2+' '+endtime).getTime()){
		   this.master.setErrorOnTransaction(GanttMaster.messages["Message2"], this);
    	   return false; 
	   }
    }
  
  var originalPeriod = {
    start: this.start,
    end:  this.end,
    duration: this.duration
  };

  var wantedStartMillis = start;

  if (start > end) {
    start = end;
  }

  start = computeStart(start);

  //if depends -> start is set to max end + lag of superior 初始化后置任务的开始时间为前置任务的结束时间
 /* var sups = this.getSuperiors();
  if (sups && sups.length > 0) {
    var supEnd = 0;
    for (var i=0;i<sups.length;i++) {
      var link = sups[i];
      supEnd = Math.max(supEnd, incrementDateByWorkingDays(link.from.end, link.lag));
    }
    if changed by depends move it    if (computeStart(supEnd) != start) {
      return this.moveTo(supEnd + 1, false);
    }
  }*/

  var somethingChanged = false;

  //move date to closest day
  var date = new Date(start);
 
      
  if (this.start != start || this.start != wantedStartMillis) {
    this.start = start;
    somethingChanged = true;
    //更改上级日期
    var newstart = new Date(this.start).format("yyyy-MM-dd");
    $(".begindateDiv_"+this.id+"_e9").find(".text").html(newstart)
	$("#begindateDiv_"+this.id+"_e9Name").val(newstart);
  }

  //set end
  var wantedEndMillis = end;
  end = computeEnd(end);

  if (this.end != end || this.end != wantedEndMillis) {
    this.end = end;
    somethingChanged = true;
    //更改上级日期
    //alert(this.end+","+end);
    var newend = new Date(this.end).format("yyyy-MM-dd");
    $(".enddateDiv_"+this.id+"_e9").find(".text").html(newend)
	$("#enddateDiv_"+this.id+"_e9Name").val(newend);
  }

 //原来的计算工期方法,弃用  
 // this.duration = recomputeDuration(this.start, this.end);
  
  //wxp add 日期转换 yyyy-MM-dd
  var start1 = new Date(this.start);
      start1 = start1.format("yyyy-MM-dd");
  
  var end1 = new Date(this.end);
      end1 = end1.format("yyyy-MM-dd");
  
      //alert(start1+","+end1);
  //处理新增任务时间未设定报错的问题
  if(typeof(starttime)=='undefined' || starttime=='0' || starttime==''){
	  starttime = '00:00';
  }
   if(typeof(endtime)=='undefined'){
	  endtime = '23:59';
  }
   if(endtime=='0' || endtime==''){
	  endtime = '23:59';
  }

  //ecology8 工期的计算方法  
  if(changeTaskDates == '1'){//手动调整时间 工期计算
	var children = this.getChildren();
	if(children.length>0){
    for (var i=0;i<children.length;i++) {
      ch = children[i];

      var startemp = new Date(ch.start);
          startemp = startemp.format("yyyy-MM-dd");
      var endtemp = new Date(ch.end);
          endtemp = endtemp.format("yyyy-MM-dd");
         
        if(new Date(start1).getTime() > new Date(startemp).getTime()){
        	this.master.setErrorOnTransaction(GanttMaster.messages["Message3"], this);
    	    return false; 
        }else if(new Date(start1+' '+starttime).getTime() > new Date(startemp+' '+ch.starttime).getTime()){      	 
          	this.master.setErrorOnTransaction(GanttMaster.messages["Message5"], this);
    	  	return false; 
        }else if(new Date(end1).getTime() <  new Date(endtemp).getTime()){
    	      this.master.setErrorOnTransaction(GanttMaster.messages["Message4"], this);
    	      return false; 
        }else if(new Date(end1+' '+endtime).getTime() <  new Date(endtemp+' '+ch.endtime).getTime()){
    	      this.master.setErrorOnTransaction(GanttMaster.messages["Message6"], this);
    	      return false; 
        }else{
    	   this.duration = getDur(start1, end1,starttime,endtime,passnoworktime);
       }     
    }
    }else{
    	this.duration = getDur(start1, end1,starttime,endtime,passnoworktime);
    }
  }else{//初始化时的工期计算
	  this.duration = getDur(start1, end1,starttime,endtime,passnoworktime);
  }
  
  
  //时间改变后重新赋值,不然时间选择框不会变
  this.starttime = starttime;
  this.endtime = endtime;
  
  //nothing changed exit
  if (!somethingChanged)
    return true;

  //cannot write exit 不能编辑报错
  //if(!this.canWrite){
   // this.master.setErrorOnTransaction(GanttMaster.messages["CANNOT_WRITE"] + "\n" + this.name, this);
    //return false;
 // }

  //external dependencies: exit with error
  if (this.hasExternalDep) {
    this.master.setErrorOnTransaction(GanttMaster.messages["TASK_HAS_EXTERNAL_DEPS"] + "\n" + this.name, this);
    return false;
  }

  var todoOk = true;

  //I'm restricting
  var deltaPeriod = originalPeriod.duration - this.duration;
  var restricting = deltaPeriod > 0;
  var restrictingStart = restricting && (originalPeriod.start < this.start);
  var restrictingEnd = restricting && (originalPeriod.end > this.end);
  
  if (restricting) {
    //loops children to get boundaries
    var children = this.getChildren();
    var bs = Infinity;
    var be = 0;
    for (var i=0;i<children.length;i++) {

      ch = children[i];    
      if (restrictingEnd) {
        be = Math.max(be, ch.end);
      } else {
        bs = Math.min(bs, ch.start);
      }
    }

    if (restrictingEnd) {
      this.end = Math.max(be, this.end);
    } else {
      this.start = Math.min(bs, this.start);
    }
    if(typeof(starttime)=='undefined'){
	      starttime = '00:00';
    }
    if(typeof(endtime)=='undefined'){
	      endtime = '23:59';
    }
    this.duration = getDur(start1, end1,starttime,endtime,passnoworktime);
  } else {
     
    //check global boundaries
    if (this.start < this.master.minEditableDate || this.end > this.master.maxEditableDate) {
      this.master.setErrorOnTransaction(GanttMaster.messages["CHANGE_OUT_OF_SCOPE"], this);
      todoOk = false;
    }
    //更改上级任务
    if (todoOk && !updateTree(this)) {
      todoOk = false;
    }
  }
 /* if (todoOk) {
    and now propagate to inferiors    var infs = this.getInferiors();
    alert('后置任务'+infs.length);    if (infs && infs.length > 0) {
      for (var i=0;i<infs.length;i++) {
        var link = infs[i];
        if (!link.to.canWrite){
          this.master.setErrorOnTransaction(GanttMaster.messages["CANNOT_WRITE"] + "\n" + link.to.name, link.to);
          break;
        }
        alert('移动操作3');
        todoOk = link.to.moveTo(end, false); //this is not the right date but moveTo checks start 这个会导致移动前置任务后置任务也会移动        todoOk = false;
        alert('todoOk1'+todoOk);        if (!todoOk)
          break;
      }
    }
  }*/
  
  return todoOk;
};


//<%---------- MOVE TO 移动操作 -------%>
Task.prototype.moveTo = function (start, ignoreMilestones) {
  //alert('移动操作');
  if (start instanceof Date) {
    start = start.getTime();
  }

  var originalPeriod = {
    start:this.start,
    end:this.end
  };

  var wantedStartMillis = start;

  //set a legal start
  start = computeStart(start);
  //alert(start);
  //if start is milestone cannot be move
  if (!ignoreMilestones && this.startIsMilestone && start != this.start) {
    //notify error
    this.master.setErrorOnTransaction(GanttMaster.messages["START_IS_MILESTONE"], this);
    return false;
  } else if (this.hasExternalDep) {
    //notify error
    this.master.setErrorOnTransaction(GanttMaster.messages["TASK_HAS_EXTERNAL_DEPS"], this);
    return false;
  }

  //if depends start is set to max end + lag of superior
  //前置任务移动时,后置任务的开始时间随之修改,不需要
 /*
  var sups = this.getSuperiors();
  if (sups && sups.length > 0) {
    var supEnd = 0;
    for (var i=0;i<sups.length;i++) {
      var link = sups[i];
      supEnd = Math.max(supEnd, incrementDateByWorkingDays(link.from.end, link.lag));
    }
    start = supEnd + 1;
  }
  //set a legal start
  start = computeStart(start);
*/
  //var end = computeEndByDuration(start, this.duration);
  var end = this.end;
  this.duration = recomputeDuration(start, end);
  /* wxp test
  var sups = this.getSuperiors();
  alert(sups.length);
  if (sups && sups.length > 0) {
	  for (var i=0;i<sups.length;i++) {
		  var aa = sups[i];
		  alert(aa.start);
	  }
  }*/

  if (this.start != start || this.start != wantedStartMillis) {
    //in case of end is milestone it never changes, but recompute duration
    if (!ignoreMilestones && this.endIsMilestone) {
      end = this.end;
      this.duration = recomputeDuration(start, end);
    }
    this.start = start;
    this.end = end;
    //profiler.stop();

    //check global boundaries
    if (this.start < this.master.minEditableDate || this.end > this.master.maxEditableDate) {
      this.master.setErrorOnTransaction(GanttMaster.messages["CHANGE_OUT_OF_SCOPE"], this);
      return false;
    }
  
   // var panDelta = originalPeriod.start - this.start;
    //console.debug("panDelta",panDelta);
    //loops children to shift them    
    var children = this.getChildren();
    //alert(children.length);
   //移动父任务自动移动子任务,并不需要这么做
    /*for (var i=0;i<children.length;i++) {
      ch = children[i];
      if (!ch.moveTo(ch.start - panDelta, false)) {
        return false;
      }
    }*/
    
    //父任务移动只需考虑开始时间是否大于子任务的开始时间
    for (var i=0;i<children.length;i++) {
      ch = children[i];
       if(new Date(start).getTime() > ch.start){   
          //this.master.setErrorOnTransaction(GanttMaster.messages["PARENT_TASK_START_TIME_LATER_THAN_THE_CHILD_TASK_START_TIME"], this);
    	  return false; 
       }
  }

    //console.debug("set period: somethingChanged",this);
    if (!updateTree(this)) {
      return false;
    }

    //and now propagate to inferiors 后置任务随前置任务拖动而动
    
    /*var infs = this.getInferiors();
    alert(infs.length);    if (infs && infs.length > 0) {
      for (var i=0;i<infs.length;i++) {
        var link = infs[i];

        this is not the right date but moveTo checks start        if (!link.to.canWrite ) {
          this.master.setErrorOnTransaction(GanttMaster.messages["CANNOT_WRITE"]+ "\n"+link.to.name, link.to);
        } else if (!link.to.moveTo(end, false)) {
          return false;
        }
      }
    }*/

  }
  return true;
};

//e8计算工期方法
function getDur(sDate1,sDate2,sDate3,sDate4,passnoworktime){
  	var aDate, oDate1, oDate2, iDays,odate3,odate4,tdate,otime1,otime2,oDatetime1, oDatetime2;	
  	
  	if(passnoworktime!=1){	
  		oDate1=new Date(sDate1);
		oDate2=new Date(sDate2);
		odate3=new Date(sDate3);
		odate4=new Date(sDate4);
		
		if(true || ""+oDate1.getFullYear()=="NaN"){
			aDate = sDate1.split("-")
			tdate = sDate3.split(":")
		    oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])   //转换为12-18-2002格式
		    oDatetime1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]+" "+tdate[0]+":"+tdate[1]) 
			//if(window.console) console.log("oDate1:"+oDate1);
			//if(window.console) console.log("oDatetime1:"+oDatetime1);
		    aDate = sDate2.split("-")
		    tdate = sDate4.split(":")
		    oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
		    oDatetime2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]+" "+tdate[0]+":"+tdate[1])	    
	    }
	    if(oDate2-oDate1<0){
	   		 iDays = -1 	//日期
	    }else if(oDate2-oDate1==0){
	    	if(sDate4<sDate3){
	    		iDays = -2 //时间
	    	}else{
	    		iDays = (Math.abs(oDatetime1-oDatetime2) / 1000 / 60 / 60 /24).toFixed(2)     
	    	}
	    }else{
	    	 iDays = (Math.abs(oDatetime1-oDatetime2) / 1000 / 60 / 60 /24).toFixed(2)     
	    }
	    //if(window.console) console.log("iDays:"+(iDays));
  	}else{ 		
  	 $.ajax({
           type: "post",
           url: "/proj/process/GetWorkDays.jsp",
           data:"begindate="+sDate1+"&begintime="+sDate3+"&enddate="+sDate2+"&endtime="+sDate4+"&manager=1",
           dataType: "text", 
           async:false,
           success:function(data){
           		iDays = data.trim();          		
           }
       });
  	}   
    return iDays;
}

//更改上级任务
function updateTree(task) {
  //console.debug("updateTree ",task);
  var error;

  //try to enlarge parent
  var p = task.getParent();

  //no parent:exit
  if (!p)
    return true;

  var newStart = p.start;
  var newEnd = p.end;

  if (p.start > task.start) {
    if (p.startIsMilestone) {
      task.master.setErrorOnTransaction(GanttMaster.messages["START_IS_MILESTONE"] + "\n" + p.name, task);
      return false;
    } else if (p.depends) {
      //task.master.setErrorOnTransaction(GanttMaster.messages["TASK_HAS_CONSTRAINTS"] + "\n" + p.name, task);
      //return false;
    }

    newStart = task.start;
  }
  if (p.end < task.end) {
    if (p.endIsMilestone) {
      task.master.setErrorOnTransaction(GanttMaster.messages["END_IS_MILESTONE"] + "\n" + p.name, task);
      return false;
    }

    newEnd = task.end;
  }

  //propagate updates if needed
  if (newStart != p.start || newEnd != p.end) {

    //can write?
    if (!p.canWrite){
      //task.master.setErrorOnTransaction(GanttMaster.messages["CANNOT_WRITE"] + "\n" + p.name, task);
      //return false;
    }

    //has external deps ?
    if (p.hasExternalDep) {
      task.master.setErrorOnTransaction(GanttMaster.messages["TASK_HAS_EXTERNAL_DEPS"] + "\n" + p.name, task);
      return false;
    }

    return p.setPeriod1(newStart,newEnd,p.starttime,p.endtime,p.passnoworktime);
  }

  return true;
}

//<%---------- CHANGE STATUS ---------------------- --%>
Task.prototype.changeStatus = function(newStatus) {
  //console.debug("changeStatus: "+this.name+" from "+this.status+" -> "+newStatus);
  //compute descendant for identify a cone where status changes propagate
  var cone = this.getDescendant();

  function propagateStatus(task, newStatus, manuallyChanged, propagateFromParent, propagateFromChildren) {
    //console.debug("propagateStatus",task.name, task.status,newStatus)
    var oldStatus = task.status;

    //no changes exit
    if(newStatus == oldStatus){
      return true;
    }
    //console.debug("propagateStatus: "+task.name + " from " + task.status + " to " + newStatus + " " + (manuallyChanged?" a manella":"")+(propagateFromParent?" da parent":"")+(propagateFromChildren?" da children":""));

    var todoOk = true;
    task.status = newStatus;

    if( task.master.cannotCloseTaskIfIssueOpen && newStatus=="STATUS_DONE" && task.openIssues>0){
      task.master.setErrorOnTransaction(GanttMaster.messages["CANNOT_CLOSE_TASK_IF_OPEN_ISSUE"] +" " +task.name);
      return false;
    }

    //xxxx -> STATUS_DONE  may activate dependent tasks, both suspended and undefined. Will set to done all descendants.
    //STATUS_FAILED -> STATUS_DONE          do nothing if not forced by hand
    if (newStatus == "STATUS_DONE") {

      if ((manuallyChanged || oldStatus != "STATUS_FAILED")) { //cannot change for cascade when failed

        //can be closed only if superiors are already done
        var sups = task.getSuperiors();
        for (var i=0;i<sups.length;i++) {
          if (cone.indexOf(sups[i].from) < 0) {
            if (sups[i].from.status != "STATUS_DONE") {
              if (manuallyChanged || propagateFromParent)
               // task.master.setErrorOnTransaction(GanttMaster.messages["GANTT_ERROR_DEPENDS_ON_OPEN_TASK"] + "\n" + sups[i].from.name + " -> " + task.name);
              todoOk = false;
              break;
            }
          }
        }

        if (todoOk) {
          //todo set progress to 100% if set on config

          var chds = task.getChildren();
          //set children as done
          for (var i=0;i<chds.length;i++)
            propagateStatus(chds[i], "STATUS_DONE", false,true,false);

          //set inferiors as active if outside the cone
          propagateToInferiors(cone, task.getInferiors(), "STATUS_ACTIVE");
        }
      } else {
        todoOk = false;
      }


      //  STATUS_UNDEFINED -> STATUS_ACTIVE       all children become active, if they have no dependencies.
      //  STATUS_SUSPENDED -> STATUS_ACTIVE       sets to active all children and their descendants that have no inhibiting dependencies.
      //  STATUS_DONE -> STATUS_ACTIVE            all those that have dependencies must be set to suspended.
      //  STATUS_FAILED -> STATUS_ACTIVE          nothing happens: child statuses must be reset by hand.
    } else if (newStatus == "STATUS_ACTIVE") {

      if ((manuallyChanged || oldStatus != "STATUS_FAILED")) { //cannot change for cascade when failed

        //activate parent if closed
        var par=task.getParent();
        if (par && par.status != "STATUS_ACTIVE") {
          todoOk=propagateStatus(par,"STATUS_ACTIVE",false,false,true);
        }

        if(todoOk){
          //can be active only if superiors are already done
          var sups = task.getSuperiors();
          for (var i=0;i<sups.length;i++) {
            if (sups[i].from.status != "STATUS_DONE") {
              if (manuallyChanged || propagateFromChildren)
             // task.master.setErrorOnTransaction(GanttMaster.messages["GANTT_ERROR_DEPENDS_ON_OPEN_TASK"] + "\n" + sups[i].from.name + " -> " + task.name);
              todoOk = false;
              break;
            }
          }
        }

        if (todoOk) {
          var chds = task.getChildren();
          if (oldStatus == "STATUS_UNDEFINED" || oldStatus == "STATUS_SUSPENDED") {
            //set children as active
            for (var i=0;i<chds.length;i++)
              if (chds[i].status != "STATUS_DONE" )
                propagateStatus(chds[i], "STATUS_ACTIVE", false,true,false);
          }

          //set inferiors as suspended
          var infs = task.getInferiors();
          for (var i=0;i<infs.length;i++)
            propagateStatus(infs[i].to, "STATUS_SUSPENDED", false,false,false);
        }
      } else {
        todoOk = false;
      }

      // xxxx -> STATUS_SUSPENDED       all active children and their active descendants become suspended. when not failed or forced
      // xxxx -> STATUS_UNDEFINED       all active children and their active descendants become suspended. when not failed or forced
    } else if (newStatus == "STATUS_SUSPENDED" || newStatus == "STATUS_UNDEFINED") {
      if (manuallyChanged || oldStatus != "STATUS_FAILED") { //cannot change for cascade when failed

        //suspend parent if not active
        var par=task.getParent();
        if (par && par.status != "STATUS_ACTIVE") {
          todoOk=propagateStatus(par,newStatus,false,false,true);
        }


        var chds = task.getChildren();
        //set children as active
        for (var i=0;i<chds.length;i++){
          if (chds[i].status != "STATUS_DONE")
            propagateStatus(chds[i], newStatus, false,true,false);
        }

        //set inferiors as STATUS_SUSPENDED or STATUS_UNDEFINED
        propagateToInferiors(cone, task.getInferiors(), newStatus);
      } else {
        todoOk = false;
      }

      // xxxx -> STATUS_FAILED children and dependent failed
    } else if (newStatus == "STATUS_FAILED") {
      var chds = task.getChildren();
      //set children as failed
      for (var i=0;i<chds.length;i++)
        propagateStatus(chds[i], "STATUS_FAILED", false,true,false);

      //set inferiors as active
      //set children as done
      propagateToInferiors(cone, task.getInferiors(), "STATUS_FAILED");
    }
    if (!todoOk){
      task.status = oldStatus;
      //console.debug("status rolled back: "+task.name + " to " + oldStatus);
    }

    return todoOk;
  }

  /**
   * A helper method to traverse an array of 'inferior' tasks
   * and signal a status change.
   */
  function propagateToInferiors(cone, infs, status) {
    for (var i=0;i<infs.length;i++) {
      if (cone.indexOf(infs[i].to) < 0) {
        propagateStatus(infs[i].to, status, false, false, false);
      }
    }
  }

  var todoOk = true;
  var oldStatus = this.status;

  todoOk = propagateStatus(this, newStatus, true,false,false);

  if (!todoOk)
    this.status = oldStatus;

  return todoOk;
};

Task.prototype.synchronizeStatus=function(){
  var oldS=this.status;
  this.status="";
  return this.changeStatus(oldS);
};

Task.prototype.isLocallyBlockedByDependencies=function(){
  var sups = this.getSuperiors();
  var blocked=false;
  for (var i=0;i<sups.length;i++) {
    if (sups[i].from.status != "STATUS_DONE") {
      blocked=true;
      break;
    }
  }
  return blocked;
};

//<%------ TASK STRUCTURE -----%>
Task.prototype.getRow = function() {
  ret = -1;
  if (this.master)
    ret = this.master.tasks.indexOf(this);
  return ret;
};


Task.prototype.getParents = function() {
  var ret;
  if (this.master) {
    var topLevel = this.level;
    var pos = this.getRow();
    ret = [];
    for (var i = pos; i >= 0; i--) {
      var par = this.master.tasks[i];
      if (topLevel > par.level) {
        topLevel = par.level;
        ret.push(par);
      }
    }
  }
  return ret;
};


Task.prototype.getParent = function() {
  var ret;
  if (this.master) {
    for (var i = this.getRow(); i >= 0; i--) {
      var par = this.master.tasks[i];
      if (this.level > par.level) {
        ret = par;
        break;
      }
    }
  }
  return ret;
};


Task.prototype.isParent = function() {
  var ret = false;
  if (this.master) {
    var pos = this.getRow();
    if (pos < this.master.tasks.length - 1)
      ret = this.master.tasks[pos + 1].level > this.level; 
      ret = this.hasChild&&ret;
  }
  return ret;
};


Task.prototype.getChildren = function() {
  var ret = [];
  if (this.master) {
    var pos = this.getRow();
    for (var i = pos + 1; i < this.master.tasks.length; i++) {
      var ch = this.master.tasks[i];
      if (ch.level == this.level + 1)
        ret.push(ch);
      else if (ch.level <= this.level) // exit loop if parent or brother
        break;
    }
  }
  return ret;
};


Task.prototype.getDescendant = function() {
  var ret = [];
  if (this.master) {
    var pos = this.getRow();
    for (var i = pos + 1; i < this.master.tasks.length; i++) {
      var ch = this.master.tasks[i];
      if (ch.level > this.level)
        ret.push(ch);
      else
        break;
    }
  }
  return ret;
};


Task.prototype.getSuperiors = function() {
  var ret = [];
  var task = this;
  if (this.master) {
    ret = this.master.links.filter(function(link) {
      return link.to == task;
    });
  }
  return ret;
};

Task.prototype.getSuperiorTasks = function() {
  var ret=[];
  var sups = this.getSuperiors();
  for (var i=0;i<sups.length;i++)
    ret.push(sups[i].from);
  return ret;
};


Task.prototype.getInferiors = function() {
  var ret = [];
  var task = this;
  if (this.master) {
    ret = this.master.links.filter(function(link) {
      return link.from == task;
    });
  }
  return ret;
};

Task.prototype.getInferiorTasks = function() {
  var ret=[];
  var infs = this.getInferiors();
  for (var i=0;i<infs.length;i++)
    ret.push(infs[i].to);
  return ret;
};

  Task.prototype.deleteTask = function() {
  
  //delete both dom elements
  if (this.rowElement) {
    this.rowElement.remove();
  }

  //delete both dom elements
  if (this.ganttElement) {
    this.ganttElement.remove();
  }

  //remove children
  var chd = this.getChildren();
  for (var i=0;i<chd.length;i++) {
    //add removed child in list
    if(!chd[i].isNew())
      this.master.deletedTaskIds.push(chd[i].id);
    chd[i].deleteTask();
  }

  if(!this.isNew())
    this.master.deletedTaskIds.push(this.id);


  //remove from in-memory collection
  this.master.tasks.splice(this.getRow(), 1);

  //remove from links
  var task = this;
  this.master.links = this.master.links.filter(function(link) {
    return link.from != task && link.to != task;
  });
};


Task.prototype.isNew=function(){
  return (this.id+"").indexOf("tmp_")==0;
};

Task.prototype.isDependent=function(t) {
  //console.debug("isDependent",this.name, t.name)
  var task=this;
  var dep= this.master.links.filter(function(link) {
    return link.from == task ;
  });

  // is t a direct dependency?
  for (var i=0;i<dep.length;i++) {
    if (dep[i].to== t)
      return true;
  }
  // is t an indirect dependency
  for (var i=0;i<dep.length;i++) {
    if (dep[i].to.isDependent(t)) {
      return true;
    }
  }
  return false;
};

Task.prototype.setLatest=function(maxCost) {
  this.latestStart = maxCost - this.criticalCost;
  this.latestFinish = this.latestStart + this.duration;
};


//<%-------INDENT/OUTDENT ---%>
Task.prototype.indent = function() {
  //console.debug("indent", this);
  //a row above must exist
  var row = this.getRow();

  //no row no party
  if (row <=0)
    return false;

  var ret = false;
  var taskAbove = this.master.tasks[row - 1];
  var newLev = this.level + 1;
  if (newLev <= taskAbove.level + 1) {
    ret = true;
    //trick to get parents after indent
    this.level++;
    var futureParents = this.getParents();
    this.level--;
    var oldLevel = this.level;
    for (var i = row; i < this.master.tasks.length; i++) {
      var desc = this.master.tasks[i];
      if (desc.level > oldLevel || desc == this) {
        desc.level++;
        //remove links from descendant to my parents
        this.master.links = this.master.links.filter(function(link) {
          var linkToParent = false;
          if (link.to == desc)
            linkToParent = futureParents.indexOf(link.from) >= 0;
          else if (link.from == desc)
            linkToParent = futureParents.indexOf(link.to) >= 0;
          return !linkToParent;
        });
      } else
        break;
    }

    var parent = this.getParent();
    // set start date to parent' start if no deps
    if(parent && !this.depends){
    	var new_end = computeEndByDuration(parent.start, this.duration);
    	this.master.changeTaskDates(this, parent.start, new_end);
    }
    //recompute depends string
    this.master.updateDependsStrings();
    //enlarge parent using a fake set period
    this.setPeriod1(this.start + 1, this.end + 1,this.starttime,this.endtime,this.passnoworktime);

    //force status check
    this.synchronizeStatus();
  }
  return ret;
};


Task.prototype.outdent = function() {
  //console.debug("outdent", this);
  //a level must be >1 -> cannot escape from root
  if (this.level < 1)
    return false;

  var ret = false;
  var oldLevel = this.level;

  ret = true;
  var row = this.getRow();
  for (var i = row; i < this.master.tasks.length; i++) {
    var desc = this.master.tasks[i];
    if (desc.level > oldLevel || desc == this) {
      desc.level--;
    } else
      break;
  }

  var task = this;
  var chds = this.getChildren();
  //remove links from me to my new children
  this.master.links = this.master.links.filter(function(link) {
    var linkExist = (link.to == task && chds.indexOf(link.from) >= 0 || link.from == task && chds.indexOf(link.to) >= 0);
    return !linkExist;
  });


  //enlarge me if inherited children are larger
  for (var i=0;i<chds.length;i++) {
    //remove links from me to my new children
    chds[i].setPeriod(chds[i].start + 1, chds[i].end + 1);
  }

  //recompute depends string
  this.master.updateDependsStrings();

  //enlarge parent using a fake set period
  this.setPeriod(this.start + 1, this.end + 1);

  //force status check
  this.synchronizeStatus();
  return ret;
};


//<%-----  MOVE UP / MOVE DOWN -----%>
Task.prototype.moveUp = function() {
  //console.debug("moveUp", this);
  var ret = false;

  //a row above must exist
  var row = this.getRow();

  //no row no party
  if (row <=0)
    return false;

  //find new row
  var newRow;
  for (newRow = row - 1; newRow >= 0; newRow--) {
    if (this.master.tasks[newRow].level <= this.level)
      break;
  }

  //is a parent or a brother
  if (this.master.tasks[newRow].level == this.level) {
    ret = true;
    //compute descendant
    var descNumber = 0;
    for (var i = row + 1; i < this.master.tasks.length; i++) {
      var desc = this.master.tasks[i];
      if (desc.level > this.level) {
        descNumber++;
      } else {
        break;
      }
    }
    //move in memory
    var blockToMove = this.master.tasks.splice(row, descNumber + 1);
    var top = this.master.tasks.splice(0, newRow);
    this.master.tasks = [].concat(top, blockToMove, this.master.tasks);
    //move on dom
    var rows = this.master.editor.element.find("tr[taskid]");
    var domBlockToMove = rows.slice(row, row + descNumber + 1);
    rows.eq(newRow).before(domBlockToMove);

    //recompute depends string
    this.master.updateDependsStrings();
  } else {
    this.master.setErrorOnTransaction(GanttMaster.messages["TASK_MOVE_INCONSISTENT_LEVEL"], this);
    ret = false;
  }
  return ret;
};


Task.prototype.moveDown = function() {
  //console.debug("moveDown", this);

  //a row below must exist, and cannot move root task
  var row = this.getRow();
  //if (row >= this.master.tasks.length - 1 || row==0)这导致第一条任务不能往下移
  if (row >= this.master.tasks.length - 1)
    return false;

  var ret = false;

  //find nearest brother
  var newRow;
  for (newRow = row + 1; newRow < this.master.tasks.length; newRow++) {
    if (this.master.tasks[newRow].level <= this.level)
      break;
  }

  //is brother
  if (this.master.tasks[newRow] && this.master.tasks[newRow].level == this.level) {
    ret = true;
    //find last desc
    for (newRow = newRow + 1; newRow < this.master.tasks.length; newRow++) {
      if (this.master.tasks[newRow].level <= this.level)
        break;
    }

    //compute descendant
    var descNumber = 0;
    for (var i = row + 1; i < this.master.tasks.length; i++) {
      var desc = this.master.tasks[i];
      if (desc.level > this.level) {
        descNumber++;
      } else {
        break;
      }
    }

    //move in memory
    var blockToMove = this.master.tasks.splice(row, descNumber + 1);
    var top = this.master.tasks.splice(0, newRow - descNumber - 1);
    this.master.tasks = [].concat(top, blockToMove, this.master.tasks);


    //move on dom
    var rows = this.master.editor.element.find("tr[taskid]");
    var aft = rows.eq(newRow - 1);
    var domBlockToMove = rows.slice(row, row + descNumber + 1);
    aft.after(domBlockToMove);

    //recompute depends string
    this.master.updateDependsStrings();
  }else{
	  this.master.setErrorOnTransaction(GanttMaster.messages["TASK_MOVE_INCONSISTENT_LEVEL"], this);
  }

  return ret;
};


//<%------------------------------------------------------------------------  LINKS OBJECT ---------------------------------------------------------------%>
function Link(taskFrom, taskTo, lagInWorkingDays) {
  this.from = taskFrom;
  this.to = taskTo;
  this.lag = lagInWorkingDays;
}


//<%------------------------------------------------------------------------  ASSIGNMENT ---------------------------------------------------------------%>
function Assignment(id, resourceId, roleId, effort) {
  this.id = id;
  this.resourceId = resourceId;
  this.roleId = roleId;
  this.effort = effort;
}


//<%------------------------------------------------------------------------  RESOURCE ---------------------------------------------------------------%>
function Resource(id, name) {
  this.id = id;
  this.name = name;
}


//<%------------------------------------------------------------------------  ROLE ---------------------------------------------------------------%>
function Role(id, name) {
  this.id = id;
  this.name = name;
}