24. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 10/18/2018 2:01:20 PM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

24.1 Files compared

# Location File Last Modified
1 VIX_SIV_v3_0_patch_201_build_8.zip\v3.0_patch_201_build_8\common\ZFViewerServices\ViewerRender-2.2.6841.19565.zip\VIX.Viewer.Service\Viewer\js\cache cache.js Mon Sep 24 17:06:26 2018 UTC
2 VIX_SIV_v3_0_patch_201_build_8.zip\v3.0_patch_201_build_8\common\ZFViewerServices\ViewerRender-2.2.6841.19565.zip\VIX.Viewer.Service\Viewer\js\cache cache.js Wed Oct 17 14:01:48 2018 UTC

24.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 1 45290
Changed 0 0
Inserted 0 0
Removed 0 0

24.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

24.4 Active regular expressions

No regular expressions were active.

24.5 Comparison detail

  1   /**
  2    * This mo dule deals  with cach ing images
  3    */
  4  
  5   var dicomV iewer = (f unction (d icomViewer ) {
  6  
  7       "use s trict";
  8  
  9       if(dic omViewer = == undefin ed) {
  10           di comViewer  = {};
  11       }
  12     
  13       var ca chedImages  = {};
  14       var ca chedImages BySeries =  {};
  15       var ma ximumSizeI nBytesForM obileDevic e = 100 *  1024 * 102 4; // 100  MB cache
  16       var ma ximumSizeI nBytesForS ystem = 80 0 * 1024 *  1024; //  800 MB cac he
  17       
  18       var ma ximumSizeI nBytes = 8 00 * 1024  * 1024; //  800 MB ca che
  19       var ma ximumSizeT oReduceInB ytes = (ma ximumSizeI nBytes * 0 .40); // 2 50 MB cach e
  20       var ma ximumSizeT oReduceInB ytesInView ingSeries  = (maximum SizeInByte s * 0.20);  // 125 MB  cache
  21  
  22       var br owserLoadi ngMemorySi ze = 50 *  1024 * 102 4; // 50 M B cache ap proximatel y
  23       var co mpilationM emorySize  = 10 * 102 4 * 1024;  // 10 MB c ache appro ximately
  24       var st ringMemory Size = 8 *  1024 * 10 24; // 8 M B cache ap proximatel y
  25       var ca cheSizeInB ytes = bro wserLoadin gMemorySiz e + compil ationMemor ySize + st ringMemory Size;
  26  
  27       var ca cheInforma tion = { s eries : {}  };
  28  
  29       // Hol d the visu al viewpor t image ra w data
  30       var vi ewportImag eDataMap =  new Map() ;
  31  
  32       functi on putImag ePromise(s tudyUid, i mageUid, f rameIndex,  imageProm ise, serie sIndex, in dex) {
  33          if( imageUid = == undefin ed) {
  34                throw "p utImagePro mise: imag eUid must  not be und efined";
  35           }
  36  
  37           if (imageProm ise === un defined) {
  38                throw "p utImagePro mise: imag ePromise m ust not be  undefined ";
  39           }
  40  
  41           if (cachedIma ges.hasOwn Property(i mageUid) = == true) {
  42                return;
  43           }
  44  
  45           va r cachedIm age = {
  46                imageUid  : imageUi d,
  47                studyUid :studyUid,
  48                frameInd ex : frame Index,
  49                imagePro mise : ima gePromise,
  50                timeStam p : new Da te(),
  51                sizeInBy tes: 0,
  52                seriesIn dex : seri esIndex,
  53                index :  index
  54           };
  55  
  56           im agePromise .done(func tion(image ) {
  57                if(image .imageType  == "image " && cache dImages[im ageUid + " _" + frame Index] ===  undefined ) {
  58  
  59                    purg eCache(stu dyUid, ima ge.sizeInB ytes);
  60                    //va r objectSi zeInBytes  = memorySi zeOf(image );
  61                    //pu rgeCache(s tudyUid, o bjectSizeI nBytes);
  62  
  63                    cach edImages[i mageUid +  "_" + fram eIndex] =  cachedImag e;
  64                    if(c achedImage sBySeries[ seriesInde x] === und efined) {
  65                         cachedImag esBySeries [seriesInd ex] = {};
  66                    }
  67  
  68                    if(c achedImage sBySeries[ seriesInde x][imageUi d] === und efined) {
  69                         cachedImag esBySeries [seriesInd ex][imageU id] = {};
  70                    }
  71                    cach edImagesBy Series[ser iesIndex][ imageUid][ frameIndex ] = imageU id + "_" +  frameInde x;
  72                    cach edImage.lo aded = tru e;
  73  
  74                    if(i mage.sizeI nBytes ===  undefined ) {
  75                         throw "put ImagePromi se: image  does not h ave sizeIn Bytes prop erty or";
  76                    }
  77  
  78                    if(i mage.sizeI nBytes.toF ixed === u ndefined)  {
  79                         throw "put ImagePromi se: image. sizeInByte s is not a  number";
  80                    }
  81  
  82                    cach edImage.si zeInBytes  = image.si zeInBytes;
  83                    //ca chedImage. sizeInByte s = memory SizeOf(ima ge);
  84                    cach edImage.im age = imag e;
  85                    cach eSizeInByt es += cach edImage.si zeInBytes;  
  86                    addC acheInfo(s tudyUid, s eriesIndex , imageUid , frameInd ex, index) ;
  87                }
  88           }) ;
  89       }
  90  
  91       functi on purgeCa che(studyU id, bytesN eeded, red ucedSizeIn Bytes, cou nt, unload ) {
  92           if  (reducedS izeInBytes  && (reduc edSizeInBy tes > byte sNeeded))  {
  93                return;
  94           }
  95  
  96           va r cacheDat a = dicomV iewer.getC acheData(s tudyUid);
  97           if  (getCache Percentage () < 90 ||  cacheData .initialCa che) {
  98                return;
  99           }
  100  
  101           va r arrayToS earchImage  = Object. keys(cache dImages);
  102           va r prevNext Count = (c ount == un defined) ?  2 : 0;
  103           re ducedSizeI nBytes = 0 ;
  104  
  105           fo r (var i =  0; i < ar rayToSearc hImage.len gth; i++)  {
  106                if (redu cedSizeInB ytes && (r educedSize InBytes >  bytesNeede d)) {
  107                    retu rn;
  108                }
  109  
  110                var last CachedImag eKey = arr ayToSearch Image[i];
  111                var last CachedImag e = cached Images[las tCachedIma geKey];
  112                if (last CachedImag e != null)  {
  113                    var  imageIndex  = parseIn t(dicomVie wer.Series .Image.get ImageIndex (lastCache dImage.stu dyUid,
  114                                                                                            lastCache dImage.ser iesIndex,
  115                                                                                            lastCache dImage.ima geUid));
  116                    var  isViewing  = false;
  117                    var  isMultiFra me = dicom Viewer.thu mbnail.isS eriesConta insMultifr ame(lastCa chedImage. studyUid,  lastCached Image.seri esIndex);
  118                    if ( isMultiFra me) {
  119                         for (var j  = imageIn dex - prev NextCount;  j <= (ima geIndex +  prevNextCo unt); j++)  {
  120                             if (di comViewer. viewports. isImageVis ible(lastC achedImage .seriesInd ex, j) ===  true) {
  121                                 is Viewing =  true;
  122                                 br eak;
  123                             }
  124                         }
  125                    } el se {
  126                         for (var j  = lastCac hedImage.s eriesIndex  - prevNex tCount; j  <= (lastCa chedImage. seriesInde x + prevNe xtCount);  j++) {
  127                             if (di comViewer. viewports. isImageVis ible(j) == = true) {
  128                                 is Viewing =  true;
  129                                 br eak;
  130                             }
  131                         }
  132                    }
  133  
  134                    if ( unload) {
  135                         isViewing  = false;
  136                    }
  137                    
  138                    var  isPurge  =  isPurgeFi rstImage(l astCachedI mage);
  139                    if ( isViewing  === false  && isPurge ) {
  140                         cacheSizeI nBytes -=  lastCached Image.size InBytes;
  141                         reducedSiz eInBytes + = cacheSiz eInBytes;
  142                         deleteCach e(lastCach edImage, l astCachedI mageKey);
  143                         var purgeS eriesIndex  = isMulti Frame ? la stCachedIm age.index  : lastCach edImage.se riesIndex;
  144                         var purgeI mageIndex  = isMultiF rame ? las tCachedIma ge.seriesI ndex : und efined;
  145                         dicomViewe r.purgeSer ies(studyU id, purgeS eriesIndex , purgeIma geIndex);
  146  
  147                         try {
  148                             var vi ewportList  = dicomVi ewer.viewp orts.getAl lViewports ();
  149                             $.each (viewportL ist, funct ion(key, v alue){
  150                                 if  (value &&  value.pro gressbar & & value.pr ogressbar. seriesInde x == purge SeriesInde x) {
  151                                      value.pr ogressbar. drawImageC acheIndica tor();
  152                                 }
  153                             });
  154                         } catch (e ) {
  155  
  156                         }
  157                    }
  158                }
  159           }
  160           ar rayToSearc hImage = [ ];
  161           if  (getCache Percentage () > 90 &&  count ==  undefined)  {
  162                purgeCac he(studyUi d, bytesNe eded, redu cedSizeInB ytes, 0);
  163           }
  164           if  (getCache Percentage () > 90 &&  count ==  0 && unloa d == undef ined) {
  165                purgeCac he(studyUi d, bytesNe eded, redu cedSizeInB ytes, 0, t rue);
  166           }
  167       }
  168  
  169       functi on clearCa che(studyU id) {
  170           va r arrayToS earchImage  = Object. keys(cache dImages);
  171           fo r(var i=0;  i< arrayT oSearchIma ge.length;  i++) {
  172                var last CachedImag eKey = arr ayToSearch Image[i];
  173                var last CachedImag e =  cache dImages[la stCachedIm ageKey];
  174                if(lastC achedImage  != null)  {
  175                    if ( studyUid ! == undefin ed && last CachedImag e.studyUid  !== study Uid) {
  176                         continue;
  177                    }
  178  
  179                    cach eSizeInByt es -= last CachedImag e.sizeInBy tes;
  180                    dele teCache(la stCachedIm age, lastC achedImage Key);
  181                }
  182           }
  183           ar rayToSearc hImage = [ ];
  184       }
  185       
  186       functi on addCach eInfo(stud yUid, seri esIndex, i mageUid, f rameIndex,  index) {
  187           va r frameInf o = {
  188                frameNum ber : fram eIndex ,
  189                imageUid  : imageUi d,
  190                seriesIn dex : seri esIndex
  191           };
  192  
  193           va r series =  cacheInfo rmation.se ries[serie sIndex];
  194           if (series == = undefine d) {
  195                series =  {};
  196                cacheInf ormation.s eries[seri esIndex] =  series;
  197           }
  198  
  199           va r image =   series[im ageUid];
  200           if (image ===  undefined ) {
  201                image =  {};
  202                series[i mageUid] =  image;
  203           }
  204           im age[frameI ndex] = fr ameInfo;
  205          
  206           va r tempInde x = index  !== undefi ned ? inde x : series Index;
  207           va r isMultiF rame = dic omViewer.t humbnail.i sSeriesCon tainsMulti frame(stud yUid, temp Index)
  208           va r tempSeri esIndex =  seriesInde x;
  209           if (isMultiFr ame && ind ex !== und efined) {
  210                tempSeri esIndex =  index;
  211           }
  212    
  213           va r imageInd ex = dicom Viewer.get ImageIndex ForImageUi d(studyUid , tempSeri esIndex, i mageUid);
  214           if (imageInde x == undef ined) {
  215                imageInd ex = 0;
  216           }
  217  
  218           $( "#cacheman ager_progr ess").trig ger("image _cache_upd ated", get CacheInfo( ));
  219           up dateCacheI ndicators( studyUid,t empSeriesI ndex, imag eUid, imag eIndex);
  220           va r progress Bar = dico mViewer.ca cheIndicat or.getCach eIndicator (seriesInd ex,imageIn dex);
  221           if (progressB ar == unde fined) {
  222                progress Bar = dico mViewer.ca cheIndicat or.getCach eIndicator (seriesInd ex,imageIn dex-1);
  223           }
  224  
  225           if (progressB ar != unde fined) {
  226                var prog ressBarId  = progress Bar.imageI ndicator.i d
  227                var imag e = dicomV iewer.Seri es.Image.g etImage(st udyUid,ser iesIndex,i mageIndex) ;
  228                if(image  !== undef ined) {
  229                    var  totalFrame  = dicomVi ewer.Serie s.Image.ge tImageFram eCount(ima ge);
  230                    fram eIndex = f rameIndex+ 1;
  231                    var  thumbnailI d = "image viewer_"+d icomViewer .replaceDo tValue(stu dyUid)+"_" +(seriesIn dex)+"_thu mb"+(image Index);   
  232                    var  element =  document.g etElementB yId(thumbn ailId);
  233                    if(e lement ==  null) {
  234                         totalFrame  = dicomVi ewer.Serie s.getImage Count(stud yUid,serie sIndex);
  235                         frameIndex  = imageIn dex+1;
  236                    }
  237  
  238                    $("# "+progress BarId).tri gger("upda te",[total Frame,fram eIndex,pro gressBar]) ;
  239                }
  240           }
  241       }
  242  
  243       functi on updateC acheIndica tors(study Uid, serie sIndex, im ageUid, im ageIndex)  {
  244           if (imageInde x == undef ined) {
  245                var imag eIndex = d icomViewer .getImageI ndexForIma geUid(stud yUid, seri esIndex, i mageUid);
  246           }
  247  
  248           if (imageInde x !== unde fined) {
  249                var imag eValue = d icomViewer .Series.Im age.getIma ge(studyUi d,seriesIn dex,imageI ndex); 
  250                if(image Value !==  undefined)  {
  251                    if(d icomViewer .thumbnail .isSeriesC ontainsMul tiframe(st udyUid,ser iesIndex))  {
  252                         var totalN umberOfFra mes = dico mViewer.Se ries.Image .getImageF rameCount( imageValue );
  253                         if((cached ImagesBySe ries[image Index] ===  undefined  || 
  254                            cachedI magesBySer ies[imageI ndex][imag eUid] ===  undefined)  || 
  255                            Object. keys(cache dImagesByS eries[imag eIndex]).l ength ===  0 || 
  256                            Object. keys(cache dImagesByS eries[imag eIndex][im ageUid]).l ength ===  0) {
  257                             update ThumbnailC acheIndica tion(image Uid, "red" );
  258                         } else {
  259                             if(Obj ect.keys(c achedImage sBySeries[ imageIndex ][imageUid ]).length  >= totalNu mberOfFram es) {
  260                                 up dateThumbn ailCacheIn dication(i mageUid, " green");
  261                             } else  if(Object .keys(cach edImagesBy Series[ima geIndex][i mageUid]). length ===  0) {
  262                                 up dateThumbn ailCacheIn dication(i mageUid, " red");
  263                             } else  {
  264                                 up dateThumbn ailCacheIn dication(i mageUid, " yellow");
  265                             }
  266                         }
  267                    } el se {
  268                         var imageV alue = dic omViewer.S eries.Imag e.getImage (studyUid, seriesInde x,0);
  269                         var totalN umberOFIma ges = dico mViewer.Se ries.getIm ageCount(s tudyUid,se riesIndex) ;
  270                         if(cachedI magesBySer ies[series Index] !==  undefined  && cached ImagesBySe ries[serie sIndex].le ngth !== 0 ) {
  271                             if(Obj ect.keys(c achedImage sBySeries[ seriesInde x]).length  >= totalN umberOFIma ges) {
  272                                var  thumbnail ImageId =   dicomView er.Series. Image.getI mageUid(di comViewer. Series.Ima ge.getImag e(studyUid ,seriesInd ex, 0));
  273                                upd ateThumbna ilCacheInd ication(th umbnailIma geId,"gree n");
  274                             } else  if(Object .keys(cach edImagesBy Series[ser iesIndex]) .length == = 0) {
  275                                 up dateThumbn ailCacheIn dication(i mageValue. imageUid," red");
  276                             } else  {
  277                                 up dateThumbn ailCacheIn dication(i mageValue. imageUid," yellow");
  278                             }
  279                         } else {
  280                             update ThumbnailC acheIndica tion(image Value.imag eUid,"red" );   
  281                         }
  282                    }
  283                }
  284           }
  285       }
  286  
  287       functi on removeC acheInfo(s eriesIndex ,imageUid, frameIndex ) {
  288           va r series =  cacheInfo rmation.se ries[serie sIndex];
  289           if (series == = undefine d) {
  290                throw "r emoveCache Info : ser ies is und efind";
  291           }
  292  
  293           va r image =   series[im ageUid];
  294           if (image ===  undefined ) {
  295                throw "r emoveCache Info : ima ge is unde find";
  296           }
  297           im age[frameI ndex] = un defined;
  298  
  299           if ( Object.k eys(image) .length ==  0) {
  300                image =  undefined;
  301           }
  302  
  303           $( "#cacheman ager_progr ess").trig ger("image _cache_upd ated", get CacheInfo( ));
  304       }
  305  
  306       
  307       functi on getImag ePromise(i mageUid) {
  308           if (imageUid  === undefi ned) {
  309                throw "g etImagePro mise: imag eUid must  not be und efined";
  310           }
  311  
  312           va r cachedIm age = cach edImages[i mageUid];
  313           if (cachedIma ge === und efined) {
  314                return u ndefined;
  315           }
  316  
  317           //  bump time  stamp for  cached im age
  318           ca chedImage. timeStamp  = new Date ();
  319           re turn cache dImage.ima gePromise;
  320       }
  321       
  322  
  323       /**
  324        * Che ck the giv en imageUi d is avail able in ca che array  or image a rray.
  325        */
  326       functi on isInCac he(imageUi d) {
  327           if (imageUid  === undefi ned) {
  328                return f alse;
  329           }
  330  
  331           va r cachedIm age = cach edImages[i mageUid];
  332           if (cachedIma ge === und efined) {
  333                return u ndefined;
  334           }
  335  
  336           re turn cache dImage.ima gePromise  != null;
  337       }
  338  
  339       functi on getCach eInfo() {
  340           re turn {
  341                maximumS izeInBytes  : maximum SizeInByte s,
  342                cacheSiz eInBytes :  cacheSize InBytes,
  343                numberOf ImagesCach ed: Object .keys(cach edImages). length
  344           };
  345       }
  346  
  347           fu nction set CacheSize( isMobileDe vice) {
  348           if (isMobileD evice) {
  349                maximumS izeInBytes  = maximum SizeInByte sForMobile Device; //  800 MB ca che
  350           }  else {
  351                maximumS izeInBytes  = maximum SizeInByte sForSystem ; // 800 M B cache
  352           }
  353  
  354           ma ximumSizeT oReduceInB ytes = (ma ximumSizeI nBytes * 0 .40); // 2 50 MB cach e
  355           ma ximumSizeT oReduceInB ytesInView ingSeries  = (maximum SizeInByte s * 0.20);  // 125 MB  cache 
  356           }
  357           
  358       /**
  359        * Get  the cache  percentag e
  360        */ 
  361       functi on getCach ePercentag e() {
  362           va r cacheInf o = getCac heInfo();
  363           re turn ((cac heInfo.cac heSizeInBy tes/cacheI nfo.maximu mSizeInByt es) * 100) ;
  364       }
  365  
  366       /**
  367        * Ret urn the im age's raw  pixel buff er array d ata
  368        * @pa ram {Type}  image - R endered im age in the  viewport
  369        */
  370       functi on getRawD ata(image)  {
  371           tr y
  372           {
  373                if(image  === undef ined || im age === nu ll) {
  374                    retu rn undefin ed;
  375                }
  376  
  377                if(!imag e.isCompre ssed) {
  378                    retu rn image.i mageData;
  379                }
  380  
  381                var rawI mageData =  pako.infl ate(image. imageData) ;
  382                if (imag e.bitsAllo cated == 1 6) {
  383                    var  imageDataL ength = ra wImageData .length;
  384                    var  rawImageDa ta16 = new  Uint16Arr ay(imageDa taLength /  2);
  385                    var  pixelIndex  = 0;
  386                    for  (var i = 0 ; i < imag eDataLengt h; i += 2)  {
  387                         rawImageDa ta16[pixel Index++] =  (rawImage Data[i + 1 ] * 256) +  rawImageD ata[i];
  388                    }
  389  
  390                    rawI mageData =  rawImageD ata16;
  391                }
  392  
  393                return r awImageDat a;
  394           }
  395           ca tch(e)
  396           {  }
  397       }
  398  
  399       /**
  400        * To  set the Vi sual viewp ort image  id as well  as raw pi xel data i n Key valu e form
  401        * @pa ram {Type}  image - R endered im age in the  viewport
  402        * @pa ram {Type}  canvasId  - specifie s the canv as id
  403        */
  404       functi on setImag eData(imag e, canvasI d, isBacku p) {
  405           tr y
  406           {
  407                if(image  == null | | image ==  undefined  || 
  408                   canva sId == nul l || canva sId == und efined) {
  409                    // I nvalid obj ect
  410                    retu rn;
  411                }
  412  
  413                if(!imag e.isCompre ssed) {
  414                    retu rn;
  415                }
  416  
  417                // Set t he default  memory
  418                if(cache SizeInByte s == 0) {
  419                    cach eSizeInByt es = brows erLoadingM emorySize  + compilat ionMemoryS ize + stri ngMemorySi ze;
  420                }
  421  
  422                var isNe wImageData  = false;
  423                var fram eNumber =  (isNaN(ima ge.frameNu mber) ? 0  : image.fr ameNumber) ;
  424                var imag eKey = can vasId + "  | " + imag e.imageUid  + "_" + f rameNumber ;
  425                var imag eData = vi ewportImag eDataMap.g et(imageKe y);
  426                if(image Data === u ndefined | | imageDat a === null ) {
  427                    view portImageD ataMap.set (imageKey,  getRawDat a(image));
  428                    isNe wImageData  = true;
  429                }
  430  
  431                // Delet e the exis ting image  in the ma p for same  renderer
  432                viewport ImageDataM ap.forEach (function( value, key , map) {
  433                    if(k ey !== ima geKey) {
  434                         if(value ! == undefin ed) {
  435                             cacheS izeInBytes  -= value. length;
  436                             cacheS izeInBytes  -= image. renderSize InBytes;
  437                         }
  438                         map.set(ke y, undefin ed);
  439                    } el se if(isNe wImageData ){
  440                         cacheSizeI nBytes +=  value.leng th;
  441                         cacheSizeI nBytes +=  image.rend erSizeInBy tes;
  442                    }
  443                });
  444  
  445                var cach eInKB = ca cheSizeInB ytes / 102 4;
  446                var cach eInMB = ca cheInKB /  1024;
  447                if(cache InMB > 800 ) {
  448                    dump ConsoleLog s(LL_WARN,  undefined , "setImag eData", "C ache size  : " + cach eInMB);
  449                }
  450  
  451                if(isBac kup === tr ue) {
  452                    retu rn viewpor tImageData Map.get(im ageKey);
  453                }
  454           }
  455           ca tch(e)
  456           {  }
  457       }
  458  
  459       /**
  460        * To  get the Vi sual viewp ort image' s raw pixe l buffer a rray data
  461        * @pa ram {Type}  image - R endered im age in the  viewport
  462        * @pa ram {Type}  canvasId  - specifie s the canv as id
  463        */
  464       functi on getImag eData(imag e, canvasI d) {
  465           tr y
  466           {
  467                if(image  == null | | image ==  undefined  || 
  468                   canva sId == nul l || canva sId == und efined) {
  469                    // I nvalid obj ect
  470                    retu rn;
  471                }
  472  
  473                if(!imag e.isCompre ssed) {
  474                    retu rn image.i mageData;
  475                } else {
  476                    var  frameNumbe r = (isNaN (image.fra meNumber)  ? 0 : imag e.frameNum ber);
  477                    var  imageKey =  canvasId  + " | " +  image.imag eUid + "_"  + frameNu mber;
  478                    var  imageData  = viewport ImageDataM ap.get(ima geKey);
  479                    if(i mageData = == undefin ed || imag eData ===  null) {
  480                         imageData  = setImage Data(image , canvasId , true);
  481                    }
  482  
  483                    retu rn imageDa ta;
  484                }
  485           }
  486           ca tch(e)
  487           {  }
  488  
  489           re turn undef ined;
  490       }
  491  
  492       /**
  493        * Del ete the ca che image
  494        * @pa ram {Type}  imageKey  - Specifie s the imag e key 
  495        */ 
  496       functi on deleteC acheImage( imageKey)  {
  497           tr y
  498           { 
  499                var cach eImage = c achedImage s[imageKey ];
  500                if(cache Image ===  undefined)  {
  501                    retu rn;
  502                }
  503  
  504                var imag e = cacheI mage.image ;
  505                if(image  === undef ined || im age === nu ll) {
  506                    retu rn;
  507                }
  508  
  509                image.im ageData =  undefined;
  510                image.wl Canvas = u ndefined;
  511                image.wl CanvasCont ext = unde fined;
  512                image.wl CanvasData  = undefin ed;
  513  
  514                delete c achedImage s[imageKey ];
  515           }
  516           ca tch(e)
  517           {  }
  518       }
  519  
  520        /**
  521        * che ck the las t cache im age is ser ies first  image or n ot
  522        * @pa ram {Type}  lastCache dImage - S pecifies t he lastCac hedImage d etails
  523        */ 
  524       functi on isPurge FirstImage (lastCache dImage){
  525           tr y {
  526                 //check  multi fra me or not.
  527                var imag eValue = d icomViewer .Series.Im age.getIma ge(lastCac hedImage.s tudyUid,0, 0);  
  528                var isMu ltiFrame =  dicomView er.thumbna il.isImage Thumbnail( imageValue ,true);
  529  
  530                var imag eIndex = ! isMultiFra me ? parse Int( dicom Viewer.Ser ies.Image. getImageIn dex(lastCa chedImage. studyUid,  lastCached Image.seri esIndex, l astCachedI mage.image Uid)) :"";
  531                if((isMu ltiFrame & & lastCach edImage.fr ameIndex = = 0) || (! isMultiFra me && imag eIndex ==  0) ) {
  532                    retu rn false;
  533                }
  534           }
  535           ca tch(e)
  536           {  }
  537           re turn true;
  538       }
  539  
  540        /**
  541        * Cac he the fir st image o f the seri es
  542        * @pa ram {Type}  study - S pecifies t he study d etails
  543        */ 
  544       functi on cacheFi rstImage ( study, app liedSeries Layout, st udyDetail,  studyUid)  {
  545           tr y
  546           {
  547                if(!stud y) {
  548                    retu rn false;
  549                }
  550  
  551                var firs tSeriesOrI mage = dic omViewer.S eries.Imag e.getImage (study.stu dyUid, 0,  0);
  552                if(!firs tSeriesOrI mage) {
  553                    retu rn false;
  554                }
  555  
  556                var cach eFirstImag ePrmoise =  $.Deferre d();
  557                var tota lImageCoun t = 0;
  558                var load edImageCou nt = 0;
  559                for(var  seriesInde x = 0; ser iesIndex <  study.ser iesCount;  seriesInde x++) {
  560                    var  noOfSeries OrImages =  (firstSer iesOrImage .isImageTh umbnail ?  study.seri es[seriesI ndex].imag es.length  : 1);
  561                    tota lImageCoun t += noOfS eriesOrIma ges;
  562                    for( var imageI ndex = 0;  imageIndex  < noOfSer iesOrImage s; imageIn dex++) {
  563                         var series OrImage =  (study.isD icom ? stu dy.series[ seriesInde x].images[ imageIndex ] : study[ seriesInde x]);
  564                         if(!isBlob (seriesOrI mage.image Type) && s eriesOrIma ge.imageTy pe !== IMA GETYPE_TIF F) {
  565                             var im ageType =  seriesOrIm age.imageT ype;
  566                             var im ageUid = s eriesOrIma ge.imageUi d;
  567                             var lo adImage =  dicomViewe r.getImage (study.stu dyUid, ima geUid, 0,  seriesInde x, imageTy pe);
  568                             loadIm age.done(f unction(im age) {
  569                                 lo adedImageC ount++;
  570                                 if  (loadedIm ageCount = = totalIma geCount) {
  571                                      cacheFir stImagePrm oise.resol ve(studyDe tail, stud yUid);
  572                                 }
  573                                 va r renderer  = dicomVi ewer.rende rer.getIma geRenderer (image.ima geUid+"_"+ image.fram eNumber);
  574                                 if (renderer)  {
  575                                      dicomVie wer.render er.removeI mageRender er(image.i mageUid+"_ "+image.fr ameNumber) ;
  576                                      var defe rred = $.D eferred();
  577                                      deferred .resolve(i mage);
  578                                      renderer .loadImage Renderer(d eferred, u ndefined,  study.stud yUid);
  579                                 }
  580                             });
  581                         }
  582                    }
  583                }
  584  
  585                return c acheFirstI magePrmois e;
  586           }
  587           ca tch(e)
  588           {  }
  589  
  590           re turn false ;
  591       }
  592  
  593       /**
  594        * Del ete the ca che
  595        * @pa ram {Type}  lastCache dImage - c ache image
  596        * @pa ram {Type}  lastCache dImageKey  - cache im age key
  597        */ 
  598       functi on deleteC ache(lastC achedImage , lastCach edImageKey ) {
  599           tr y
  600           {
  601                if(!last CachedImag e) {
  602                    retu rn false;
  603                }
  604  
  605                removeCa cheInfo(la stCachedIm age.series Index, las tCachedIma ge.imageUi d, lastCac hedImage.f rameIndex) ;
  606                deleteCa cheImage(l astCachedI mageKey);
  607                cachedIm agesBySeri es[lastCac hedImage.s eriesIndex ][lastCach edImage.im ageUid][la stCachedIm age.frameI ndex] = un defined;
  608                delete c achedImage sBySeries[ lastCached Image.seri esIndex][l astCachedI mage.image Uid][lastC achedImage .frameInde x];
  609  
  610                if(cache dImagesByS eries[last CachedImag e.seriesIn dex][lastC achedImage .imageUid]  !== undef ined && Ob ject.keys( cachedImag esBySeries [lastCache dImage.ser iesIndex][ lastCached Image.imag eUid]).len gth === 0)  {
  611                    dele te cachedI magesBySer ies[lastCa chedImage. seriesInde x][lastCac hedImage.i mageUid];
  612                }
  613  
  614                if(cache dImagesByS eries[last CachedImag e.seriesIn dex] !== u ndefined & &
  615                   Objec t.keys(cac hedImagesB ySeries[la stCachedIm age.series Index]).le ngth === 0 ) {
  616                    dele te cachedI magesBySer ies[lastCa chedImage. seriesInde x];
  617                }
  618  
  619                updateCa cheIndicat ors(lastCa chedImage. studyUid,l astCachedI mage.serie sIndex, la stCachedIm age.imageU id);
  620  
  621                return t rue;
  622           }
  623           ca tch(e)
  624           {  }
  625  
  626           re turn false ;
  627       }
  628  
  629       functi on memoryS izeOf(obj)  {
  630           va r bytes =  0;
  631  
  632           fu nction siz eOf(obj) {
  633                if(obj ! == null &&  obj !== u ndefined)  {
  634                    swit ch(typeof  obj) {
  635                    case  'number':
  636                         bytes += 8 ;
  637                         break;
  638                    case  'string':
  639                         bytes += o bj.length  * 2;
  640                         break;
  641                    case  'boolean' :
  642                         bytes += 4 ;
  643                         break;
  644                    case  'object':
  645                         var objCla ss = Objec t.prototyp e.toString .call(obj) .slice(8,  -1);
  646                         if(objClas s === 'Obj ect' || ob jClass ===  'Array')  {
  647                             for(va r key in o bj) {
  648                                 if (!obj.hasO wnProperty (key)) con tinue;
  649                                 si zeOf(obj[k ey]);
  650                             }
  651                         } else byt es += obj. toString() .length *  2;
  652                         break;
  653                    }
  654                }
  655                return b ytes;
  656           };
  657  
  658           fu nction for matByteSiz e(bytes) {
  659                if(bytes  < 1024) r eturn byte s + " byte s";
  660                else if( bytes < 10 48576) ret urn(bytes  / 1024).to Fixed(3) +  " KiB";
  661                else if( bytes < 10 73741824)  return(byt es / 10485 76).toFixe d(3) + " M iB";
  662                else ret urn(bytes  / 10737418 24).toFixe d(3) + " G iB";
  663           };
  664  
  665           re turn sizeO f(obj);
  666       };
  667  
  668       functi on isMemor yAvailable (allocated Memory) {
  669           va r cacheInf o = getCac heInfo();
  670           re turn (((al locatedMem ory / cach eInfo.maxi mumSizeInB ytes) * 10 0) < 80 ?  true : fal se);
  671       }
  672  
  673       // mod ule export s
  674       dicomV iewer.imag eCache = {
  675           pu tImageProm ise: putIm agePromise ,
  676           ge tImageProm ise: getIm agePromise ,
  677           ge tCacheInfo : getCache Info,
  678           is InCache: i sInCache,
  679           se tCacheSize : setCache Size,
  680           cl earCache:  clearCache ,
  681           ge tCachePerc entage: ge tCachePerc entage,
  682           se tImageData : setImage Data,
  683           ge tImageData : getImage Data,
  684           ge tRawData:  getRawData ,
  685           ca cheFirstIm age: cache FirstImage ,
  686           pu rgeCache:  purgeCache ,
  687           is MemoryAvai lable : is MemoryAvai lable
  688       };
  689  
  690       return  dicomView er;
  691   }(dicomVie wer));/**
  692    * New nod e file
  693    */
  694   var dicomV iewer = (f unction (d icomViewer ) {
  695  
  696       "use s trict";
  697  
  698       var im ageRendere rMap = {};
  699       var pr evNextCoun t = 2;
  700       var ti meOutSecs  = 2;
  701       var ca cheDataMap  = {};
  702       var st udiesToCac he = new A rray();
  703       var CA CHE_START  = 0;
  704       var CA CHE_INPROG RESS = 1;
  705       var CA CHE_INCOMP LETE = 2;
  706       var CA CHE_END =  3;
  707  
  708       functi on cacheIm ages(study Uid) {
  709           va r cacheDat a = getCac heData(stu dyUid);
  710           if  (!cacheDa ta || cach eData.enab led === fa lse) {
  711                return;
  712           }
  713  
  714           if  (cacheDat a.cacheSta tus == CAC HE_INPROGR ESS || cac heData.cac heStatus = = CACHE_EN D) {
  715                return;
  716           }
  717  
  718           if  (cacheDat a.cacheSta tus == CAC HE_START | | cacheDat a.cacheSta tus == CAC HE_INCOMPL ETE) {
  719                cacheDat a.cacheSta tus = CACH E_INPROGRE SS;
  720                setCache Data(study Uid, cache Data);
  721           }
  722  
  723           va r studyDet ail = cach eData.stud yDetail;
  724           if  (cacheDat a.seriesIn dexToCache  != undefi ned) {
  725                var seri esIndexToC ache = cac heData.ser iesIndexTo Cache;
  726                var seri es = study Detail.ser ies[series IndexToCac he];
  727                var imag eIndexToCa che = (cac heData.ima geIndexToC ache == un defined) ?  getImageI ndexToLoad (series) :  cacheData .imageInde xToCache;
  728                cacheDat a.seriesIn dexToCache  = undefin ed;
  729                cacheDat a.imageInd exToCache  = undefine d;
  730                setCache Data(study Uid, cache Data);
  731  
  732                getImage s(studyUid , series,  seriesInde xToCache,  imageIndex ToCache, t rue);
  733           }  else {
  734                var deta il = dicom Viewer.get StudyDetai ls(studyUi d);
  735                var appl iedSeriesL ayout = (d etail.disp laySetting s.Rows * d etail.disp laySetting s.Columns) ;
  736                var cach eFirstImag eDeferred  = dicomVie wer.imageC ache.cache FirstImage (detail, a ppliedSeri esLayout,  studyDetai l, studyUi d);
  737                cacheFir stImageDef erred.done (function( studyDetai l, studyUi d) {
  738                    var  prioritySe riesPromis e = new $. Deferred() ;
  739                    cach eData.prio ritySeries Promise =  prioritySe riesPromis e;
  740                    cach eSelectedS eries(stud yDetail, s tudyUid, d etail.sele ctedImage) ;
  741                    prio ritySeries Promise.do ne(functio n(priority Series) {
  742                         if (!prior itySeries. isCacheFul l) {
  743                             var ne xtSeriesIn dex = 0;
  744                             var ne xtImageInd ex = 0;
  745                             for (;  nextSerie sIndex < s tudyDetail .seriesCou nt; nextSe riesIndex+ +) {
  746                                 va r series =  studyDeta il.series[ nextSeries Index];
  747                                 if (series &&  series.im ageCount >  nextImage Index && n extSeriesI ndex != pr ioritySeri es.seriesI ndex) {
  748                                      getImage s(studyUid , series,  nextSeries Index, nex tImageInde x);
  749                                 }
  750                             }
  751                         }
  752                    });
  753                });
  754           }
  755       }
  756  
  757       functi on getImag eIndexToLo ad(series)  {
  758           va r imageInd exToLoad =  0;
  759           $. each(serie s.images,  function(k ey, image)  {
  760                if (!ima ge.isCompl eted || im age.isPurg ed) {
  761                    imag eIndexToLo ad = key;
  762                    retu rn false;
  763                }
  764           }) ;
  765           re turn image IndexToLoa d;
  766       }
  767  
  768       functi on cacheSe lectedSeri es(studyDe tail, stud yUid, sele ctedImage)  {
  769           va r seriesIn dex = 0;
  770           va r imageInd ex = 0;
  771           if (selectedI mage) {
  772                seriesIn dex = sele ctedImage. seriesInde x;
  773                imageInd ex = selec tedImage.i mageIndex;
  774           }
  775  
  776           va r series =  studyDeta il.series[ seriesInde x];
  777           if (selectedI mage) {
  778                var imag e = undefi ned;
  779                if (seri es.images)  {
  780                    imag e = series .images[im ageIndex];
  781                } else {
  782                    imag e = series ;
  783                }
  784                if (!ima ge.frameCo unt) {
  785                    imag eIndex = " ";
  786                }
  787                $("#" +  "imageview er_" + dic omViewer.r eplaceDotV alue(study Uid) + "_"  + seriesI ndex + "_t humb" + im ageIndex)[ 0].click() ;
  788           }
  789           ge tImages(st udyUid, se ries, seri esIndex, i mageIndex) ;
  790       }
  791  
  792       functi on getImag es(studyUi d, series,  seriesInd ex, imageI ndex, isRe cache) {
  793           va r image =  undefined;
  794           if  (series.i mages) {
  795                image =  series.ima ges[imageI ndex];
  796           }  else {
  797                image =  series;
  798           }
  799           
  800           if  (!image.i sDicom) {
  801                
  802           }  else {
  803                if (imag e.frameCou nt) {
  804                    getF rames(stud yUid, imag e, seriesI ndex, imag eIndex, 0) ;
  805                    if ( isRecache)  {
  806                         return;
  807                    }
  808                    imag eIndex++;
  809                    if ( imageIndex  < series. imageCount ) {
  810                         getImages( studyUid,  series, se riesIndex,  imageInde x);
  811                    }
  812                } else {
  813                    var  cacheDefer red = getI mageOrFram e(studyUid , seriesIn dex, image Index, 0);
  814                    cach eDeferred. done(funct ion(indexT oCache) {
  815                         dumpCacheS ize();
  816                         setCacheIm ageComplet e(studyUid , seriesIn dex, image Index, fal se, CACHE_ INPROGRESS );
  817                         imageIndex ++;
  818                         var isCach eFull = (d icomViewer .imageCach e.getCache Percentage () > 90);
  819                         var cacheD ata = getC acheData(s tudyUid);
  820                         if (isCach eFull && ! cacheData. initialCac he) {
  821                             var by tesNeeded  = series.i mageCount  * 5 * 1000 ;
  822                             dicomV iewer.imag eCache.pur geCache(st udyUid, by tesNeeded) ;
  823                             isCach eFull = fa lse;
  824                         }
  825                         if (imageI ndex < ser ies.imageC ount && !i sCacheFull ) {
  826                             if (in dexToCache .seriesInd exToCache  != undefin ed && inde xToCache.s eriesIndex ToCache !=  seriesInd ex) {
  827                                 se riesIndex  = indexToC ache.serie sIndexToCa che;
  828                                 im ageIndex =  0;
  829                             }
  830                             series  = cacheDa ta.studyDe tail.serie s[seriesIn dex];
  831                             getIma ges(studyU id, series , seriesIn dex, image Index);
  832                         } else {
  833                             if(cac heData.pri oritySerie sPromise)  {
  834                                 ca cheData.pr ioritySeri esPromise. resolve({
  835                                      seriesIn dex : seri esIndex,
  836                                      isCacheF ull : isCa cheFull
  837                                 }) ;
  838                                 ca cheData.pr ioritySeri esPromise  = null;
  839                             }
  840                             setCac heSeriesCo mplete(stu dyUid, ser iesIndex,  imageIndex , isCacheF ull);
  841                         }
  842                    });
  843                }
  844           }
  845       }
  846  
  847       functi on getFram es(studyUi d, image,  seriesInde x, imageIn dex, frame Index) {
  848           if  (image.is Completed)  {
  849                return;
  850           }
  851           va r cacheDef erred = ge tImageOrFr ame(studyU id, series Index, ima geIndex, f rameIndex) ;
  852           ca cheDeferre d.done(fun ction(inde xToCache)  {
  853                dumpCach eSize();
  854                frameInd ex++;
  855                var isCa cheFull =  (dicomView er.imageCa che.getCac hePercenta ge() > 90) ;
  856                var cach eData = ge tCacheData (studyUid) ;
  857                if (isCa cheFull &&  !cacheDat a.initialC ache) {
  858                    var  bytesNeede d = image. frameCount  * 5 * 100 0;
  859                    dico mViewer.im ageCache.p urgeCache( studyUid,  bytesNeede d);
  860                    isCa cheFull =  false;
  861                }
  862                if (fram eIndex < i mage.frame Count && ! isCacheFul l) {
  863                    if ( (indexToCa che.series IndexToCac he != unde fined && i ndexToCach e.seriesIn dexToCache  != series Index) ||  (indexToCa che.imageI ndexToCach e != undef ined && in dexToCache .imageInde xToCache ! = imageInd ex)) {
  864                         seriesInde x = cacheD ata.series IndexToCac he;
  865                         imageIndex  = cacheDa ta.imageIn dexToCache ;
  866                         frameIndex  = 0;
  867                    }
  868                    var  series = c acheData.s tudyDetail .series[se riesIndex] ;
  869                    if ( series.ima ges) {
  870                         image = se ries.image s[imageInd ex];
  871                    } el se {
  872                         image = se ries;
  873                    }
  874                    getF rames(stud yUid, imag e, seriesI ndex, imag eIndex, fr ameIndex);
  875                } else {
  876                    setC acheImageC omplete(st udyUid, se riesIndex,  imageInde x, isCache Full);
  877                }
  878           }) ;
  879       }
  880  
  881       functi on setCach eImageComp lete(study Uid, serie sIndex, im ageIndex,  isCacheFul l, cacheSt atus) {
  882           va r cacheDat a = getCac heData(stu dyUid);
  883           va r studyDet ail = cach eData.stud yDetail;
  884           if  (isCacheF ull) {
  885                setCache SeriesComp lete(study Uid, serie sIndex, im ageIndex,  isCacheFul l);
  886           }  else {
  887                var seri es = study Detail.ser ies[series Index];
  888                if (seri es.images)  {
  889                    var  image = se ries.image s[imageInd ex];
  890                    imag e.isComple ted = true ;
  891                    imag e.isPurged  = false;
  892                    seri es.images[ imageIndex ] = image;
  893                    stud yDetail.se ries[serie sIndex] =  series;
  894                    var  isSeriesCo mplete = t rue;
  895                    $.ea ch(series. images, fu nction(key , image) {
  896                         if (!image .isComplet ed || imag e.isPurged ) {
  897                             isSeri esComplete  = false;
  898                             return  false;
  899                         }
  900                    });
  901  
  902                    if ( isSeriesCo mplete) {
  903                         setCacheSe riesComple te(studyUi d, seriesI ndex, imag eIndex, is CacheFull) ;
  904                    } el se {
  905                         cacheData. cacheStatu s = cacheS tatus ? ca cheStatus  : CACHE_IN COMPLETE;
  906                         cacheData. studyDetai l = studyD etail;
  907                         setCacheDa ta(studyUi d, cacheDa ta);
  908                    }
  909                } else {
  910                    seri es.isCompl eted = tru e;
  911                    stud yDetail.se ries[serie sIndex] =  series;
  912                    setC acheStudyC omplete(st udyUid);
  913                }
  914           }
  915       }
  916  
  917       functi on setCach eSeriesCom plete(stud yUid, seri esIndex, i mageIndex,  isCacheFu ll) {
  918           va r cacheDat a = getCac heData(stu dyUid);
  919           va r studyDet ail = cach eData.stud yDetail;
  920           if  (isCacheF ull && cac heData.req uestCount  == 0) {
  921                cacheDat a.initialC ache = fal se;
  922                cacheDat a.cacheSta tus = CACH E_INCOMPLE TE;
  923                cacheDat a.enabled  = false;
  924                setCache Data(study Uid, cache Data);
  925           }  else if (! isCacheFul l) {
  926                var seri es = study Detail.ser ies[series Index];
  927                series.i sCompleted  = true;
  928                series.i sPurged =  false;
  929                studyDet ail.series [seriesInd ex] = seri es;
  930                setCache StudyCompl ete(studyU id);
  931           }
  932       }
  933  
  934       functi on setCach eStudyComp lete(study Uid) {
  935           va r cacheDat a = getCac heData(stu dyUid);
  936           va r studyDet ail = cach eData.stud yDetail;
  937           va r isStudyC omplete =  true;
  938           $. each(study Detail.ser ies, funct ion(key, s eries) {
  939                if (!ser ies.isComp leted || s eries.isPu rged) {
  940                    isSt udyComplet e = false;
  941                    retu rn false;
  942                }
  943           }) ;
  944           if  (isStudyC omplete) {
  945                studyDet ail.isComp leted = tr ue;
  946                cacheDat a.enabled  = false;
  947                cacheDat a.cacheSta tus = CACH E_END;
  948                cacheDat a.studyDet ail = stud yDetail;
  949                setCache Data(study Uid, cache Data);
  950           }  else {
  951                studyDet ail.isComp leted = fa lse;
  952                cacheDat a.enabled  = true;
  953                cacheDat a.cacheSta tus = CACH E_START;
  954                cacheDat a.studyDet ail = stud yDetail;
  955                setCache Data(study Uid, cache Data);
  956           }
  957       }
  958  
  959       functi on getImag eOrFrame(s tudyUid, s eriesIndex , imageInd ex, frameI ndex) {
  960           va r loadImag eDeferred;
  961           va r cachePrm oise = $.D eferred();
  962           va r imageInf o = dicomV iewer.Seri es.Image.g etImage(st udyUid, se riesIndex,  imageInde x);
  963           va r imageUid  = dicomVi ewer.Serie s.Image.ge tImageUid( imageInfo) ;
  964           va r cacheDat a = getCac heData(stu dyUid);
  965           ca cheData.re questCount ++;
  966           se tCacheData (studyUid,  cacheData );
  967           va r isMultiF rame = dic omViewer.t humbnail.i sImageThum bnail(imag eInfo, tru e);
  968           if  (isMultiF rame) {
  969                loadImag eDeferred  = dicomVie wer.getIma ge(studyUi d, imageUi d, frameIn dex, image Index, ima geInfo.ima geType, se riesIndex) ;
  970           }  else {
  971                loadImag eDeferred  = dicomVie wer.getIma ge(studyUi d, imageUi d, frameIn dex, serie sIndex, im ageInfo.im ageType);
  972           }
  973  
  974           lo adImageDef erred.done (function( image) {
  975                var cach eData = ge tCacheData (studyUid) ;
  976                cacheDat a.requestC ount--;
  977                setCache Data(study Uid, cache Data);
  978                if (!ima ge.studyUi d) {
  979                    dump ConsoleLog s(LL_DEBUG , undefine d, "getIma geOrFrame" , "Image p romise did  not have  studyUid") ;
  980                    retu rn;
  981                }
  982  
  983                // Dump  the cache  memory siz e in conso le
  984                dumpCach eSize();
  985                var inde xToCache =  {
  986                    seri esIndexToC ache : cac heData.ser iesIndexTo Cache,
  987                    imag eIndexToCa che : cach eData.imag eIndexToCa che
  988                }
  989                cachePrm oise.resol ve(indexTo Cache);
  990  
  991                //Get Re nderer obj ect
  992                var rend erer = dic omViewer.r enderer.ge tImageRend erer(image .imageUid  + "_" + im age.frameN umber);
  993                if(rende rer) {
  994                    remo veImageRen derer(imag e.imageUid  + "_" + i mage.frame Number);
  995                    var  deferred =  $.Deferre d();
  996                    defe rred.resol ve(image);
  997                    var  serieLayou t = dicomV iewer.getA ctiveSerie sLayout();
  998                    var  imageCanva sValue = d icomViewer .getimageC anvasOfVie wPort(seri eLayout.ge tSeriesLay outId());
  999                    rend erer.loadI mageRender er(deferre d, undefin ed, image. studyUid);
  1000                }
  1001           }) ;
  1002  
  1003           re turn cache Prmoise;
  1004       }
  1005  
  1006       functi on setImag eRenderer( imageUid,r enderer) {
  1007           if (imageUid  === undefi ned) {
  1008                throw "E xception:  imageUid s hould not  be null/un defined"
  1009           }
  1010           im ageRendere rMap[image Uid] = ren derer;
  1011       }
  1012  
  1013       functi on getImag eRenderer( imageUid)  {
  1014           re turn image RendererMa p[imageUid ];
  1015       }
  1016  
  1017       functi on removeI mageRender er(imageUi d) {
  1018           de lete image RendererMa p[imageUid ];
  1019       }
  1020  
  1021       /**
  1022        * Dum p cache me mory size
  1023        */ 
  1024       functi on dumpCac heSize() {
  1025           va r cacheInf o = dicomV iewer.imag eCache.get CacheInfo( );
  1026           if (cacheInfo  !== undef ined && ca cheInfo != = null) {
  1027                var size s = ['Byte s', 'KB',  'MB', 'GB' , 'TB'];
  1028                var i =  parseInt(M ath.floor( Math.log(c acheInfo.c acheSizeIn Bytes) / M ath.log(10 24)));
  1029                var tota lsize = Ma th.round(c acheInfo.c acheSizeIn Bytes / Ma th.pow(102 4, i), 2)  + ' ' + si zes[i];
  1030                dumpCons oleLogs(LL _DEBUG, un defined, " dumpCacheS ize", "Cac he size :  " + totals ize);
  1031           }
  1032       }
  1033  
  1034       functi on getCach eData(stud yUid) {
  1035           if  (!cacheDa taMap[stud yUid]) {
  1036                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  1037                if (!stu dyDetails)  {
  1038                    retu rn undefin ed;
  1039                }
  1040  
  1041                var seri esCount =  studyDetai ls.seriesC ount;
  1042                var imag eCount = u ndefined;
  1043                var fram eCount = u ndefined;
  1044                var seri esCol = [] ;
  1045                var imag eCol = [];
  1046                if(study Details.se ries) {
  1047                    $.ea ch(studyDe tails.seri es, functi on(key, se ries) {
  1048                         imageCount  = series. imageCount ;
  1049                         $.each(ser ies.images , function (key, imag es) {
  1050                             if (se ries.hasMu tiframeIma ges) {
  1051                                 fr ameCount =  images.nu mberOfFram es;
  1052                             }
  1053                             var im ageType =  {
  1054                                 ty pe : image s.imageTyp e,
  1055                                 is Dicom : is DicomModal ity(images .imageType ),
  1056                                 fr ameCount :  frameCoun t,
  1057                                 is Completed  : false,
  1058                                 is Purged : f alse
  1059                             };
  1060                             imageC ol.push(im ageType);
  1061                         });
  1062                         var series  = {
  1063                             imageC ount : ima geCount,
  1064                             images  : imageCo l,
  1065                             isComp leted : fa lse
  1066                         };
  1067                         imageCol =  [];
  1068                         seriesCol. push(serie s);
  1069                    });
  1070                } else i f (Array.i sArray(stu dyDetails) ) {
  1071                    $.ea ch(studyDe tails, fun ction(key,  series) {
  1072                         imageCount  = series. imageCount ;
  1073                         frameCount  = series. numberOfFr ames;
  1074                         var series  = {
  1075                             type :  series.im ageType,
  1076                             isDico m : isDico mModality( series.ima geType),
  1077                             imageC ount : ima geCount,
  1078                             frameC ount : fra meCount,
  1079                             isComp leted : fa lse,
  1080                             isPurg ed : false
  1081                         };
  1082                         seriesCol. push(serie s);
  1083                    });
  1084                }
  1085  
  1086                var stud yDetail =  {
  1087                    seri esCount :  seriesCoun t,
  1088                    seri es : serie sCol,
  1089                    isCo mpleted :  false,
  1090                };
  1091                seriesCo l = [];
  1092  
  1093                var cach eData = {
  1094                    stud yUid : stu dyUid,
  1095                    enab led : true ,
  1096                    stud yDetail :  studyDetai l,
  1097                    init ialCache :  true,
  1098                    cach eStatus :  CACHE_STAR T,
  1099                    seri esIndexToC ache : und efined,
  1100                    imag eIndexToCa che : unde fined,
  1101                    requ estCount :  0
  1102                };
  1103                setCache Data(study Uid, cache Data);
  1104           }
  1105  
  1106           re turn cache DataMap[st udyUid];
  1107       }
  1108  
  1109       functi on isDicom Modality(i mageType)  {
  1110           if (imageType  == IMAGET YPE_RAD ||  imageType  == IMAGET YPE_RADECH O || 
  1111               imageType  === IMAGE TYPE_JPEG  || imageTy pe == IMAG ETYPE_RADS R || 
  1112               imageType  == IMAGET YPE_CDA) {
  1113                return t rue;
  1114           }
  1115           re turn false ;
  1116       }
  1117  
  1118       functi on setCach eData(stud yUid, cach eData) {
  1119           ca cheDataMap [studyUid]  = cacheDa ta;
  1120       }
  1121  
  1122       functi on enableC acheData(s tudyUid, e nabled) {
  1123           ca cheDataMap [studyUid] .enabled =  enabled;
  1124       }
  1125  
  1126       functi on isSerie sInComplet e(studyUid , seriesIn dex, image Index) {
  1127           va r cacheDat a = getCac heData(stu dyUid);
  1128           va r series =  cacheData .studyDeta il.series[ seriesInde x];
  1129           if  (!cacheDa ta.initial Cache) {
  1130                if (imag eIndex !=  undefined)  {
  1131                    var  image = se ries.image s[imageInd ex];
  1132                    if ( !image.isC ompleted | | image.im ageIndexTo Cache != i mageIndex  || image.i sPurged) {
  1133                         cacheData. seriesInde xToCache =  seriesInd ex;
  1134                         cacheData. imageIndex ToCache =  imageIndex ;
  1135                         setCacheDa ta(studyUi d, cacheDa ta);
  1136                         return tru e;
  1137                    }
  1138                } else {
  1139                    if ( !series.is Completed  || (cacheD ata.series IndexToCac he != unde fined && c acheData.s eriesIndex ToCache !=  seriesInd ex) || ser ies.isPurg ed) {
  1140                         cacheData. seriesInde xToCache =  seriesInd ex;
  1141                         setCacheDa ta(studyUi d, cacheDa ta);
  1142                         return tru e;
  1143                    }
  1144                }
  1145           }
  1146           re turn false ;
  1147       }
  1148  
  1149       functi on purgeSe ries(study Uid, serie sIndex, im ageIndex)  {
  1150           va r cacheDat a = getCac heData(stu dyUid);
  1151           va r series =  cacheData .studyDeta il.series[ seriesInde x];
  1152           se ries.isCom pleted = f alse;
  1153           if  (series.i mages) {
  1154                var imag es = [];
  1155                $.each(s eries.imag es, functi on(key, im age) {
  1156                    var  canPurge =  true;
  1157                    if ( imageIndex  != undefi ned && ima geIndex !=  key) {
  1158                         canPurge =  false;
  1159                    }
  1160                    if ( canPurge)  {
  1161                         image.isCo mpleted =  false;
  1162                         image.isPu rged = tru e;
  1163                    }
  1164                    imag es.push(im age);
  1165                });
  1166                series.i mages = im ages;
  1167                series.i sPurged =  true;
  1168           }
  1169           ca cheData.st udyDetail. series[ser iesIndex]  = series;
  1170           se tCacheData (studyUid,  cacheData );
  1171       }
  1172  
  1173       dicomV iewer.rend erer = {
  1174           se tImageRend erer : set ImageRende rer,
  1175           ge tImageRend erer : get ImageRende rer,
  1176           re moveImageR enderer :  removeImag eRenderer
  1177       };
  1178  
  1179       dicomV iewer.cach eImages =  cacheImage s;
  1180       dicomV iewer.getC acheData =  getCacheD ata;
  1181       dicomV iewer.isSe riesInComp lete = isS eriesInCom plete;
  1182       dicomV iewer.enab leCacheDat a = enable CacheData;
  1183       dicomV iewer.purg eSeries =  purgeSerie s;
  1184       dicomV iewer.getC acheData =  getCacheD ata;
  1185       dicomV iewer.setC acheData =  setCacheD ata;
  1186  
  1187       return  dicomView er;
  1188  
  1189   }(dicomVie wer));var  dicomViewe r = (funct ion(dicomV iewer) {
  1190  
  1191       if (di comViewer  === undefi ned) {
  1192           di comViewer  = {};
  1193       }
  1194  
  1195       var di comHeaders  = {};
  1196       /**
  1197        *@par am url
  1198        *Send  the reque st based   on the url (image inf o call)
  1199        *when  the call  is success (200) it w ill be res olved in j query deff ered
  1200        *if t he result  is not suc cess it wi ll be reje cted in jq uery deffe red
  1201        *and  return the  jquery de ffered obj ect
  1202        */
  1203       functi on getDico mHeaderInf o(url) {
  1204           tr y {
  1205  
  1206                if (url  === undefi ned) {
  1207                    thro w "Excepti on: url sh ould not b e undefine d";
  1208                }
  1209                var defe rred = $.D eferred();
  1210                var oReq  = new XML HttpReques t();
  1211                oReq.ope n("get", u rl, true);
  1212                oReq.res ponseType  = 'applica tion/json' ;
  1213                oReq.onr eadystatec hange = fu nction(oEv ent) {
  1214                    var  t0 = Date. now();
  1215                    dump ConsoleLog s(LL_INFO,  undefined , "getDico mHeaderInf o ", "Star t", undefi ned, true) ;
  1216  
  1217                    // T ODO: consi der sendin g out prog ress messa ges here a s we recei ve the pix el data
  1218                    if ( oReq.ready State ===  4) {
  1219                         if (oReq.s tatus ===  200) {
  1220                             var te xt = oReq. responseTe xt;
  1221                             deferr ed.resolve (text);
  1222                             dumpCo nsoleLogs( LL_INFO, u ndefined,  "getDicomH eaderInfo" , "End", ( Date.now()  - t0), tr ue);
  1223                         } else {
  1224                             deferr ed.reject( );
  1225                         }
  1226                    }
  1227                    else  if(oReq.s tatus ===  500) {
  1228                         var descri ption = xh ttp.status Text + "\n Failed to  get the di com geader  informati on for thi s url." +  "\nURL: "  + url;  
  1229                         sendViewer StatusMess age(xhttp. status.toS tring(), d escription );
  1230                         dumpConsol eLogs(LL_E RROR, unde fined, "ge tDicomHead erInfo", d escription , undefine d, true); 
  1231                    }
  1232                };
  1233                oReq.sen d();
  1234                return d eferred;
  1235           }
  1236           ca tch(e)
  1237           {
  1238                dumpCons oleLogs(LL _ERROR, un defined, " getDicomHe aderInfo",  e.message , undefine d, true); 
  1239           }
  1240           fi nally {
  1241  
  1242           }
  1243       }
  1244  
  1245       functi on getDico mHeaderInf o(url) {
  1246           tr y {
  1247  
  1248                if (url  === undefi ned) {
  1249                    thro w "Excepti on: url sh ould not b e undefine d";
  1250                }
  1251                var defe rred = $.D eferred();
  1252                var oReq  = new XML HttpReques t();
  1253                oReq.ope n("get", u rl, true);
  1254                //oReq.r esponseTyp e = 'appli cation/jso n';
  1255                oReq.onr eadystatec hange = fu nction(oEv ent) {
  1256  
  1257                    var  t0 = Date. now();
  1258                    dump ConsoleLog s(LL_INFO,  undefined , "getDico mHeaderInf o", "Start ", undefin ed, true);
  1259  
  1260                    // T ODO: consi der sendin g out prog ress messa ges here a s we recei ve the pix el data
  1261                    if ( oReq.ready State ===  4) {
  1262  
  1263                         if (oReq.s tatus ===  200) {
  1264                             var te xt = oReq. responseTe xt;
  1265                             deferr ed.resolve (text);
  1266                             
  1267                             dumpCo nsoleLogs( LL_INFO, u ndefined,  "getDicomH eaderInfo" , "End", ( Date.now()  - t0), tr ue);
  1268                         } else {
  1269                             deferr ed.reject( );
  1270                         }
  1271                    }
  1272                    else  if(oReq.s tatus ===  500) {
  1273                         var descri ption = xh ttp.status Text + "\n Failed to  get the di com geader  informati on for thi s url." +  "\nURL: "  + url; 
  1274                         sendViewer StatusMess age(xhttp. status.toS tring(), d escription );
  1275                         dumpConsol eLogs(LL_E RROR, unde fined, "ge tDicomHead erInfo", d escription );
  1276                    }
  1277                };
  1278                oReq.sen d();
  1279                return d eferred;
  1280           }
  1281           ca tch(e)
  1282           {
  1283                dumpCons oleLogs(LL _ERROR, un defined, " getDicomHe aderInfo",  e.message , undefine d, true); 
  1284           }
  1285           fi nally {
  1286  
  1287           }
  1288       }
  1289  
  1290       functi on getDico mHeaderVal ues(studyU id, imageU id) {
  1291                    var  urlParamet ers = dico mViewer.ge tDicomHead erUrl(imag eUid);
  1292           va r metaURL  = dicomVie wer.url.ge tDicomImag eURL(urlPa rameters);
  1293           va r request  = new XMLH ttpRequest ();
  1294           re quest.open ('GET', me taURL, fal se);
  1295           va r thumbnai lRendererO bject = th is;         
  1296           if (request.s tatus ===  500) {
  1297                var desc ription =  xhttp.stat usText + " \nFailed t o get the  dicom head er values  for the re spective i mages." +  "\nImage U ID: " + im ageUid + " \nStudy UI D: " + stu dyUid; 
  1298                    send ViewerStat usMessage( xhttp.stat us.toStrin g(), descr iption);
  1299           }
  1300           re quest.send ();
  1301           re turn JSON. parse(requ est.respon seText);
  1302       }
  1303  
  1304           fu nction get Metadata(s tudyUid, i mageUid) {
  1305                    var  urlParamet ers = dico mViewer.ge tDicomHead erUrl(imag eUid);
  1306           va r metaURL  = dicomVie wer.url.ge tDicomImag eMetadataU RL(urlPara meters);
  1307           va r deferred  = $.Defer red();
  1308           va r oReq = n ew XMLHttp Request();
  1309           oR eq.open("g et", metaU RL, true);
  1310           // oReq.respo nseType =  'applicati on/json';
  1311           oR eq.onready statechang e = functi on(oEvent)  {
  1312                // TODO:  consider  sending ou t progress  messages  here as we  receive t he pixel d ata
  1313                if (oReq .readyStat e === 4) {
  1314  
  1315                    if ( oReq.statu s === 200)  {
  1316                         var text =  oReq.resp onseText;
  1317                         deferred.r esolve(tex t);
  1318                    } el se {
  1319                         deferred.r eject();
  1320                    }
  1321                }
  1322                else if( oReq.statu s === 500)  {
  1323                    var  descriptio n = xhttp. statusText  + "\nFail ed to get  the meta d ata for th e respecti ve image."  + "\nImag e UID: " +  imageUid  + "\nStudy  UID: " +  studyUid; 
  1324                    send ViewerStat usMessage( xhttp.stat us.toStrin g(), descr iption);
  1325                }
  1326           };
  1327           oR eq.send();
  1328           re turn defer red;
  1329       }
  1330           
  1331       functi on putDico mHeader(im ageUid, di comHeader)  {
  1332           if  (imageUid  === undef ined) {
  1333                throw "p utDicomHea der: image Uid should  not be nu ll/undefin ed";
  1334           }
  1335           if  (dicomHea der === un defined) {
  1336                throw "p utDicomHea der: dicom Header not  be null/u ndefined";
  1337           }
  1338           di comHeaders [imageUid]  = dicomHe ader;
  1339       }
  1340  
  1341       /**
  1342        *@par am imageUi d
  1343        *@par am dicomHe ader
  1344        *stor e the imag eInfo obje ct to the  dicomHeade rs using t he image i d as key
  1345        */
  1346       functi on putDico mHeader(im ageUid, di comHeader)  {
  1347           if  (imageUid  === undef ined) {
  1348                throw "p utDicomHea der: image Uid should  not be nu ll/undefin ed";
  1349           }
  1350           if  (dicomHea der === un defined) {
  1351                throw "p utDicomHea der: dicom Header not  be null/u ndefined";
  1352           }
  1353  
  1354           di comHeaders [imageUid]  = dicomHe ader;
  1355       }
  1356  
  1357       /**
  1358        *@par am imageUi d
  1359        *Retr ieve the i mageInfo o bject from  the dicom Headers us ing the im age id as  key
  1360        */
  1361       functi on getDico mHeader(im ageUid) {
  1362           if  (imageUid  === undef ined) {
  1363                throw "g etDicomHea der: image Uid should  not be nu ll/undefin ed";
  1364           }
  1365           re turn dicom Headers[im ageUid];
  1366       }
  1367  
  1368       dicomV iewer.head er = {
  1369           ge tDicomHead erInfo: ge tDicomHead erInfo,
  1370           pu tDicomHead er: putDic omHeader,
  1371           ge tDicomHead er: getDic omHeader,
  1372           ge tDicomHead er: getDic omHeader,
  1373           ge tDicomHead erValues:  getDicomHe aderValues ,
  1374           ge tMetadata:  getMetada ta
  1375       };
  1376  
  1377       return  dicomView er;
  1378  
  1379   }(dicomVie wer));/*
  1380       To ren der the pa tient orie ntation la bles
  1381   */
  1382   var dicomV iewer = (f unction (d icomViewer ) {
  1383  
  1384       "use s trict";
  1385  
  1386       if(dic omViewer = == undefin ed) {
  1387           di comViewer  = {};
  1388       }
  1389       var hF lipCount =  false;
  1390       var vF lipCount =  false;
  1391       var di rectionalM arker = {
  1392                left : ' L',
  1393                right :  'R',
  1394                bottom :  'F',
  1395                top : 'H '
  1396       };
  1397       
  1398       functi on initDir ectionalMa rker(image info)
  1399       { 
  1400           if (imageinfo  != undefi ned) {
  1401                var mark ers = imag einfo.getD irectional Markers();
  1402                if(marke rs != null )
  1403                {
  1404                    // S et the def ault value s if the m arkers is  not availa ble to avo id null co ndition.
  1405                    if ( directiona lMarker ==  null)
  1406                    {
  1407                         directiona lMarker =  {
  1408                         left : 'L' ,
  1409                         right : 'R ',
  1410                         bottom : ' F',
  1411                         top : 'H'
  1412                      };
  1413                    }
  1414  
  1415                    dire ctionalMar ker.left =  markers.l eft;
  1416                    dire ctionalMar ker.right  = markers. right;
  1417                    dire ctionalMar ker.bottom   = marker s.bottom;
  1418                    dire ctionalMar ker.top =  markers.to p;
  1419                }
  1420                else
  1421                {
  1422                    dire ctionalMar ker = null ;
  1423                }
  1424           }
  1425       }
  1426       
  1427       /* Get  the image  orientati on */
  1428       functi on getDire ctionalMar ker( )
  1429       {
  1430           re turn  dire ctionalMar ker;      
  1431       }
  1432       
  1433       /* Rot ate the pa tient labl es to the  degree giv en */
  1434       functi on rotateD irectional Marker(pre sentation)
  1435       {
  1436           va r rotation  = (presen tation.get Rotation() ) / 90; //  Find the  number of  times to r otate the  patient la bles
  1437           va r rotation Direction  = rotation  < 0 ? -1  : 1;  // F ind the ro tation dir ection fro m current  position         
  1438           ro tation = r otation *  rotationDi rection;
  1439           if (direction alMarker ! = null)
  1440           {
  1441                for( var  rotationC ount = 0;  rotationCo unt < rota tion; rota tionCount+ +)
  1442                {
  1443                    if(r otationDir ection ==1 )   // Rot ate in clo ck wise
  1444                    { 
  1445                         var left =  direction alMarker.l eft;
  1446                         directiona lMarker.le ft = direc tionalMark er.bottom;
  1447                         directiona lMarker.bo ttom = dir ectionalMa rker.right ;
  1448                         directiona lMarker.ri ght = dire ctionalMar ker.top;
  1449                         directiona lMarker.to p = left;
  1450                    }els e // Rotat e in anti- clock wise
  1451                    {
  1452                         var left =  direction alMarker.l eft;
  1453                         directiona lMarker.le ft = direc tionalMark er.top;
  1454                         directiona lMarker.to p = direct ionalMarke r.right;
  1455                         directiona lMarker.ri ght = dire ctionalMar ker.bottom ;
  1456                         directiona lMarker.bo ttom = lef t;
  1457                    }
  1458                }
  1459                if(prese ntation.ge tHorizonta lFilp() &&  presentat ion.getVer ticalFilp( ))
  1460                {
  1461                   hFlip Count = fa lse;
  1462                   vFlip Count = fa lse;
  1463                }
  1464                if((pres entation.g etHorizont alFilp() & & !hFlipCo unt) || (p resentatio n.getHoriz ontalFilp( ) && !vFli pCount) ||  (presenta tion.getHo rizontalFi lp() && vF lipCount))
  1465                {
  1466                    var  left = dir ectionalMa rker.left;
  1467                    dire ctionalMar ker.left =  direction alMarker.r ight;
  1468                    dire ctionalMar ker.right  = left;
  1469                    hFli pCount = ! hFlipCount ;
  1470                }
  1471                if((pres entation.g etVertical Filp() &&  !vFlipCoun t) || (pre sentation. getVertica lFilp() &&  !hFlipCou nt) || (pr esentation .getVertic alFilp() & & hFlipCou nt))
  1472                {
  1473                    var  top = dire ctionalMar ker.top;
  1474                    dire ctionalMar ker.top =  directiona lMarker.bo ttom;
  1475                    dire ctionalMar ker.bottom  = top;
  1476                    vFli pCount = ! vFlipCount ;
  1477                }
  1478           }
  1479       }    
  1480       
  1481       
  1482       dicomV iewer.dire ctionalMar ker = {
  1483                    init Directiona lMarker :  initDirect ionalMarke r,
  1484                getDirec tionalMark er : getDi rectionalM arker,
  1485                    rota teDirectio nalMarker  : rotateDi rectionalM arker                
  1486       };
  1487       
  1488       return  dicomView er;
  1489   }(dicomVie wer));/**
  1490    * New nod e file
  1491    */
  1492  
  1493   var dicomV iewer = (f unction(di comViewer)  {
  1494  
  1495       if (di comViewer  === undefi ned) {
  1496           di comViewer  = {};
  1497       }
  1498  
  1499       var is Measuremen tEdit;
  1500       var di comImageMe asurements  = {};
  1501       
  1502       var di comImageAn gleMeasure ments = {} ;
  1503       
  1504       var di comImageEl lipseMeasu rements =  {};
  1505       
  1506       var di comImageRe ctangleMea surements  = {};
  1507  
  1508       var di comImageTr aceMeasure ments = {} ;
  1509  
  1510       var di comImageVo lumeMeasur ements = { };
  1511  
  1512       var di comImageMi tralGradie ntMeasurem ents = {};
  1513  
  1514       var di comImagePe nMeasureme nts = {};
  1515  
  1516       var mo usePressed Counter =  0;
  1517       
  1518       var te mpdata = u ndefined;  // On goin g data
  1519  
  1520           va r lineMeas urementUni t = "UNITS _CM"; // c entimeters  as defaul t
  1521           
  1522       var da taToDelete  = {
  1523           me asurmentTy pe: "",
  1524           ke y: "",
  1525           ar ryIndex: " ",
  1526           is Editable:  "",
  1527           se ssionType:  0
  1528       };
  1529  
  1530       var da taToEdit =  undefined ;
  1531  
  1532       var ac tiveImageR enderer =  undefined;
  1533  
  1534       var is LineDelete Check = fa lse;
  1535       var is PointDelet eCheck = f alse;
  1536       var is AngleDelet eCheck = f alse;
  1537       var is EllipseDel eteCheck =  false;
  1538       var is RectangleD eleteCheck  = false;
  1539       var is TraceDelet eCheck = f alse;
  1540       var is VolumeDele teCheck =  false;
  1541           va r isMitral GradineDel ete = fals e;
  1542       var is PenDelete  = false;
  1543  
  1544       var MT _GLOBAL =  "GLOBAL";
  1545       var MT _LENGTH =  "LENGTH";
  1546       var MT _LINE = "L INE";
  1547       var MT _ARROW = " ARROW";
  1548       var MT _POINT = " POINT";
  1549       var MT _ANGLE = " ANGLE";
  1550       var MT _ELLIPSE =  "ELLIPSE" ;
  1551       var MT _HOUNSFIEL DELLIPSE =  "HOUNSFIE LDELLIPSE" ;
  1552       var MT _RECT = "R ECT";
  1553       var MT _HOUNSFIEL DRECT = "H OUNSFIELDR ECT";
  1554       var MT _TEXT = "T EXT";
  1555       var MT _TRACE = " TRACE";
  1556       var MT _MG = "MG" ;
  1557       var MT _ASPV = "A SPV";
  1558       var MT _ARPV = "A RPV";
  1559       var MT _MRPV = "M RPV";
  1560       var MT _ARL = "AR L";
  1561       var MT _MRL = "MR L";
  1562       var MT _MVALT = " MVALT";
  1563       var MT _FREEHAND  = "FREEHAN D";
  1564       var MT _PEN = "PE N";
  1565       var MT _LABEL = " LABEL";
  1566  
  1567       var se lectedSess ionType =  2;
  1568  
  1569       functi on setTemp Data(mouse Data) {
  1570           te mpdata = m ouseData;
  1571       }
  1572  
  1573       functi on getTemp Data() {
  1574           re turn tempd ata;
  1575       }
  1576  
  1577       functi on removeT empdata()  {
  1578           te mpdata = u ndefined;
  1579       }
  1580  
  1581       functi on getDefa ultLineMea surement()  {
  1582           re turn {
  1583                start: {
  1584                    x: u ndefind,
  1585                    y: u ndefined
  1586                },
  1587                end: {
  1588                    x: u ndefined,
  1589                    y: u ndefined
  1590                },
  1591                measurem entType: " line"
  1592           };
  1593       }
  1594  
  1595       functi on getImag eDataForMo useData(mo useData, i mageRender er, contex t) {
  1596           va r start, e nd = null;
  1597           va r first, s econd, thi rd, fourth , center =  null;
  1598           st art = dico mViewer.me asurement. draw.getIm ageCoordin atesForMou sePoint(mo useData.st art, image Renderer,  context);
  1599           en d = dicomV iewer.meas urement.dr aw.getImag eCoordinat esForMouse Point(mous eData.end,  imageRend erer, cont ext);
  1600           if  (mouseDat a.measureT ype == "el lipse") {
  1601                first =  dicomViewe r.measurem ent.draw.g etImageCoo rdinatesFo rMousePoin t(mouseDat a.first, i mageRender er, contex t);
  1602                second =  dicomView er.measure ment.draw. getImageCo ordinatesF orMousePoi nt(mouseDa ta.second,  imageRend erer, cont ext);
  1603                third =  dicomViewe r.measurem ent.draw.g etImageCoo rdinatesFo rMousePoin t(mouseDat a.third, i mageRender er, contex t);
  1604                fourth =  dicomView er.measure ment.draw. getImageCo ordinatesF orMousePoi nt(mouseDa ta.fourth,  imageRend erer, cont ext);
  1605                center =  dicomView er.measure ment.draw. getImageCo ordinatesF orMousePoi nt(mouseDa ta.center,  imageRend erer, cont ext);
  1606           }
  1607  
  1608           va r imageDat a = {};
  1609           im ageData.st art = star t;
  1610           im ageData.en d = end;
  1611           im ageData.fi rst = firs t;
  1612           im ageData.se cond = sec ond;
  1613           im ageData.th ird = thir d;
  1614           im ageData.fo urth = fou rth;
  1615           im ageData.ce nter = cen ter;
  1616           im ageData.is CustomElli pse = mous eData.isCu stomEllips e;
  1617           im ageData.me asureType  = mouseDat a.measureT ype;
  1618           im ageData.me asurementI d = mouseD ata.measur ementId;
  1619           im ageData.me asurementT ype = mous eData.meas urementTyp e;
  1620           im ageData.me asurementU nits = mou seData.mea surementUn its;
  1621           im ageData.me asurementC omplete =  mouseData. measuremen tComplete;
  1622           im ageData.me asurementS ubType = m ouseData.m easurement SubType;
  1623           im ageData.me asurementT ext = mous eData.meas urementTex t;
  1624           im ageData.st udyUid = m ouseData.s tudyUid;
  1625           im ageData.is Editable =  mouseData .isEditabl e;
  1626           im ageData.se ssionType  = mouseDat a.sessionT ype;
  1627           im ageData.st yle = mous eData.styl e;
  1628           im ageData.ca librationD ata=mouseD ata.calibr ationData;
  1629           re turn image Data;
  1630       }
  1631  
  1632  
  1633       functi on getCanv asDataForI mageData(i mageData,  imageRende rer) {
  1634           va r start, e nd = null;
  1635           va r first, s econd, thi rd, fourth , center =  null;
  1636           st art = dico mViewer.me asurement. draw.getCa nvasCoordi natesForIm ageCoordin ates(image Data.start , imageRen derer);
  1637           en d = dicomV iewer.meas urement.dr aw.getCanv asCoordina tesForImag eCoordinat es(imageDa ta.end, im ageRendere r);
  1638  
  1639           if  (imageDat a.measureT ype == "el lipse") {
  1640                first =  dicomViewe r.measurem ent.draw.g etCanvasCo ordinatesF orImageCoo rdinates(i mageData.f irst, imag eRenderer) ;
  1641                second =  dicomView er.measure ment.draw. getCanvasC oordinates ForImageCo ordinates( imageData. second, im ageRendere r);
  1642                third =  dicomViewe r.measurem ent.draw.g etCanvasCo ordinatesF orImageCoo rdinates(i mageData.t hird, imag eRenderer) ;
  1643                fourth =  dicomView er.measure ment.draw. getCanvasC oordinates ForImageCo ordinates( imageData. fourth, im ageRendere r);
  1644                center =  dicomView er.measure ment.draw. getCanvasC oordinates ForImageCo ordinates( imageData. center, im ageRendere r);
  1645           }
  1646  
  1647           va r canvasDa ta = {};
  1648           ca nvasData.s tart = sta rt;
  1649           ca nvasData.e nd = end;
  1650           ca nvasData.f irst = fir st;
  1651           ca nvasData.s econd = se cond;
  1652           ca nvasData.t hird = thi rd;
  1653           ca nvasData.f ourth = fo urth;
  1654           ca nvasData.c enter = ce nter;
  1655           ca nvasData.i sCustomEll ipse = ima geData.isC ustomEllip se;
  1656           ca nvasData.m easureType  = imageDa ta.measure Type;
  1657           ca nvasData.m easurement Id = image Data.measu rementId;
  1658           ca nvasData.m easurement Type = ima geData.mea surementTy pe;
  1659           ca nvasData.m easurement Units = im ageData.me asurementU nits;
  1660           ca nvasData.m easurement Complete =  imageData .measureme ntComplete ;
  1661           ca nvasData.m easurement SubType =  imageData. measuremen tSubType;
  1662           ca nvasData.m easurement Text = ima geData.mea surementTe xt;
  1663           ca nvasData.s tudyUid =  imageData. studyUid;
  1664           ca nvasData.i sEditable  = imageDat a.isEditab le;
  1665           ca nvasData.s essionType  = imageDa ta.session Type;
  1666           ca nvasData.s tyle = ima geData.sty le;
  1667           ca nvasData.c alibration Data=image Data.calib rationData ;
  1668           ca nvasData.i mageData =  imageData ;
  1669  
  1670           re turn canva sData;
  1671       }
  1672  
  1673       var li neMeasurem entEnd = f alse;
  1674  
  1675       functi on setLine Measuremen tEnd(flag)  {
  1676           li neMeasurem entEnd = f lag;
  1677       }
  1678  
  1679       functi on isLineM easurement End() {
  1680           re turn lineM easurement End;
  1681       }
  1682  
  1683       var me asurementB roken = fa lse;
  1684  
  1685       functi on setMeas urementBro ken(flag)  {
  1686           me asurementB roken = fl ag;
  1687       }
  1688  
  1689       functi on isMeasu rementBrok en() {
  1690           re turn measu rementBrok en;
  1691       }
  1692       
  1693       var tr aceMeasure mentEnd =  false;
  1694  
  1695       functi on setTrac eMeasureme ntEnd(flag ) {
  1696           tr aceMeasure mentEnd =  flag;
  1697       }
  1698  
  1699           fu nction isT raceMeasur ementEnd()  {
  1700           re turn trace Measuremen tEnd;
  1701       }
  1702  
  1703       var tr aceMeasure mentId = - 1;
  1704  
  1705       functi on setTrac eMeasureme ntId(trace Id) {
  1706           tr aceMeasure mentId = t raceId;
  1707       }
  1708  
  1709       functi on getTrac eMeasureme ntId() {
  1710           re turn trace Measuremen tId;
  1711       }
  1712       
  1713       // Ang le Measure ment
  1714       var an gleMeasure mentEnd =  false;
  1715  
  1716       functi on setAngl eMeasureme ntEnd(flag ) {
  1717           an gleMeasure mentEnd =  flag;
  1718       }
  1719  
  1720           fu nction isA ngleMeasur ementEnd()  {
  1721           re turn angle Measuremen tEnd;
  1722       }
  1723       
  1724       var an gleMeasure mentId = - 1;
  1725  
  1726       functi on setAngl eMeasureme ntId(angle Id) {
  1727           an gleMeasure mentId = a ngleId;
  1728       }
  1729  
  1730       functi on getAngl eMeasureme ntId() {
  1731           re turn angle Measuremen tId;
  1732       }
  1733  
  1734       functi on resetMo usePressed Counter()  {
  1735           mo usePressed Counter =  0;
  1736       }
  1737       functi on getMous ePressedCo unter() {
  1738           re turn mouse PressedCou nter;
  1739       }
  1740       functi on increas eMousePres sedCounter () {
  1741           mo usePressed Counter =  mousePress edCounter+ 1;
  1742       }
  1743       
  1744       
  1745       var vo lumeMeasur ementEndFl ag = false ;
  1746  
  1747       functi on setVolu meMeasurem entEnd(fla g) {
  1748           vo lumeMeasur ementEndFl ag = flag;
  1749       }
  1750  
  1751       functi on isVolum eMeasureme ntEnd() {
  1752           re turn volum eMeasureme ntEndFlag;
  1753       }
  1754  
  1755       var vo lumeMeasur ementId =  -1;
  1756  
  1757       functi on setVolu meMeasurem entId(volu meId) {
  1758           vo lumeMeasur ementId =  volumeId;
  1759       }
  1760  
  1761       functi on getVolu meMeasurem entId() {
  1762           re turn volum eMeasureme ntId;
  1763       }
  1764  
  1765       var mi tralMeanGr adientMeas urementEnd  = false;
  1766  
  1767       functi on setMitr alMeanGrad ientMeasur ementEnd(f lag) {
  1768           mi tralMeanGr adientMeas urementEnd  = flag;
  1769       }
  1770  
  1771           fu nction isM itralMeanG radientMea surementEn d() {
  1772           re turn mitra lMeanGradi entMeasure mentEnd;
  1773       }
  1774  
  1775       var mi tralMeanGr adientMeas urementId  = -1;
  1776  
  1777       functi on setMitr alMeanGrad ientMeasur ementId(Id ) {
  1778           mi tralMeanGr adientMeas urementId  = Id;
  1779       }
  1780  
  1781       functi on getMitr alMeanGrad ientMeasur ementId()  {
  1782           re turn mitra lMeanGradi entMeasure mentId;
  1783       }
  1784  
  1785       var pe nToolEnd =  false;
  1786       functi on setPenT oolEnd(fla g) {
  1787           pe nToolEnd =  flag;
  1788       }
  1789  
  1790       functi on isPenTo olEnd() {
  1791           re turn penTo olEnd;
  1792       }
  1793  
  1794       functi on addMeas urements(i mageUid, f rameIndex,  imageRend erer, mosu eData, con text) {
  1795           re moveTempda ta();                
  1796           if  (imageRen derer ===  undefined)  {
  1797                throw "a ddMeasurem ents : ima geRenderer  is null/u ndefined";
  1798           }
  1799  
  1800           va r measurem ents = dic omImageMea surements[ imageUid +  "_" + fra meIndex];
  1801           if  (measurem ents === u ndefined)  {
  1802                measurem ents = [];
  1803           }
  1804           va r imageDat a = getIma geDataForM ouseData(m osueData,  imageRende rer, conte xt);
  1805           im ageData.te xtPosition  = mosueDa ta.textPos ition;
  1806           mo sueData =  undefined;  // Releas e the memo ry for the  data 
  1807           me asurements [measureme nts.length ] = imageD ata;
  1808           im ageData =  undefined;  // Releas e the memo ry for the  data
  1809           di comImageMe asurements [imageUid  + "_" + fr ameIndex]  = measurem ents;
  1810  
  1811           up dateDirtyP State(imag eRenderer. seriesLeve lDivId);
  1812       }
  1813  
  1814       var is NearToStar tPoint, is NearToFirs tPoint;
  1815       var is NearToEndP oint, isNe arToSecond Point;
  1816       var is NearToStar tX, isNear ToThirdPoi nt;
  1817       var is NearToEndX , isNearTo FourthPoin t;
  1818       var in dexToEditM itral = 0;
  1819  
  1820           fu nction res etHandeler ()
  1821           {
  1822                    isNe arToStartP oint = und efined;
  1823                    isNe arToEndPoi nt = undef ined;
  1824           is NearToStar tX = undef ined;
  1825           is NearToEndX  = undefin ed;
  1826  
  1827           is NearToFirs tPoint = u ndefined;
  1828           is NearToSeco ndPoint =  undefined;
  1829           is NearToThir dPoint = u ndefined;
  1830           is NearToFour thPoint =  undefined;
  1831           in dexToEditM itral = 0;
  1832           }
  1833       functi on updateM easurement s(dataToed it, imageR enderer, m osueData,  context) {
  1834                    remo veTempdata ();
  1835           if  (imageRen derer ===  undefined)  {
  1836                throw "a ddMeasurem ents : ima geRenderer  is null/u ndefined";
  1837           }
  1838  
  1839           va r measurem ent = dico mImageMeas urements[d ataToedit. key];
  1840           if  (measurem ent === un defined) {
  1841                return;
  1842           }
  1843  
  1844           up dateDirtyP State(imag eRenderer. seriesLeve lDivId, da taToedit);
  1845                    meas urement =  measuremen t[dataToed it.arryInd ex];
  1846                    var  imageData  = getImage DataForMou seData(mos ueData, im ageRendere r, context );
  1847                    if(m easurement .measureTy pe === "li ne")
  1848                    {
  1849                             if(isN earToStart Point == u ndefined)
  1850                             {
  1851                              isNea rToStartPo int = find NearHanleB yPoint(ima geData.end , measurem ent.start) ;
  1852                             }
  1853                             else i f(isNearTo EndPoint = = undefine d)
  1854                             {
  1855                 isNearT oEndPoint  = findNear HanleByPoi nt(imageDa ta.end, me asurement. end);
  1856                             }
  1857                             if(isN earToStart Point)
  1858                             {
  1859                             measur ement.star t.x = imag eData.end. x;
  1860                             measur ement.star t.y = imag eData.end. y;
  1861                             }
  1862                             else i f(isNearTo EndPoint)
  1863                             {
  1864                             measur ement.end. x = imageD ata.end.x;
  1865                             measur ement.end. y = imageD ata.end.y;
  1866                             }
  1867                
  1868                if(mosue Data){
  1869                   measu rement.tex tPosition  = mosueDat a.textPosi tion;
  1870                }
  1871                             dicomI mageMeasur ements[dat aToedit.ke y][dataToe dit.arryIn dex] = mea surement;
  1872                    }els e
  1873                    {
  1874           mo sueData =  undefined;  // Releas e the memo ry for the  data
  1875                    if(m easurement .measureme ntId === i mageData.m easurement Id)
  1876                    {
  1877                    meas urement =  imageData;
  1878                    }els e
  1879                    {
  1880                             measur ement.end  = imageDat a.end;
  1881                             measur ement.star t = imageD ata.start;
  1882                    }
  1883           di comImageMe asurements [dataToedi t.key][dat aToedit.ar ryIndex] =  measureme nt;
  1884                    }
  1885       }
  1886  
  1887       functi on getMeas urements(i mageUid, f rameIndex)  {
  1888           if  (imageUid  === undef ined) {
  1889                throw "g etMeasurem ents: imag eUid is nu ll/undefin ed";
  1890           }
  1891           if  (frameInd ex === und efined) {
  1892                throw "g etMeasurem ents : fra meIndex is  null/unde fined";
  1893           }                 
  1894           re turn dicom ImageMeasu rements[im ageUid + " _" + frame Index];
  1895       }
  1896       // Ang le measure ment
  1897       functi on getAngl eMeasureme nts(imageU id, frameI ndex) {
  1898           if  (imageUid  === undef ined) {
  1899                throw "g etMeasurem ents: imag eUid is nu ll/undefin ed";
  1900           }
  1901           if  (frameInd ex === und efined) {
  1902                throw "g etMeasurem ents : fra meIndex is  null/unde fined";
  1903           }
  1904           re turn dicom ImageAngle Measuremen ts[imageUi d + "_" +  frameIndex ];
  1905       }
  1906       
  1907       functi on resetAn gleEditMod e(imageUid , frameInd ex, dataTo Edit) {
  1908           if  (imageUid  === undef ined) {
  1909                throw "r esetAngleE ditMode: i mageUid is  null/unde fined";
  1910           }
  1911           if  (frameInd ex === und efined) {
  1912                throw "r esetAngleE ditMode :  frameIndex  is null/u ndefined";
  1913           }
  1914           va r angleMea surement =  dicomImag eAngleMeas urements[i mageUid +  "_" + fram eIndex];
  1915           if  (angleMea surement = == undefin ed) {
  1916                throw "r esetAngleE ditMode :  angleMeasu rement is  null/undef ined";
  1917           }
  1918           va r measurem entData =  angleMeasu rement[dat aToEdit.ar ryIndex];
  1919           fo r(i=0; i<m easurement Data.lengt h; i++) {
  1920                measurem entData[i] .editMode  = false;
  1921           }
  1922           an gleMeasure ment[dataT oEdit.arry Index] = m easurement Data;
  1923           di comImageAn gleMeasure ments[imag eUid + "_"  + frameIn dex] = ang leMeasurem ent;
  1924       }
  1925  
  1926       functi on addAngl eMeasureme nts(imageU id, frameI ndex, imag eRenderer,  mosueData , context)  {
  1927           re moveTempda ta();
  1928           if  (imageRen derer ===  undefined)  {
  1929                throw "a ddAngleMea surements  : imageRen derer is n ull/undefi ned";
  1930           }
  1931  
  1932           va r angleMea surements  = dicomIma geAngleMea surements[ imageUid +  "_" + fra meIndex];
  1933  
  1934           if  (angleMea surements  === undefi ned) {
  1935                angleMea surements  = [];
  1936           }
  1937           va r measurem ents = ang leMeasurem ents[mosue Data.measu rementId];
  1938           if  (measurem ents === u ndefined)  {
  1939                measurem ents = [];
  1940           }
  1941           va r imageDat a = getIma geDataForM ouseData(m osueData,  imageRende rer, conte xt);
  1942           im ageData.te xtPosition  = mosueDa ta.textPos ition;
  1943           va r measureL ength = me asurements .length;
  1944           me asurements [measureLe ngth] = im ageData;
  1945           if  (measureL ength == 1 ) {
  1946                measurem ents[0].ed itMode = f alse;
  1947                measurem ents[1].ed itMode = f alse;
  1948           }
  1949  
  1950           an gleMeasure ments[mosu eData.meas urementId]  = measure ments;
  1951           di comImageAn gleMeasure ments[imag eUid + "_"  + frameIn dex] = ang leMeasurem ents;
  1952  
  1953           mo sueData =  undefined;  // Releas e the memo ry for the  data 
  1954           im ageData =  undefined;  // Releas e the memo ry for the  data
  1955  
  1956           up dateDirtyP State(imag eRenderer. seriesLeve lDivId);
  1957       }
  1958       
  1959       functi on addTrac eMeasureme nts(imageU id, frameI ndex, imag eRenderer,  mosueData , context)  {
  1960           re moveTempda ta();
  1961           if  (imageRen derer ===  undefined)  {
  1962                throw "a ddTraceMea surements  : imageRen derer is n ull/undefi ned";
  1963           }
  1964  
  1965           va r tarceMea surements  = dicomIma geTraceMea surements[ imageUid +  "_" + fra meIndex];
  1966  
  1967           if  (tarceMea surements  === undefi ned) {
  1968                tarceMea surements  = [];
  1969           }
  1970           va r measurem ents = tar ceMeasurem ents[mosue Data.measu rementId];
  1971           if  (measurem ents === u ndefined)  {
  1972                measurem ents = [];
  1973           }
  1974           va r imageDat a = getIma geDataForM ouseData(m osueData,  imageRende rer, conte xt);
  1975           im ageData.te xtPosition  = mosueDa ta.textPos ition;
  1976           va r measureL ength = me asurements .length;
  1977           me asurements [measureLe ngth] = im ageData;
  1978           ta rceMeasure ments[mosu eData.meas urementId]  = measure ments;
  1979           di comImageTr aceMeasure ments[imag eUid + "_"  + frameIn dex] = tar ceMeasurem ents;
  1980  
  1981           mo sueData =  undefined;  // Releas e the memo ry for the  data 
  1982           im ageData =  undefined;  // Releas e the memo ry for the  data
  1983  
  1984           up dateDirtyP State(imag eRenderer. seriesLeve lDivId);
  1985       }
  1986       
  1987       functi on getTrac eMeasureme nts(imageU id, frameI ndex) {
  1988           if  (imageUid  === undef ined) {
  1989                throw "g etMeasurem ents: imag eUid is nu ll/undefin ed";
  1990           }
  1991           if  (frameInd ex === und efined) {
  1992                throw "g etMeasurem ents : fra meIndex is  null/unde fined";
  1993           }
  1994           re turn dicom ImageTrace Measuremen ts[imageUi d + "_" +  frameIndex ];
  1995       }
  1996       functi on updateT raceMeasur ements(dat aToedit, i mageRender er, mosueD ata, conte xt) {
  1997                    remo veTempdata ();
  1998           if  (imageRen derer ===  undefined)  {
  1999                throw "a ddMeasurem ents : ima geRenderer  is null/u ndefined";
  2000           }
  2001  
  2002           va r measurem ent = dico mImageTrac eMeasureme nts[dataTo edit.key];
  2003           if  (measurem ent === un defined) {
  2004                return;
  2005           }
  2006  
  2007           up dateDirtyP State(imag eRenderer. seriesLeve lDivId, da taToedit);
  2008                    meas urement =  measuremen t[dataToed it.arryInd ex];
  2009                    var  imageData  = getImage DataForMou seData(mos ueData, im ageRendere r, context );
  2010                    if(m easurement .measureTy pe === "li ne")
  2011                    {
  2012                             if(isN earToStart Point == u ndefined)
  2013                             {
  2014                              isNea rToStartPo int = find NearHanleB yPoint(ima geData.end , measurem ent.start) ;
  2015                             }
  2016                             else i f(isNearTo EndPoint = = undefine d)
  2017                             {
  2018                 isNearT oEndPoint  = findNear HanleByPoi nt(imageDa ta.end, me asurement. end);
  2019                             }
  2020                             if(isN earToStart Point)
  2021                             {
  2022                             measur ement.star t.x = imag eData.end. x;
  2023                             measur ement.star t.y = imag eData.end. y;
  2024                             }
  2025                             else i f(isNearTo EndPoint)
  2026                             {
  2027                             measur ement.end. x = imageD ata.end.x;
  2028                             measur ement.end. y = imageD ata.end.y;
  2029                             }
  2030                             dicomI mageTraceM easurement s[dataToed it.key][da taToedit.a rryIndex]  = measurem ent;
  2031                    }els e
  2032                    {
  2033           mo sueData =  undefined;  // Releas e the memo ry for the  data
  2034                    if(m easurement .measureme ntId === i mageData.m easurement Id)
  2035                    {
  2036                    meas urement =  imageData;
  2037                    }els e
  2038                    {
  2039                             measur ement.end  = imageDat a.end;
  2040                             measur ement.star t = imageD ata.start;
  2041                    }
  2042           di comImageTr aceMeasure ments[data Toedit.key ][dataToed it.arryInd ex] = meas urement;
  2043                    }
  2044       }
  2045  
  2046       functi on resetTr aceEditMod e(imageUid , frameInd ex, dataTo Edit) {
  2047           if  (imageUid  === undef ined) {
  2048                throw "r esetTraceE ditMode: i mageUid is  null/unde fined";
  2049           }
  2050           if  (frameInd ex === und efined) {
  2051                throw "r esetTraceE ditMode :  frameIndex  is null/u ndefined";
  2052           }
  2053           va r traceMea surement =  dicomImag eTraceMeas urements[i mageUid +  "_" + fram eIndex];
  2054           if  (traceMea surement = == undefin ed) {
  2055                throw "r esetTraceE ditMode :  traceMeasu rement is  null/undef ined";
  2056           }
  2057  
  2058           va r measurem entIndex;
  2059           if  (dataToEd it == unde fined) {
  2060                measurem entIndex =  traceMeas urement.le ngth - 1;
  2061           }  else {
  2062                measurem entIndex =  dataToEdi t.arryInde x;
  2063           }
  2064           va r measurem entData =  traceMeasu rement[mea surementIn dex];
  2065           fo r(i=0; i<m easurement Data.lengt h; i++) {
  2066                measurem entData[i] .editMode  = false;
  2067           }
  2068           tr aceMeasure ment[measu rementInde x] = measu rementData ;
  2069           di comImageTr aceMeasure ments[imag eUid + "_"  + frameIn dex] = tra ceMeasurem ent;
  2070       }
  2071  
  2072       functi on addElli pseMeasure ments(imag eUid, fram eIndex, im ageRendere r, mosueDa ta, contex t, measure mentResult ) {
  2073           re moveTempda ta();
  2074           if  (imageRen derer ===  undefined)  {
  2075                throw "a ddTraceMea surements  : imageRen derer is n ull/undefi ned";
  2076           }
  2077  
  2078           va r ellipseM easurement s = dicomI mageEllips eMeasureme nts[imageU id + "_" +  frameInde x];
  2079  
  2080           if  (ellipseM easurement s === unde fined) {
  2081                ellipseM easurement s = [];
  2082           }
  2083  
  2084           va r imageDat a = getIma geDataForM ouseData(m osueData,  imageRende rer, conte xt); 
  2085           im ageData.te xtPosition  = mosueDa ta.textPos ition;
  2086           va r measureL ength = el lipseMeasu rements.le ngth;
  2087           el lipseMeasu rements[me asureLengt h] = image Data;
  2088           el lipseMeasu rements[me asureLengt h].measure mentResult  = measure mentResult ;
  2089           el lipseMeasu rements[me asureLengt h].editMod e = false;
  2090           di comImageEl lipseMeasu rements[im ageUid + " _" + frame Index] = e llipseMeas urements;
  2091  
  2092           mo sueData =  undefined;  // Releas e the memo ry for the  data 
  2093           im ageData =  undefined;  // Releas e the memo ry for the  data
  2094  
  2095           up dateDirtyP State(imag eRenderer. seriesLeve lDivId);
  2096       }
  2097       
  2098       functi on resetEl lipseEditM ode(imageU id, frameI ndex, data ToEdit) {
  2099           if  (imageUid  === undef ined) {
  2100                throw "r esetEditMo de: imageU id is null /undefined ";
  2101           }
  2102           if  (frameInd ex === und efined) {
  2103                throw "r esetEditMo de : frame Index is n ull/undefi ned";
  2104           }
  2105           va r measurem entData =  dicomImage EllipseMea surements[ imageUid +  "_" + fra meIndex];
  2106           if  (measurem entData == = undefine d) {
  2107                throw "r esetEllips eEditMode  : measurem entData is  null/unde fined";
  2108           }
  2109  
  2110           me asurementD ata[dataTo Edit.arryI ndex].edit Mode = fal se;
  2111           di comImageEl lipseMeasu rements[im ageUid + " _" + frame Index] = m easurement Data;
  2112       }
  2113       
  2114       functi on getElli pseMeasure ments(imag eUid, fram eIndex) {
  2115           if  (imageUid  === undef ined) {
  2116                throw "g etMeasurem ents: imag eUid is nu ll/undefin ed";
  2117           }
  2118           if  (frameInd ex === und efined) {
  2119                throw "g etMeasurem ents : fra meIndex is  null/unde fined";
  2120           }
  2121           re turn dicom ImageEllip seMeasurem ents[image Uid + "_"  + frameInd ex];
  2122       }
  2123       functi on updateE llipseMeas urements(d ataToedit,  imageRend erer, mosu eData, con text) {
  2124                    remo veTempdata ();
  2125           if  (imageRen derer ===  undefined)  {
  2126                throw "a ddMeasurem ents : ima geRenderer  is null/u ndefined";
  2127           }
  2128  
  2129           va r measurem ent = dico mImageElli pseMeasure ments[data Toedit.key ];
  2130           if  (measurem ent === un defined) {
  2131                return;
  2132           }
  2133  
  2134           up dateDirtyP State(imag eRenderer. seriesLeve lDivId, da taToedit);
  2135                    meas urement =  measuremen t[dataToed it.arryInd ex];
  2136                    var  imageData  = getImage DataForMou seData(mos ueData, im ageRendere r, context );
  2137           if (measureme nt.measure Type === " ellipse")
  2138                    {
  2139                var firs t, second;
  2140                if (meas urement.is CustomElli pse) {
  2141                    firs t = measur ement.firs t;
  2142                    seco nd = measu rement.sec ond;
  2143                } else {
  2144                    firs t = measur ement.star t;
  2145                    seco nd = measu rement.end ;
  2146                }
  2147                if (isNe arToFirstP oint == un defined) {
  2148                    isNe arToFirstP oint = fin dNearHanle ByPoint(im ageData.en d, first);
  2149                } if (is NearToSeco ndPoint ==  undefined ) {
  2150                    isNe arToSecond Point = fi ndNearHanl eByPoint(i mageData.e nd, second );
  2151                } if (is NearToThir dPoint ==  undefined)  {
  2152                    isNe arToThirdP oint = (me asurement. isCustomEl lipse) ? f indNearHan leByPoint( imageData. end, measu rement.thi rd) : isHa ndleNearBy X(imageDat a.end, mea surement.s tart);
  2153                } if (is NearToFour thPoint ==  undefined ) {
  2154                    isNe arToFourth Point = (m easurement .isCustomE llipse) ?  findNearHa nleByPoint (imageData .end, meas urement.fo urth) : is HandleNear ByX(imageD ata.end, m easurement .end);
  2155                }
  2156  
  2157                if (isNe arToFirstP oint) {
  2158                    if(m easurement .isCustomE llipse &&  !validateE llipseMove ment(1, im ageData, m easurement )) {
  2159                         return;
  2160                    }
  2161                    var  startAngle  = findAng le(1, meas urement);
  2162                    meas urement.st art.x = im ageData.en d.x;
  2163                    meas urement.st art.y = im ageData.en d.y;
  2164                    if(m easurement .isCustomE llipse) {
  2165                         measuremen t.first.x  = imageDat a.end.x;
  2166                         measuremen t.first.y  = imageDat a.end.y;
  2167                         adjustQuad rantsOfEll ipse(1, me asurement,  startAngl e);
  2168                    }
  2169                    
  2170                    isNe arToSecond Point = un defined;
  2171                    isNe arToThirdP oint = und efined;
  2172                    isNe arToFourth Point = un defined;
  2173                 } else  if (isNear ToSecondPo int) {
  2174                    if(m easurement .isCustomE llipse &&  !validateE llipseMove ment(2, im ageData, m easurement )) {
  2175                         return;
  2176                    }
  2177                    var  startAngle  = findAng le(2, meas urement);
  2178                    meas urement.en d.x = imag eData.end. x;
  2179                    meas urement.en d.y = imag eData.end. y;
  2180                    if(m easurement .isCustomE llipse) {
  2181                         measuremen t.second.x  = imageDa ta.end.x;
  2182                         measuremen t.second.y  = imageDa ta.end.y;
  2183                         adjustQuad rantsOfEll ipse(2, me asurement,  startAngl e);
  2184                    }
  2185                    
  2186                    isNe arToFirstP oint = und efined;
  2187                    isNe arToThirdP oint = und efined;
  2188                    isNe arToFourth Point = un defined;
  2189                 } else  if (isNear ToThirdPoi nt) {
  2190                     if  (measureme nt.isCusto mEllipse)  {
  2191                          if(!valid ateEllipse Movement(3 , imageDat a, measure ment)) {
  2192                             return ;
  2193                         }
  2194                         var startA ngle = fin dAngle(3,  measuremen t);
  2195                         measuremen t.third.x  = imageDat a.end.x;
  2196                         measuremen t.third.y  = imageDat a.end.y;
  2197                         adjustQuad rantsOfEll ipse(3, me asurement,  startAngl e);
  2198                         measuremen t.start =  measuremen t.first;
  2199                         measuremen t.end = me asurement. second;
  2200                     } e lse {
  2201                          measureme nt.start.x  = imageDa ta.end.x;
  2202                          measureme nt.end.y =  imageData .end.y;
  2203                     }
  2204  
  2205                    isNe arToFirstP oint = und efined;
  2206                    isNe arToSecond Point = un defined;
  2207                    isNe arToFourth Point = un defined;
  2208                 } else  if (isNear ToFourthPo int) {
  2209                     if  (measureme nt.isCusto mEllipse)  {
  2210                          if(!valid ateEllipse Movement(4 , imageDat a, measure ment)) {
  2211                             return ;
  2212                         }
  2213                         var startA ngle = fin dAngle(4,  measuremen t);
  2214                         measuremen t.fourth.x  = imageDa ta.end.x;
  2215                         measuremen t.fourth.y  = imageDa ta.end.y;
  2216                         adjustQuad rantsOfEll ipse(4, me asurement,  startAngl e);
  2217                         measuremen t.start =  measuremen t.first;
  2218                         measuremen t.end = me asurement. second;
  2219                     } e lse {
  2220                          measureme nt.start.y  = imageDa ta.end.y;
  2221                          measureme nt.end.x =  imageData .end.x;
  2222                     }
  2223                    
  2224                    isNe arToFirstP oint = und efined;
  2225                    isNe arToSecond Point = un defined;
  2226                    isNe arToThirdP oint = und efined;
  2227                 } else  {
  2228                    isNe arToFirstP oint = und efined;
  2229                    isNe arToSecond Point = un defined;
  2230                    isNe arToThirdP oint = und efined;
  2231                    isNe arToFourth Point = un defined;
  2232                }
  2233  
  2234                measurem ent.editMo de = true;
  2235                             dicomI mageEllips eMeasureme nts[dataTo edit.key][ dataToedit .arryIndex ] = measur ement;
  2236                    }els e
  2237                    {
  2238           mo sueData =  undefined;  // Releas e the memo ry for the  data
  2239                    if(m easurement .measureme ntId === i mageData.m easurement Id)
  2240                    {
  2241                    meas urement =  imageData;
  2242                    }els e
  2243                    {
  2244                             measur ement.end  = imageDat a.end;
  2245                             measur ement.star t = imageD ata.start;
  2246                measurem ent.second  = imageDa ta.second;
  2247                measurem ent.first  = imageDat a.first;
  2248  
  2249                    }
  2250           di comImageEl lipseMeasu rements[da taToedit.k ey][dataTo edit.arryI ndex] = me asurement;
  2251                    }
  2252       }
  2253       
  2254       /**
  2255        * Ret urns false  if distan ce is less  than mini mum.
  2256        * @pa ram {Type}  nearToPoi nt 
  2257        * @pa ram {Type}  imageData  
  2258        * @pa ram {Type}  measureme nt 
  2259        */ 
  2260       functi on validat eEllipseMo vement(nea rToPoint,  imageData,  measureme nt) {
  2261           va r tempData  = {
  2262                start :  measuremen t.center,
  2263                end : im ageData.en d
  2264           };
  2265           va r dist2Cen ter = find QuadrantsD istance(ne arToPoint,  measureme nt, measur ement.cent er);
  2266           va r distance  = parseFl oat(getLen gth(tempDa ta), 2);
  2267           if  (distance  < 50 && d istance !=  dist2Cent er) {
  2268                return f alse;
  2269           }
  2270           va r totalDis t = findQu adrantsDis tance(near ToPoint, m easurement , imageDat a.end);
  2271  
  2272           if  ((distanc e + dist2C enter - to talDist) >  10) {
  2273                return f alse;
  2274           }
  2275           re turn true;
  2276       }
  2277  
  2278       /**
  2279        * 
  2280        * @pa ram {Type}  nearToPoi nt 
  2281        * @pa ram {Type}  measureme nt 
  2282        * @pa ram {Type}  startAngl
  2283        */ 
  2284       functi on adjustQ uadrantsOf Ellipse(ne arToPoint,  measureme nt, startA ngle) {
  2285           va r cx = mea surement.c enter.x,
  2286                cy = mea surement.c enter.y,
  2287                endAngle  = adjustC enterOfEll ipse(nearT oPoint, me asurement) ,
  2288                toAngle  = endAngle  - startAn gle;
  2289           if  (nearToPo int == 1 | | nearToPo int == 2)  {
  2290                applyTra nsform(cx,  cy, measu rement, 3,  toAngle);
  2291           }  else if (n earToPoint  == 3 || n earToPoint  == 4) {
  2292                applyTra nsform(cx,  cy, measu rement, 1,  toAngle);
  2293           }
  2294       }
  2295  
  2296       /**
  2297        * App ly the tra nsform to  the center  of quadra nt in case  of rotati on.
  2298        * @pa ram {Type}  nearToPoi nt 
  2299        * @pa ram {Type}  measureme nt 
  2300        */ 
  2301       functi on adjustC enterOfEll ipse(nearT oPoint, me asurement)  {
  2302           va r point =  measuremen t.first;
  2303           if  (nearToPo int == 3 | | nearToPo int == 4)  {
  2304                point =  measuremen t.fourth;
  2305           }
  2306           va r dx = poi nt.x - mea surement.c enter.x,
  2307                dy = poi nt.y - mea surement.c enter.y,
  2308                distance  = Math.sq rt(Math.po w(dx, 2) +  Math.pow( dy, 2)),
  2309                angle =  findAngle( nearToPoin t, measure ment);
  2310           me asurement. center = {
  2311                x: point .x + Math. cos(angle)  * distanc e,
  2312                y: point .y + Math. sin(angle)  * distanc e
  2313           };
  2314           re turn angle ;
  2315       }
  2316  
  2317       /**
  2318        * Ret urns angle  between t wo given p oints.
  2319        * @pa ram {Type}  nearToPoi nt 
  2320        * @pa ram {Type}  measureme nt 
  2321        */ 
  2322       functi on findAng le(nearToP oint, meas urement) {
  2323           va r isFirstH alf = (nea rToPoint = = 1 || nea rToPoint = = 2),
  2324                start =  isFirstHal f ? measur ement.star t : measur ement.four th,
  2325                end = is FirstHalf  ? measurem ent.end :  measuremen t.third,
  2326                dx = end .x - start .x,
  2327                dy = end .y - start .y,
  2328                distance  = Math.sq rt(Math.po w(dx, 2) +  Math.pow( dy, 2)),
  2329                cosalpha  = dx / di stance,
  2330                angle;
  2331           if  (dy / dis tance < 0)
  2332           {
  2333                angle =  (Math.PI *  2 - Math. acos(cosal pha));
  2334           }
  2335           el se
  2336           {
  2337                angle =  (Math.acos (cosalpha) );
  2338           }
  2339           re turn angle ;
  2340       }
  2341  
  2342       /**
  2343        * App ly the tra nsform to  all the qu adrants in  case of r otation.
  2344        * @pa ram {Type}  cx 
  2345        * @pa ram {Type}  cy 
  2346        * @pa ram {Type}  measureme nt 
  2347        * @pa ram {Type}  applyToPo int 
  2348        * @pa ram {Type}  toAngle 
  2349        */ 
  2350       functi on applyTr ansform(cx , cy, meas urement, a pplyToPoin t, toAngle ) {
  2351           va r rotatedP t,
  2352                translat edPt,
  2353                xDiff =  measuremen t.center.x  - cx,
  2354                yDiff =  measuremen t.center.y  - cy;
  2355           if  (applyToP oint == 3)  {
  2356                rotatedP t = rotate (cx, cy, m easurement , 3, -toAn gle, 0, tr ue);
  2357                translat edPt = {
  2358                    x: r otatedPt.x  + xDiff,
  2359                    y: r otatedPt.y  + yDiff
  2360                }
  2361                measurem ent.third  = translat edPt;
  2362                rotatedP t = rotate (cx, cy, m easurement , 4, -toAn gle, 0, tr ue);
  2363                translat edPt = {
  2364                    x: r otatedPt.x  + xDiff,
  2365                    y: r otatedPt.y  + yDiff
  2366                }
  2367                measurem ent.fourth  = transla tedPt;
  2368           }  else if (a pplyToPoin t == 1) {
  2369                rotatedP t = rotate (cx, cy, m easurement , 1, -toAn gle, 0, tr ue);
  2370                translat edPt = {
  2371                    x: r otatedPt.x  + xDiff,
  2372                    y: r otatedPt.y  + yDiff
  2373                }
  2374                measurem ent.first  = translat edPt;
  2375                rotatedP t = rotate (cx, cy, m easurement , 2, -toAn gle, 0, tr ue);
  2376                translat edPt = {
  2377                    x: r otatedPt.x  + xDiff,
  2378                    y: r otatedPt.y  + yDiff
  2379                }
  2380                measurem ent.second  = transla tedPt;
  2381           }
  2382       }
  2383  
  2384       /**
  2385        * Rot ate a poin t to given  radians w ith given  center poi nt.
  2386        * @pa ram {Type}  cx 
  2387        * @pa ram {Type}  cy 
  2388        * @pa ram {Type}  measureme nt 
  2389        * @pa ram {Type}  toRotate 
  2390        * @pa ram {Type}  radians 
  2391        * @pa ram {Type}  distance 
  2392        * @pa ram {Type}  isCenter 
  2393        */ 
  2394       functi on rotate( cx, cy, me asurement,  toRotate,  radians,  distance,  isCenter)  {
  2395           va r point;
  2396           if  (toRotate  == 1) {
  2397                point =  {
  2398                    x: m easurement .first.x,
  2399                    y: m easurement .first.y
  2400                }
  2401           }  else if (t oRotate ==  2) {
  2402                point =  {
  2403                    x: m easurement .second.x,
  2404                    y: m easurement .second.y
  2405                }
  2406           }  else if (t oRotate ==  3) {
  2407                point =  {
  2408                    x: m easurement .third.x,
  2409                    y: m easurement .third.y
  2410                }
  2411           }  else if (t oRotate ==  4) {
  2412                point =  {
  2413                    x: m easurement .fourth.x,
  2414                    y: m easurement .fourth.y
  2415                }
  2416           }
  2417           if  (isCenter ) {
  2418                var cos  = Math.cos (radians),
  2419                sin = Ma th.sin(rad ians),
  2420                nx = (co s * (point .x - cx))  + (sin * ( point.y -  cy)) + cx,
  2421                ny = (co s * (point .y - cy))  - (sin * ( point.x -  cx)) + cy;
  2422                return {  x: nx, y:  ny };
  2423           }
  2424           va r rotatedP oint = {
  2425                x: point .x + Math. cos(radian s) * dista nce,
  2426                y: point .y + Math. sin(radian s) * dista nce
  2427           }
  2428           re turn rotat edPoint;
  2429       }
  2430  
  2431       /**
  2432        * 
  2433        * @pa ram {Type}  measureme nt 
  2434        * @pa ram {Type}  endPt 
  2435        */ 
  2436       functi on findQua drantsDist ance(nearT oPoint, me asurement,  endPt) {
  2437           va r tempData , distance ;
  2438           if  (nearToPo int == 1)  {
  2439                tempData  = {
  2440                    star t : measur ement.seco nd,
  2441                    end  : endPt
  2442                };
  2443           }  else if (n earToPoint  == 2) {
  2444                tempData  = {
  2445                    star t : measur ement.firs t,
  2446                    end  : endPt
  2447                };
  2448           }  else if (n earToPoint  == 3) {
  2449                tempData  = {
  2450                    star t : measur ement.four th,
  2451                    end  : endPt
  2452                };
  2453           }  else if (n earToPoint  == 4) {
  2454                tempData  = {
  2455                    star t : measur ement.thir d,
  2456                    end  : endPt
  2457                };
  2458           }
  2459           di stance = p arseFloat( getLength( tempData),  2);
  2460           re turn dista nce;
  2461       }
  2462  
  2463       /**
  2464        * To  hold recta ngle measu rements an d annotati ons
  2465        * @pa ram {Type}  imageUid 
  2466        * @pa ram {Type}  frameInde
  2467        * @pa ram {Type}  imageRend erer 
  2468        * @pa ram {Type}  mosueData  
  2469        * @pa ram {Type}  context 
  2470        * @pa ram {Type}  measureme ntResult 
  2471        */ 
  2472       functi on addRect angleMeasu rements(im ageUid, fr ameIndex,  imageRende rer, mosue Data, cont ext, measu rementResu lt) {
  2473           re moveTempda ta();
  2474           if  (imageRen derer ===  undefined)  {
  2475                throw "a ddTraceMea surements  : imageRen derer is n ull/undefi ned";
  2476           }
  2477  
  2478           va r rectangl eMeasureme nts = dico mImageRect angleMeasu rements[im ageUid + " _" + frame Index];
  2479  
  2480           if  (rectangl eMeasureme nts === un defined) {
  2481                rectangl eMeasureme nts = [];
  2482           }
  2483  
  2484           va r imageDat a = getIma geDataForM ouseData(m osueData,  imageRende rer, conte xt); 
  2485           im ageData.te xtPosition  = mosueDa ta.textPos ition;
  2486           va r measureL ength = re ctangleMea surements. length;
  2487           re ctangleMea surements[ measureLen gth] = ima geData;
  2488           re ctangleMea surements[ measureLen gth].measu rementResu lt = measu rementResu lt;
  2489           re ctangleMea surements[ measureLen gth].editM ode = fals e;
  2490           di comImageRe ctangleMea surements[ imageUid +  "_" + fra meIndex] =  rectangle Measuremen ts;
  2491  
  2492           mo sueData =  undefined;  // Releas e the memo ry for the  data 
  2493           im ageData =  undefined;  // Releas e the memo ry for the  data
  2494  
  2495           up dateDirtyP State(imag eRenderer. seriesLeve lDivId);
  2496       }
  2497  
  2498       /**
  2499        * To  reset the  edit mode  of rectang le measure ments
  2500        * @pa ram {Type}  imageUid 
  2501        * @pa ram {Type}  frameInde
  2502        * @pa ram {Type}  dataToEdi
  2503        */ 
  2504       functi on resetRe ctangleEdi tMode(imag eUid, fram eIndex, da taToEdit)  {
  2505           if  (imageUid  === undef ined) {
  2506                throw "r esetEditMo de: imageU id is null /undefined ";
  2507           }
  2508           if  (frameInd ex === und efined) {
  2509                throw "r esetEditMo de : frame Index is n ull/undefi ned";
  2510           }
  2511           va r measurem entData =  dicomImage RectangleM easurement s[imageUid  + "_" + f rameIndex] ;
  2512           me asurementD ata[dataTo Edit.arryI ndex].edit Mode = fal se;
  2513           di comImageRe ctangleMea surements[ imageUid +  "_" + fra meIndex] =  measureme ntData;
  2514       }
  2515  
  2516       /**
  2517        * To  get rectan gle measur ement from  the array
  2518        * @pa ram {Type}  imageUid 
  2519        * @pa ram {Type}  frameInde
  2520        */ 
  2521       functi on getRect angleMeasu rements(im ageUid, fr ameIndex)  {
  2522           if  (imageUid  === undef ined) {
  2523                throw "g etMeasurem ents: imag eUid is nu ll/undefin ed";
  2524           }
  2525           if  (frameInd ex === und efined) {
  2526                throw "g etMeasurem ents : fra meIndex is  null/unde fined";
  2527           }
  2528           re turn dicom ImageRecta ngleMeasur ements[ima geUid + "_ " + frameI ndex];
  2529       }
  2530  
  2531       /**
  2532        * To  update rec tangle mea surement d ata
  2533        * @pa ram {Type}  dataToedi
  2534        * @pa ram {Type}  imageRend erer 
  2535        * @pa ram {Type}  mosueData  
  2536        * @pa ram {Type}  context 
  2537        */ 
  2538       functi on updateR ectangleMe asurements (dataToedi t, imageRe nderer, mo sueData, c ontext, is Update) {
  2539           re moveTempda ta();
  2540           if  (imageRen derer ===  undefined)  {
  2541                throw "a ddMeasurem ents : ima geRenderer  is null/u ndefined";
  2542           }
  2543  
  2544           va r measurem ent = dico mImageRect angleMeasu rements[da taToedit.k ey];
  2545           if  (measurem ent === un defined) {
  2546                return;
  2547           }
  2548  
  2549           up dateDirtyP State(imag eRenderer. seriesLeve lDivId, da taToedit);
  2550           me asurement  = measurem ent[dataTo edit.arryI ndex];
  2551           va r imageDat a = getIma geDataForM ouseData(m osueData,  imageRende rer, conte xt);
  2552           if (measureme nt.measure Type === " rectangle" ) {
  2553  
  2554                if(isUpd ate !== fa lse) {
  2555                    if ( isNearToSt artPoint = = undefine d) {
  2556                         isNearToSt artPoint =  findNearH anleByPoin t(imageDat a.end, mea surement.s tart);
  2557                    } if  (isNearTo EndPoint = = undefine d) {
  2558                         isNearToEn dPoint = f indNearHan leByPoint( imageData. end, measu rement.end );
  2559                    } if  (isNearTo StartX ==  undefined)  {
  2560                         isNearToSt artX = isH andleNearB yX(imageDa ta.end, me asurement. start);
  2561                    } if  (isNearTo EndX == un defined) {
  2562                         isNearToEn dX = isHan dleNearByX (imageData .end, meas urement.en d);
  2563                    }
  2564                } else {
  2565                    isNe arToStartP oint = und efined;
  2566                    isNe arToEndPoi nt = undef ined;
  2567                    isNe arToStartX  = undefin ed;
  2568                    isNe arToEndX =  undefined ;
  2569                }
  2570                
  2571                if (isNe arToStartP oint) {
  2572                    meas urement.st art.x = im ageData.en d.x;
  2573                    meas urement.st art.y = im ageData.en d.y;
  2574                    isNe arToEndPoi nt = undef ined;
  2575                    isNe arToStartX  = undefin ed;
  2576                    isNe arToEndX =  undefined ;
  2577                 } else  if (isNear ToEndPoint ) {
  2578                    meas urement.en d.x = imag eData.end. x;
  2579                    meas urement.en d.y = imag eData.end. y;
  2580                    isNe arToStartP oint = und efined;
  2581                    isNe arToStartX  = undefin ed;
  2582                    isNe arToEndX =  undefined ;
  2583                 } else  if (isNear ToStartX)  {
  2584                    meas urement.st art.x = im ageData.en d.x;
  2585                    meas urement.en d.y = imag eData.end. y;
  2586                    isNe arToStartP oint = und efined;
  2587                    isNe arToEndPoi nt = undef ined;
  2588                    isNe arToEndX =  undefined ;
  2589                 } else  if (isNear ToEndX) {
  2590                    meas urement.st art.y = im ageData.en d.y;
  2591                    meas urement.en d.x = imag eData.end. x;
  2592                    isNe arToStartP oint = und efined;
  2593                    isNe arToEndPoi nt = undef ined;
  2594                    isNe arToStartX  = undefin ed;
  2595                 } else  {
  2596                    isNe arToStartP oint = und efined;
  2597                    isNe arToEndPoi nt = undef ined;
  2598                    isNe arToStartX  = undefin ed;
  2599                    isNe arToEndX =  undefined ;
  2600                }
  2601                
  2602                measurem ent.editMo de = true;
  2603                dicomIma geRectangl eMeasureme nts[dataTo edit.key][ dataToedit .arryIndex ] = measur ement;
  2604           }  else {
  2605                mosueDat a = undefi ned; // Re lease the  memory for  the data
  2606                if(measu rement.mea surementId  === image Data.measu rementId)  {
  2607                    meas urement =  imageData;
  2608                } else {
  2609                    meas urement.en d = imageD ata.end;
  2610                    meas urement.st art = imag eData.star t;
  2611                }
  2612                dicomIma geRectangl eMeasureme nts[dataTo edit.key][ dataToedit .arryIndex ] = measur ement;
  2613           }
  2614       }
  2615  
  2616       /**
  2617        * To  check if t he mouse p oint is ne ar by rect angle meas urement co rners
  2618        * @pa ram {Type}  mouseData  
  2619        * @pa ram {Type}  point 
  2620        */ 
  2621       functi on isHandl eNearByX(m ouseData,  point) {
  2622           if  (point.x  - 2 <= mou seData.x & &
  2623                point.x  + 2 >= mou seData.x)  {
  2624                return t rue;
  2625           }
  2626           re turn false ;
  2627       }
  2628  
  2629       functi on addVolu meMeasurem ents(image Uid, frame Index, ima geRenderer , mosueDat a, context ) {
  2630           re moveTempda ta();
  2631           if  (imageRen derer ===  undefined)  {
  2632                throw "a ddVolumeMe asurements  : imageRe nderer is  null/undef ined";
  2633           }
  2634  
  2635           va r volumeMe asurements  = dicomIm ageVolumeM easurement s[imageUid  + "_" + f rameIndex] ;
  2636  
  2637           if  (volumeMe asurements  === undef ined) {
  2638                volumeMe asurements  = [];
  2639           }
  2640           va r measurem ents = vol umeMeasure ments[mosu eData.meas urementId] ;
  2641           if  (measurem ents === u ndefined)  {
  2642                measurem ents = [];
  2643           }
  2644           va r imageDat a = getIma geDataForM ouseData(m osueData,  imageRende rer, conte xt);
  2645           me asurements [measureme nts.length ] = imageD ata;
  2646           vo lumeMeasur ements[mos ueData.mea surementId ] = measur ements;
  2647           di comImageVo lumeMeasur ements[ima geUid + "_ " + frameI ndex] = vo lumeMeasur ements;
  2648  
  2649           mo sueData =  undefined;  // Releas e the memo ry for the  data 
  2650           im ageData =  undefined;  // Releas e the memo ry for the  data
  2651  
  2652       }
  2653      
  2654       functi on getVolu meMeasurem ents(image Uid, frame Index) {
  2655           if  (imageUid  === undef ined) {
  2656                throw "g etMeasurem ents: imag eUid is nu ll/undefin ed";
  2657           }
  2658           if  (frameInd ex === und efined) {
  2659                throw "g etMeasurem ents : fra meIndex is  null/unde fined";
  2660           }
  2661           re turn dicom ImageVolum eMeasureme nts[imageU id + "_" +  frameInde x];
  2662       }
  2663  
  2664       functi on removeM easurement (imageUid,  frameInde x) {
  2665  
  2666       }
  2667  
  2668       functi on addMitr alGradient Measuremen ts(imageUi d, frameIn dex, image Renderer,  mosueData,  context)  {
  2669           re moveTempda ta();
  2670           if  (imageRen derer ===  undefined)  {
  2671                throw "a ddMitralGr adientMeas urements :  imageRend erer is nu ll/undefin ed";
  2672           }
  2673  
  2674           va r mitralMe asurements  = dicomIm ageMitralG radientMea surements[ imageUid +  "_" + fra meIndex];
  2675  
  2676           if  (mitralMe asurements  === undef ined) {
  2677                mitralMe asurements  = [];
  2678           }
  2679           va r measurem ents = mit ralMeasure ments[mosu eData.meas urementInd ex];
  2680           if  (measurem ents === u ndefined)  {
  2681                measurem ents = [];
  2682           }
  2683           va r imageDat a = getIma geDataForM ouseData(m osueData,  imageRende rer, conte xt);
  2684           im ageData.te xtPosition  = mosueDa ta.textPos ition;
  2685           va r measureL ength = me asurements .length;
  2686           me asurements [measureLe ngth] = im ageData;
  2687           if  (!mitralM eanGradien tMeasureme ntEnd) {
  2688                for (i =  0; i < me asureLengt h; i++) {
  2689                    meas urements[i ].editMode  = false;
  2690                }
  2691           }
  2692           mi tralMeasur ements[mos ueData.mea surementIn dex] = mea surements;
  2693           di comImageMi tralGradie ntMeasurem ents[image Uid + "_"  + frameInd ex] = mitr alMeasurem ents;
  2694  
  2695           mo sueData =  undefined;  // Releas e the memo ry for the  data 
  2696           im ageData =  undefined;  // Releas e the memo ry for the  data
  2697  
  2698           up dateDirtyP State(imag eRenderer. seriesLeve lDivId);
  2699       }
  2700  
  2701       functi on resetMi tralEditMo de(imageUi d, frameIn dex, dataT oEdit) {
  2702           if  (imageUid  === undef ined) {
  2703                throw "r esetMitral EditMode:  imageUid i s null/und efined";
  2704           }
  2705           if  (frameInd ex === und efined) {
  2706                throw "r esetMitral EditMode :  frameInde x is null/ undefined" ;
  2707           }
  2708           va r mitralMe asurement  = dicomIma geMitralGr adientMeas urements[i mageUid +  "_" + fram eIndex];
  2709           if  (mitralMe asurement  === undefi ned) {
  2710                throw "r esetMitral EditMode :  mitralMea surement i s null/und efined";
  2711           }
  2712  
  2713           va r measurem entIndex;
  2714           if  (dataToEd it == unde fined) {
  2715                measurem entIndex =  mitralMea surement.l ength - 1;
  2716           }  else {
  2717                measurem entIndex =  dataToEdi t.arryInde x;
  2718           }
  2719           va r measurem entData =  mitralMeas urement[me asurementI ndex];
  2720           if (measureme ntData ==  undefined) {
  2721                return;
  2722           }
  2723  
  2724           fo r(i=0; i<m easurement Data.lengt h; i++) {
  2725                measurem entData[i] .editMode  = false;
  2726           }
  2727           mi tralMeasur ement[meas urementInd ex] = meas urementDat a;
  2728           di comImageMi tralGradie ntMeasurem ents[image Uid + "_"  + frameInd ex] = mitr alMeasurem ent;
  2729       }
  2730  
  2731       functi on getMitr alGradient Measuremen ts(imageUi d, frameIn dex) {
  2732           if  (imageUid  === undef ined) {
  2733                throw "g etMitralGr adientMeas urements:  imageUid i s null/und efined";
  2734           }
  2735           if  (frameInd ex === und efined) {
  2736                throw "g etMitralGr adientMeas urements :  frameInde x is null/ undefined" ;
  2737           }
  2738           re turn dicom ImageMitra lGradientM easurement s[imageUid  + "_" + f rameIndex] ;
  2739       }
  2740       
  2741       functi on getLeng th(data) {
  2742           va r dx = (da ta.start.x  - data.en d.x);
  2743           va r dy = (da ta.start.y  - data.en d.y);
  2744           va r lengthIn Pixels = M ath.sqrt(d x * dx + d y * dy);
  2745  
  2746           re turn lengt hInPixels. toFixed(2) ;
  2747       }
  2748  
  2749       functi on getMous ePos(canva s, pointX,  pointY) {
  2750           va r rect = c anvas.getB oundingCli entRect();
  2751           re turn {
  2752                x: point X - rect.l eft,
  2753                y: point Y - rect.t op
  2754           };
  2755       }
  2756  
  2757       functi on findTra ceToDelete (mouseData , imageRen derer) {
  2758           is TraceDelet eCheck = t rue;
  2759           ac tiveImageR enderer =  undefined;
  2760           re moveTempda ta();
  2761           va r measurem entKey = i mageRender er.anUIDs. replace("* ","_");
  2762   //         loop: for  (var i in  dicomImage TraceMeasu rements) {
  2763     //           if (di comImageTr aceMeasure ments.hasO wnProperty (i)) {
  2764                    var  tarceMeasu rements =  dicomImage TraceMeasu rements[me asurementK ey];
  2765                    if ( tarceMeasu rements != = undefine d) {
  2766                         for (var n  = 0; n <  tarceMeasu rements.le ngth; n++)  {
  2767                             if (ac tiveImageR enderer == = undefine d) {
  2768                                 va r measurem ents = tar ceMeasurem ents[n];
  2769                                 if  (measurem ents !== u ndefined)  {
  2770                                      for (var  m = 0; m  < measurem ents.lengt h; m++) {
  2771                                          var  data = mea surements[ m];
  2772                                          if ( data !== u ndefined & & data.mea sureType = = "trace")  {
  2773                                               var origin alLineDist ance = get Length(dat a);
  2774  
  2775                                               var tempDa ta = {
  2776                                                   start:  {
  2777                                                       x:  data.star t.x,
  2778                                                       y:  data.star t.y
  2779                                                   },
  2780                                                   end: {
  2781                                                       x:  mouseData .x,
  2782                                                       y:  mouseData .y
  2783                                                   },
  2784                                                   measur eType: "li ne"
  2785                                               };
  2786                                               var firstD istance =  getLength( tempData);
  2787  
  2788                                               var tempDa ta2 = {
  2789                                                   start:  {
  2790                                                       x:  mouseData .x,
  2791                                                       y:  mouseData .y
  2792                                                   },
  2793                                                   end: {
  2794                                                       x:  data.end. x,
  2795                                                       y:  data.end. y
  2796                                                   },
  2797                                                   measur eType: "li ne"
  2798                                               };
  2799  
  2800                                               var second Distance =  getLength (tempData2 );
  2801  
  2802                                               var totalD istance =  parseInt(f irstDistan ce) + pars eInt(secon dDistance) ;
  2803                                               if (Math.a bs(totalDi stance - o riginalLin eDistance)  < 5) {
  2804                                                   dataTo Delete.mea surmentTyp e = "Trace ";
  2805                                                   dataTo Delete.key  = measure mentKey;
  2806                                                   dataTo Delete.arr yIndex = n ;
  2807                                                   dataTo Delete.isE ditable =  data.isEdi table;
  2808                                                   dataTo Delete.ses sionType =  data.sess ionType;
  2809                                                   active ImageRende rer = imag eRenderer;
  2810                                                   return ;
  2811                                               }
  2812                                          }
  2813                                      }
  2814                                 }
  2815                             }
  2816                         }
  2817                    }
  2818              //  }
  2819           // }
  2820  
  2821           if  (activeIm ageRendere r === unde fined && i sLineDelet eCheck ===  false) {
  2822                findLine ToDelete(m ouseData,  imageRende rer)
  2823           }  else if (a ctiveImage Renderer = == undefin ed && isPo intDeleteC heck === f alse) {
  2824                findPoin tToDelete( mouseData,  imageRend erer)
  2825           }  else if (a ctiveImage Renderer = == undefin ed && isVo lumeDelete Check ===  false) {
  2826                findVolu meToDelete (mouseData , imageRen derer)
  2827           }  else if (a ctiveImage Renderer = == undefin ed && isMi tralGradin eDelete == = false) {
  2828                findMitr alToDelete (mouseData , imageRen derer)
  2829           }  else if (a ctiveImage Renderer = == undefin ed && isAn gleDeleteC heck === f alse) {
  2830                findAngl eToDelete( mouseData,  imageRend erer)
  2831           }  else if (a ctiveImage Renderer = == undefin ed && isEl lipseDelet eCheck ===  false) {
  2832                findElli pseToDelet e(mouseDat a, imageRe nderer)
  2833           }  else if (a ctiveImage Renderer = == undefin ed && isRe ctangleDel eteCheck = == false)  {
  2834                findRect angleToDel ete(mouseD ata, image Renderer)
  2835           }  else if (a ctiveImage Renderer = == undefin ed) {
  2836                dataToDe lete = {
  2837                    meas urmentType : "",
  2838                    key:  "",
  2839                    arry Index: "",
  2840                    isEd itable: "" ,
  2841                    sess ionType: 0
  2842                };
  2843           }
  2844       }
  2845  
  2846       functi on findVol umeToDelet e(mouseDat a, imageRe nderer) {
  2847           is VolumeDele teCheck =  true;
  2848           ac tiveImageR enderer =  undefined;
  2849           re moveTempda ta();
  2850           va r measurem entKey = i mageRender er.anUIDs. replace("* ","_");
  2851           // loop: for  (var i in  dicomImage VolumeMeas urements)  {
  2852              //  if (di comImageVo lumeMeasur ements.has OwnPropert y(i)) {
  2853                    var  volumeMeas urements =  dicomImag eVolumeMea surements[ measuremen tKey];
  2854                    if ( volumeMeas urements ! == undefin ed) {
  2855                         for (var n  = 0; n <  volumeMeas urements.l ength; n++ ) {
  2856                             var me asurements  = volumeM easurement s[n];
  2857                             if (me asurements  !== undef ined) {
  2858                                 fo r (var m =  0; m < me asurements .length; m ++) {
  2859                                      var data  = measure ments[m];
  2860                                      if (data  !== undef ined && da ta.measure Type == "v olume") {
  2861                                          var  originalLi neDistance  = getLeng th(data);
  2862  
  2863                                          var  tempData =  {
  2864                                               start: {
  2865                                                   x: dat a.start.x,
  2866                                                   y: dat a.start.y
  2867                                               },
  2868                                               end: {
  2869                                                   x: mou seData.x,
  2870                                                   y: mou seData.y
  2871                                               },
  2872                                               measureTyp e: "line"
  2873                                          };
  2874                                          var  firstDista nce = getL ength(temp Data);
  2875  
  2876                                          var  tempData2  = {
  2877                                               start: {
  2878                                                   x: mou seData.x,
  2879                                                   y: mou seData.y
  2880                                               },
  2881                                               end: {
  2882                                                   x: dat a.end.x,
  2883                                                   y: dat a.end.y
  2884                                               },
  2885                                               measureTyp e: "line"
  2886                                          };
  2887  
  2888                                          var  secondDist ance = get Length(tem pData2);
  2889  
  2890                                          var  totalDista nce = pars eInt(first Distance)  + parseInt (secondDis tance);
  2891                                          if ( Math.abs(t otalDistan ce - origi nalLineDis tance) < 5  || (origi nalLineDis tance < 5  && origina lLineDista nce > 0))  {
  2892                                               dataToDele te.measurm entType =  "volume";
  2893                                               dataToDele te.key = m easurement Key;
  2894                                               dataToDele te.arryInd ex = n;
  2895                                               dataToDele te.isEdita ble = data .isEditabl e;
  2896                                               dataToDele te.session Type = dat a.sessionT ype;
  2897                                               activeImag eRenderer  = imageRen derer;
  2898                                               return;
  2899  
  2900                                          }
  2901                                      }
  2902                                 }
  2903                             }
  2904                         }
  2905                    }
  2906               // }
  2907          //  }
  2908           if  (activeIm ageRendere r === unde fined && i sLineDelet eCheck ===  false) {
  2909                findLine ToDelete(m ouseData,  imageRende rer)
  2910           }  else if (a ctiveImage Renderer = == undefin ed && isPo intDeleteC heck === f alse) {
  2911                findPoin tToDelete( mouseData,  imageRend erer)
  2912           }  else if (a ctiveImage Renderer = == undefin ed && isTr aceDeleteC heck === f alse) {
  2913                findTrac eToDelete( mouseData,  imageRend erer)
  2914           }  else if (a ctiveImage Renderer = == undefin ed && isMi tralGradin eDelete == = false) {
  2915                findMitr alToDelete (mouseData , imageRen derer)
  2916           }  else if (a ctiveImage Renderer = == undefin ed && isAn gleDeleteC heck === f alse) {
  2917                findAngl eToDelete( mouseData,  imageRend erer)
  2918           }  else if (a ctiveImage Renderer = == undefin ed && isEl lipseDelet eCheck ===  false) {
  2919                findElli pseToDelet e(mouseDat a, imageRe nderer)
  2920           }  else if (a ctiveImage Renderer = == undefin ed && isRe ctangleDel eteCheck = == false)  {
  2921                findRect angleToDel ete(mouseD ata, image Renderer)
  2922           }  else if (a ctiveImage Renderer = == undefin ed) {
  2923                dataToDe lete = {
  2924                    meas urmentType : "",
  2925                    key:  "",
  2926                    arry Index: "",
  2927                    isEd itable: "" ,
  2928                    sess ionType: 0
  2929                };
  2930           }
  2931       }
  2932  
  2933       functi on findMit ralToDelet e(mouseDat a, imageRe nderer){
  2934           is MitralGrad ineDelete  = true;
  2935           ac tiveImageR enderer =  undefined;
  2936           re moveTempda ta();
  2937           va r measurem entKey = i mageRender er.anUIDs. replace("* ","_");
  2938           // loop: for  (var i in  dicomImage VolumeMeas urements)  {
  2939              //  if (di comImageVo lumeMeasur ements.has OwnPropert y(i)) {
  2940                    var  volumeMeas urements =  dicomImag eMitralGra dientMeasu rements[me asurementK ey];
  2941                    if ( volumeMeas urements ! == undefin ed) {
  2942                         for (var n  = 0; n <  volumeMeas urements.l ength; n++ ) {
  2943                             var me asurements  = volumeM easurement s[n];
  2944                             if (me asurements  !== undef ined) {
  2945                                 fo r (var m =  0; m < me asurements .length; m ++) {
  2946                                      var data  = measure ments[m];
  2947                                      if (data  !== undef ined && da ta.measure Type == "m itralGradi ent") {
  2948                                          var  originalLi neDistance  = getLeng th(data);
  2949  
  2950                                          var  tempData =  {
  2951                                               start: {
  2952                                                   x: dat a.start.x,
  2953                                                   y: dat a.start.y
  2954                                               },
  2955                                               end: {
  2956                                                   x: mou seData.x,
  2957                                                   y: mou seData.y
  2958                                               },
  2959                                               measureTyp e: "mitral Gradient"
  2960                                          };
  2961                                          var  firstDista nce = getL ength(temp Data);
  2962  
  2963                                          var  tempData2  = {
  2964                                               start: {
  2965                                                   x: mou seData.x,
  2966                                                   y: mou seData.y
  2967                                               },
  2968                                               end: {
  2969                                                   x: dat a.end.x,
  2970                                                   y: dat a.end.y
  2971                                               },
  2972                                               measureTyp e: "mitral Gradient"
  2973                                          };
  2974  
  2975                                          var  secondDist ance = get Length(tem pData2);
  2976  
  2977                                          var  totalDista nce = pars eInt(first Distance)  + parseInt (secondDis tance);
  2978                                          if ( Math.abs(t otalDistan ce - origi nalLineDis tance) < 5 ) {
  2979                                               dataToDele te.measurm entType =  "mitralGra dient";
  2980                                               dataToDele te.key = m easurement Key;
  2981                                               dataToDele te.arryInd ex = n;
  2982                                               dataToDele te.isEdita ble = data .isEditabl e;
  2983                                               dataToDele te.session Type = dat a.sessionT ype;
  2984                                               activeImag eRenderer  = imageRen derer;
  2985                                               return;
  2986  
  2987                                          }
  2988                                      }
  2989                                 }
  2990                             }
  2991                         }
  2992                    }
  2993               // }
  2994          //  }
  2995           if  (activeIm ageRendere r === unde fined && i sLineDelet eCheck ===  false) {
  2996                findLine ToDelete(m ouseData,  imageRende rer)
  2997           }  else if (a ctiveImage Renderer = == undefin ed && isPo intDeleteC heck === f alse) {
  2998                findPoin tToDelete( mouseData,  imageRend erer)
  2999           }  else if (a ctiveImage Renderer = == undefin ed && isTr aceDeleteC heck === f alse) {
  3000                findTrac eToDelete( mouseData,  imageRend erer)
  3001           }  else if (a ctiveImage Renderer = == undefin ed && isVo lumeDelete Check ===  false) {
  3002                findVolu meToDelete (mouseData , imageRen derer)
  3003           }  else if (a ctiveImage Renderer = == undefin ed && isAn gleDeleteC heck === f alse) {
  3004                findAngl eToDelete( mouseData,  imageRend erer)
  3005           }  else if (a ctiveImage Renderer = == undefin ed && isEl lipseDelet eCheck ===  false) {
  3006                findElli pseToDelet e(mouseDat a, imageRe nderer)
  3007           }  else if (a ctiveImage Renderer = == undefin ed && isRe ctangleDel eteCheck = == false)  {
  3008                findRect angleToDel ete(mouseD ata, image Renderer)
  3009           }  else if (a ctiveImage Renderer = == undefin ed) {
  3010                dataToDe lete = {
  3011                    meas urmentType : "",
  3012                    key:  "",
  3013                    arry Index: "",
  3014                    isEd itable: "" ,
  3015                    sess ionType: 0
  3016                };
  3017           }
  3018       }
  3019  
  3020       functi on deleteS electedMea surment()  {
  3021           if  (activeIm ageRendere r != undef ined) {
  3022                var key  = dataToDe lete.key;
  3023                var arra yIndex = d ataToDelet e.arryInde x;                      
  3024                var meas urementTyp e = dataTo Delete.mea surmentTyp e;
  3025                if(measu rementType  === "mitr alGradient ") {
  3026                    dele te dicomIm ageMitralG radientMea surements[ key][array Index];
  3027                }
  3028                else if  (measureme ntType ===  "Trace")  {
  3029                    dele te dicomIm ageTraceMe asurements [key][arra yIndex];
  3030                } else i f (measure mentType = == "volume ") {
  3031                    dele te dicomIm ageVolumeM easurement s[key][arr ayIndex];
  3032                } else i f (measure mentType = == "line"  || measure mentType = == "point" ) {
  3033                                      delete d icomImageM easurement s[key][arr ayIndex];
  3034                } else i f (measure mentType = == "angle" ) {
  3035                                      delete d icomImageA ngleMeasur ements[key ][arrayInd ex];
  3036                } else i f (measure mentType = == "ellips e") {
  3037                                      delete d icomImageE llipseMeas urements[k ey][arrayI ndex];
  3038                } else i f (measure mentType = == "rectan gle") {
  3039                    dele te dicomIm ageRectang leMeasurem ents[key][ arrayIndex ];
  3040                } else i f (measure mentType = == "pen")  {
  3041                    dele te dicomIm agePenMeas urements[k ey][arrayI ndex];
  3042                }
  3043  
  3044                updateDi rtyPState( activeImag eRenderer. seriesLeve lDivId, da taToDelete , true);
  3045                             dataTo Edit = und efined;
  3046                setDataT oDelete();
  3047                activeIm ageRendere r.renderIm age(false) ;
  3048                activeIm ageRendere r = undefi ned;
  3049           }
  3050       }
  3051  
  3052       functi on updateM easurement TextData(d ataToedit,  text) {
  3053           va r measurem ent = dico mImageRect angleMeasu rements[da taToedit.k ey];
  3054           if  (measurem ent === un defined) {
  3055                return;
  3056           }
  3057           di comImageRe ctangleMea surements[ dataToedit .key][data Toedit.arr yIndex].me asurementT ext = text ;
  3058       }
  3059  
  3060       functi on findLin eToDelete( mouseData,  imageRend erer) {
  3061           va r flagFor2 dLengthCal ibration =  dicomView er.tools.g etFlagFor2 dLengthCal ibration() ;
  3062           is LineDelete Check = tr ue;
  3063           ac tiveImageR enderer =  undefined;
  3064           re moveTempda ta();
  3065           va r measurem entKey = i mageRender er.anUIDs. replace("* ", "_");
  3066        //    loop: for  (var i in  dicomImage Measuremen ts) {
  3067           //     if (di comImageMe asurements .hasOwnPro perty(i))  {
  3068                    var  measuremen ts = dicom ImageMeasu rements[me asurementK ey];
  3069                    if ( measuremen ts !== und efined) {
  3070                         for (var m  = 0; m <  measuremen ts.length;  m++) {
  3071                             var da ta = measu rements[m] ;
  3072                             if (da ta !== und efined &&  data.measu reType ==  "line") {
  3073                                 va r original LineDistan ce = getLe ngth(data) ;
  3074  
  3075                                 va r tempData  = {
  3076                                      start: {
  3077                                          x: d ata.start. x,
  3078                                          y: d ata.start. y
  3079                                      },
  3080                                      end: {
  3081                                          x: m ouseData.x ,
  3082                                          y: m ouseData.y
  3083                                      },
  3084                                      measureT ype: "line "
  3085                                 };
  3086                                 va r firstDis tance = ge tLength(te mpData);
  3087  
  3088                                 va r tempData 2 = {
  3089                                      start: {
  3090                                          x: m ouseData.x ,
  3091                                          y: m ouseData.y
  3092                                      },
  3093                                      end: {
  3094                                          x: d ata.end.x,
  3095                                          y: d ata.end.y
  3096                                      },
  3097                                      measureT ype: "line "
  3098                                 };
  3099  
  3100                                 va r secondDi stance = g etLength(t empData2);
  3101  
  3102                                 va r totalDis tance = pa rseInt(fir stDistance ) + parseI nt(secondD istance);
  3103                                 if  (Math.abs (totalDist ance - ori ginalLineD istance) <  5 /*|| or iginalLine Distance <  5*/ ) {
  3104                                      //delete  dicomImag eMeasureme nts[i][m];
  3105                                      dataToDe lete.measu rmentType  = "line";
  3106                                      dataToDe lete.key =  measureme ntKey;
  3107                                      dataToDe lete.arryI ndex = m;
  3108                                      dataToDe lete.isEdi table = da ta.isEdita ble;
  3109                                      dataToDe lete.sessi onType = d ata.sessio nType;
  3110                                      activeIm ageRendere r = imageR enderer;
  3111                                      return;
  3112                                 }
  3113                             }
  3114                         }
  3115                    }
  3116                    if(f lagFor2dLe ngthCalibr ation) {
  3117                         dataToDele te.measurm entType =  "line";
  3118                         dataToDele te.key = m easurement Key;
  3119                         dataToDele te.arryInd ex = m;
  3120                         activeImag eRenderer  = imageRen derer;
  3121                         setDataToD elete();
  3122                         return;
  3123                    }
  3124               // }
  3125           // }
  3126           if  (activeIm ageRendere r === unde fined && i sPointDele teCheck == = false) {
  3127                findPoin tToDelete( mouseData,  imageRend erer);
  3128           }  else if (a ctiveImage Renderer = == undefin ed && isTr aceDeleteC heck === f alse) {
  3129                findTrac eToDelete( mouseData,  imageRend erer);
  3130           }  else if (a ctiveImage Renderer = == undefin ed && isVo lumeDelete Check ===  false) {
  3131                findVolu meToDelete (mouseData , imageRen derer);
  3132           }  else if (a ctiveImage Renderer = == undefin ed && isMi tralGradin eDelete == = false) {
  3133                findMitr alToDelete (mouseData , imageRen derer)
  3134           }  else if (a ctiveImage Renderer = == undefin ed && isEl lipseDelet eCheck ===  false) {
  3135                findElli pseToDelet e(mouseDat a, imageRe nderer)
  3136           }  else if (a ctiveImage Renderer = == undefin ed && isRe ctangleDel eteCheck = == false)  {
  3137                findRect angleToDel ete(mouseD ata, image Renderer)
  3138           }  else if (a ctiveImage Renderer = == undefin ed) {
  3139                dataToDe lete = {
  3140                    meas urmentType : "",
  3141                    key:  "",
  3142                    arry Index: "",
  3143                    isEd itable: "" ,
  3144                    sess ionType: 0
  3145                };
  3146           }
  3147       }
  3148  
  3149       functi on findPoi ntToDelete (mouseData , imageRen derer) {
  3150           is PointDelet eCheck = t rue;
  3151           ac tiveImageR enderer =  undefined;
  3152           re moveTempda ta();
  3153           va r measurem entKey = i mageRender er.anUIDs. replace("* ","_");
  3154          //  loop: for  (var i in  dicomImage Measuremen ts) {
  3155         //       if (di comImageMe asurements .hasOwnPro perty(i))  {
  3156                    var  measuremen ts = dicom ImageMeasu rements[me asurementK ey];
  3157                    if ( measuremen ts !== und efined) {
  3158                         for (var m  = 0; m <  measuremen ts.length;  m++) {
  3159                             var da ta = measu rements[m] ;
  3160                             if (da ta !== und efined &&  data.measu reType ==  "point") {
  3161                                 if  (Math.abs (data.end. x - mouseD ata.x) < 5  && Math.a bs(data.en d.y - mous eData.y) <  5) {
  3162                                      dataToDe lete.measu rmentType  = "point";
  3163                                      dataToDe lete.key =  measureme ntKey;
  3164                                      dataToDe lete.arryI ndex = m;
  3165                                      dataToDe lete.isEdi table = da ta.isEdita ble;
  3166                                      dataToDe lete.sessi onType = d ata.sessio nType;
  3167                                      activeIm ageRendere r = imageR enderer;
  3168                                      return;
  3169                                 }
  3170                             }
  3171                         }
  3172                    }
  3173       //         }
  3174       //     }
  3175          if  (activeIma geRenderer  === undef ined && is LineDelete Check ===  false) {
  3176                findLine ToDelete(m ouseData,  imageRende rer)
  3177           }  else if (a ctiveImage Renderer = == undefin ed && isTr aceDeleteC heck === f alse) {
  3178                findTrac eToDelete( mouseData,  imageRend erer)
  3179           }  else if (a ctiveImage Renderer = == undefin ed && isLi neDeleteCh eck === fa lse) {
  3180                findVolu meToDelete (mouseData , imageRen derer)
  3181           }  else if (a ctiveImage Renderer = == undefin ed && isMi tralGradin eDelete == = false) {
  3182                findMitr alToDelete (mouseData , imageRen derer)
  3183           }  else if (a ctiveImage Renderer = == undefin ed && isAn gleDeleteC heck === f alse) {
  3184                findAngl eToDelete( mouseData,  imageRend erer)
  3185           }  else if (a ctiveImage Renderer = == undefin ed && isEl lipseDelet eCheck ===  false) {
  3186                findElli pseToDelet e(mouseDat a, imageRe nderer)
  3187           }  else if (a ctiveImage Renderer = == undefin ed && isRe ctangleDel eteCheck = == false)  {
  3188                findRect angleToDel ete(mouseD ata, image Renderer)
  3189           }  else if (a ctiveImage Renderer = == undefin ed) {
  3190                dataToDe lete = {
  3191                    meas urmentType : "",
  3192                    key:  "",
  3193                    arry Index: "",
  3194                    isEd itable: "" ,
  3195                    sess ionType: 0
  3196                };
  3197           }
  3198       }
  3199  
  3200       functi on findEll ipseToDele te(mouseDa ta, imageR enderer) {
  3201           is EllipseDel eteCheck =  true;
  3202           ac tiveImageR enderer =  undefined;
  3203           re moveTempda ta();
  3204           va r measurem entKey = i mageRender er.anUIDs. replace("* ", "_");
  3205        //    loop: for  (var i in  dicomImage Measuremen ts) {
  3206           //     if (di comImageMe asurements .hasOwnPro perty(i))  {
  3207                    var  measuremen ts = dicom ImageEllip seMeasurem ents[measu rementKey] ;
  3208                    if ( measuremen ts !== und efined) {
  3209                         for (var m  = 0; m <  measuremen ts.length;  m++) {
  3210                             var da ta = measu rements[m] ;
  3211                             if (da ta !== und efined &&  data.measu reType ==  "ellipse")  {
  3212                                 va r original LineDistan ce = getLe ngth(data) ;
  3213  
  3214                                 va r tempData 1 = {
  3215                                      start: {
  3216                                          x: d ata.start. x,
  3217                                          y: d ata.start. y
  3218                                      },
  3219                                      end: {
  3220                                          x: m ouseData.x ,
  3221                                          y: m ouseData.y
  3222                                      },
  3223                                      measureT ype: "elli pse"
  3224                                 };
  3225                                 va r firstDis tance = ge tLength(te mpData1);
  3226  
  3227                                 va r tempData 2 = {
  3228                                      start: {
  3229                                          x: m ouseData.x ,
  3230                                          y: m ouseData.y
  3231                                      },
  3232                                      end: {
  3233                                          x: d ata.end.x,
  3234                                          y: d ata.end.y
  3235                                      },
  3236                                      measureT ype: "elli pse"
  3237                                 };
  3238  
  3239                                 va r secondDi stance = g etLength(t empData2);
  3240  
  3241                                 va r totalDis tance = pa rseInt(fir stDistance ) + parseI nt(secondD istance);
  3242                                 va r isEditab le = false ;
  3243                                 if  (Math.abs (totalDist ance - ori ginalLineD istance) <  15) {
  3244                                      isEditab le = true;
  3245                                 }  else if (d ata.third  !== undefi ned && dat a.third != = null) {
  3246                                      var temp Data = {
  3247                                          star t: {
  3248                                               x: data.th ird.x,
  3249                                               y: data.th ird.y
  3250                                          },
  3251                                          end:  {
  3252                                               x: data.fo urth.x,
  3253                                               y: data.fo urth.y
  3254                                          },
  3255                                          meas ureType: " ellipse"
  3256                                      };
  3257                                      var seco ndLineDist ance = get Length(tem pData);
  3258  
  3259                                      var temp Data3 = {
  3260                                          star t: {
  3261                                               x: data.th ird.x,
  3262                                               y: data.th ird.y
  3263                                          },
  3264                                          end:  {
  3265                                               x: mouseDa ta.x,
  3266                                               y: mouseDa ta.y
  3267                                          },
  3268                                          meas ureType: " ellipse"
  3269                                      };
  3270                                      var thir dDistance  = getLengt h(tempData 3);
  3271  
  3272                                      var temp Data4 = {
  3273                                          star t: {
  3274                                               x: mouseDa ta.x,
  3275                                               y: mouseDa ta.y
  3276                                          },
  3277                                          end:  {
  3278                                               x: data.fo urth.x,
  3279                                               y: data.fo urth.y
  3280                                          },
  3281                                          meas ureType: " ellipse"
  3282                                      };
  3283  
  3284                                      var four thDistance  = getLeng th(tempDat a4);
  3285  
  3286                                      totalDis tance = pa rseInt(thi rdDistance ) + parseI nt(fourthD istance);
  3287                                      if (Math .abs(total Distance -  secondLin eDistance)  < 15) {
  3288                                          isEd itable = t rue;
  3289                                      }
  3290                                 }
  3291  
  3292                                 if  (isEditab le) {
  3293                                      //delete  dicomImag eMeasureme nts[i][m];
  3294                                      dataToDe lete.measu rmentType  = "ellipse ";
  3295                                      dataToDe lete.key =  measureme ntKey;
  3296                                      dataToDe lete.arryI ndex = m;
  3297                                      dataToDe lete.isEdi table = da ta.isEdita ble;
  3298                                      dataToDe lete.sessi onType = d ata.sessio nType;
  3299                                      activeIm ageRendere r = imageR enderer;
  3300                                      return;
  3301                                 }
  3302                             }
  3303                         }
  3304                    }
  3305               // }
  3306           // }
  3307           if  (activeIm ageRendere r === unde fined && i sPointDele teCheck == = false) {
  3308                findPoin tToDelete( mouseData,  imageRend erer);
  3309           }  else if (a ctiveImage Renderer = == undefin ed && isTr aceDeleteC heck === f alse) {
  3310                findTrac eToDelete( mouseData,  imageRend erer);
  3311           }  else if (a ctiveImage Renderer = == undefin ed && isVo lumeDelete Check ===  false) {
  3312                findVolu meToDelete (mouseData , imageRen derer);
  3313           }  else if (a ctiveImage Renderer = == undefin ed && isMi tralGradin eDelete == = false) {
  3314                findMitr alToDelete (mouseData , imageRen derer)
  3315           }  else if (a ctiveImage Renderer = == undefin ed && isLi neDeleteCh eck === fa lse) {
  3316                findLine ToDelete(m ouseData,  imageRende rer)
  3317           }  else if (a ctiveImage Renderer = == undefin ed && isEl lipseDelet eCheck ===  false) {
  3318                findElli pseToDelet e(mouseDat a, imageRe nderer)
  3319           }  else if (a ctiveImage Renderer = == undefin ed && isRe ctangleDel eteCheck = == false)  {
  3320                findRect angleToDel ete(mouseD ata, image Renderer)
  3321           }  else if (a ctiveImage Renderer = == undefin ed) {
  3322                dataToDe lete = {
  3323                    meas urmentType : "",
  3324                    key:  "",
  3325                    arry Index: "",
  3326                    isEd itable: "" ,
  3327                    sess ionType: 0
  3328                };
  3329           }
  3330       }
  3331  
  3332       functi on findRec tangleToDe lete(mouse Data, imag eRenderer)  {
  3333           is RectangleD eleteCheck  = true;
  3334           ac tiveImageR enderer =  undefined;
  3335           re moveTempda ta();
  3336           va r measurem entKey = i mageRender er.anUIDs. replace("* ", "_");
  3337        //    loop: for  (var i in  dicomImage Measuremen ts) {
  3338           //     if (di comImageMe asurements .hasOwnPro perty(i))  {
  3339                    var  measuremen ts = dicom ImageRecta ngleMeasur ements[mea surementKe y];
  3340                    if ( measuremen ts !== und efined) {
  3341                         for (var m  = 0; m <  measuremen ts.length;  m++) {
  3342                             var da ta = measu rements[m] ;
  3343                             if (da ta !== und efined &&  data.measu reType ==  "rectangle ") {
  3344                                 va r original LineDistan ce = getLe ngth(data) ;
  3345  
  3346                                 va r tempData  = {
  3347                                      start: {
  3348                                          x: d ata.start. x,
  3349                                          y: d ata.start. y
  3350                                      },
  3351                                      end: {
  3352                                          x: m ouseData.x ,
  3353                                          y: m ouseData.y
  3354                                      },
  3355                                      measureT ype: "rect angle"
  3356                                 };
  3357                                 va r firstDis tance = ge tLength(te mpData);
  3358  
  3359                                 va r tempData 2 = {
  3360                                      start: {
  3361                                          x: m ouseData.x ,
  3362                                          y: m ouseData.y
  3363                                      },
  3364                                      end: {
  3365                                          x: d ata.end.x,
  3366                                          y: d ata.end.y
  3367                                      },
  3368                                      measureT ype: "rect angle"
  3369                                 };
  3370  
  3371                                 va r secondDi stance = g etLength(t empData2);
  3372                                 
  3373                                 va r tempData 3 = {
  3374                                      start: {
  3375                                          x: d ata.start. x,
  3376                                          y: d ata.end.y
  3377                                      },
  3378                                      end: {
  3379                                          x: m ouseData.x ,
  3380                                          y: m ouseData.y
  3381                                      },
  3382                                      measureT ype: "rect angle"
  3383                                 };
  3384  
  3385                                 va r thirdDis tance = ge tLength(te mpData3);
  3386                                 
  3387                                 va r tempData 4 = {
  3388                                      start: {
  3389                                          x: m ouseData.x ,
  3390                                          y: m ouseData.y
  3391                                      },
  3392                                      end: {
  3393                                          x: d ata.end.x,
  3394                                          y: d ata.start. y
  3395                                      },
  3396                                      measureT ype: "rect angle"
  3397                                 };
  3398  
  3399                                 va r fourthDi stance = g etLength(t empData4);
  3400  
  3401                                 va r totalDis tance = pa rseInt(fir stDistance ) + parseI nt(secondD istance);
  3402                                 va r totalDis tance1 = p arseInt(th irdDistanc e) + parse Int(fourth Distance);
  3403                                 if  (Math.abs (totalDist ance - ori ginalLineD istance) <  15 || Mat h.abs(tota lDistance1  - origina lLineDista nce) < 15)  {
  3404                                      //delete  dicomImag eMeasureme nts[i][m];
  3405                                      dataToDe lete.measu rmentType  = "rectang le";
  3406                                      dataToDe lete.key =  measureme ntKey;
  3407                                      dataToDe lete.arryI ndex = m;
  3408                                      dataToDe lete.isEdi table = da ta.isEdita ble;
  3409                                      dataToDe lete.sessi onType = d ata.sessio nType;
  3410                                      activeIm ageRendere r = imageR enderer;
  3411                                      return;
  3412                                 }
  3413                             }
  3414                         }
  3415                    }
  3416               // }
  3417           // }
  3418           if  (activeIm ageRendere r === unde fined && i sPointDele teCheck == = false) {
  3419                findPoin tToDelete( mouseData,  imageRend erer);
  3420           }  else if (a ctiveImage Renderer = == undefin ed && isTr aceDeleteC heck === f alse) {
  3421                findTrac eToDelete( mouseData,  imageRend erer);
  3422           }  else if (a ctiveImage Renderer = == undefin ed && isVo lumeDelete Check ===  false) {
  3423                findVolu meToDelete (mouseData , imageRen derer);
  3424           }  else if (a ctiveImage Renderer = == undefin ed && isMi tralGradin eDelete == = false) {
  3425                findMitr alToDelete (mouseData , imageRen derer)
  3426           }  else if (a ctiveImage Renderer = == undefin ed && isLi neDeleteCh eck === fa lse) {
  3427                findLine ToDelete(m ouseData,  imageRende rer)
  3428           }  else if (a ctiveImage Renderer = == undefin ed && isEl lipseDelet eCheck ===  false) {
  3429                findElli pseToDelet e(mouseDat a, imageRe nderer)
  3430           }  else if (a ctiveImage Renderer = == undefin ed && isRe ctangleDel eteCheck = == false)  {
  3431                findRect angleToDel ete(mouseD ata, image Renderer)
  3432           }  else if (a ctiveImage Renderer = == undefin ed) {
  3433                dataToDe lete = {
  3434                    meas urmentType : "",
  3435                    key:  "",
  3436                    arry Index: "",
  3437                    isEd itable: "" ,
  3438                    sess ionType: 0
  3439                };
  3440           }
  3441       }
  3442       
  3443       functi on PointIn Rect(x, y)  {
  3444           re turn this. x <= x &&  x <= this. x + this.w idth &&
  3445                   this. y <= y &&  y <= this. y + this.h eight;
  3446       }
  3447  
  3448       functi on findAng leToDelete (mouseData , imageRen derer) {
  3449           is AngleDelet eCheck = t rue;
  3450           ac tiveImageR enderer =  undefined;
  3451           re moveTempda ta();
  3452           va r measurem entKey = i mageRender er.anUIDs. replace("* ","_");
  3453           va r tarceMea surements  = dicomIma geAngleMea surements[ measuremen tKey];
  3454           if  (tarceMea surements  !== undefi ned) {
  3455                for (var  n = 0; n  < tarceMea surements. length; n+ +) {
  3456                    if ( activeImag eRenderer  === undefi ned) {
  3457                         var measur ements = t arceMeasur ements[n];
  3458                         if (measur ements !==  undefined ) {
  3459                             for (v ar m = 0;  m < measur ements.len gth; m++)  {
  3460                                 va r data = m easurement s[m];
  3461                                 if  (data !==  undefined  && data.m easureType  == "angle ") {
  3462                                      var orig inalLineDi stance = g etLength(d ata);
  3463  
  3464                                      var temp Data = {
  3465                                          star t: {
  3466                                               x: data.st art.x,
  3467                                               y: data.st art.y
  3468                                          },
  3469                                          end:  {
  3470                                               x: mouseDa ta.x,
  3471                                               y: mouseDa ta.y
  3472                                          },
  3473                                          meas ureType: " line"
  3474                                      };
  3475                                      var firs tDistance  = getLengt h(tempData );
  3476  
  3477                                      var temp Data2 = {
  3478                                          star t: {
  3479                                               x: mouseDa ta.x,
  3480                                               y: mouseDa ta.y
  3481                                          },
  3482                                          end:  {
  3483                                               x: data.en d.x,
  3484                                               y: data.en d.y
  3485                                          },
  3486                                          meas ureType: " line"
  3487                                      };
  3488  
  3489                                      var seco ndDistance  = getLeng th(tempDat a2);
  3490  
  3491                                      var tota lDistance  = parseInt (firstDist ance) + pa rseInt(sec ondDistanc e);
  3492                                      if (Math .abs(total Distance -  originalL ineDistanc e) < 5) {
  3493                                          data ToDelete.m easurmentT ype = "ang le";
  3494                                          data ToDelete.k ey = measu rementKey;
  3495                                          data ToDelete.a rryIndex =  n;
  3496                                          data ToDelete.i sEditable  = data.isE ditable;
  3497                                          data ToDelete.s essionType  = data.se ssionType;
  3498                                          acti veImageRen derer = im ageRendere r;
  3499                                          retu rn;
  3500                                      }
  3501                                 }
  3502                             }
  3503                         }
  3504                    }
  3505                }
  3506           }
  3507           if  (activeIm ageRendere r === unde fined && i sPointDele teCheck == = false) {
  3508                findPoin tToDelete( mouseData,  imageRend erer);
  3509           }  else if (a ctiveImage Renderer = == undefin ed && isTr aceDeleteC heck === f alse) {
  3510                findTrac eToDelete( mouseData,  imageRend erer);
  3511           }  else if (a ctiveImage Renderer = == undefin ed && isVo lumeDelete Check ===  false) {
  3512                findVolu meToDelete (mouseData , imageRen derer);
  3513           }  else if (a ctiveImage Renderer = == undefin ed && isMi tralGradin eDelete == = false) {
  3514                findMitr alToDelete (mouseData , imageRen derer)
  3515           }  else if (a ctiveImage Renderer = == undefin ed && isLi neDeleteCh eck === fa lse) {
  3516                findLine ToDelete(m ouseData,  imageRende rer)
  3517           }  else if (a ctiveImage Renderer = == undefin ed && isEl lipseDelet eCheck ===  false) {
  3518                findElli pseToDelet e(mouseDat a, imageRe nderer)
  3519           }  else if (a ctiveImage Renderer = == undefin ed && isRe ctangleDel eteCheck = == false)  {
  3520                findRect angleToDel ete(mouseD ata, image Renderer)
  3521           }  else if (a ctiveImage Renderer = == undefin ed) {
  3522                dataToDe lete = {
  3523                    meas urmentType : "",
  3524                    key:  "",
  3525                    arry Index: "",
  3526                    isEd itable: "" ,
  3527                    sess ionType: 0
  3528                };
  3529           }
  3530       }
  3531  
  3532       functi on resetMe asurementF lag() {
  3533           is LineDelete Check = fa lse;
  3534           is PointDelet eCheck = f alse;
  3535           is AngleDelet eCheck = f alse;
  3536           is EllipseDel eteCheck =  false;
  3537           is RectangleD eleteCheck  = false;
  3538           is TraceDelet eCheck = f alse;
  3539           is VolumeDele teCheck =  false;
  3540           is MitralGrad ineDelete  = false;
  3541           is PenToolEnd  = false;
  3542       }
  3543  
  3544       functi on findNea rHandle(mo useData, i mageRender er, contex t) {
  3545           va r imageDat a = dicomV iewer.meas urement.dr aw.getImag eCoordinat esForMouse Point(mous eData, ima geRenderer , context) ;
  3546           va r i;
  3547           va r data = u ndefined;
  3548           lo op: for (i  in dicomI mageMeasur ements) {
  3549                if (dico mImageMeas urements.h asOwnPrope rty(i)) {
  3550                    var  measuremen ts = dicom ImageMeasu rements[i] ;
  3551                    if ( measuremen ts !== und efined) {
  3552                         for (var m  = 0; m <  measuremen ts.length;  m++) {
  3553                             data =  measureme nts[m];
  3554                             if (da ta !== und efined) {
  3555                                 va r isNearTo StartPoint  = findNea rHanleByPo int(imageD ata, data. start);
  3556                                 va r isNearTo EndPoint =  findNearH anleByPoin t(imageDat a, data.en d);
  3557                                 if  (isNearTo StartPoint ) {
  3558                                      data.sta rt.handleA ctive = tr ue;
  3559                                      measurem ents.splic e(m, 1);
  3560                                      break lo op;
  3561                                 }  else if (i sNearToEnd Point) {
  3562                                      data.end .handleAct ive = true ;
  3563                                      measurem ents.splic e(m, 1);
  3564                                      break lo op;
  3565                                 }  else {
  3566                                      data = u ndefined;
  3567                                 }
  3568                             }
  3569                         }
  3570                    }
  3571                }
  3572           }
  3573           if  (data !==  undefined ) {
  3574                return g etMouseDat aForImageD ata(data,  imageRende rer, conte xt);
  3575           }
  3576           re turn undef ined;
  3577       }
  3578  
  3579  
  3580       functi on findNea rHandleToE dit(mouseD ata, image Renderer,  context, d ataToEdit)  {
  3581           va r imageDat a = dicomV iewer.meas urement.dr aw.getImag eCoordinat esForMouse Point(mous eData, ima geRenderer , context) ;
  3582           va r i;
  3583           va r data = u ndefined;
  3584           va r key = da taToEdit.k ey;
  3585           va r arrayInd ex = dataT oEdit.arry Index;
  3586                    var  parentDiv  = $('#'+im ageRendere r.parentEl ement).par ent().clos est('div') .attr('id' );
  3587           va r measurem ents = dic omImageMea surements[ key];
  3588                    if(m easurement s === unde fined)
  3589                             return ;
  3590                    meas urements =  measureme nts[arrayI ndex];
  3591           da ta = dicom ImageMeasu rements[ke y][arrayIn dex];
  3592           if  (data !==  undefined ) {
  3593                var isNe arToStartP oint = fin dNearHanle ByPoint(im ageData, d ata.start) ;
  3594                var isNe arToEndPoi nt = findN earHanleBy Point(imag eData, dat a.end);
  3595                if (isNe arToStartP oint) {
  3596                    data .start.han dleActive  = true;
  3597                    data .start.x =  imageData .x;
  3598                    data .start.y =  imageData .y;
  3599                } else i f (isNearT oEndPoint)  {
  3600                    data .end.handl eActive =  true;
  3601                    data .end.x = i mageData.x ;
  3602                    data .end.y = i mageData.y ;
  3603                } else {
  3604                    data  = undefin ed;
  3605                }
  3606  
  3607           }
  3608           if  (data !==  undefined ) {
  3609                return g etMouseDat aForImageD ata(data,  imageRende rer, conte xt);
  3610           }
  3611           re turn undef ined;
  3612       }
  3613  
  3614       functi on updateV olumeintoA rray(mouse Data, imag eRenderer,  context,  dataToEdit ) {
  3615           va r imageDat a = dicomV iewer.meas urement.dr aw.getImag eCoordinat esForMouse Point(mous eData, ima geRenderer , context) ;
  3616           va r i;
  3617           va r data = u ndefined;
  3618           va r key = da taToEdit.k ey;
  3619           va r arrayInd ex = dataT oEdit.arry Index;
  3620                    var  parentDiv  = $('#'+im ageRendere r.parentEl ement).par ent().clos est('div') .attr('id' );
  3621           va r measurem ents = dic omImageVol umeMeasure ments[key] ;
  3622  
  3623                    if(m easurement s === unde fined)
  3624                             return ;
  3625                    meas urements =  measureme nts[arrayI ndex];
  3626           da ta = dicom ImageVolum eMeasureme nts[key][a rrayIndex] ;
  3627           fo r (var ind ex = 0; in dex < data .length; i ndex++) {
  3628               var tempD ata = data [index];
  3629                if (temp Data !== u ndefined)  {
  3630                    var  isNearToSt artPoint =  findNearH anleByPoin t(imageDat a, tempDat a.start);
  3631                    var  isNearToEn dPoint = f indNearHan leByPoint( imageData,  tempData. end);
  3632                    if ( (data.leng th -1) ===  index) {
  3633                         if (isNear ToEndPoint ) {
  3634                             tempDa ta.start.x  = imageDa ta.x;
  3635                             tempDa ta.start.y  = imageDa ta.y;
  3636                             tempDa ta.end.x =  imageData .x;
  3637                             tempDa ta.end.y =  imageData .y;
  3638                         }
  3639                    } el se {
  3640                         if (isNear ToStartPoi nt) {
  3641                             tempDa ta.start.x  = imageDa ta.x;
  3642                             tempDa ta.start.y  = imageDa ta.y;
  3643                         } else if  (isNearToE ndPoint) {
  3644                             tempDa ta.end.x =  imageData .x;
  3645                             tempDa ta.end.y =  imageData .y;
  3646                         }
  3647                    }
  3648                }
  3649           }
  3650       }
  3651       
  3652           fu nction upd ateTraceIn toArray(mo useData, i mageRender er, contex t, dataToE dit) {
  3653           va r imageDat a = dicomV iewer.meas urement.dr aw.getImag eCoordinat esForMouse Point(mous eData, ima geRenderer , context) ;
  3654           va r i;
  3655           va r data = u ndefined;
  3656           va r key = da taToEdit.k ey;
  3657           va r arrayInd ex = dataT oEdit.arry Index;
  3658                    var  parentDiv  = $('#'+im ageRendere r.parentEl ement).par ent().clos est('div') .attr('id' );
  3659           va r measurem ents = dic omImageTra ceMeasurem ents[key];
  3660  
  3661                    if(m easurement s === unde fined)
  3662                             return ;
  3663           up dateDirtyP State(imag eRenderer. seriesLeve lDivId, da taToEdit);
  3664                    meas urements =  measureme nts[arrayI ndex];
  3665           da ta = dicom ImageTrace Measuremen ts[key][ar rayIndex];
  3666           fo r (var ind ex = index ToEditMitr al; index  < data.len gth; index ++) {
  3667               var tempD ata = data [index];
  3668                if (temp Data !== u ndefined)  {
  3669                    var  isNearToSt artPoint =  findNearH anleByPoin t(imageDat a, tempDat a.start);
  3670                    if ( isNearToSt artPoint & & index ==  0) {
  3671                         tempData.s tart.x = i mageData.x ;
  3672                         tempData.s tart.y = i mageData.y ;
  3673                         indexToEdi tMitral =  index;
  3674                         index = da ta.length;
  3675                    } el se if (isN earToStart Point && i ndex == da ta.length  - 1){
  3676                         tempData.s tart.x = i mageData.x ;
  3677                         tempData.s tart.y = i mageData.y ;
  3678                         tempData.e nd.x = ima geData.x;
  3679                         tempData.e nd.y = ima geData.y;
  3680                         data[index  - 1].end. x = imageD ata.x;
  3681                         data[index  - 1].end. y = imageD ata.y;
  3682                         dicomImage TraceMeasu rements[ke y][arrayIn dex] = dat a;
  3683                         indexToEdi tMitral =  index;
  3684                         index = da ta.length;
  3685                    } el se if (isN earToStart Point){
  3686                         tempData.s tart.x = i mageData.x ;
  3687                         tempData.s tart.y = i mageData.y ;
  3688                         data[index  - 1].end. x = imageD ata.x;
  3689                         data[index  - 1].end. y = imageD ata.y;
  3690                         dicomImage TraceMeasu rements[ke y][arrayIn dex] = dat a;
  3691                         indexToEdi tMitral =  index;
  3692                         index = da ta.length;
  3693                    }
  3694                }
  3695                tempData .editMode  = true;
  3696           }
  3697       }
  3698       
  3699       functi on updateA ngleIntoAr ray(mouseD ata, image Renderer,  context, d ataToEdit)  {
  3700           va r imageDat a = dicomV iewer.meas urement.dr aw.getImag eCoordinat esForMouse Point(mous eData, ima geRenderer , context) ;
  3701           va r i;
  3702           va r data = u ndefined;
  3703           va r key = da taToEdit.k ey;
  3704           va r arrayInd ex = dataT oEdit.arry Index;
  3705           va r measurem ents = dic omImageAng leMeasurem ents[key];
  3706  
  3707                    if(m easurement s === unde fined)
  3708                             return ;
  3709  
  3710           up dateDirtyP State(imag eRenderer. seriesLeve lDivId, da taToEdit);
  3711                    meas urements =  measureme nts[arrayI ndex];
  3712           da ta = dicom ImageAngle Measuremen ts[key][ar rayIndex];
  3713           fo r (var ind ex = 0; in dex < data .length; i ndex++) {
  3714               var tempD ata = data [index];
  3715                if (temp Data !== u ndefined)  {
  3716                    var  isNearToSt artPoint =  findNearH anleByPoin t(imageDat a, tempDat a.start);
  3717                    var  isNearToEn dPoint = f indNearHan leByPoint( imageData,  tempData. end);
  3718                    if ( isNearToEn dPoint) {
  3719                         tempData.e nd.x = ima geData.x;
  3720                         tempData.e nd.y = ima geData.y;
  3721                    }els e if(isNea rToStartPo int){
  3722                         tempData.s tart.x = i mageData.x ;
  3723                         tempData.s tart.y = i mageData.y ;
  3724                    }
  3725                    temp Data.editM ode = true ;
  3726                }
  3727           }
  3728       }
  3729       
  3730           fu nction upd ateMitralM eanGradien tintoArray (mouseData , imageRen derer, con text, data ToEdit) {
  3731           va r imageDat a = dicomV iewer.meas urement.dr aw.getImag eCoordinat esForMouse Point(mous eData, ima geRenderer , context) ;
  3732           va r i;
  3733           va r data = u ndefined;
  3734           va r key = da taToEdit.k ey;
  3735           va r arrayInd ex = dataT oEdit.arry Index;
  3736                    var  parentDiv  = $('#'+im ageRendere r.parentEl ement).par ent().clos est('div') .attr('id' );
  3737           va r measurem ents = dic omImageMit ralGradien tMeasureme nts[key];
  3738  
  3739                    if(m easurement s === unde fined)
  3740                             return ;
  3741  
  3742           up dateDirtyP State(imag eRenderer. seriesLeve lDivId, da taToEdit);
  3743                    meas urements =  measureme nts[arrayI ndex];
  3744           da ta = dicom ImageMitra lGradientM easurement s[key][arr ayIndex];
  3745           fo r (var ind ex = index ToEditMitr al; index  < data.len gth; index ++) {
  3746               var tempD ata = data [index];
  3747                if (temp Data !== u ndefined)  {
  3748                    var  isNearToSt artPoint =  findNearH anleByPoin t(imageDat a, tempDat a.start);
  3749                    if ( isNearToSt artPoint & & index ==  0) {
  3750                         tempData.s tart.x = i mageData.x ;
  3751                         tempData.s tart.y = i mageData.y ;
  3752                         indexToEdi tMitral =  index;
  3753                         index = da ta.length;
  3754                    } el se if (isN earToStart Point && i ndex == da ta.length  - 1 && tem pData.meas urementSub Type == "m itral"){
  3755                         tempData.s tart.x = i mageData.x ;
  3756                         tempData.s tart.y = i mageData.y ;
  3757                         tempData.e nd.x = ima geData.x;
  3758                         tempData.e nd.y = ima geData.y;
  3759                         data[index  - 1].end. x = imageD ata.x;
  3760                         data[index  - 1].end. y = imageD ata.y;
  3761                         dicomImage MitralGrad ientMeasur ements[key ][arrayInd ex] = data ;
  3762                         indexToEdi tMitral =  index;
  3763                         index = da ta.length;
  3764                    } el se if (isN earToStart Point){
  3765                         tempData.s tart.x = i mageData.x ;
  3766                         tempData.s tart.y = i mageData.y ;
  3767                         data[index  - 1].end. x = imageD ata.x;
  3768                         data[index  - 1].end. y = imageD ata.y;
  3769                         dicomImage MitralGrad ientMeasur ements[key ][arrayInd ex] = data ;
  3770                         indexToEdi tMitral =  index;
  3771                         index = da ta.length;
  3772                    }
  3773                }
  3774                tempData .editMode  = true;
  3775           }
  3776       }
  3777           
  3778       functi on findNea rHanleByPo int(mouseD ata, point ) {
  3779           if  (point.x  - 10 <= mo useData.x  &&
  3780                point.x  + 10 >= mo useData.x  &&
  3781                point.y  - 10 <= mo useData.y  &&
  3782                point.y  + 10 >= mo useData.y)  {
  3783                return t rue;
  3784           }
  3785           re turn false ;
  3786       }   
  3787       
  3788  
  3789       functi on getMous eDataForIm ageData(im ageData, i mageRender er, contex t) {
  3790           va r startPoi nt = dicom Viewer.mea surement.d raw.getMou sePointFor ImageCoord inates(ima geData.sta rt, imageR enderer, c ontext);
  3791           va r endPoint  = dicomVi ewer.measu rement.dra w.getMouse PointForIm ageCoordin ates(image Data.end,  imageRende rer, conte xt);
  3792           va r mouseDat a = {};
  3793           mo useData.st art = star tPoint;
  3794           mo useData.en d = endPoi nt;
  3795           mo useData.me asureType  = imageDat a.measureT ype;
  3796           mo useData.me asurementT ext = imag eData.meas urementTex t;
  3797           re turn mouse Data;
  3798       }
  3799  
  3800  
  3801       functi on removeA llMeasurem ents(image Uid, frame Index, ren derer) {
  3802           if  (imageUid  === undef ined || fr ameIndex = == undefin ed) {
  3803                throw "E rror in im ageUid or  FrameIndex ";
  3804           }                 
  3805           de lete dicom ImageMeasu rements[im ageUid + " _" + frame Index];
  3806           de lete dicom ImageTrace Measuremen ts[imageUi d + "_" +  frameIndex ];
  3807           de lete dicom ImageVolum eMeasureme nts[imageU id + "_" +  frameInde x];
  3808           de lete dicom ImageMitra lGradientM easurement s[imageUid  + "_" + f rameIndex] ;
  3809           de lete dicom ImageAngle Measuremen ts[imageUi d + "_" +  frameIndex ];
  3810           de lete dicom ImageEllip seMeasurem ents[image Uid + "_"  + frameInd ex];
  3811           de lete dicom ImageRecta ngleMeasur ements[ima geUid + "_ " + frameI ndex];
  3812           de lete dicom ImagePenMe asurements [imageUid  + "_" + fr ameIndex];
  3813                    setD ataToEdit( undefined) ;
  3814  
  3815           if (renderer  !== undefi ned && ren derer !==  null) {
  3816                updateDi rtyPState( renderer.s eriesLevel DivId, { k ey: imageU id + "_" +  frameInde x }, true) ;
  3817           }
  3818       }
  3819  
  3820       var im ageContext s = {};
  3821  
  3822       functi on setImag eContext(i mageUid, f rameIndex,  context)  {
  3823           im ageContext s[imageUid  + "_" + f rameIndex]  = context ;
  3824       }
  3825  
  3826       functi on getImag eContext(i mageUid, f rameIndex)  {
  3827           re turn image Contexts[i mageUid +  "_" + fram eIndex];
  3828       }
  3829  
  3830       functi on setData ToEdit(dat a, isPrope rty) {
  3831           if  (activeIm ageRendere r != undef ined && da ta === "ed it") {
  3832                dataToEd it = dataT oDelete;
  3833                var auid s = dataTo Edit.key.s plit("_");
  3834                             var se reiesId =  $('#'+acti veImageRen derer.pare ntElement) .parent(). closest('d iv').attr( 'id');
  3835                if(isFul lScreenEna bled){
  3836                    sere iesId = pr eviousLayo utSelectio n;
  3837                }
  3838                var meas urementDat a;
  3839                if (data ToEdit.mea surmentTyp e === "vol ume") {
  3840                    meas urementDat a = getVol umeMeasure ments(auid s[0], auid s[1], sere iesId)[dat aToEdit.ar ryIndex];
  3841                    dico mViewer.me asurement. setTempDat a(measurem entData);
  3842                    meas urementDat a.measureT ype = "vol umeedit";
  3843                    dico mViewer.me asurement. setTempDat a(measurem entData);
  3844                } else i f (dataToE dit.measur mentType = == "mitral Gradient")  {
  3845                    meas urementDat a = getMit ralGradien tMeasureme nts(auids[ 0], auids[ 1], sereie sId)[dataT oEdit.arry Index];
  3846                    dico mViewer.me asurement. setTempDat a(measurem entData[0] );
  3847                }else if  (dataToEd it.measurm entType == = "Trace")  {
  3848                    meas urementDat a = getTra ceMeasurem ents(auids [0], auids [1], serei esId)[data ToEdit.arr yIndex];
  3849                    dico mViewer.me asurement. setTempDat a(measurem entData[0] );
  3850                }else if  (dataToEd it.measurm entType == = "angle")  {
  3851                    meas urementDat a = getAng leMeasurem ents(auids [0], auids [1], serei esId)[data ToEdit.arr yIndex];
  3852                    dico mViewer.me asurement. setTempDat a(measurem entData[0] );
  3853                }else if  (dataToEd it.measurm entType == = "ellipse ") {
  3854                    meas urementDat a = getEll ipseMeasur ements(aui ds[0], aui ds[1], ser eiesId)[da taToEdit.a rryIndex];
  3855                    dico mViewer.me asurement. setTempDat a(measurem entData);
  3856                } else i f (dataToE dit.measur mentType = == "rectan gle") {
  3857                    meas urementDat a = getRec tangleMeas urements(a uids[0], a uids[1], s ereiesId)[ dataToEdit .arryIndex ];
  3858                    dico mViewer.me asurement. setTempDat a(measurem entData);
  3859                }else if  (dataToEd it.measurm entType == = "pen") {
  3860                    meas urementDat a = getPen Measuremen ts(auids[0 ], auids[1 ], sereies Id)[dataTo Edit.arryI ndex];
  3861                    dico mViewer.me asurement. setTempDat a(measurem entData);
  3862                } else {
  3863                    meas urementDat a = getMea surements( auids[0],  auids[1],  sereiesId) [dataToEdi t.arryInde x];
  3864                    meas urementDat a.end.hand leActive =  true;
  3865                    meas urementDat a.start.ha ndleActive  = true;
  3866                }
  3867                setTool( measuremen tData);
  3868                activeIm ageRendere r.renderIm age(false) ;
  3869                isMeasur ementEdit  = true;
  3870  
  3871                if (isPr operty) {
  3872                    var  tool = dic omViewer.m ouseTools. getActiveT ool();
  3873                    if(t ool && !to ol.activeI mageRender er) {
  3874                         tool.activ eImageRend erer = act iveImageRe nderer;
  3875                    }
  3876  
  3877                    retu rn measure mentData.l ength > 0  ? measurem entData[0]  : measure mentData;
  3878                }
  3879           }
  3880           if  (data ===  undefined ) {
  3881                //editin g done
  3882                isMeasur ementEdit  = false;
  3883                dataToEd it = data;
  3884           }
  3885       }
  3886  
  3887       /**
  3888        * Upd ate measur ement styl e of selec ted annota tion
  3889        * @pa ram {Type}   
  3890        */ 
  3891       functi on udpateM easurement Property(m easurement Style) {
  3892           if  (dataToEd it != unde fined && m easurement Style != u ndefined)  {
  3893                var auid s = dataTo Edit.key.s plit("_");
  3894                var sere iesId = $( '#'+active ImageRende rer.parent Element).p arent().cl osest('div ').attr('i d');
  3895                if(isFul lScreenEna bled){
  3896                    sere iesId = pr eviousLayo utSelectio n;
  3897                }
  3898                var meas urementDat a;
  3899                if (data ToEdit.mea surmentTyp e === "vol ume") {
  3900                    meas urementDat a = getVol umeMeasure ments(auid s[0], auid s[1], sere iesId)[dat aToEdit.ar ryIndex];
  3901                    meas urementDat a.style =  measuremen tStyle;
  3902                    meas urementDat a.measureT ype = "vol umeedit";
  3903                    dico mViewer.me asurement. setTempDat a(measurem entData);
  3904                } else i f (dataToE dit.measur mentType = == "mitral Gradient")  {
  3905                    meas urementDat a = getMit ralGradien tMeasureme nts(auids[ 0], auids[ 1], sereie sId)[dataT oEdit.arry Index];
  3906                    if ( measuremen tData.leng th > 0) {
  3907                         $.each(mea surementDa ta, functi on(key, va lue){
  3908                             value. style = me asurementS tyle;
  3909                         });
  3910                    }
  3911                    dico mViewer.me asurement. setTempDat a(measurem entData[0] );
  3912                }else if  (dataToEd it.measurm entType == = "Trace")  {
  3913                    meas urementDat a = getTra ceMeasurem ents(auids [0], auids [1], serei esId)[data ToEdit.arr yIndex];
  3914                    if ( measuremen tData.leng th > 0) {
  3915                         $.each(mea surementDa ta, functi on(key, va lue){
  3916                             value. style = me asurementS tyle;
  3917                         });
  3918                    }
  3919                    dico mViewer.me asurement. setTempDat a(measurem entData[0] );
  3920                }else if  (dataToEd it.measurm entType == = "angle")  {
  3921                    meas urementDat a = getAng leMeasurem ents(auids [0], auids [1], serei esId)[data ToEdit.arr yIndex];
  3922                    if ( measuremen tData.leng th > 0) {
  3923                         $.each(mea surementDa ta, functi on(key, va lue){
  3924                             value. style = me asurementS tyle;
  3925                         });
  3926                    }
  3927                    dico mViewer.me asurement. setTempDat a(measurem entData[0] );
  3928                }else if  (dataToEd it.measurm entType == = "ellipse ") {
  3929                    meas urementDat a = getEll ipseMeasur ements(aui ds[0], aui ds[1], ser eiesId)[da taToEdit.a rryIndex];
  3930                    meas urementDat a.style =  measuremen tStyle;
  3931                    dico mViewer.me asurement. setTempDat a(measurem entData);
  3932                } else i f (dataToE dit.measur mentType = == "rectan gle") {
  3933                    meas urementDat a = getRec tangleMeas urements(a uids[0], a uids[1], s ereiesId)[ dataToEdit .arryIndex ];
  3934                    meas urementDat a.style =  measuremen tStyle;
  3935                    dico mViewer.me asurement. setTempDat a(measurem entData);
  3936                }else if  (dataToEd it.measurm entType == = "pen") {
  3937                    meas urementDat a = getPen Measuremen ts(auids[0 ], auids[1 ], sereies Id)[dataTo Edit.arryI ndex];
  3938                    meas urementDat a.style =  measuremen tStyle;
  3939                    dico mViewer.me asurement. setTempDat a(measurem entData);
  3940                } else {
  3941                    meas urementDat a = getMea surements( auids[0],  auids[1],  sereiesId) [dataToEdi t.arryInde x];
  3942                    meas urementDat a.style =  measuremen tStyle;
  3943                    meas urementDat a.end.hand leActive =  false;
  3944                    meas urementDat a.start.ha ndleActive  = false;
  3945                }
  3946                setTool( measuremen tData);
  3947                activeIm ageRendere r.renderIm age(false) ;
  3948                isMeasur ementEdit  = true;
  3949           }
  3950           va r tool = d icomViewer .mouseTool s.getActiv eTool();
  3951           if  (tool.Too lType == " angleMeasu rement") {
  3952                dicomVie wer.measur ement.setT empData(un defined);
  3953           }
  3954           to ol.hanleDo ubleClick( );
  3955       }
  3956  
  3957       /**
  3958        * Set  the image  tool whil e editing  the select ed shape
  3959        * @pa ram {Type}  measureme nt - type  of the ann otation/me asurement  data
  3960        */ 
  3961       functi on setTool (measureme nt) {
  3962           di comViewer. mouseTools .setPrevio usTool(dic omViewer.m ouseTools. getActiveT ool());
  3963           di comViewer. mouseTools .setCursor (dicomView er.mouseTo ols.getToo lCursor(1) );
  3964           if (measureme nt.measure Type == "l ine") {
  3965                LineMeas urement.pr ototype.se tMeasureme ntSubType( );
  3966                if(measu rement.mea surementSu bType == " 2DLength")  {
  3967                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DLengthMea sureTool() );
  3968                    Line Measuremen t.prototyp e.setMeasu rementSubT ype(measur ement.meas urementSub Type);
  3969                } else i f (measure ment.measu rementSubT ype == "2D Line") {
  3970                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DLengthMea sureTool(4 ));
  3971                    Line Measuremen t.prototyp e.setMeasu rementSubT ype(measur ement.meas urementSub Type);
  3972                } else i f(measurem ent.measur ementSubTy pe == "Arr ow") {
  3973                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DLengthMea sureTool(5 ));
  3974                    Line Measuremen t.prototyp e.setMeasu rementSubT ype(measur ement.meas urementSub Type);
  3975                } else i f(measurem ent.measur ementId ==  "mitralRe gurgitatio nLength")  {
  3976                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DLengthMea sureTool(1 ));
  3977                    dico mViewer.me asurement. draw.setMe asurementT ype(0,'mit ralRegurgi tationLeng th','cm');
  3978                } else i f(measurem ent.measur ementId ==  "aorticRe gurgitatio nLength")  {
  3979                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DLengthMea sureTool(2 ));
  3980                    dico mViewer.me asurement. draw.setMe asurementT ype(1,'aor ticRegurgi tationPeak Velocity', 'm/s');
  3981                } else i f(measurem ent.measur ementId ==  "mitralVa lveAnterio rLeafletTh ickness")  {
  3982                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DLengthMea sureTool(3 ));
  3983                    dico mViewer.me asurement. draw.setMe asurementT ype(0,'mit ralValveAn teriorLeaf letThickne ss','mm');
  3984                }
  3985                return;
  3986           }
  3987           if (measureme nt.measure Type == "r ectangle")  {
  3988                if(measu rement.mea surementSu bType == " hounsfield ") {
  3989                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getR ectangleMe asureTool( ));
  3990                    Rect angleMeasu rement.pro totype.set Measuremen tSubType(" hounsfield ");
  3991                } else i f(measurem ent.measur ementSubTy pe == "rec tangle") {
  3992                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getR ectangleMe asureTool( 1));
  3993                    Rect angleMeasu rement.pro totype.set Measuremen tSubType(" rectangle" );
  3994                } else i f(measurem ent.measur ementSubTy pe == "tex t") {
  3995                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getR ectangleMe asureTool( 2));
  3996                    Rect angleMeasu rement.pro totype.set Measuremen tSubType(" text");
  3997                }
  3998                return;
  3999           }
  4000           if (measureme nt.measure Type == "e llipse") {
  4001                if(measu rement.mea surementSu bType == " hounsfield ") {
  4002                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getE llipseMeas ureTool()) ;
  4003                    Elli pseMeasure ment.proto type.setMe asurementS ubType("ho unsfield") ;
  4004                } else i f(measurem ent.measur ementSubTy pe == "ell ipse") {
  4005                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getE llipseMeas ureTool(1) );
  4006                    Elli pseMeasure ment.proto type.setMe asurementS ubType("el lipse");
  4007                }
  4008                return;
  4009           }
  4010           if (measureme nt.measure Type == "p oint") {
  4011                if(measu rement.mea surementId  == "mitra lRegurgita tionPeakVe locity") {
  4012                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DPointMeas ureTool(1) );
  4013                    dico mViewer.me asurement. draw.setMe asurementT ype(1,'mit ralRegurgi tationPeak Velocity', 'm/s');
  4014                } else i f(measurem ent.measur ementId ==  "aorticRe gurgitatio nPeakVeloc ity") {
  4015                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DPointMeas ureTool(2) );
  4016                    dico mViewer.me asurement. draw.setMe asurementT ype(1,'aor ticRegurgi tationPeak Velocity', 'm/s');
  4017                } else i f(measurem ent.measur ementId ==  "aorticSt enosisPeak Velocity")  {
  4018                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DPointMeas ureTool(3) );
  4019                    dico mViewer.me asurement. draw.setMe asurementT ype(1,'aor ticStenosi sPeakVeloc ity','m/s' );
  4020                } else {
  4021                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DPointMeas ureTool()) ;
  4022                    dico mViewer.me asurement. draw.setMe asurementT ype(1,null ,null);
  4023                }
  4024                return;
  4025           }
  4026           if ($.isArray (measureme nt) && mea surement.l ength > 0)  {
  4027                if(measu rement[0]. measureTyp e == "angl e") {
  4028                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getA ngleMeasur eTool());
  4029                } else i f(measurem ent[0].mea sureType = = "trace")  {
  4030                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getT raceMeasur eTool());
  4031                }
  4032                if(measu rement[0]. measureTyp e == "mitr alGradient ") {
  4033                    if(m easurement [0].measur ementSubTy pe == "mit ral") {
  4034                         dicomViewe r.mouseToo ls.setActi veTool(dic omViewer.m ouseTools. getMitralM eanGradien tMeasureTo ol());
  4035                    } el se if(meas urement[0] .measureme ntSubType  == "freeha nd") {
  4036                         dicomViewe r.mouseToo ls.setActi veTool(dic omViewer.m ouseTools. getMitralM eanGradien tMeasureTo ol(1));
  4037                    }
  4038                }
  4039           }
  4040       }
  4041  
  4042       functi on getData ToDelete()  {
  4043           re turn dataT oDelete;
  4044       }
  4045  
  4046       functi on getData ToEdit() {
  4047           re turn dataT oEdit;
  4048       }
  4049           
  4050           fu nction set DataToDele te()
  4051           {
  4052                    data ToDelete =  {
  4053                    meas urmentType : "",
  4054                    key:  "",
  4055                    arry Index: "",
  4056                    isEd itable: "" ,
  4057                    sess ionType: 0
  4058                };
  4059           }
  4060           
  4061           fu nction set Coordinate (coordinat e) {
  4062           th is.coordin ate = coor dinate;
  4063       }
  4064       
  4065       functi on getCoor dinate() {
  4066           re turn this. coordinate ;
  4067       }
  4068  
  4069       /**
  4070        * 
  4071        * set  the defau lt the uni t type  
  4072        */ 
  4073       functi on getDefa ultLineMea surementUn it() {
  4074           re turn this. lineMeasur ementUnit=  lineMeasu rementUnit ;
  4075       }
  4076  
  4077       /**
  4078        * 
  4079        * ver ify the im age uid ha ving pixel  spacing o r not
  4080        */ 
  4081       functi on isCalib ratePixelS pacing(ren der){
  4082           if (dicomView er.tools.i sCaliberEn abled(rend er)){
  4083                dicomVie wer.tools. setLengthC alibration Flag(true) ;
  4084                dicomVie wer.tools. setCalibra tionActive Tool();
  4085           }
  4086       }
  4087  
  4088       /**
  4089        * Sav e the stud y presenta tion state
  4090        * @pa ram {Type}  pStateDet ails - Spe cifies the  PState de tails
  4091        */ 
  4092       functi on savePSt ate(pState Details) {
  4093           tr y
  4094           {
  4095                if(pStat eDetails = == undefin ed) {
  4096                    // I nvalid inp ut paramet ers
  4097                    retu rn;
  4098                }
  4099  
  4100                // Check  whether t he present ation stat e is enabl ed or not
  4101                if(isPSt ateEnabled () !== tru e) {
  4102                    retu rn;
  4103                }
  4104  
  4105                var stud yUid = pSt ateDetails .studyUid;
  4106                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  4107                if(study Details == = undefine d || study Details == = undefine d) {
  4108                    // I nvalid stu dy details
  4109                    retu rn;
  4110                }
  4111                showAndH ideSplashW indow("sho w", "Savin g Presenta tion", pSt ateDetails .viewportI d);
  4112                var imag ePStates =  {};
  4113  
  4114                // Lengt h measurem ents
  4115                $.each(d icomImageM easurement s, functio n(key, val ues) {
  4116                    valu es.forEach (function( value) {
  4117                         if(!isSame Study(stud yUid, valu e.studyUid )) {
  4118                             return ;
  4119                         }
  4120  
  4121                         var measur ementType  = undefine d;
  4122                         if(value.m easureType  === "line ") {
  4123                             switch (value.mea surementSu bType) {
  4124                                 ca se "2DLeng th":
  4125                                      measurem entType =  MT_LENGTH;
  4126                                      break;
  4127  
  4128                                 ca se "2DLine ":
  4129                                      measurem entType =  MT_LINE;
  4130                                      break;
  4131  
  4132                                 ca se "Arrow" :
  4133                                      measurem entType =  MT_ARROW;
  4134                                      break;
  4135                             }
  4136  
  4137                             if(mea surementTy pe === und efined) {
  4138                                 if (value.mea surementId  !== undef ined && va lue.measur ementId != = null) {
  4139                                      measurem entType =  getUSMeasu rementType (value.mea surementId );
  4140                                 }
  4141                             }
  4142                         } else if( value.meas ureType == = "point")  {
  4143                             measur ementType  = MT_POINT ;
  4144                             if(val ue.measure mentId !==  undefined  && value. measuremen tId !== nu ll) {
  4145                                 me asurementT ype = getU SMeasureme ntType(val ue.measure mentId);
  4146                             }
  4147                         }
  4148  
  4149                         addImagePS tate(image PStates, k ey, value,  measureme ntType, st udyDetails );
  4150                    });
  4151                });
  4152  
  4153                // Angle  measureme nts
  4154                $.each(d icomImageA ngleMeasur ements, fu nction(key , values)  {
  4155                    valu es.forEach (function( value) {
  4156                         if(!isSame Study(stud yUid, valu e[0].study Uid)) {
  4157                             return ;
  4158                         }
  4159  
  4160                         addImagePS tate(image PStates, k ey, value,  MT_ANGLE,  studyDeta ils);
  4161                    });
  4162                });
  4163  
  4164                // Ellip se measure ments
  4165                $.each(d icomImageE llipseMeas urements,  function(k ey, values ) {
  4166                    valu es.forEach (function( value) {
  4167                         if(!isSame Study(stud yUid, valu e.studyUid )) {
  4168                             return ;
  4169                         }
  4170  
  4171                         var measur ementType  = undefine d;
  4172                         switch(val ue.measure mentSubTyp e) {
  4173                             case " hounsfield ":
  4174                                 me asurementT ype = MT_H OUNSFIELDE LLIPSE;
  4175                                 br eak;
  4176  
  4177                             case " ellipse":
  4178                                 me asurementT ype = MT_E LLIPSE;
  4179                                 br eak;
  4180                         }
  4181  
  4182                         addImagePS tate(image PStates, k ey, value,  measureme ntType, st udyDetails );
  4183                    });
  4184                });
  4185  
  4186                // Recta ngle measu rements
  4187                $.each(d icomImageR ectangleMe asurements , function (key, valu es) {
  4188                    valu es.forEach (function( value) {
  4189                         if(!isSame Study(stud yUid, valu e.studyUid )) {
  4190                             return ;
  4191                         }
  4192  
  4193                         var measur ementType  = undefine d;
  4194                         switch(val ue.measure mentSubTyp e) {
  4195                             case " hounsfield ":
  4196                                 me asurementT ype = MT_H OUNSFIELDR ECT;
  4197                                 br eak;
  4198  
  4199                             case " rectangle" :
  4200                                 me asurementT ype = MT_R ECT;
  4201                                 br eak;
  4202  
  4203                             case " text":
  4204                                 me asurementT ype = MT_T EXT;
  4205                                 br eak;
  4206                         }
  4207  
  4208                         addImagePS tate(image PStates, k ey, value,  measureme ntType, st udyDetails );
  4209                    });
  4210                });
  4211  
  4212                // Trace  measureme nts
  4213                $.each(d icomImageT raceMeasur ements, fu nction(key , values)  {
  4214                    valu es.forEach (function( value) {
  4215                         if(!isSame Study(stud yUid, valu e[0].study Uid)) {
  4216                             return ;
  4217                         }
  4218  
  4219                         addImagePS tate(image PStates, k ey, value,  MT_TRACE,  studyDeta ils);
  4220                    });
  4221                });
  4222  
  4223                // Mitra l gradient  measureme nts
  4224                $.each(d icomImageM itralGradi entMeasure ments, fun ction(key,  values) {
  4225                    valu es.forEach (function( value) {
  4226                         if(!isSame Study(stud yUid, valu e[0].study Uid)) {
  4227                             return ;
  4228                         }
  4229  
  4230                         var measur ementType  = MT_MG;
  4231                         switch(val ue[0].meas urementSub Type)
  4232                         {
  4233                             case " freehand":
  4234                                 me asurementT ype = MT_F REEHAND;
  4235                                 br eak;
  4236                         }
  4237  
  4238                         addImagePS tate(image PStates, k ey, value,  measureme ntType, st udyDetails );
  4239                    });
  4240                });
  4241  
  4242                // pen m easurement s
  4243                $.each(d icomImageP enMeasurem ents, func tion(key,  values) {
  4244                    valu es.forEach (function( value) {
  4245                         if(!isSame Study(stud yUid, valu e[0].study Uid)) {
  4246                             return ;
  4247                         }
  4248                         addImagePS tate(image PStates, k ey, value,  MT_PEN, s tudyDetail s);
  4249                    });
  4250                });
  4251  
  4252                // Save  the presen tation sta te
  4253                var stud yPState =  getStudyPS tate(image PStates, p StateDetai ls);
  4254                if(study PState ===  undefined  || studyP State ===  null) {
  4255                    // I nvalid PSt ate object s
  4256                    retu rn;
  4257                }
  4258  
  4259                // Send  the presen tation sta te to serv er
  4260                var cont extId = st udyDetails .modality  == "Genera l" ? study Details[0] .contextId  : studyDe tails.cont extId;
  4261                var pSta teUrl = di comViewer. url.getPSt ateUrl(con textId);
  4262                var pSta te = JSON. stringify( studyPStat e);
  4263                $.ajax({
  4264                    type : 'POST',
  4265                    cont entType: " applicatio n/json; ch arset=utf- 8",
  4266                    url:  pStateUrl ,
  4267                    asyn c: false,
  4268                    data : pState,
  4269                    cach e: false
  4270                })
  4271                .success (function( data) {
  4272                    var  descriptio n = "Succe ssfully sa ved the pr esentation  state for  the conte xt id: " +  decodeURI Component( studyDetai ls.context Id);
  4273                    send ViewerStat usMessage( "200", des cription);
  4274                    show AndHideSpl ashWindow( "success",  "Presenta tion state  saved suc cessfully" );
  4275  
  4276                    // R efresh PSt ates
  4277                    load PState(stu dyUid, und efined, tr ue);
  4278                    $("# saveAndLoa dPStateMen u_"+pState Details.vi ewportId)[ 0].style.d isplay="no ne";
  4279                })
  4280                .fail(fu nction(dat a) {
  4281                    var  descriptio n = "Faile d to save  the presen tation sta te for the  context i d: " + dec odeURIComp onent(stud yDetails.c ontextId);
  4282                    send ViewerStat usMessage( "500", des cription);
  4283                    show AndHideSpl ashWindow( "error", " Failed to  save the p resentatio n state");
  4284  
  4285                })
  4286                .error(f unction(xh r, status)  {
  4287                    var  descriptio n = xhr.st atusText +  "\nFailed  to save t he present ation stat e to serve r";
  4288                    send ViewerStat usMessage( xhr.status .toString( ), descrip tion);
  4289                    show AndHideSpl ashWindow( "error", " Failed to  save prese ntation st ate in ser ver");
  4290  
  4291                });
  4292           }
  4293           ca tch(e) {
  4294                showAndH ideSplashW indow("err or", "Fail ed to save  presentat ion state" );
  4295           }
  4296           se tTimeout(f unction(){ $("#saveAn dLoadPStat eMenu_"+pS tateDetail s.viewport Id)[0].sty le.display ="block";} ,1500)
  4297       }
  4298  
  4299       /**
  4300        * sho w and hide  the spala sh window
  4301        * @pa ram {Type}  messageTy pe - Type  of message
  4302        * @pa ram {Type}  message -  message c ontent
  4303        * @pa ram {Type}  studyView er - study  viewer vi ewportID
  4304        */ 
  4305       functi on showAnd HideSplash Window(mes sageType,  message, v iewportId)  {
  4306           tr y
  4307           {
  4308                if(messa geType ==  "show") {
  4309                    $("# splash-win dow").show ().center( viewportId );
  4310                    $("# splash-con tent")[0]. innerHTML= "<img src  = images/p resentaion Loader.gif >  "+messa ge+"";
  4311                    $("# splash-con tent").sho w();
  4312                    $("# saveAndLoa dPStateMen u_"+viewpo rtId)[0].s tyle.displ ay = "none ";
  4313                }
  4314                else if( messageTyp e == "succ ess") {
  4315                    setT imeout(fun ction(){$( "#splash-c ontent")[0 ].innerHTM L=""+messa ge+"";},10 00)
  4316                } else {
  4317                    setT imeout(fun ction(){$( "#splash-c ontent")[0 ].innerHTM L=""+messa ge+"";},10 00)
  4318                }
  4319           }c atch(e) 
  4320           {  }
  4321           se tTimeout(f unction(){ $("#splash -window"). fadeOut(10 00);}, 150 0)
  4322       }
  4323  
  4324       /**
  4325        * Loa d the stud y presenta tion
  4326        * @pa ram {Type}  studyUid  - Specifie s the stud yUid
  4327        * @pa ram {Type}  selectedP State - Sp ecifies th e selected  PState
  4328        * @pa ram {Type}  isRefresh MenuOnly -  Specifies  the flag  to refesh  the PState  menu
  4329        */ 
  4330       functi on loadPSt ate(studyU id, select edPState,  isRefreshM enuOnly, i sStatus, i sAsync) {
  4331           tr y {
  4332                var t0 =  Date.now( );
  4333                dumpCons oleLogs(LL _INFO, und efined, "l oadPState  ", "Start" , undefine d, true);
  4334  
  4335                if(study Uid === un defined) {
  4336                    // I nvalid inp ut paramet ers
  4337                    retu rn;
  4338                }
  4339  
  4340                // Check  whether t he present ation stat e is enabl ed or not
  4341                if(isPSt ateEnabled () !== tru e) {
  4342                    retu rn;
  4343                }
  4344  
  4345                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  4346                if(study Details == = undefine d || study Details == = undefine d) {
  4347                    // I nvalid stu dy details
  4348                    retu rn;
  4349                }
  4350  
  4351                var view portId = ( selectedPS tate == un defined) ?  undefined  : ((selec tedPState  == null) ?  undefined  : selecte dPState.sp lit("_"));
  4352                if(isRef reshMenuOn ly === und efined &&  viewportId !=undefine d && isSta tus !== fa lse) {
  4353                    show AndHideSpl ashWindow( "show", "A pplying Pr esentation ",viewport Id[1]);
  4354                }
  4355  
  4356                if (isAs ync === un defined) {
  4357                    isAs ync = fals e;
  4358                }
  4359  
  4360                var cont extId = st udyDetails .modality  == "Genera l" ? study Details[0] .contextId  : studyDe tails.cont extId;
  4361                var pSta teUrl = di comViewer. url.getPSt ateUrl(con textId);
  4362                $.ajax({
  4363                    url:  pStateUrl ,
  4364                    cach e: false,
  4365                    asyn c: isAsync
  4366                })
  4367                .done(fu nction(dat a) {
  4368                    if(d ata == und efined ||  data == nu ll || data .length ==  0) {
  4369                         if(isRefre shMenuOnly  == false)  {
  4370                             resetP State(stud yDetails);
  4371                         }
  4372  
  4373                         return;
  4374                    }
  4375  
  4376                    // P arse the J SON PState  string
  4377                    data .forEach(f unction(it em) {
  4378                         if(item.da ta !== und efined &&  item.data  !== null)  {
  4379                             item.p resentatio nStates =  JSON.parse (item.data );
  4380                             item.p resentatio nStates =  item.prese ntationSta tes.filter (function( o) {
  4381                                 if (getImageU rnFromUId( studyDetai ls, o.imag eId) != un defined) {
  4382                                      return t rue;
  4383                                 }
  4384  
  4385                                 re turn o.ima geUrn !==  undefined;
  4386                             });
  4387  
  4388                             item.i sOldPState  = (item.p resentatio nStates.le ngth == 0  ? true : f alse);
  4389                         }
  4390                    });
  4391  
  4392                    // F ilter the  new pstate  only
  4393                    data  = data.fi lter(funct ion(o) {re turn o.isO ldPState = = false;}) ;
  4394                    if(d ata.length  == 0) {
  4395                         resetPStat e(studyDet ails);
  4396                         return;
  4397                    }
  4398  
  4399                    var  userDUZ =  getUserDuz ();
  4400                    var  recentPSta te = undef ined;
  4401                    if(s electedPSt ate !== un defined) {
  4402                         // Get the  selected  presentati on state
  4403                         recentPSta te = data. filter(fun ction(o) { return o.i d === sele ctedPState .split("_" )[2];})[0] ;
  4404  
  4405                         // Check w hether the  pstate is  external
  4406                         if(recentP State ===  undefined)  {
  4407                             var ex istingPSta te = study Details.PS tates.All. filter(fun ction(o) { return o.i d === sele ctedPState .split("_" )[2];})[0] ;
  4408                             if(exi stingPStat e !== unde fined) {
  4409                                 re centPState  = data.fi lter(funct ion(o) {re turn o.con textId ===  existingP State.cont extId;})[0 ];
  4410                             }
  4411                         }
  4412  
  4413                         // Check w hether the  selected  PState is  other user  
  4414                         var isOthe rUser = (u serDUZ !==  parseInt( recentPSta te.userId) );
  4415                         if(isOther User) {
  4416                             recent PState.isE ditable =  false;
  4417                         }
  4418                    } el se {
  4419                         // Get the  recent pr esentation  state
  4420                         var userPS tates = da ta.filter( function(o ) { return  userDUZ = == parseIn t(o.userId ); });
  4421                         if(!userPS tates || u serPStates .length == = 0) {
  4422                             userPS tates = da ta.filter( function(o ) { return  userDUZ ! == parseIn t(o.userId ); });
  4423                         }
  4424  
  4425                         if(userPSt ates !== u ndefined & & userPSta tes !== nu ll) {
  4426                             var re centDate =  Math.max. apply(null , userPSta tes.map(fu nction(o)  {
  4427                                 if (!o.isExte rnal) {
  4428                                      return n ew Date(pa rseDate(o. dateTime)) ;
  4429                                 }  else {
  4430                                      return - 1;
  4431                                 }
  4432                             }));
  4433  
  4434                             // Che ck whether  the pstat e is exter nal
  4435                             var re centPState s = undefi ned;
  4436                             if(rec entDate == = -1) {
  4437                                 re centPState s = userPS tates.filt er(functio n (o) { re turn (o.is External = == true);  });
  4438                             } else  {
  4439                                 re centPState s = userPS tates.filt er(functio n (o) { if  (o.dateTi me === nul l) return  false; ret urn new Da te(parseDa te(o.dateT ime)).valu eOf() ===  recentDate ; });
  4440                             }
  4441  
  4442                             if (!r ecentPStat es || rece ntPStates. length ===  0) {
  4443                                 re centPState s = recent PStates;
  4444                             }
  4445  
  4446                             recent PState = r ecentPStat es[0];
  4447                             if(rec entPState  && userDUZ  == -1) {
  4448                                 re centPState .isEditabl e = false;
  4449                             }
  4450                         }
  4451                    }
  4452  
  4453                    // U pdate the  presentati on state
  4454                    upda tePState(r ecentPStat e, studyDe tails);
  4455                    refr eshPState( studyUid);
  4456  
  4457                    if(i sRefreshMe nuOnly ===  undefined  && isStat us !== fal se) {
  4458                         showAndHid eSplashWin dow("succe ss", "Appl ied Presen tation suc cessfully" );
  4459                    }
  4460  
  4461                    // U pdate the  study pres entations  states
  4462                    var  activePSta teId = (re centPState  !== undef ined ? rec entPState. id : undef ined);
  4463                    isRe freshMenuO nly = (isR efreshMenu Only == tr ue ? true  : (selecte dPState !=  undefined  ? true :  false));
  4464                    upda teStudyPSt ates(data,  studyDeta ils, activ ePStateId,  isRefresh MenuOnly);
  4465                    view portId !=  undefined  ? $("#save AndLoadPSt ateMenu_"+ viewportId [1])[0].st yle.displa y="none" :  "";
  4466                })
  4467                .fail(fu nction(dat a) {
  4468                    rese tPState(st udyDetails );
  4469  
  4470                    var  descriptio n = "Faile d to get t he present ation stat e for the  context id : " + deco deURICompo nent(study Details.co ntextId);
  4471                    send ViewerStat usMessage( "500", des cription);
  4472                    if(i sRefreshMe nuOnly ===  undefined ) {
  4473                         showAndHid eSplashWin dow("error ", "Failed  to Apply  Presentati on state") ;
  4474                    }
  4475                })
  4476                .error(f unction(xh r, status)  {
  4477                    rese tPState(st udyDetails );
  4478  
  4479                    var  descriptio n = xhr.st atusText +  "\nFailed  to get th e presenta tion state  from serv er";
  4480                    send ViewerStat usMessage( xhr.status .toString( ), descrip tion);
  4481                    if(i sRefreshMe nuOnly ===  undefined ) {
  4482                         showAndHid eSplashWin dow("error ", "Failed  to get pr esentation  state fro m server") ;
  4483                    }
  4484                });
  4485           }
  4486           ca tch(e)
  4487           {
  4488                dumpCons oleLogs(LL _ERROR, un defined, " loadPState ", e.messa ge, undefi ned, true)
  4489           }
  4490           fi nally {
  4491                (viewpor tId!=undef ined ) ? s etTimeout( function() {$("#saveA ndLoadPSta teMenu_"+v iewportId[ 1])[0].sty le.display ="block";} ,1500) : " ";
  4492                dumpCons oleLogs(LL _INFO, und efined, "l oadPState  ", "End",  (Date.now( ) - t0), t rue);
  4493           }
  4494       }
  4495  
  4496       /**
  4497        * To  convert gi ven date f ormat into  milliseco nds
  4498        * @pa ram {Type}  dateStrin
  4499        */ 
  4500       functi on parseDa te(dateStr ing){
  4501           va r time = D ate.parse( dateString );
  4502           if (!time){
  4503                if(!time ){
  4504                    boun d = dateSt ring.index Of(' ');
  4505                    var  dateData =  dateStrin g.slice(0,  bound).sp lit('-');
  4506                    var  timeData =  dateStrin g.slice(bo und+1, -1) .split(':' );
  4507  
  4508                    time  = Date.UT C(dateData [0],dateDa ta[1]-1,da teData[2], timeData[0 ],timeData [1],timeDa ta[2]);
  4509                }
  4510           }
  4511           re turn time;
  4512       }
  4513  
  4514       /**
  4515        * Loa d the leng th or poin t measurem ent
  4516        * @pa ram {Type}  imageKey  - Specifie s the imag e key
  4517        * @pa ram {Type}  measureme ntKey - Sp ecifies th e measurem ent key
  4518        * @pa ram {Type}  measureme nts - Spec ifies the  measuremen t array
  4519        * @pa ram {Type}  isEditabl e - Specif ies the fl ag to edit  the measu rement/ann otation
  4520        */ 
  4521       functi on loadLen gthOrPoint Measuremen t(imageKey , measurem entKey, me asurement,  isEditabl e) {
  4522           tr y
  4523           {
  4524                if(image Key === un defined ||  measureme ntKey ===  undefined  || measure ment === u ndefined)  {
  4525                    // I nvalid inp ut paramet ers
  4526                    retu rn;
  4527                }
  4528  
  4529                var poin ts = measu rement.poi nts;
  4530                if(point s === unde fined || p oints ===  null || po ints.lengt h == 0) {
  4531                    retu rn;
  4532                }
  4533  
  4534                var meas ureType =  undefined;
  4535                var meas urementSub Type = und efined;
  4536                var meas urementTyp e = -1;
  4537                var meas urementUni ts = undef ined;
  4538                var meas urementId  = undefine d;
  4539                switch(m easurement Key) {
  4540                    case  MT_LENGTH :
  4541                         measuremen tSubType =  "2DLength ";
  4542                         measuremen tType = 0;
  4543                         measuremen tUnits = " cm";
  4544                         measureTyp e = "line" ;
  4545                         break;
  4546  
  4547                    case  MT_LINE:
  4548                         measuremen tSubType =  "2DLine";
  4549                         measuremen tType = 9;
  4550                         measureTyp e = "line" ;
  4551                         break;
  4552  
  4553                    case  MT_ARROW:
  4554                         measuremen tSubType =  "Arrow";
  4555                         measuremen tType = 10 ;
  4556                         measureTyp e = "line" ;
  4557                         break;
  4558  
  4559                    case  MT_MVALT:
  4560                         measuremen tSubType =  "mitralVa lveAnterio rLeafletTh ickness";
  4561                         measuremen tId = meas urementSub Type;
  4562                         measuremen tType = 0;
  4563                         measuremen tUnits = " mm";
  4564                         measureTyp e = "line" ;
  4565                         break;
  4566  
  4567                    case  MT_MRL:
  4568                         measuremen tSubType =  "mitralRe gurgitatio nLength";
  4569                         measuremen tId = meas urementSub Type;
  4570                         measuremen tType = 0;
  4571                         measuremen tUnits = " cm";
  4572                         measureTyp e = "line" ;
  4573                         break;
  4574  
  4575                    case  MT_ARL:
  4576                         measuremen tSubType =  "aorticRe gurgitatio nLength";
  4577                         measuremen tId = meas urementSub Type;
  4578                         measuremen tType = 0;
  4579                         measuremen tUnits = " cm";
  4580                         measureTyp e = "line" ;
  4581                         break;
  4582  
  4583                    case  MT_POINT:
  4584                         measuremen tSubType =  "point";
  4585                         measuremen tType = 1;
  4586                         measureTyp e = "point ";
  4587                         break;
  4588  
  4589                    case  MT_MRPV:
  4590                         measuremen tSubType =  "mitralRe gurgitatio nPeakVeloc ity";
  4591                         measuremen tId = meas urementSub Type;
  4592                         measuremen tType = 1;
  4593                         measuremen tUnits = " m/s";
  4594                         measureTyp e = "point ";
  4595                         break;
  4596  
  4597                    case  MT_ARPV:
  4598                         measuremen tSubType =  "aorticRe gurgitatio nPeakVeloc ity";
  4599                         measuremen tId = meas urementSub Type;
  4600                         measuremen tType = 1;
  4601                         measuremen tUnits = " m/s";
  4602                         measureTyp e = "point ";
  4603                         break;
  4604  
  4605                    case  MT_ASPV:
  4606                         measuremen tSubType =  "aorticSt enosisPeak Velocity";
  4607                         measuremen tId = meas urementSub Type;
  4608                         measuremen tType = 1;
  4609                         measuremen tUnits = " m/s";
  4610                         measureTyp e = "point ";
  4611                         break;
  4612                }
  4613  
  4614                var meas urements =  dicomImag eMeasureme nts[imageK ey];
  4615                if (meas urements = == undefin ed) {
  4616                    meas urements =  [];
  4617                }
  4618  
  4619                var star t = {};
  4620                var end  = {};
  4621                for(var  index = 0;  index < p oints.leng th; index+ =4) {
  4622                    var  start = 
  4623                    {
  4624                         handleActi ve: false,
  4625                         x: parseFl oat(points [index]),
  4626                         y: parseFl oat(points [index+1])
  4627                    };
  4628  
  4629                    var  end =
  4630                    {
  4631                         handleActi ve: false,
  4632                         x: parseFl oat(points [index+2]) ,
  4633                         y: parseFl oat(points [index+3])
  4634                    };
  4635  
  4636                    var  measuremen tData =
  4637                    {
  4638                         start: sta rt,
  4639                         end: end,
  4640                         measureTyp e: measure Type,
  4641                         measuremen tSubType:  measuremen tSubType,
  4642                         measuremen tId: measu rementId,
  4643                         measuremen tComplete:  true,
  4644                         measuremen tType: mea surementTy pe,
  4645                         measuremen tUnits: me asurementU nits,
  4646                         studyUid:  measuremen t.studyUid ,
  4647                         isEditable : isEditab le,
  4648                         sessionTyp e: 1,
  4649                         calibratio nData: mea surement.c alibration Data,
  4650                         style : ge tGrpahicSt yle(measur ement, und efined, is Editable)
  4651                    };
  4652  
  4653                    meas urements.p ush(measur ementData) ;
  4654                }
  4655                dicomIma geMeasurem ents[image Key] = mea surements;
  4656           }
  4657           ca tch(e)
  4658           {  }
  4659       }
  4660  
  4661       /**
  4662        * Loa d the angl e measurem ent
  4663        * @pa ram {Type}  imageKey  - Specifie s the imag e key
  4664        * @pa ram {Type}  measureme nt - Speci fies the m easurement  array
  4665        * @pa ram {Type}  isEditabl e - Specif ies the fl ag to edit  the measu rement/ann otation
  4666        */ 
  4667       functi on loadAng leMeasurem ent(imageK ey, measur ement, isE ditable) {
  4668           tr y
  4669           {
  4670                if(image Key === un defined ||  measureme nt === und efined) {
  4671                    // I nvalid inp ut paramet ers
  4672                    retu rn;
  4673                }
  4674  
  4675                var poin ts = measu rement.poi nts;
  4676                if(point s === unde fined || p oints ===  null || po ints.lengt h == 0) {
  4677                    retu rn;
  4678                }
  4679  
  4680                var angl eMeasureme nts = dico mImageAngl eMeasureme nts[imageK ey];
  4681                if (angl eMeasureme nts === un defined) {
  4682                    angl eMeasureme nts = [];
  4683                }
  4684  
  4685                var meas urementId  = angleMea surements. length;
  4686                var meas urements =  angleMeas urements[m easurement Id];
  4687                if (meas urements = == undefin ed) {
  4688                    meas urements =  [];
  4689                }
  4690  
  4691                var star t = {};
  4692                var end  = {};
  4693                for(var  index = 0;  index < p oints.leng th; index+ =4) {
  4694                    var  start = 
  4695                    {
  4696                         handleActi ve: false,
  4697                         x: parseFl oat(points [index]),
  4698                         y: parseFl oat(points [index+1])
  4699                    };
  4700  
  4701                    var  end =
  4702                    {
  4703                         handleActi ve: false,
  4704                         x: parseFl oat(points [index+2]) ,
  4705                         y: parseFl oat(points [index+3])
  4706                    };
  4707  
  4708                    var  measuremen tData =
  4709                    {
  4710                         start: sta rt,
  4711                         end: end,
  4712                         measureTyp e: "angle" ,
  4713                         measuremen tSubType:  undefined,
  4714                         measuremen tId: measu rementId,
  4715                         measuremen tComplete:  true,
  4716                         measuremen tType: und efined,
  4717                         measuremen tUnits: un defined,
  4718                         editMode:  false,
  4719                         studyUid:  measuremen t.studyUid ,
  4720                         isEditable : isEditab le,
  4721                         sessionTyp e: 1,
  4722                         style : ge tGrpahicSt yle(measur ement, und efined, is Editable)
  4723                    };
  4724  
  4725                    meas urements.p ush(measur ementData) ;
  4726                }
  4727  
  4728                angleMea surements[ measuremen tId] = mea surements;
  4729                dicomIma geAngleMea surements[ imageKey]  = angleMea surements;
  4730           }
  4731           ca tch(e)
  4732           {  }
  4733       }
  4734  
  4735       /**
  4736        * Loa d the elli pse measur ement
  4737        * @pa ram {Type}  imageKey  - Specifie s the imag e key
  4738        * @pa ram {Type}  measureme ntKey - Sp ecifies th e measurem ent key
  4739        * @pa ram {Type}  measureme nts - Spec ifies the  measuremen t array
  4740        * @pa ram {Type}  isEditabl e - Specif ies the fl ag to edit  the measu rement/ann otation
  4741        */
  4742       functi on loadEll ipseMeasur ement(imag eKey, meas urementKey , measurem ent, isEdi table) {
  4743           tr y
  4744           {
  4745                if(image Key === un defined ||  measureme ntKey ===  undefined   || measur ement ===  undefined)  {
  4746                    // I nvalid inp ut paramet ers
  4747                    retu rn;
  4748                }
  4749  
  4750                var poin ts = measu rement.poi nts;
  4751                if(point s === unde fined || p oints ===  null || po ints.lengt h == 0) {
  4752                    retu rn;
  4753                }
  4754  
  4755                var meas urementSub Type = und efined;
  4756                var meas urementTyp e = undefi ned;
  4757                var meas urementUni ts = undef ined;
  4758                switch(m easurement Key) {
  4759                    case  MT_ELLIPS E:
  4760                         measuremen tSubType =  "ellipse" ;
  4761                         measuremen tType = 11 ;
  4762                         break;
  4763  
  4764                    case  MT_HOUNSF IELDELLIPS E:
  4765                         measuremen tSubType =  "hounsfie ld";
  4766                         measuremen tType = 7;
  4767                         measuremen tUnits = " cm";
  4768                         break;
  4769                }
  4770  
  4771                var elli pseMeasure ments = di comImageEl lipseMeasu rements[im ageKey];
  4772                if (elli pseMeasure ments ===  undefined)  {
  4773                    elli pseMeasure ments = [] ;
  4774                }
  4775  
  4776                var meas urementRes ult = unde fined;
  4777                if(measu rementSubT ype === "h ounsfield" ) {
  4778                    var  text = mea surement.t ext;
  4779                    if(t ext !== un defined) {
  4780                         measuremen tResult =  text.split (",");
  4781                    }
  4782                }
  4783  
  4784                var star t = {};
  4785                var end  = {};
  4786                var isCu stomEllips e = false;
  4787                for(var  index = 0;  index < p oints.leng th; index+ =4) {
  4788                    var  start, end  = null;
  4789                    var  first, sec ond, third , fourth,  center = n ull;
  4790                    star t = 
  4791                    {
  4792                         handleActi ve: false,
  4793                         x: parseFl oat(points [index]),
  4794                         y: parseFl oat(points [index+1])
  4795                    };
  4796  
  4797                    end  =
  4798                    {
  4799                         handleActi ve: false,
  4800                         x: parseFl oat(points [index+2]) ,
  4801                         y: parseFl oat(points [index+3])
  4802                    };
  4803  
  4804                    if ( points.len gth > 4) {
  4805                         isCustomEl lipse = tr ue;
  4806                         first = 
  4807                         {
  4808                             x: par seFloat(po ints[index ]),
  4809                             y: par seFloat(po ints[index +1])
  4810                         };
  4811  
  4812                         second =
  4813                         {
  4814                             x: par seFloat(po ints[index +2]),
  4815                             y: par seFloat(po ints[index +3])
  4816                         };
  4817  
  4818                         third = 
  4819                         {
  4820                             x: par seFloat(po ints[index +4]),
  4821                             y: par seFloat(po ints[index +5])
  4822                         };
  4823  
  4824                         fourth =
  4825                         {
  4826                             x: par seFloat(po ints[index +6]),
  4827                             y: par seFloat(po ints[index +7])
  4828                         };
  4829                    }
  4830  
  4831                    if ( points.len gth > 8) {
  4832                         center = 
  4833                         {
  4834                             x: par seFloat(po ints[index +8]),
  4835                             y: par seFloat(po ints[index +9])
  4836                         };
  4837                    }
  4838  
  4839                    inde x = points .length;
  4840  
  4841                    var  measuremen tData =
  4842                    {
  4843                         start: sta rt,
  4844                         end: end,
  4845                         first: fir st,
  4846                         second: se cond,
  4847                         third: thi rd,
  4848                         fourth: fo urth,
  4849                         center: ce nter,
  4850                         isCustomEl lipse: isC ustomEllip se,
  4851                         measureTyp e: "ellips e",
  4852                         measuremen tSubType:  measuremen tSubType,
  4853                         measuremen tId: -1,
  4854                         measuremen tComplete:  true,
  4855                         measuremen tType: mea surementTy pe,
  4856                         measuremen tUnits: me asurementU nits,
  4857                         editMode:  false,
  4858                         measuremen tResult: m easurement Result,
  4859                         studyUid:  measuremen t.studyUid ,
  4860                         isEditable : isEditab le,
  4861                         sessionTyp e: 1,
  4862                         style : ge tGrpahicSt yle(measur ement, und efined, is Editable)
  4863                    };
  4864  
  4865                    elli pseMeasure ments.push (measureme ntData);
  4866                }
  4867  
  4868                dicomIma geEllipseM easurement s[imageKey ] = ellips eMeasureme nts;
  4869           }
  4870           ca tch(e)
  4871           {  }
  4872       }
  4873  
  4874       /**
  4875        * Loa d the rect angle meas urement
  4876        * @pa ram {Type}  imageKey  - Specifie s the imag e key
  4877        * @pa ram {Type}  measureme ntKey - Sp ecifies th e measurem ent key
  4878        * @pa ram {Type}  measureme nts - Spec ifies the  measuremen t array
  4879        * @pa ram {Type}  isEditabl e - Specif ies the fl ag to edit  the measu rement/ann otation
  4880        */
  4881       functi on loadRec tangleMeas urement(im ageKey, me asurementK ey, measur ement, isE ditable) {
  4882           tr y
  4883           {
  4884                if(image Key === un defined ||  measureme ntKey ===  undefined   || measur ement ===  undefined)  {
  4885                    // I nvalid inp ut paramet ers
  4886                    retu rn;
  4887                }
  4888  
  4889                var poin ts = measu rement.poi nts;
  4890                if(point s === unde fined || p oints ===  null || po ints.lengt h == 0) {
  4891                    retu rn;
  4892                }
  4893  
  4894                var meas urementSub Type = und efined;
  4895                var meas urementTyp e = undefi ned;
  4896                var meas urementUni ts = undef ined;
  4897                switch(m easurement Key) {
  4898                    case  MT_RECT:
  4899                         measuremen tSubType =  "rectangl e";
  4900                         measuremen tType = 12 ;
  4901                         break;
  4902  
  4903                    case  MT_HOUNSF IELDRECT:
  4904                         measuremen tSubType =  "hounsfie ld";
  4905                         measuremen tType = 14 ;
  4906                         measuremen tUnits = " cm";
  4907                         break;
  4908  
  4909                    case  MT_TEXT:
  4910                         measuremen tSubType =  "text";
  4911                         measuremen tType = 8;
  4912                         break;
  4913                }
  4914  
  4915                var rect angleMeasu rements =  dicomImage RectangleM easurement s[imageKey ];
  4916                if (rect angleMeasu rements == = undefine d) {
  4917                    rect angleMeasu rements =  [];
  4918                }
  4919  
  4920                var meas urementRes ult = unde fined;
  4921                var meas urementTex t = undefi ned;
  4922                if(measu rementSubT ype === "h ounsfield"  || measur ementSubTy pe === "te xt") {
  4923                    var  text = mea surement.t ext;
  4924                    if(t ext !== un defined) {
  4925                         if(measure mentSubTyp e === "tex t") {
  4926                             measur ementText  = text.rep lace("<BR> ", "\n");
  4927                             measur ementText  = measurem entText.re place("<br >", "\n");
  4928                         } else {
  4929                             measur ementResul t = text.s plit(",");
  4930                         }
  4931                    }
  4932                }
  4933  
  4934                var star t = {};
  4935                var end  = {};
  4936                for(var  index = 0;  index < p oints.leng th; index+ =4) {
  4937                    var  start = 
  4938                    {
  4939                         handleActi ve: false,
  4940                         x: parseFl oat(points [index]),
  4941                         y: parseFl oat(points [index+1])
  4942                    };
  4943  
  4944                    var  end =
  4945                    {
  4946                         handleActi ve: false,
  4947                         x: parseFl oat(points [index+2]) ,
  4948                         y: parseFl oat(points [index+3])
  4949                    };
  4950  
  4951                    var  measuremen tData =
  4952                    {
  4953                         start: sta rt,
  4954                         end: end,
  4955                         measureTyp e: "rectan gle",
  4956                         measuremen tSubType:  measuremen tSubType,
  4957                         measuremen tId: -1,
  4958                         measuremen tComplete:  true,
  4959                         measuremen tType: mea surementTy pe,
  4960                         measuremen tUnits: me asurementU nits,
  4961                         editMode:  false,
  4962                         measuremen tResult: m easurement Result,
  4963                         measuremen tText: mea surementTe xt,
  4964                         studyUid:  measuremen t.studyUid ,
  4965                         isEditable : isEditab le,
  4966                         sessionTyp e: 1,
  4967                         style : ge tGrpahicSt yle(measur ement, und efined, is Editable)
  4968                    };
  4969  
  4970                    rect angleMeasu rements.pu sh(measure mentData);
  4971                }
  4972  
  4973                dicomIma geRectangl eMeasureme nts[imageK ey] = rect angleMeasu rements;
  4974           }
  4975           ca tch(e)
  4976           {  }
  4977       }
  4978  
  4979       /**
  4980        * Loa d the trac e measurem ent
  4981        * @pa ram {Type}  imageKey  - Specifie s the imag e key
  4982        * @pa ram {Type}  measureme nt - Speci fies the m easurement  array
  4983        * @pa ram {Type}  isEditabl e - Specif ies the fl ag to edit  the measu rement/ann otation
  4984        */ 
  4985       functi on loadTra ceMeasurem ent(imageK ey, measur ement, isE ditable) {
  4986           tr y
  4987           {
  4988                if(image Key === un defined ||  measureme nt === und efined) {
  4989                    // I nvalid inp ut paramet ers
  4990                    retu rn;
  4991                }
  4992  
  4993                var poin ts = measu rement.poi nts;
  4994                if(point s === unde fined || p oints ===  null || po ints.lengt h == 0) {
  4995                    retu rn;
  4996                }
  4997  
  4998                var tarc eMeasureme nts = dico mImageTrac eMeasureme nts[imageK ey];
  4999                if (tarc eMeasureme nts === un defined) {
  5000                    tarc eMeasureme nts = [];
  5001                }
  5002  
  5003                var meas urementId  = tarceMea surements. length;
  5004                var meas urements =  tarceMeas urements[m easurement Id];
  5005                if (meas urements = == undefin ed) {
  5006                    meas urements =  [];
  5007                } 
  5008                
  5009                var star t = {};
  5010                var end  = {};
  5011                for(var  index = 0;  index < p oints.leng th; index+ =4) {
  5012                    var  start = 
  5013                    {
  5014                         handleActi ve: false,
  5015                         x: parseFl oat(points [index]),
  5016                         y: parseFl oat(points [index+1])
  5017                    };
  5018  
  5019                    var  end =
  5020                    {
  5021                         handleActi ve: false,
  5022                         x: parseFl oat(points [index+2]) ,
  5023                         y: parseFl oat(points [index+3])
  5024                    };
  5025  
  5026                    var  measuremen tData =
  5027                    {
  5028                         start: sta rt,
  5029                         end: end,
  5030                         measureTyp e: "trace" ,
  5031                         measuremen tSubType:  undefined,
  5032                         measuremen tId: measu rementId,
  5033                         measuremen tComplete:  true,
  5034                         measuremen tType: 2,
  5035                         measuremen tUnits: un defined,
  5036                         editMode:  false,
  5037                         studyUid:  measuremen t.studyUid ,
  5038                         isEditable : isEditab le,
  5039                         sessionTyp e: 1,
  5040                         style : ge tGrpahicSt yle(measur ement, und efined, is Editable)
  5041                    };
  5042  
  5043                    meas urements.p ush(measur ementData) ;
  5044                }
  5045                
  5046                tarceMea surements[ measuremen tId] = mea surements;
  5047                dicomIma geTraceMea surements[ imageKey]  = tarceMea surements;
  5048           }
  5049           ca tch(e)
  5050           {  }
  5051       }
  5052  
  5053       /**
  5054        * Loa d the Mitr al Gradien t measurem ent
  5055        * @pa ram {Type}  imageKey  - Specifie s the imag e key
  5056        * @pa ram {Type}  measureme ntKey - Sp ecifies th e measurem ent key* 
  5057        * @pa ram {Type}  measureme nt - Speci fies the m easurement  array
  5058        * @pa ram {Type}  isEditabl e - Specif ies the fl ag to edit  the measu rement/ann otation
  5059        */ 
  5060       functi on loadMit ralGradien tMeasureme nt(imageKe y, measure mentKey, m easurement , isEditab le) {
  5061           tr y
  5062           {
  5063                if(image Key === un defined ||  measureme nt === und efined) {
  5064                    // I nvalid inp ut paramet ers
  5065                    retu rn;
  5066                }
  5067  
  5068                var poin ts = measu rement.poi nts;
  5069                if(point s === unde fined || p oints ===  null || po ints.lengt h == 0) {
  5070                    retu rn;
  5071                }
  5072  
  5073                var meas urementSub Type = und efined;
  5074                var meas urementTyp e = undefi ned;
  5075                switch(m easurement Key) {
  5076                    case  MT_MG:
  5077                         measuremen tSubType =  MT_MG;
  5078                         measuremen tType = 5;
  5079                         break;
  5080  
  5081                    case  MT_FREEHA ND:
  5082                         measuremen tSubType =  "freehand ";
  5083                         measuremen tType = 13 ;
  5084                         break;
  5085                }
  5086  
  5087                var mitr alMeasurem ents = dic omImageMit ralGradien tMeasureme nts[imageK ey];
  5088                if (mitr alMeasurem ents === u ndefined)  {
  5089                    mitr alMeasurem ents = [];
  5090                }
  5091  
  5092                var meas urementId  = mitralMe asurements .length;
  5093                var meas urements =  mitralMea surements[ measuremen tId];
  5094                if (meas urements = == undefin ed) {
  5095                    meas urements =  [];
  5096                }
  5097  
  5098                var star t = {};
  5099                var end  = {};
  5100                for(var  index = 0;  index < p oints.leng th; index+ =4) {
  5101                    var  start = 
  5102                    {
  5103                         handleActi ve: false,
  5104                         x: parseFl oat(points [index]),
  5105                         y: parseFl oat(points [index+1])
  5106                    };
  5107  
  5108                    var  end =
  5109                    {
  5110                         handleActi ve: false,
  5111                         x: parseFl oat(points [index+2]) ,
  5112                         y: parseFl oat(points [index+3])
  5113                    };
  5114  
  5115                    var  measuremen tData =
  5116                    {
  5117                         start: sta rt,
  5118                         end: end,
  5119                         measureTyp e: "mitral Gradient",
  5120                         measuremen tSubType:  measuremen tSubType,
  5121                         measuremen tId: measu rementId,
  5122                         measuremen tComplete:  true,
  5123                         measuremen tType: mea surementTy pe,
  5124                         measuremen tUnits: un defined,
  5125                         editMode:  false,
  5126                         studyUid:  measuremen t.studyUid ,
  5127                         isEditable : isEditab le,
  5128                         sessionTyp e: 1,
  5129                         style : ge tGrpahicSt yle(measur ement, und efined, is Editable)
  5130                    };
  5131  
  5132                    meas urements.p ush(measur ementData) ;
  5133                }
  5134                
  5135                mitralMe asurements [measureme ntId] = me asurements ;
  5136                dicomIma geMitralGr adientMeas urements[i mageKey] =  mitralMea surements;
  5137           }
  5138           ca tch(e)
  5139           {  }
  5140       }
  5141  
  5142       /**
  5143        * get  image PSt ate
  5144        * @pa ram {Type}  imagePSta tes - Spec ifies the  image PSta tes
  5145        * @pa ram {Type}  imageKey  - Specifie s the imag e key 
  5146        * @pa ram {Type}  studyDeta ils - Spec ifies the  study deta ils 
  5147        */ 
  5148       functi on getImag ePState(im agePStates , imageKey , studyDet ails) {
  5149           tr y
  5150           {
  5151                var imag ePState =  imagePStat es[imageKe y];
  5152                if(image PState !==  undefined ) {
  5153                    retu rn imagePS tate;
  5154                } else {
  5155                    var  imageUids  = imageKey .split("_" );
  5156                    imag ePState =  {};
  5157                    imag ePState.id  = getUUID ();
  5158                    imag ePState.im ageId = im ageUids[0] ;
  5159                    imag ePState.fr ameNumber  = imageUid s[1];
  5160                    imag ePState.ob jects = [] ;
  5161                    imag ePState.la yers = [];
  5162                    imag ePState.im ageUrn = g etImageUrn FromUId(st udyDetails , imagePSt ate.imageI d);
  5163  
  5164                    imag ePStates[i mageKey] =  imagePSta te;
  5165                }
  5166  
  5167                return i magePState ;
  5168           }
  5169           ca tch(e)
  5170           {  }
  5171       }
  5172  
  5173       /**
  5174        * Get  the study  PState
  5175        * @pa ram {Type}  imagePSta tes - Spec ifies the  image PSta te
  5176        * @pa ram {Type}  pStateDes cription -  Specifies  the prese ntation st ate descri ption
  5177        * @pa ram {Type}  isPrivate  - Specifi es the fla g to make  private
  5178        * @pa ram {Type}  isEditabl e - Specif ies the fl ag to make  editalbe
  5179        */ 
  5180       functi on getStud yPState(im agePStates , pStateDe tails, isP rivate, is Editable)  {
  5181           tr y
  5182           {
  5183                if(image PStates ==  undefined  || imageP States ==  null || im agePStates .length ==  0) {
  5184                    // I nvalid or  empty imag e PStates
  5185                    retu rn undefin ed;
  5186                }
  5187  
  5188                var stud yUid = pSt ateDetails .studyUid;
  5189                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  5190                if(study Details == = undefine d || study Details == = undefine d) {
  5191                    // I nvalid stu dy details
  5192                    retu rn;
  5193                }
  5194  
  5195                var desc ription =  "";
  5196                if(study Details.PS tates !==  undefined  && studyDe tails.PSta tes !== nu ll) {
  5197                    desc ription =  studyDetai ls.PStates .Active.de scription;
  5198                }
  5199  
  5200                var stud yPState =  {};
  5201                var isPr ivate = (p StateDetai ls.isPriva te === und efined ? f alse : pSt ateDetails .isPrivate );
  5202                var isEd itable = ( pStateDeta ils.isEdit able === u ndefined ?  true : pS tateDetail s.isEditab le);
  5203                var isNe w = (pStat eDetails.i sNew === u ndefined ?  false : p StateDetai ls.isNew);
  5204                descript ion = (des cription = == undefin ed ? "" :  descriptio n);
  5205  
  5206                // Updat e the PSta te with an  existing  PState
  5207                if(!isNe w) {
  5208                    if(s tudyDetail s.PStates  !== undefi ned) {
  5209                         if(studyDe tails.PSta tes.Active .isNew ==  true) {
  5210                             remove UnSavedPSt ate(studyD etails);
  5211                             studyP State.id =  null;
  5212                         } else {
  5213                             studyP State.id =  studyDeta ils.PState s.Active.i d;
  5214                         }
  5215                    }
  5216                }
  5217  
  5218                studyPSt ate.isPriv ate = isPr ivate;
  5219                studyPSt ate.isEdit able = isE ditable;
  5220                studyPSt ate.descri ption = de scription;
  5221  
  5222                var pres entationSt ates = [];
  5223                $.each(i magePState s, functio n(key, ima gePState)  {
  5224                    pres entationSt ates.push( imagePStat e);
  5225                });
  5226                studyPSt ate.data =  JSON.stri ngify(pres entationSt ates);
  5227  
  5228                return s tudyPState ;
  5229           }
  5230           ca tch(e)
  5231           {  }
  5232  
  5233           re turn undef ined;
  5234       }
  5235  
  5236       /**
  5237        * Get  the graph ic object  PState
  5238        * @pa ram {Type}  measuemen ts - Speci fies the m easurement s
  5239        * @pa ram {Type}  measureme ntType - S pecifies t he measure ment type
  5240        */ 
  5241       functi on getGrap hicObjectP State(meas uements, m easurement Type) {
  5242           tr y
  5243           {
  5244                if(measu ements ==  undefined  || measuem ents == nu ll) {
  5245                    // I nvalid mea surements
  5246                    retu rn undefin ed;
  5247                }
  5248  
  5249                var grap hicObject  = {};
  5250                graphicO bject.id =  getUUID() ;
  5251                graphicO bject.type  = measure mentType;
  5252                graphicO bject.poin ts = [];
  5253                graphicO bject.text  = "";
  5254                graphicO bject.grap hicLayerIn dex = 0;
  5255                graphicO bject.styl e = getGrp ahicStyle( measuement s, measure mentType,  true);
  5256                if(measu ements.cal ibrationDa ta) {
  5257                    grap hicObject. calibratio nData = me asuements. calibratio nData;
  5258                }
  5259  
  5260                switch(m easurement Type)
  5261                {
  5262                    case  MT_LENGTH :
  5263                    case  MT_LINE:
  5264                    case  MT_ARROW:
  5265                    case  MT_POINT:
  5266                    case  MT_MVALT:
  5267                    case  MT_MRL:
  5268                    case  MT_ARL:
  5269                    case  MT_MRPV:
  5270                    case  MT_ARPV:
  5271                    case  MT_ASPV:
  5272                    {
  5273                         addPointsI nPState(me asuements,  graphicOb ject.point s);
  5274                         break;
  5275                    }
  5276  
  5277                    case  MT_LABEL:
  5278                    {
  5279                         if(measuem ents.textB ounds && m easuements .measureme ntText) {
  5280                             graphi cObject.te xt = measu ements.mea surementTe xt;
  5281                             measue ments.text Bounds.for Each(funct ion(pt){
  5282                                 gr aphicObjec t.points.p ush(Math.r ound(pt.x) );
  5283                                 gr aphicObjec t.points.p ush(Math.r ound(pt.y) );
  5284                             });
  5285                         }
  5286  
  5287                         break;
  5288                    }
  5289  
  5290                    case  MT_ANGLE:
  5291                    case  MT_TRACE:
  5292                    case  MT_MG:
  5293                    case  MT_PEN:
  5294                    case  MT_FREEHA ND:
  5295                    {
  5296                         measuement s.forEach( function(v alue) {
  5297                             addPoi ntsInPStat e(value, g raphicObje ct.points) ;
  5298                         });
  5299                         break;
  5300                    }
  5301  
  5302                    case  MT_ELLIPS E:
  5303                    case  MT_HOUNSF IELDELLIPS E:
  5304                    case  MT_RECT:
  5305                    case  MT_HOUNSF IELDRECT:
  5306                    case  MT_TEXT:
  5307                    {
  5308                         var isElli spe = (mea surementTy pe === MT_ HOUNSFIELD ELLIPSE ||
  5309                                                                meas urementTyp e === MT_E LLIPSE);
  5310                         addPointsI nPState(me asuements,  graphicOb ject.point s, isEllis pe);
  5311                         if(measuem ents.measu rementResu lt) {
  5312                             var te xt = "";
  5313                             measue ments.meas urementRes ult.forEac h(function (textItem)  {
  5314                                 te xt += text Item;
  5315                                 te xt += ",";
  5316                             });
  5317                             graphi cObject.te xt = text. slice(0, - 1);
  5318                         } else if( measuremen tType ===  MT_TEXT) {
  5319                             graphi cObject.te xt = measu ements.mea surementTe xt;
  5320                         }
  5321                         break;
  5322                    }
  5323                }
  5324  
  5325                return g raphicObje ct;
  5326           }
  5327           ca tch(e)
  5328           {  }
  5329  
  5330           re turn undef ined;
  5331       }
  5332  
  5333       /**
  5334        * Add  points in  PState 
  5335        * @pa ram {Type}  measuemen ts -  Spec ifies the  measuremen ts
  5336        * @pa ram {Type}  points -  points
  5337        */ 
  5338       functi on addPoin tsInPState (measuemen ts, points , isEllisp e) {
  5339           tr y
  5340           {
  5341                points.p ush(Math.r ound(measu ements.sta rt.x));
  5342                points.p ush(Math.r ound(measu ements.sta rt.y));
  5343                points.p ush(Math.r ound(measu ements.end .x));
  5344                points.p ush(Math.r ound(measu ements.end .y));
  5345  
  5346                if (isEl lispe && m easuements .isCustomE llipse) {
  5347                    if ( measuement s.first !=  null) {
  5348                         points.pus h(Math.rou nd(measuem ents.third .x));
  5349                         points.pus h(Math.rou nd(measuem ents.third .y));
  5350                         points.pus h(Math.rou nd(measuem ents.fourt h.x));
  5351                         points.pus h(Math.rou nd(measuem ents.fourt h.y));
  5352                    }
  5353                    if ( measuement s.center ! = null) {
  5354                         points.pus h(Math.rou nd(measuem ents.cente r.x));
  5355                         points.pus h(Math.rou nd(measuem ents.cente r.y));
  5356                    }
  5357                }
  5358           }
  5359           ca tch(e)
  5360           {  }
  5361       }
  5362  
  5363       /**
  5364        * Add  the image  PState
  5365        * @pa ram {Type}  imagePSta tes - Spec ifies the  image PSta tes
  5366        * @pa ram {Type}  imageKey  - Specifie s the imag e key
  5367        * @pa ram {Type}  measuemen ts - Speci fies the m easurement s
  5368        * @pa ram {Type}  measureme ntType - S pecifies t he measure ment type
  5369        * @pa ram {Type}  studyDeta ils - Spec ifies the  study deta ils
  5370        */ 
  5371       functi on addImag ePState(im agePStates , imageKey , measueme nts, measu rementType , studyDet ails) {
  5372           tr y
  5373           {
  5374                var imag ePState =  getImagePS tate(image PStates, i mageKey, s tudyDetail s);
  5375                var grap hicObject  = getGraph icObjectPS tate(measu ements, me asurementT ype);
  5376                if(graph icObject = == undefin ed) {
  5377                    retu rn;
  5378                }
  5379  
  5380                imagePSt ate.object s.push(gra phicObject );
  5381  
  5382                var meas uements =  measuement s;
  5383                if(measu rementType  == MT_ANG LE) {
  5384                    meas uements =  measuement s[0];
  5385                }
  5386  
  5387                if(measu ements.tex tBounds) {
  5388                    grap hicObject  = getGraph icObjectPS tate(measu ements, MT _LABEL);
  5389                    if(g raphicObje ct) {
  5390                         imagePStat e.objects. push(graph icObject);
  5391                    }
  5392                }
  5393  
  5394                imagePSt ates[image Key] = ima gePState;
  5395           }
  5396           ca tch(e)
  5397           {  }
  5398       }
  5399  
  5400       /**
  5401        * Get  US measur ement type
  5402        * @pa ram {Type}  measureme nt - Speci fies the m easurement  subtype
  5403        */ 
  5404       functi on getUSMe asurementT ype(measur ementSubTy pe) {
  5405           sw itch(measu rementSubT ype) {
  5406                case "mi tralValveA nteriorLea fletThickn ess":
  5407                    retu rn MT_MVAL T;
  5408  
  5409                case "mi tralRegurg itationLen gth":
  5410                    retu rn MT_MRL;
  5411  
  5412                case "ao rticRegurg itationLen gth":
  5413                    retu rn MT_ARL;
  5414  
  5415                case "mi tralRegurg itationPea kVelocity" :
  5416                    retu rn MT_MRPV ;
  5417  
  5418                case "ao rticRegurg itationPea kVelocity" :
  5419                    retu rn MT_ARPV ;
  5420  
  5421                case "ao rticStenos isPeakVelo city":
  5422                    retu rn MT_ASPV ;
  5423           }
  5424  
  5425           re turn undef ined;
  5426       }
  5427  
  5428       /**
  5429        * Get  the graph ic style
  5430        * @pa ram {Type}  measureme nts - Spec ifies the  measuermen t data
  5431        * @pa ram {Type}  measureme ntType - S pecifies t he measuer ment type
  5432        */ 
  5433       functi on getGrpa hicStyle(m easurement s, measure mentType,  isEditable ) {
  5434           tr y
  5435           {
  5436                var meas urementSty le = measu rements.st yle;
  5437                var type  = null;
  5438                if (meas urementTyp e !== unde fined) {
  5439                    type  = measure mentType;
  5440                } else {
  5441                    type  = measure ments.type ;
  5442                }
  5443  
  5444                var user Measuremen tStyle = d icomViewer .measureme nt.draw.ge tUserMeasu rementStyl eByType((i sEditable  ? type : u ndefined)) ;
  5445                if(!meas urementSty le) {
  5446                    meas urementSty le = userM easurement Style;
  5447                }
  5448                
  5449                if (meas urementTyp e == undef ined && (m easurement s.style != = undefine d && measu rements.st yle.isUnde rlined ==  undefined) ) {
  5450                    meas urementSty le.isUnder lined = us erMeasurem entStyle.i sUnderline d;
  5451                    meas urementSty le.isStrik eout = use rMeasureme ntStyle.is Strikeout;
  5452                    meas urementSty le.isFill  = userMeas urementSty le.isFill;
  5453                    meas urementSty le.fillCol or = userM easurement Style.fill Color;
  5454                    meas urementSty le.gaugeLe ngth = use rMeasureme ntStyle.ga ugeLength;
  5455                    meas urementSty le.gaugeSt yle = user Measuremen tStyle.gau geStyle;
  5456                    meas urementSty le.precisi on = userM easurement Style.prec ision;
  5457                    meas urementSty le.measure mentUnits  = userMeas urementSty le.measure mentUnits;
  5458                    meas urementSty le.arcRadi us = userM easurement Style.arcR adius;
  5459                }
  5460  
  5461                var styl e =
  5462                {
  5463                    line Color : me asurementS tyle.lineC olor,
  5464                    line Width : pa rseFloat(m easurement Style.line Width),
  5465                    text Color : me asurementS tyle.textC olor,
  5466                    font Name : mea surementSt yle.fontNa me,
  5467                    font Size : par seInt(meas urementSty le.fontSiz e),
  5468                    isBo ld : measu rementStyl e.isBold,
  5469                    isIt alic : mea surementSt yle.isItal ic,
  5470                    isUn derlined:  measuremen tStyle.isU nderlined,
  5471                    isSt rikeout: m easurement Style.isSt rikeout,
  5472                    isFi ll: measur ementStyle .isFill,
  5473                    fill Color: mea surementSt yle.fillCo lor,
  5474                    gaug eLength: m easurement Style.gaug eLength,
  5475                    gauu geStyle: m easurement Style.gaug eStyle,
  5476                    prec ision: mea surementSt yle.precis ion,
  5477                    meas urementUni ts: measur ementStyle .measureme ntUnits,
  5478                    arcR adius: mea surementSt yle.arcRad ius
  5479                };
  5480  
  5481                return s tyle;
  5482           }
  5483           ca tch(e)
  5484           {  }
  5485       }
  5486  
  5487       /**
  5488        * Che ck whether  the study  is same
  5489        * @pa ram {Type}  selectedS tudyUid -  Specifies  the select ed study U id
  5490        * @pa ram {Type}  measureme ntStudyUid   - Specif ies the me asurement  study Uid
  5491        */ 
  5492       functi on isSameS tudy(selec tedStudyUi d, measure mentStudyU id) {
  5493           if (measureme ntStudyUid  === undef ined || se lectedStud yUid === u ndefined)  {
  5494                return f alse;
  5495           }
  5496  
  5497           if (selectedS tudyUid == = measurem entStudyUi d) {
  5498                return t rue;
  5499           }
  5500  
  5501           re turn false ;
  5502       }
  5503  
  5504       /**
  5505        * Upd ate the pr esentation  state
  5506        * @pa ram {Type}  selctedPS tate - Spe cifies the  presentat ion state
  5507        * @pa ram {Type}  studyDeta ils - Spec ifies the  study deta ils
  5508        */ 
  5509       functi on updateP State(selc tedPState,  studyDeta ils) {
  5510           tr y
  5511           {
  5512                // Delet e all meas urements a nd annotat ions
  5513                deleteAl lPStates(s tudyDetail s.studyUid );
  5514  
  5515                if(selct edPState = == undefin ed ||
  5516                   selct edPState = == null ||
  5517                   study Details == = undefine d ||
  5518                   study Details == = null) {
  5519                   // In valid inpu t paramete rs 
  5520                    retu rn;
  5521                }
  5522  
  5523                // Flag  to edit th e measurem ent or ann otation
  5524                var isEd itable = t rue;
  5525                if(selct edPState.i sEditable  !== undefi ned && sel ctedPState .isEditabl e !== null ) {
  5526                    isEd itable = s elctedPSta te.isEdita ble;
  5527                }
  5528  
  5529                selctedP State.pres entationSt ates.forEa ch(functio n(pState)  {
  5530                    var  imageKey =  getImageU idFromUrn( studyDetai ls, pState ) + "_" +  pState.fra meNumber;
  5531                    pSta te.objects .forEach(f unction(gr aphicObjec ts) {
  5532                         graphicObj ects.study Uid = stud yDetails.s tudyUid;
  5533                         switch(gra phicObject s.type) {
  5534                             case M T_LENGTH:
  5535                             case M T_LINE:
  5536                             case M T_ARROW:
  5537                             case M T_MVALT:
  5538                             case M T_MRL:
  5539                             case M T_ARL:
  5540                             case M T_POINT:
  5541                             case M T_MRPV:
  5542                             case M T_ARPV:
  5543                             case M T_ASPV:
  5544                             {
  5545                                 lo adLengthOr PointMeasu rement(ima geKey, gra phicObject s.type, gr aphicObjec ts, isEdit able);
  5546                                 br eak;
  5547                             }
  5548  
  5549                             case M T_ANGLE:
  5550                             {
  5551                                 lo adAngleMea surement(i mageKey, g raphicObje cts, isEdi table);
  5552                                 br eak;
  5553                             }
  5554  
  5555                             case M T_ELLIPSE:
  5556                             case M T_HOUNSFIE LDELLIPSE:
  5557                             {
  5558                                 lo adEllipseM easurement (imageKey,  graphicOb jects.type , graphicO bjects, is Editable);
  5559                                 br eak;
  5560                             }
  5561  
  5562                             case M T_RECT:
  5563                             case M T_HOUNSFIE LDRECT:
  5564                             case M T_TEXT:
  5565                             {
  5566                                 lo adRectangl eMeasureme nt(imageKe y, graphic Objects.ty pe, graphi cObjects,  isEditable );
  5567                                 br eak;
  5568                             }
  5569  
  5570                             case M T_TRACE:
  5571                             {
  5572                                 lo adTraceMea surement(i mageKey, g raphicObje cts, isEdi table);
  5573                                 br eak;
  5574                             }
  5575  
  5576                             case M T_MG:
  5577                             case M T_FREEHAND :
  5578                             {
  5579                                 lo adMitralGr adientMeas urement(im ageKey, gr aphicObjec ts.type, g raphicObje cts, isEdi table);
  5580                                 br eak;
  5581                             }
  5582                             case M T_PEN:
  5583                             {
  5584                                 lo adPenMeasu rement(ima geKey, gra phicObject s.type, gr aphicObjec ts, isEdit able);
  5585                                 br eak;
  5586                             }
  5587                         }
  5588                    });
  5589                });
  5590           }
  5591           ca tch(e)
  5592           {  }
  5593       }
  5594  
  5595       /**
  5596        * Upd ate the st udy presen tation sta tes
  5597        * @pa ram {Type}  pStates -  Specifies  the PStat es
  5598        * @pa ram {Type}  studyDeta ils - Spec ifies the  study deta ils
  5599        * @pa ram {Type}  activePSt ateId - Sp ecifies th e active P State Id
  5600        * @pa ram {Type}  isRefresh Menu - Spe cifies the  flag to r efesh PSta te menu
  5601        */ 
  5602       functi on updateS tudyPState s(pStates,  studyDeta ils, activ ePStateId,  isRefresh Menu) {
  5603           tr y
  5604           {
  5605                if(pStat es == unde fined || 
  5606                   pStat es === nul l || 
  5607                   study Details == = undefine d ||
  5608                   study Details == = null) {
  5609                    retu rn;
  5610                }
  5611  
  5612                // Creat e the obje ct to hold  the PStat e
  5613                studyDet ails.PStat es = {};
  5614                studyDet ails.PStat es.All = [ ];
  5615                studyDet ails.PStat es.userDUZ  = getUser Duz();
  5616  
  5617                pStates. forEach(fu nction(pSt ate) {
  5618                    var  isOtherUse r = (study Details.PS tates.user DUZ !== pa rseInt(pSt ate.userId ));
  5619                    var  isEditable  = (isOthe rUser ? fa lse : pSta te.isEdita ble);
  5620                    var  descriptio n = isNull OrUndefine d(pState.d escription ) ? pState .dateTime  : pState.d escription ;
  5621  
  5622                    if(! isDuplicat ePState(st udyDetails .PStates.A ll, pState )) {
  5623                         studyDetai ls.PStates .All.push(
  5624                         {
  5625                             id: pS tate.id,
  5626                             name:  descriptio n,
  5627                             dateTi me: pState .dateTime,
  5628                             descri ption: des cription,
  5629                             isEdit able: isEd itable,
  5630                             isOthe rUser: isO therUser,
  5631                             isExte rnal: pSta te.isExter nal,
  5632                             contex tId : pSta te.context Id,
  5633                             toolti p : (!pSta te.tooltip  ? descrip tion : pSt ate.toolti p)
  5634                         });
  5635                    }
  5636  
  5637                    if(p State.id = == activeP StateId) {
  5638                         studyDetai ls.PStates .Active =
  5639                         {
  5640                             id: pS tate.id,
  5641                             name:  descriptio n,
  5642                             dateTi me: pState .dateTime,
  5643                             descri ption: des cription,
  5644                             isEdit able: isEd itable,
  5645                             isDirt y: false,
  5646                             imageP States: pS tate.prese ntationSta tes,
  5647                             isOthe rUser: isO therUser,
  5648                             isExte rnal: pSta te.isExter nal,
  5649                             contex tId : pSta te.context Id,
  5650                             toolti p : (!pSta te.tooltip  ? descrip tion : pSt ate.toolti p)
  5651                         };
  5652                    } el se if(acti vePStateId  == undefi ned && stu dyDetails. PStates.Ac tive === u ndefined)  {
  5653                         studyDetai ls.PStates .Active =  { isEmpty:  true };
  5654                    }
  5655                });
  5656  
  5657                // Sort  by recent  date
  5658                studyDet ails.PStat es.All.sor t(function (a, b)
  5659                {
  5660                    if(! a.isExtern al && !b.i sExternal)  {
  5661                         return new  Date(pars eDate(b.da teTime)) -  new Date( parseDate( a.dateTime ));
  5662                    } el se {
  5663                         return -1;
  5664                    }
  5665                });
  5666                dicomVie wer.update PState(stu dyDetails. studyUid);
  5667           }
  5668           ca tch(e)
  5669           {  }
  5670       }
  5671       
  5672       /**
  5673        * Che ck the if  a value is  null or u ndefined
  5674        **/
  5675       functi on isNullO rUndefined (obj) 
  5676       {
  5677           if  (obj ===  undefined  || obj ===  null || o bj === "")  
  5678           {
  5679                return t rue;
  5680           }
  5681           re turn false ;
  5682       }
  5683  
  5684       /**
  5685        * Che ck whether  the PStat e is dupli cated or n ot
  5686        * @pa ram {Type}  pStates -  Specifies  the PStat es
  5687        * @pa ram {Type}  pState -  Specifies  the select ed PState
  5688        */ 
  5689       functi on isDupli catePState (pStates,  pState) {
  5690           tr y
  5691           {
  5692                var isDu plicate =  false; 
  5693  
  5694                pStates. forEach(fu nction(ite m) {
  5695                    if(p State.id = == item.id ) {
  5696                         isDuplicat e = true;
  5697                         return fal se;
  5698                    }
  5699                });
  5700  
  5701                return i sDuplicate ;
  5702           }
  5703           ca tch(e)
  5704           {  }
  5705  
  5706           re turn false ;
  5707       }
  5708  
  5709       /**
  5710        * Del ete all me asurements
  5711        * @pa ram {Type}  studyUid  - Specifie s the stud y Uid
  5712        */ 
  5713       functi on deleteA llPStates( studyUid)  {
  5714           tr y
  5715           {
  5716                if(study Uid === un defined ||  studyUid  === null)  {
  5717                    retu rn;
  5718                }
  5719                var dele teAllPStat e = [];
  5720                deleteAl lPState.pu sh(dicomIm ageMeasure ments);
  5721                deleteAl lPState.pu sh(dicomIm ageAngleMe asurements );
  5722                deleteAl lPState.pu sh(dicomIm ageEllipse Measuremen ts);
  5723                deleteAl lPState.pu sh(dicomIm ageRectang leMeasurem ents);
  5724                deleteAl lPState.pu sh(dicomIm ageTraceMe asurements );
  5725                deleteAl lPState.pu sh(dicomIm ageMitralG radientMea surements) ;
  5726                deleteAl lPState.pu sh(dicomIm agePenMeas urements);
  5727                var imag eUids=[];
  5728                var isIn dex = fals e;
  5729  
  5730                dicomVie wer.mouseT ools.setPr eviousTool (dicomView er.mouseTo ols.getAct iveTool()) ;
  5731                dicomVie wer.mouseT ools.setCu rsor(dicom Viewer.mou seTools.ge tToolCurso r(1));
  5732  
  5733                $.each(d eleteAllPS tate, func tion(key,  values) {
  5734                    $.ea ch(values,  function( id, ImageI d) {
  5735                         ImageId.so me(functio n(o) {
  5736                             var ob j = o;
  5737                             var st udyId = (O bject.prot otype.toSt ring.call( obj) === ' [object Ar ray]') ? o bj[0].stud yUid : obj .studyUid;
  5738                             if(stu dyId === s tudyUid &&  !isIndex)  {
  5739                                 im ageUids.pu sh(id);
  5740                                 re turn true;
  5741                             } else  if(studyI d === stud yUid && im ageUids.in dexOf(id)  == -1) {
  5742                                 im ageUids.pu sh(id);
  5743                                 re turn true;
  5744                             }
  5745                         });
  5746                    });
  5747                    isIn dex = true ;
  5748                });
  5749  
  5750                imageUid s.forEach( function(i mageUid) {
  5751                    var  imageUidFr ameNumber  = imageUid .split("_" );
  5752                    remo veAllMeasu rements(im ageUidFram eNumber[0] , imageUid FrameNumbe r[1]);
  5753                });
  5754           }
  5755           ca tch(e)
  5756           {  }
  5757       }
  5758  
  5759       /**
  5760        * Cre ate the ne w presenta tion state
  5761        * @pa ram {Type}  e - Speci fies the i d
  5762        */ 
  5763       functi on newPSta te(e) {
  5764           tr y
  5765           {
  5766                var stud yUid = e.s plit("_")[ 1];
  5767                if(study Uid === un defined ||  studyUid  === null)  {
  5768                    // I nvalid par ameters
  5769                    retu rn;
  5770                }
  5771  
  5772                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  5773                if(study Details == = undefine d || study Details == = undefine d) {
  5774                    // I nvalid stu dy details
  5775                    retu rn;
  5776                }
  5777  
  5778                // Creat e the obje ct to hold  the PStat e
  5779                if(study Details.PS tates == u ndefined | | studyDet ails.PStat es == null ) {
  5780                    stud yDetails.P States = { };
  5781                }
  5782  
  5783                // Creat e the arra y to hold  all PState s
  5784                if(study Details.PS tates.All  == undefin ed || stud yDetails.P States.All  == null)  {
  5785                    stud yDetails.P States.All  = [];
  5786                }
  5787  
  5788                var newI d = null;
  5789                var newT itle = "un titled";
  5790                studyDet ails.PStat es.All.pus h({ id: ne wId, name:  newTitle,  dateTime:  "", descr iption: ""  });
  5791                studyDet ails.PStat es.Active  = { id: ne wId, name:  newTitle,  dateTime:  "", descr iption: "" , isNew: t rue };
  5792                updateNe wDirtyActi vePState(s tudyDetail s);
  5793           }
  5794           ca tch(e)
  5795           {  }
  5796       }
  5797  
  5798       /**
  5799        * Del ete the pr esentation  state
  5800        * @pa ram {Type}  e - Speci fies the i d
  5801        */ 
  5802       functi on deleteP State(e) {
  5803           tr y
  5804           {
  5805                var stud yUid = e.s plit("_")[ 1];
  5806                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  5807                // Send  the presen tation sta te to serv er
  5808                var cont extId = st udyDetails .modality  == "Genera l" ? study Details[0] .contextId  : studyDe tails.cont extId;
  5809                var pSta teUrl = di comViewer. url.getPSt ateUrl(con textId);
  5810                var pSta te = JSON. stringify( {id: study Details.PS tates.Acti ve.id});
  5811                $.ajax({
  5812                    type : 'DELETE' ,
  5813                    url:  pStateUrl ,
  5814                    asyn c: false,
  5815                    data : pState,
  5816                    cach e: false
  5817                })
  5818                .success (function( data) {
  5819                    var  descriptio n = "Succe ssfully de leted the  presentati on state f or the con text id: "  + decodeU RIComponen t(studyDet ails.conte xtId);
  5820                    send ViewerStat usMessage( "200", des cription);
  5821  
  5822                    // R efresh PSt ates
  5823                    load PState(stu dyUid, und efined, fa lse);
  5824                })
  5825                .fail(fu nction(dat a) {
  5826                    var  descriptio n = "Faile d to delet e the pres entation s tate for t he context  id: " + d ecodeURICo mponent(st udyDetails .contextId );
  5827                    send ViewerStat usMessage( "500", des cription);
  5828                })
  5829                .error(f unction(xh r, status)  {
  5830                    var  descriptio n = xhr.st atusText +  "\nFailed  to delete  the prese ntation st ate to ser ver";
  5831                    send ViewerStat usMessage( xhr.status .toString( ), descrip tion);
  5832                });
  5833           }
  5834           ca tch(e)
  5835           {  }
  5836       }
  5837  
  5838       /**
  5839        * Rem ove the un saved PSta te
  5840        * @pa ram {Type}  studyDeta ils - Spec ifies the  study deta ils
  5841        */ 
  5842       functi on removeU nSavedPSta te(studyDe tails) {
  5843           tr y
  5844           {
  5845                var unsa vedPStateI ndex = stu dyDetails. PStates.Al l.map(func tion(item)
  5846                {
  5847                    retu rn item.id
  5848                }).index Of(studyDe tails.PSta tes.Active .id);
  5849  
  5850                if(unsav edPStateIn dex !== -1 ) {
  5851                    stud yDetails.P States.All .splice(un savedPStat eIndex, 1) ;
  5852                }
  5853           }
  5854           ca tch(e)
  5855           {  }
  5856       }
  5857  
  5858       /**
  5859        * Res et the PSt ates
  5860        * @pa ram {Type}  studyDeta ils - Spec ify the st udy detail s
  5861        */ 
  5862       functi on resetPS tate(study Details) {
  5863           tr y
  5864           {
  5865                if(study Details.PS tates ===  undefined  || studyDe tails.PSta tes === nu ll) {
  5866                    retu rn;
  5867                }
  5868  
  5869                var stud yUid = stu dyDetails. studyUid;
  5870                studyDet ails.PStat es = undef ined;
  5871  
  5872                dicomVie wer.update PState(stu dyUid);
  5873                deleteAl lPStates(s tudyUid);
  5874                refreshP State(stud yUid);
  5875           }
  5876           ca tch(e)
  5877           {  }
  5878       }
  5879  
  5880       /**
  5881       * Refr esh the PS tates
  5882       * @par am {Type}  studyUid -  Specify t he study U id
  5883       */ 
  5884       functi on refresh PState(stu dyUid) {
  5885           tr y
  5886           {
  5887                var allV iewports =  dicomView er.viewpor ts.getAllV iewports() ;
  5888                if(allVi ewports == = null ||  allViewpor ts === und efined) {
  5889                    retu rn;
  5890                }
  5891  
  5892                // Refre sh rendere r
  5893                $.each(a llViewport s, functio n(key, val ue) {
  5894                    if(v alue.study Uid === st udyUid) {
  5895                         $("#"+valu e.seriesLa youtId+" d iv").each( function()  {
  5896                             var im ageLevelId  = $(this) .attr('id' );
  5897                             var im ageRender   = value.g etImageRen der(imageL evelId);
  5898                             if(ima geRender)  {
  5899                                 im ageRender. drawDicomI mage(false );
  5900                             }
  5901                         });
  5902                    }
  5903                });
  5904           }
  5905           ca tch(e)
  5906           {  }
  5907       }
  5908  
  5909       /**
  5910        * Sav e or delet e the unsa ved PState
  5911        * @pa ram {Type}  studyDeta ils - Spec ifies the  PState
  5912        * @pa ram {Type}  isSave -  Specify th e flag to  save or ed it the PSt ate
  5913        */ 
  5914       functi on saveOrD eleteUnSav edPState(s tudyDetail s, isSave)  {
  5915           tr y
  5916           {
  5917                if(isSav e == true)  {
  5918                    save PState({ s tudyUid: s tudyDetail s.studyUid , isNew: t rue });
  5919                } else {
  5920                    remo veUnSavedP State(stud yDetails);
  5921                    load PState(stu dyDetails. studyUid,  undefined,  false);
  5922                }
  5923           }
  5924           ca tch(e)
  5925           {  }
  5926       }
  5927  
  5928       /**
  5929        * Edi t presenta ion state 
  5930        * @pa ram {Type}  e - Speci fies the i d
  5931        */ 
  5932       functi on editPSt ate(e) {
  5933           tr y
  5934           {
  5935                var stud yDetails =  dicomView er.getStud yDetails(e .split("_" )[1]);
  5936                if(study Details == = undefine d || study Details == = undefine d) {
  5937                    // I nvalid stu dy details
  5938                    retu rn;
  5939                }
  5940  
  5941                if(study Details.PS tates ===  undefined  || studyDe tails.PSta tes === nu ll) {
  5942                    retu rn null;
  5943                }
  5944  
  5945                var acti vePState =  studyDeta ils.PState s.Active;
  5946                document .getElemen tById("pre sentationN ame").valu e = active PState.nam e;
  5947                document .getElemen tById("edi tPStateDes cription") .value = ( activePSta te.descrip tion == un defined) ?  "" : acti vePState.d escription ;
  5948                $("#edit -PState"). dialog("op en");
  5949           }
  5950           ca tch(e)
  5951           {  }
  5952       }
  5953  
  5954       /**
  5955        * Sho w the conf irmation m essage box
  5956        */ 
  5957       functi on showCon firmMessag e(message)  {
  5958           re turn windo w.confirm( message);
  5959       }
  5960       
  5961       /**
  5962        * 
  5963        * To  get sessio n type  
  5964        */ 
  5965       functi on getSess ionType()  {
  5966           re turn selec tedSession Type;
  5967       }
  5968       
  5969       /**
  5970        * To  set sessio n type
  5971        * @pa ram {int}  sessionTyp e, 0 - Ses sion; 1 -  Stored; 2  - All
  5972        */ 
  5973       functi on setSess ionType(se ssionType)  {
  5974           se lectedSess ionType =  sessionTyp e;
  5975       }
  5976       
  5977       /**
  5978        * To  show measu rements ba sed on sel ected sess ion type
  5979        * @pa ram {int}  sessionTyp e
  5980        */ 
  5981       functi on isMeasu rementDraw able(sessi onType) {
  5982           if  (selected SessionTyp e === 2) {
  5983                return t rue;
  5984           }
  5985           re turn selec tedSession Type === s essionType ;
  5986       }
  5987  
  5988       /**
  5989        * Upd ate dirty  presentati on state 
  5990        * @pa ram {Type}  seriesLev elDivId -  Specifies  the viewpo rt id
  5991        * @pa ram {Type}  measureme ntData - S pecifies t he measure ment data
  5992        * @pa ram {Type}  isDelete  - Specifie s the flag  to delete  PState 
  5993        * @pa ram {Type}  isUpdate  - Specifie s the flag  to update  PState 
  5994        */ 
  5995       functi on updateD irtyPState (seriesLev elDivId, m easurement Data, isDe lete, isUp date) {
  5996           tr y
  5997           {
  5998                // Check  whether t he present ation stat e is enabl ed or not
  5999                if(isPSt ateEnabled () !== tru e) {
  6000                    retu rn;
  6001                }
  6002  
  6003                var stud yDiv = get StudyLayou tId(series LevelDivId );
  6004                if(study Div === nu ll || stud yDiv === u ndefined)  {
  6005                    retu rn;
  6006                }
  6007  
  6008                var view port = dic omViewer.v iewports.g etViewport (seriesLev elDivId);
  6009                if(viewp ort === nu ll || view port === u ndefined)  {
  6010                    retu rn;
  6011                }
  6012  
  6013                var stud yUid = vie wport.stud yUid;
  6014                if(study Uid === nu ll || stud yUid === u ndefined)  {
  6015                    retu rn;
  6016                }
  6017  
  6018                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  6019                if(study Details == = undefine d || study Details == = undefine d) {
  6020                    retu rn;
  6021                }
  6022  
  6023                // Creat e new pres entation i f an exist ing PState  is invali d
  6024                if(study Details.PS tates == u ndefined | |
  6025                   study Details.PS tates == n ull ||
  6026                   study Details.PS tates.Acti ve.isEmpty  == true)  {
  6027                    retu rn newPSta te("newPSt ate_"+stud yUid);
  6028                }
  6029  
  6030                if(study Details.PS tates.Acti ve.isNew = = true || 
  6031                   study Details.PS tates.Acti ve.isEdita ble == fal se) {
  6032                    upda teNewDirty ActivePSta te(studyDe tails);
  6033                    retu rn;
  6034                }
  6035  
  6036                if(study Details.PS tates.Acti ve.isDescr iptionUpda ted == tru e) {
  6037                    upda teDirtyAct ivePState( studyDetai ls, studyD iv, true);
  6038                    retu rn;
  6039                }
  6040  
  6041                var isDi rty = fals e;
  6042                if(measu rementData  !== undef ined && me asurementD ata !== nu ll) {
  6043                    var  imagePStat es = study Details.PS tates.Acti ve.imagePS tates;
  6044                    var  key = meas urementDat a.key;
  6045                    var  arrayIndex  = measure mentData.a rryIndex;
  6046                    var  measuremen tType = me asurementD ata.measur mentType;
  6047                    var  sessionTyp e = measur ementData. sessionTyp e;
  6048                    var  measuremen t = undefi ned;
  6049  
  6050                    // G et the ses sion type  if we call  delete al l measurem ent/annota tions
  6051                    if(s essionType  === undef ined && is Update !==  true) {
  6052                         sessionTyp e = 0;
  6053                         if(imagePS tates !==  undefined)  {
  6054                             var im ageUids =  key.split( "_");
  6055                             imageP States.som e(function (o)
  6056                             {
  6057                                 if (o.imageId  === image Uids[0] &&  o.frameNu mber == im ageUids[1] ) {
  6058                                      sessionT ype = 1;
  6059                                 }
  6060  
  6061                                 re turn (sess ionType ==  1 ? true  : false);
  6062                             });
  6063                         }
  6064                    }
  6065  
  6066                    if(i sDelete ==  true || i sUpdate ==  true) {
  6067                         var imageU ids = key. split("_") ;
  6068                         if(imagePS tates !==  undefined  && session Type == 1)  {
  6069                             imageP States.som e(function (o)
  6070                             {
  6071                                 if (o.imageId  === image Uids[0] &&  o.frameNu mber == im ageUids[1] ) {
  6072                                      o.isDirt y = true;
  6073                                      isDirty  = true;
  6074                                 }
  6075  
  6076                                 re turn isDir ty;
  6077                             });
  6078                         } else if( imagePStat es !== und efined) {
  6079                             imageP States.som e(function (o)
  6080                             {
  6081                                 if (o.isDirty  == true)  {
  6082                                      isDirty  = true;
  6083                                 }
  6084  
  6085                                 re turn isDir ty;
  6086                             });
  6087                         }
  6088                    } el se {
  6089                         if(measure mentType = == "mitral Gradient")  {
  6090                             measur ement = di comImageMi tralGradie ntMeasurem ents[key][ arrayIndex ];
  6091                         } else if  (measureme ntType ===  "Trace")  {
  6092                             measur ement = di comImageTr aceMeasure ments[key] [arrayInde x];
  6093                         } else if  (measureme ntType ===  "volume")  {
  6094                             measur ement = di comImageVo lumeMeasur ements[key ][arrayInd ex];
  6095                         } else if  (measureme ntType ===  "line" ||  measureme ntType ===  "point")  {
  6096                             measur ement = di comImageMe asurements [key][arra yIndex];
  6097                         } else if  (measureme ntType ===  "angle")  {
  6098                             measur ement = di comImageAn gleMeasure ments[key] [arrayInde x];
  6099                         } else if  (measureme ntType ===  "ellipse" ) {
  6100                             measur ement = di comImageEl lipseMeasu rements[ke y][arrayIn dex];
  6101                         } else if  (measureme ntType ===  "rectangl e") {
  6102                             measur ement = di comImageRe ctangleMea surements[ key][array Index];
  6103                         }
  6104  
  6105                         if(Object. prototype. toString.c all(measur ement) ===  '[object  Array]') {
  6106                             measur ement = me asurement[ 0];
  6107                         }
  6108  
  6109                         isDirty =  (measureme nt.session Type == 1  ? true : f alse);
  6110                         if(imagePS tates !==  undefined  && isDirty  == true)  {
  6111                             var im ageUids =  key.split( "_");
  6112                             imageP States.som e(function (o)
  6113                             {
  6114                                 if (o.imageId  === image Uids[0] &&  o.frameNu mber == im ageUids[1] ) {
  6115                                      o.isDirt y = true;
  6116                                      return t rue;
  6117                                 }
  6118                             });
  6119                         }
  6120                    }
  6121  
  6122                    if(! isDirty) {
  6123                         isDirty =  isNewPStat eAddedInAn ExistingPS tate(study Uid);
  6124                    }
  6125                } else {
  6126                    isDi rty = isNe wPStateAdd edInAnExis tingPState (studyUid) ;
  6127                }
  6128  
  6129                updateDi rtyActiveP State(stud yDetails,  studyDiv,  isDirty);
  6130           }
  6131           ca tch(e)
  6132           {  }
  6133       }
  6134  
  6135       /**
  6136        * Che ck whether  the measu rement is  dirty or n ot
  6137        * @pa ram {Type}  values -  Specifies  the measur ement valu es
  6138        * @pa ram {Type}  studyUid  - Specifie s the stud y Uid
  6139        */ 
  6140       functi on isDirty PState(val ues, study Uid) {
  6141           tr y
  6142           {
  6143                var isDi rty = fals e;
  6144                values.s ome(functi on(o)
  6145                {
  6146                    if(o .studyUid  === studyU id && o.se ssionType  == 0) {
  6147                         isDirty =  true;
  6148                    }
  6149  
  6150                    retu rn isDirty ;
  6151                });
  6152           }
  6153           ca tch(e)
  6154           {  }
  6155  
  6156           re turn isDir ty;
  6157       }
  6158  
  6159       /**
  6160        * upd ate the di rty active  presentat ion state
  6161        * @pa ram {Type}  studyDeta ils - Spec ifies the  study deta ils
  6162        * @pa ram {Type}  studyDiv  - Specifie s the stud y layout i d
  6163        * @pa ram {Type}  isDirty -  Specifies  the flag  for dirty
  6164        */ 
  6165       functi on updateD irtyActive PState(stu dyDetails,  studyLayo utId, isDi rty) {
  6166           tr y
  6167           {
  6168                var acti vePStateNa me = study Details.PS tates.Acti ve.name ;
  6169                
  6170                var sele ctedPState Id = 0;
  6171                var menu Id = "#loa dPSSubmenu _"+studyLa youtId+"_" ;
  6172                studyDet ails.PStat es.All.som e(function (pState) {
  6173                    if(p State.id = == studyDe tails.PSta tes.Active .id) {
  6174                         selectedPS tateId = p State.menu Id;
  6175                         return tru e;
  6176                    }
  6177                });
  6178  
  6179                var inne rHtml = ($ (menuId +  selectedPS tateId)[0] .innerHTML ).replace( "*","");
  6180                var upda tedText =  isDirty ?  activePSta teName+"<f ont color= 'red' size =4>*</font >" : "<fon t color='w hite'>"+ac tivePState Name+"</fo nt>";
  6181                innerHtm l = innerH tml.replac e(studyDet ails.PStat es.Active. name,updat edText);
  6182                $(menuId  + selecte dPStateId) [0].innerH TML = inne rHtml;
  6183                studyDet ails.PStat es.Active. isDirty =  isDirty;
  6184                dicomVie wer.enable OrDisableP StatesMenu (studyDeta ils, study LayoutId);
  6185  
  6186                return t rue;
  6187           }
  6188           ca tch(e)
  6189           {  }
  6190  
  6191           re turn false ;
  6192       }
  6193  
  6194       /**
  6195        * Che ck whether  the new P State is a dded in an  existing  PState
  6196        * @pa ram {Type}  studyUid  - Specifie s the stud y Uid
  6197        */ 
  6198       functi on isNewPS tateAddedI nAnExistin gPState(st udyUid) {
  6199           tr y
  6200           {
  6201                var isAd ded = fals e;
  6202                var allM easurement PState = [ ];
  6203                allMeasu rementPSta te.push(di comImageMe asurements );
  6204                allMeasu rementPSta te.push(di comImageEl lipseMeasu rements);
  6205                allMeasu rementPSta te.push(di comImageRe ctangleMea surements) ;
  6206  
  6207                $.each(a llMeasurem entPState,  function( key, value s) {
  6208                    $.ea ch(values,  function( id, measur ementArray ) {
  6209                         isAdded =  isDirtyPSt ate(measur ementArray , studyUid );
  6210                         return (is Added == t rue ? fals e : true);
  6211                    });
  6212                    retu rn (isAdde d == true  ? false :  true);
  6213                });
  6214  
  6215                if(isAdd ed) {
  6216                    retu rn isAdded ;
  6217                }
  6218  
  6219                allMeasu rementPSta te = [];
  6220                allMeasu rementPSta te.push(di comImageAn gleMeasure ments);
  6221                allMeasu rementPSta te.push(di comImageTr aceMeasure ments);
  6222                allMeasu rementPSta te.push(di comImageMi tralGradie ntMeasurem ents);
  6223                allMeasu rementPSta te.push(di comImagePe nMeasureme nts);
  6224  
  6225                $.each(a llMeasurem entPState,  function( key, value s) {
  6226                    $.ea ch(values,  function( id, measur ementArray ) {
  6227                         measuremen tArray.som e(function (o) {
  6228                             isAdde d = isDirt yPState(o,  studyUid) ;
  6229                             return  isAdded;
  6230                         });
  6231                         return (is Added == t rue ? fals e : true);
  6232                    });
  6233                    retu rn (isAdde d == true  ? false :  true);
  6234                });
  6235  
  6236                if(isAdd ed) {
  6237                    retu rn isAdded ;
  6238                }
  6239           }
  6240           ca tch(e)
  6241           {  }
  6242  
  6243           re turn false ;
  6244       }
  6245  
  6246       /**
  6247        * Upd ate the ac tive PStat e descript ion
  6248        * @pa ram {Type}  descripti on - Speci fies the d escription
  6249        */ 
  6250       functi on updateA ctivePStat eDescripti on(descrip tion) {
  6251           tr y
  6252           {
  6253                var view port = dic omViewer.g etActiveSe riesLayout ();
  6254                if(viewp ort == und efined ||  viewport = = null) {
  6255                    retu rn;
  6256                }
  6257  
  6258                var stud yUid = vie wport.stud yUid;
  6259                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  6260                if(study Details ==  undefined  || studyD etails ==  null) {
  6261                    retu rn;
  6262                }
  6263  
  6264                if(study Details.PS tates == u ndefined | | studyDet ails.PStat es == null ) {
  6265                    retu rn;
  6266                }
  6267  
  6268                var isDi rty = fals e;
  6269                var acti vePState =  studyDeta ils.PState s.Active;
  6270                activePS tate.descr iption = d escription ;
  6271                studyDet ails.PStat es.All.som e(function (o) {
  6272                    if(a ctivePStat e.descript ion !== o. descriptio n && activ ePState.id  == o.id)  {
  6273                         isDirty =  true;
  6274                         return tru e;
  6275                    }
  6276                });
  6277  
  6278                studyDet ails.PStat es.Active. isDescript ionUpdated  = isDirty ;
  6279                var imag eRender =  viewport.i mageRender s;
  6280                for (var  key in im ageRender)  {
  6281                    var  render = i mageRender [key];
  6282                    var  frameIndex  = render. anUIDs.spl it("*")[1] ;
  6283                    upda teDirtyPSt ate(render .seriesLev elDivId,
  6284                                        { key:  render.im ageUid + " _" + frame Index },
  6285                                        false,
  6286                                        true);
  6287                }
  6288           }
  6289           ca tch(e)
  6290           {  }
  6291       }
  6292  
  6293       /**
  6294        * upd ate the ne w dirty ac tive state
  6295        * @pa ram {Type}  studyDeta ils - Spec ifies the  study deta ils
  6296        */ 
  6297       functi on updateN ewDirtyAct ivePState( studyDetai ls) {
  6298           tr y
  6299           {
  6300                if(study Details.PS tates.Acti ve.isNew ! == true) {
  6301                    retu rn;
  6302                }
  6303  
  6304                studyDet ails.PStat es.Active. isDirty =  !isEmptyPS tate(study Details.st udyUid);
  6305                if(study Details.PS tates.All. length ==  1 && study Details.PS tates.Acti ve.isDirty  == false)  {
  6306                    stud yDetails.P States = u ndefined;
  6307                }
  6308  
  6309                dicomVie wer.update PState(stu dyDetails. studyUid);
  6310           }
  6311           ca tch(e)
  6312           {  }
  6313       }
  6314  
  6315       /**
  6316        * Che ck whether  the PStat es are emp ty or not
  6317        * @pa ram {Type}  values -  Specifies  the measur ement valu es
  6318        * @pa ram {Type}  studyUid  - Specifie s the stud y Uid
  6319        */ 
  6320       functi on isEmpty PStates(va lues, stud yUid) {
  6321           tr y
  6322           {
  6323                var isEm pty = true ;
  6324                values.s ome(functi on(o)
  6325                {
  6326                    if(o .studyUid  === studyU id) {
  6327                         isEmpty =  false;
  6328                    }
  6329  
  6330                    retu rn (isEmpt y == true  ? false :  true);
  6331                });
  6332           }
  6333           ca tch(e)
  6334           {  }
  6335  
  6336           re turn isEmp ty;
  6337       }
  6338  
  6339       /**
  6340        * Che ck whether  the PStat e is empty  or not
  6341        * @pa ram {Type}  studyUid  - Specifie s the stud y Uid
  6342        */ 
  6343       functi on isEmpty PState(stu dyUid) {
  6344           tr y
  6345           {
  6346                var isEm pty = true ;
  6347                var allM easurement PState = [ ];
  6348                allMeasu rementPSta te.push(di comImageMe asurements );
  6349                allMeasu rementPSta te.push(di comImageEl lipseMeasu rements);
  6350                allMeasu rementPSta te.push(di comImageRe ctangleMea surements) ;
  6351  
  6352                $.each(a llMeasurem entPState,  function( key, value s) {
  6353                    if(j Query.isEm ptyObject( values)) {
  6354                         return tru e;
  6355                    }
  6356  
  6357                    $.ea ch(values,  function( id, measur ementArray ) {
  6358                         if(jQuery. isEmptyObj ect(measur ementArray )) {
  6359                             return  true;
  6360                         }
  6361  
  6362                         isEmpty =  isEmptyPSt ates(measu rementArra y, studyUi d);
  6363                         return isE mpty;
  6364                    });
  6365  
  6366                    retu rn isEmpty ;
  6367                });
  6368  
  6369                if(!isEm pty) {
  6370                    retu rn isEmpty ;
  6371                }
  6372  
  6373                allMeasu rementPSta te = [];
  6374                allMeasu rementPSta te.push(di comImageAn gleMeasure ments);
  6375                allMeasu rementPSta te.push(di comImageTr aceMeasure ments);
  6376                allMeasu rementPSta te.push(di comImageMi tralGradie ntMeasurem ents);
  6377                allMeasu rementPSta te.push(di comImagePe nMeasureme nts);
  6378  
  6379                $.each(a llMeasurem entPState,  function( key, value s) {
  6380                    if(j Query.isEm ptyObject( values)) {
  6381                         return tru e;
  6382                    }
  6383  
  6384                    $.ea ch(values,  function( id, measur ementArray ) {
  6385                         if(jQuery. isEmptyObj ect(measur ementArray )) {
  6386                             return  true;
  6387                         }
  6388  
  6389                         measuremen tArray.som e(function (o) {
  6390                             isEmpt y = isEmpt yPStates(o , studyUid );
  6391                             return  (isEmpty  == true ?  false : tr ue);
  6392                         });
  6393  
  6394                         return isE mpty;
  6395                    });
  6396  
  6397                    retu rn isEmpty ;
  6398                });
  6399  
  6400                if(!isEm pty) {
  6401                    retu rn isEmpty ;
  6402                }
  6403           }
  6404           ca tch(e)
  6405           {  }
  6406  
  6407           re turn true;
  6408       }
  6409  
  6410       /**
  6411        * Ret urn the po sition(i.e . left, ri ght or top -left) of  the hounsf ield measu rement tex t
  6412        * @pa ram {Type}  data - St art and En d value of  the houns field shap e(Ellipse/ Rectangle)
  6413        */
  6414       functi on hounsfi eldTextPos ition(data , renderer ) {
  6415           st artPoint =  {
  6416                    x :  data.start .x,
  6417                    y :  data.start .y
  6418           };
  6419           va r pos = "r ight";
  6420           va r widget =  renderer. getRenderW idget();
  6421           if ((startPoi nt.x >= wi dget.width /2) && (st artPoint.y  >= widget .height/2) ) {
  6422                pos = "t op-left";
  6423           }  else if(st artPoint.y  >= widget .height/2)  {
  6424                pos = "t op";
  6425           }  else if(st artPoint.x  >= widget .width/2)  {
  6426                pos = "l eft";
  6427           }
  6428           re turn pos;
  6429       }
  6430  
  6431        /**
  6432        * Ret urn the po sition(i.e . left, ri ght or top -left) of  the hounsf ield measu rement tex t
  6433        * @pa ram {Type}  data - St art and En d value of  the point , angle sh ape(Point/ Angle)
  6434        */
  6435       functi on pointTe xtPosition (data, ren derer) {
  6436           va r point =  data.end;
  6437           if (!data.end .x){
  6438                point =  data.start ;
  6439           }
  6440  
  6441           st artPoint =  {
  6442                    x :  point.x,
  6443                    y :  point.y
  6444           };
  6445           va r pos = "r ight";
  6446           va r widget =  renderer. getRenderW idget();
  6447  
  6448           va r headerIn fo = rende rer.header Info
  6449           if (headerInf o && heade rInfo.imag eInfo) {
  6450                var  ima geHeight =  headerInf o.imageInf o.imageHei ght;
  6451                var  ima geWidth =  headerInfo .imageInfo .imageWidt h;
  6452  
  6453                var scal eValue = r enderer.sc aleValue;
  6454                var imag eCanvas_H  = imageHei ght * scal eValue;
  6455                var imag eCanvas_W  = imageWid th * scale Value;
  6456                var diff _W = widge t.width -  imageCanva s_W;
  6457                var diff _H = widge t.height -  imageCanv as_H;
  6458  
  6459                var pos  = "right";
  6460                if(start Point.x >=  (diff_W/2  + imageCa nvas_W/2))  {
  6461                    pos  = "left";
  6462                } else i f(startPoi nt.y >= (d iff_H/2 +  imageCanva s_H/2)) {
  6463                    pos  = "top";
  6464                }
  6465           }
  6466           re turn pos;
  6467  
  6468       }
  6469       
  6470       /**
  6471        * set  the flag  if measure ment is ed ited
  6472        */ 
  6473       functi on isEditM easurement () {
  6474           re turn isMea surementEd it;
  6475       }
  6476  
  6477       /**
  6478        * Add  the drawn  measureme nts
  6479        * @pa ram {Type}  imageUid 
  6480        * @pa ram {Type}  frameInde
  6481        * @pa ram {Type}  imageRend erer 
  6482        * @pa ram {Type}  mosueData  
  6483        * @pa ram {Type}  context 
  6484        */ 
  6485       functi on addPenM easurement s(imageUid , frameInd ex, imageR enderer, m osueData,  context) {
  6486           re moveTempda ta();
  6487           if  (imageRen derer ===  undefined)  {
  6488                throw "a ddMitralGr adientMeas urements :  imageRend erer is nu ll/undefin ed";
  6489           }
  6490  
  6491           va r penMeasu rements =  dicomImage PenMeasure ments[imag eUid + "_"  + frameIn dex];
  6492  
  6493           if (penMeasur ements ===  undefined ) {
  6494                penMeasu rements =  [];
  6495           }
  6496           va r measurem ents = pen Measuremen ts[mosueDa ta.measure mentIndex] ;
  6497           if  (measurem ents === u ndefined)  {
  6498                measurem ents = [];
  6499           }
  6500           va r imageDat a = getIma geDataForM ouseData(m osueData,  imageRende rer, conte xt);
  6501           va r measureL ength = me asurements .length;
  6502           me asurements [measureLe ngth] = im ageData;
  6503           if  (!mitralM eanGradien tMeasureme ntEnd) {
  6504                for (i =  0; i < me asureLengt h; i++) {
  6505                    meas urements[i ].editMode  = false;
  6506                }
  6507           }
  6508           pe nMeasureme nts[mosueD ata.measur ementIndex ] = measur ements;
  6509           di comImagePe nMeasureme nts[imageU id + "_" +  frameInde x] = penMe asurements ;
  6510  
  6511           mo sueData =  undefined;  // Releas e the memo ry for the  data 
  6512           im ageData =  undefined;  // Releas e the memo ry for the  data
  6513  
  6514           up dateDirtyP State(imag eRenderer. seriesLeve lDivId);
  6515       }
  6516       
  6517       /**
  6518        * Get  the drawn  measuremn ts
  6519        * @pa ram {Type}  imageUid 
  6520        * @pa ram {Type}  frameInde
  6521        */ 
  6522       functi on getPenM easurement s(imageUid , frameInd ex) {
  6523           if  (imageUid  === undef ined) {
  6524                throw "g etMitralGr adientMeas urements:  imageUid i s null/und efined";
  6525           }
  6526           if  (frameInd ex === und efined) {
  6527                throw "g etMitralGr adientMeas urements :  frameInde x is null/ undefined" ;
  6528           }
  6529           re turn dicom ImagePenMe asurements [imageUid  + "_" + fr ameIndex];
  6530       }
  6531  
  6532       /**
  6533        * Fin d the mous e postion  is near th e drawn pe n measurem ent to del ete.
  6534        * @pa ram {Type}  mouseData  
  6535        * @pa ram {Type}  imageRend erer 
  6536        */ 
  6537       functi on findPen ToDelete(m ouseData,  imageRende rer){
  6538           is PenDelete  = true;
  6539           ac tiveImageR enderer =  undefined;
  6540           re moveTempda ta();
  6541           va r measurem entKey = i mageRender er.anUIDs. replace("* ","_");
  6542  
  6543           va r penMeasu rements =  dicomImage PenMeasure ments[meas urementKey ];
  6544           if  (penMeasu rements != = undefine d) {
  6545                for (var  n = 0; n  < penMeasu rements.le ngth; n++)  {
  6546                    var  measuremen ts = penMe asurements [n];
  6547                    if ( measuremen ts !== und efined) {
  6548                         for (var m  = 0; m <  measuremen ts.length;  m++) {
  6549                             var da ta = measu rements[m] ;
  6550                             if (da ta !== und efined &&  data.measu reType ==  "pen") {
  6551                                 va r original LineDistan ce = getLe ngth(data) ;
  6552  
  6553                                 va r tempData  = {
  6554                                      start: {
  6555                                          x: d ata.start. x,
  6556                                          y: d ata.start. y
  6557                                      },
  6558                                      end: {
  6559                                          x: m ouseData.x ,
  6560                                          y: m ouseData.y
  6561                                      },
  6562                                      measureT ype: "pen"
  6563                                 };
  6564                                 va r firstDis tance = ge tLength(te mpData);
  6565  
  6566                                 va r tempData 2 = {
  6567                                      start: {
  6568                                          x: m ouseData.x ,
  6569                                          y: m ouseData.y
  6570                                      },
  6571                                      end: {
  6572                                          x: d ata.end.x,
  6573                                          y: d ata.end.y
  6574                                      },
  6575                                      measureT ype: "pen"
  6576                                 };
  6577  
  6578                                 va r secondDi stance = g etLength(t empData2);
  6579  
  6580                                 va r totalDis tance = pa rseInt(fir stDistance ) + parseI nt(secondD istance);
  6581                                 if  (Math.abs (totalDist ance - ori ginalLineD istance) <  5) {
  6582                                      dataToDe lete.measu rmentType  = "pen";
  6583                                      dataToDe lete.key =  measureme ntKey;
  6584                                      dataToDe lete.arryI ndex = n;
  6585                                      dataToDe lete.isEdi table = da ta.isEdita ble;
  6586                                      dataToDe lete.sessi onType = d ata.sessio nType;
  6587                                      activeIm ageRendere r = imageR enderer;
  6588                                      return;
  6589                                 }
  6590                             }
  6591                         }
  6592                    }
  6593                }
  6594           }
  6595  
  6596           if  (activeIm ageRendere r === unde fined && i sLineDelet eCheck ===  false) {
  6597                findLine ToDelete(m ouseData,  imageRende rer)
  6598           }  else if (a ctiveImage Renderer = == undefin ed && isPo intDeleteC heck === f alse) {
  6599                findPoin tToDelete( mouseData,  imageRend erer)
  6600           }  else if (a ctiveImage Renderer = == undefin ed && isTr aceDeleteC heck === f alse) {
  6601                findTrac eToDelete( mouseData,  imageRend erer)
  6602           }  else if (a ctiveImage Renderer = == undefin ed && isVo lumeDelete Check ===  false) {
  6603                findVolu meToDelete (mouseData , imageRen derer)
  6604           }  else if (a ctiveImage Renderer = == undefin ed && isAn gleDeleteC heck === f alse) {
  6605                findAngl eToDelete( mouseData,  imageRend erer)
  6606           }  else if (a ctiveImage Renderer = == undefin ed && isEl lipseDelet eCheck ===  false) {
  6607                findElli pseToDelet e(mouseDat a, imageRe nderer)
  6608           }  else if (a ctiveImage Renderer = == undefin ed && isRe ctangleDel eteCheck = == false)  {
  6609                findRect angleToDel ete(mouseD ata, image Renderer)
  6610           }  else if (a ctiveImage Renderer = == undefin ed) {
  6611                dataToDe lete = {
  6612                    meas urmentType : "",
  6613                    key:  "",
  6614                    arry Index: "",
  6615                    isEd itable: "" ,
  6616                    sess ionType: 0
  6617                };
  6618           }
  6619       }
  6620  
  6621       var Pe nMeasureme ntId = -1;
  6622       /**
  6623        * set  the no.of  measuremt s drawn in  pen.
  6624        * @pa ram {Type}  Id -  it  specifies  the intege r.
  6625        */ 
  6626       functi on setPenM easurement Id(Id) {
  6627           Pe nMeasureme ntId = Id;
  6628       }
  6629  
  6630       /**
  6631       * get  the count  of the dra wn measure ments
  6632       */ 
  6633       functi on getPenM easurement Id() {
  6634           re turn PenMe asurementI d;
  6635       }
  6636  
  6637       /**
  6638        * Upd ate the pe n measurem ents in to  the array
  6639        * @pa ram {Type}  mouseData  
  6640        * @pa ram {Type}  imageRend erer 
  6641        * @pa ram {Type}  context 
  6642        * @pa ram {Type}  dataToEdi
  6643        */ 
  6644       functi on updateP enintoArra y(mouseDat a, imageRe nderer, co ntext, dat aToEdit) {
  6645           va r imageDat a = dicomV iewer.meas urement.dr aw.getImag eCoordinat esForMouse Point(mous eData, ima geRenderer , context) ;
  6646           va r i;
  6647           va r data = u ndefined;
  6648           va r key = da taToEdit.k ey;
  6649           va r arrayInd ex = dataT oEdit.arry Index;
  6650           va r parentDi v = $('#'+ imageRende rer.parent Element).p arent().cl osest('div ').attr('i d');
  6651           va r measurem ents = dic omImagePen Measuremen ts[key];
  6652  
  6653           if (measureme nts === un defined)
  6654                return;
  6655  
  6656           up dateDirtyP State(imag eRenderer. seriesLeve lDivId, da taToEdit);
  6657           me asurements  = measure ments[arra yIndex];
  6658           da ta = dicom ImagePenMe asurements [key][arra yIndex];
  6659           fo r (var ind ex = index ToEditMitr al; index  < data.len gth; index ++) {
  6660                var temp Data = dat a[index];
  6661                if (temp Data !== u ndefined)  {
  6662                    var  isNearToSt artPoint =  findNearH anleByPoin t(imageDat a, tempDat a.start);
  6663                    if ( isNearToSt artPoint & & index ==  0) {
  6664                         tempData.s tart.x = i mageData.x ;
  6665                         tempData.s tart.y = i mageData.y ;
  6666                         indexToEdi tMitral =  index;
  6667                         index = da ta.length;
  6668                    } 
  6669                    else  if (isNea rToStartPo int && ind ex == data .length -  1 && tempD ata.measur ementSubTy pe == "pen "){
  6670                         tempData.s tart.x = i mageData.x ;
  6671                         tempData.s tart.y = i mageData.y ;
  6672                         tempData.e nd.x = ima geData.x;
  6673                         tempData.e nd.y = ima geData.y;
  6674                         data[index  - 1].end. x = imageD ata.x;
  6675                         data[index  - 1].end. y = imageD ata.y;
  6676                         dicomImage MitralGrad ientMeasur ements[key ][arrayInd ex] = data ;
  6677                         indexToEdi tMitral =  index;
  6678                         index = da ta.length;
  6679                    } el se if (isN earToStart Point){
  6680                         tempData.s tart.x = i mageData.x ;
  6681                         tempData.s tart.y = i mageData.y ;
  6682                         data[index  - 1].end. x = imageD ata.x;
  6683                         data[index  - 1].end. y = imageD ata.y;
  6684                         dicomImage PenMeasure ments[key] [arrayInde x] = data;
  6685                         indexToEdi tMitral =  index;
  6686                         index = da ta.length;
  6687                    }
  6688                }
  6689                tempData .editMode  = true;
  6690           }
  6691       }
  6692  
  6693       /**
  6694        * Loa d the Mitr al Gradien t measurem ent
  6695        * @pa ram {Type}  imageKey  - Specifie s the imag e key
  6696        * @pa ram {Type}  measureme ntKey - Sp ecifies th e measurem ent key* 
  6697        * @pa ram {Type}  measureme nt - Speci fies the m easurement  array
  6698        * @pa ram {Type}  isEditabl e - Specif ies the fl ag to edit  the measu rement/ann otation
  6699        */ 
  6700       functi on loadPen Measuremen t(imageKey , measurem entKey, me asurement,  isEditabl e) {
  6701           tr y
  6702           {
  6703                if(image Key === un defined ||  measureme nt === und efined) {
  6704                    // I nvalid inp ut paramet ers
  6705                    retu rn;
  6706                }
  6707  
  6708                var poin ts = measu rement.poi nts;
  6709                if(point s === unde fined || p oints ===  null || po ints.lengt h == 0) {
  6710                    retu rn;
  6711                }
  6712  
  6713                var meas urementSub Type = und efined;
  6714                var meas urementTyp e = undefi ned;
  6715  
  6716                switch(m easurement Key) {
  6717                    case  MT_PEN:
  6718                         measuremen tSubType =  "pen";
  6719                         measuremen tType = 15 ;
  6720                         break;
  6721                }
  6722  
  6723                var penM easurement s = dicomI magePenMea surements[ imageKey];
  6724                if (penM easurement s === unde fined) {
  6725                    penM easurement s = [];
  6726                }
  6727  
  6728                var meas urementId  = penMeasu rements.le ngth;
  6729                var meas urements =  penMeasur ements[mea surementId ];
  6730                if (meas urements = == undefin ed) {
  6731                    meas urements =  [];
  6732                }
  6733  
  6734                var star t = {};
  6735                var end  = {};
  6736                for(var  index = 0;  index < p oints.leng th; index+ =4) {
  6737                    var  start = 
  6738                         {
  6739                             handle Active: fa lse,
  6740                             x: par seFloat(po ints[index ]),
  6741                             y: par seFloat(po ints[index +1])
  6742                         };
  6743  
  6744                    var  end =
  6745                         {
  6746                             handle Active: fa lse,
  6747                             x: par seFloat(po ints[index +2]),
  6748                             y: par seFloat(po ints[index +3])
  6749                         };
  6750  
  6751                    var  measuremen tData =
  6752                         {
  6753                             start:  start,
  6754                             end: e nd,
  6755                             measur eType: "pe n",
  6756                             measur ementSubTy pe: measur ementSubTy pe,
  6757                             measur ementId: m easurement Id,
  6758                             measur ementCompl ete: true,
  6759                             measur ementType:  measureme ntType,
  6760                             measur ementUnits : undefine d,
  6761                             editMo de: false,
  6762                             studyU id: measur ement.stud yUid,
  6763                             isEdit able: isEd itable,
  6764                             sessio nType: 1,
  6765                             style  : getGrpah icStyle(me asurement,  undefined , isEditab le)
  6766                         };
  6767  
  6768                    meas urements.p ush(measur ementData) ;
  6769                }
  6770  
  6771                penMeasu rements[me asurementI d] = measu rements;
  6772                dicomIma gePenMeasu rements[im ageKey] =  penMeasure ments;
  6773           }
  6774           ca tch(e)
  6775           {  }
  6776       }
  6777       
  6778       /**
  6779        * Get s ImageUid  from Imag eUrn
  6780        */ 
  6781       functi on getImag eUidFromUr n (studyDe tails, pSt ate) {
  6782           if  (pState.i mageUrn == = undefine d || pStat e.imageUrn  === null)  {
  6783                return p State.imag eId;
  6784           }  else if (s tudyDetail s.imageUrn s !== null  && studyD etails.ima geUrns !==  undefined ) {
  6785                return s tudyDetail s.imageUrn s[pState.i mageUrn];
  6786           }
  6787       }
  6788       
  6789       /**
  6790        * Get s ImageUrn  from Imag eUid
  6791        */ 
  6792       functi on getImag eUrnFromUI d (studyDe tails, ima geUid) {
  6793           va r imageUrn  = undefin ed;
  6794           if  (studyDet ails.image Urns !== n ull && stu dyDetails. imageUrns  !== undefi ned) {
  6795                $.each(s tudyDetail s.imageUrn s, functio n(key, val ue) {
  6796                    if ( value ===  imageUid)  {
  6797                         imageUrn =  key;
  6798                         return fal se;
  6799                    }
  6800                });
  6801                return i mageUrn;
  6802           }
  6803       }
  6804       
  6805       /**
  6806        * Set  the defau lt global  measuremen t style ke y/value pa ir
  6807        * @pa ram {Type}  styleCol  - Specifie s the styl e color
  6808        * @pa ram {Type}  type - Sp ecifies th e type
  6809        * @pa ram {Type}  isFailed  - Specifie s the serv er status  flag
  6810        */ 
  6811       functi on setDefa ultStyleCo l(styleCol , type, is Failed) {
  6812           tr y
  6813           {
  6814                $.each(M T_PS_TypeC ol, functi on(key, va lue) {
  6815                    valu e = (type  == "SYSTEM ") ? ("sys " + value)  : value;
  6816                    var  useDefault  = isFaile d ? false  : true;
  6817                    dico mViewer.me asurement. draw.setUs erMeasurem entStyleBy Type(value , useDefau lt, styleC ol);
  6818                });
  6819           }
  6820           ca tch(e)
  6821           {  }
  6822       }
  6823  
  6824       /**
  6825        * Get  correspon ding enum  value for  respective  measureme nt type or  subtype
  6826        * @pa ram {Type}  measureTy pe 
  6827        * @pa ram {Type}  measureSu bType 
  6828        */ 
  6829       functi on getEnum MT(measure Type, meas ureSubType ) {
  6830           if (measureTy pe == "lin e") {
  6831                if(measu reSubType  == "2DLeng th") {
  6832                    retu rn "LENGTH ";
  6833                } else i f (measure SubType ==  "2DLine")  {
  6834                    retu rn "LINE";
  6835                } else i f(measureS ubType ==  "Arrow") {
  6836                    retu rn "ARROW" ;
  6837                } else i f(measureS ubType ==  "mitralReg urgitation Length") {
  6838                    retu rn "MRL";
  6839                } else i f(measureS ubType ==  "aorticReg urgitation Length") {
  6840                    retu rn "ARL";
  6841                } else i f(measureS ubType ==  "mitralVal veAnterior LeafletThi ckness") {
  6842                    retu rn "MVALT" ;
  6843                }
  6844                return " LENGTH";
  6845           }
  6846           if (measureTy pe == "rec tangle") {
  6847                if(measu reSubType  == "hounsf ield") {
  6848                    retu rn "HOUNSF IELDRECT";
  6849                } else i f(measureS ubType ==  "rectangle ") {
  6850                    retu rn "RECT";
  6851                } else i f(measureS ubType ==  "text") {
  6852                    retu rn "TEXT";
  6853                }
  6854           }
  6855           if (measureTy pe == "ell ipse") {
  6856                if(measu reSubType  == "hounsf ield") {
  6857                    retu rn "HOUNSF IELDELLIPS E";
  6858                } else i f(measureS ubType ==  "ellipse")  {
  6859                    retu rn "ELLIPS E";
  6860                }
  6861           }
  6862           if (measureTy pe == "poi nt") {
  6863                if(measu reSubType  == "mitral Regurgitat ionPeakVel ocity") {
  6864                    retu rn "MRPV";
  6865                } else i f(measureS ubType ==  "aorticReg urgitation PeakVeloci ty") {
  6866                    retu rn "ARPV";
  6867                } else i f(measureS ubType ==  "aorticSte nosisPeakV elocity")  {
  6868                    retu rn "ASPV";
  6869                }
  6870                return " POINT";
  6871           }
  6872           if (measureTy pe == "ang le") {
  6873                return " ANGLE";
  6874           }
  6875           if (measureTy pe == "tra ce") {
  6876                return " TRACE";
  6877           }
  6878           if (measureTy pe == "mit ralGradien t") {
  6879                if(measu reSubType  == "mitral ") {
  6880                    retu rn "MRL";
  6881                } else i f(measureS ubType ==  "freehand" ) {
  6882                    retu rn "FREEHA ND";
  6883                }
  6884           }
  6885           if (measureTy pe == "pen ") {
  6886                return " PEN";
  6887           }
  6888       }
  6889  
  6890       dicomV iewer.meas urement =  {
  6891           ge tMeasureme nts: getMe asurements ,
  6892           ad dMeasureme nts: addMe asurements ,
  6893           up dateMeasur ements: up dateMeasur ements,
  6894           ge tTraceMeas urements:  getTraceMe asurements ,
  6895           ad dTraceMeas urements:  addTraceMe asurements ,
  6896           up dateTraceM easurement s: updateT raceMeasur ements,
  6897           ge tEllipseMe asurements : getEllip seMeasurem ents,
  6898           ad dEllipseMe asurements : addEllip seMeasurem ents,
  6899           up dateEllips eMeasureme nts: updat eEllipseMe asurements ,
  6900           up dateTraceI ntoArray:  updateTrac eIntoArray ,
  6901           up dateAngleI ntoArray:  updateAngl eIntoArray ,
  6902           ge tVolumeMea surements:  getVolume Measuremen ts,
  6903           ad dVolumeMea surements:  addVolume Measuremen ts,
  6904           ad dMitralGra dientMeasu rements: a ddMitralGr adientMeas urements,
  6905           ge tMitralGra dientMeasu rements: g etMitralGr adientMeas urements,
  6906           re moveAllMea surements:  removeAll Measuremen ts,
  6907           se tTempData:  setTempDa ta,
  6908           ge tTempData:  getTempDa ta,
  6909           fi ndNearHand le: findNe arHandle,
  6910           ge tMouseData ForImageDa ta: getMou seDataForI mageData,
  6911           ge tImageData ForMouseDa ta: getIma geDataForM ouseData,
  6912           ge tCanvasDat aForImageD ata: getCa nvasDataFo rImageData ,
  6913           se tImageCont ext: setIm ageContext ,
  6914           ge tImageCont ext: getIm ageContext ,
  6915           se tLineMeasu rementEnd:  setLineMe asurementE nd,
  6916           se tTraceMeas urementEnd : setTrace Measuremen tEnd,
  6917                    setV olumeMeasu rementEnd:  setVolume Measuremen tEnd,
  6918           se tMitralMea nGradientM easurement End: setMi tralMeanGr adientMeas urementEnd ,
  6919           is LineMeasur ementEnd:  isLineMeas urementEnd ,
  6920           is TraceMeasu rementEnd:  isTraceMe asurementE nd,
  6921           is VolumeMeas urementEnd : isVolume Measuremen tEnd,
  6922           is MitralMean GradientMe asurementE nd: isMitr alMeanGrad ientMeasur ementEnd,
  6923           se tTraceMeas urementId:  setTraceM easurement Id,
  6924           se tMitralMea nGradientM easurement Id: setMit ralMeanGra dientMeasu rementId,
  6925           ge tTraceMeas urementId:  getTraceM easurement Id,
  6926           se tVolumeMea surementId : setVolum eMeasureme ntId,
  6927           ge tVolumeMea surementId : getVolum eMeasureme ntId,
  6928           ge tMitralMea nGradientM easurement Id: getMit ralMeanGra dientMeasu rementId,
  6929                    upda teMitralMe anGradient intoArray:  updateMit ralMeanGra dientintoA rray,
  6930           fi ndLineToDe lete: find LineToDele te,
  6931           fi ndPointToD elete: fin dPointToDe lete,
  6932           fi ndAngleToD elete: fin dAngleToDe lete,
  6933           fi ndTraceToD elete: fin dTraceToDe lete,
  6934                    find MitralToDe lete: find MitralToDe lete,
  6935           de leteSelect edMeasurme nt: delete SelectedMe asurment,
  6936           fi ndVolumeTo Delete: fi ndVolumeTo Delete,
  6937           re setMeasure mentFlag:  resetMeasu rementFlag ,
  6938           se tDataToEdi t: setData ToEdit,
  6939           ge tDataToEdi t: getData ToEdit,
  6940           ge tDataToDel ete: getDa taToDelete ,
  6941           fi ndNearHand leToEdit:  findNearHa ndleToEdit ,
  6942                    rese tHandeler  : resetHan deler,
  6943                    remo veTempdata  : removeT empdata,
  6944           up dateVolume intoArray  : updateVo lumeintoAr ray,
  6945                    setD ataToDelet e : setDat aToDelete,
  6946           is Measuremen tBroken :  isMeasurem entBroken,
  6947           se tMeasureme ntBroken :  setMeasur ementBroke n,
  6948           ge tAngleMeas urements:  getAngleMe asurements ,
  6949           se tAngleMeas urementEnd : setAngle Measuremen tEnd,
  6950           is AngleMeasu rementEnd:  isAngleMe asurementE nd,
  6951           se tAngleMeas urementId:  setAngleM easurement Id,
  6952           ge tAngleMeas urementId:  getAngleM easurement Id,
  6953           ad dAngleMeas urements:  addAngleMe asurements ,
  6954           re setMousePr essedCount er: resetM ousePresse dCounter,
  6955           ge tMousePres sedCounter : getMouse PressedCou nter,
  6956           in creaseMous ePressedCo unter: inc reaseMouse PressedCou nter,
  6957                    setC oordinate:  setCoordi nate,
  6958           ge tCoordinat e: getCoor dinate,
  6959           fi ndEllipseT oDelete: f indEllipse ToDelete,
  6960           ge tDefaultLi neMeasurem entUnit:ge tDefaultLi neMeasurem entUnit,
  6961           is CalibrateP ixelSpacin g : isCali bratePixel Spacing,
  6962           re setEllipse EditMode:  resetEllip seEditMode ,
  6963           re setAngleEd itMode: re setAngleEd itMode,
  6964           re setTraceEd itMode: re setTraceEd itMode,
  6965           re setMitralE ditMode: r esetMitral EditMode,
  6966           ge tRectangle Measuremen ts: getRec tangleMeas urements,
  6967           ad dRectangle Measuremen ts: addRec tangleMeas urements,
  6968           up dateRectan gleMeasure ments: upd ateRectang leMeasurem ents,
  6969           re setRectang leEditMode : resetRec tangleEdit Mode,
  6970           fi ndRectangl eToDelete:  findRecta ngleToDele te,
  6971           sa vePState:  savePState ,
  6972           lo adPState:  loadPState ,
  6973           ed itPState:  editPState ,
  6974           up dateMeasur ementTextD ata: updat eMeasureme ntTextData ,
  6975           ne wPState: n ewPState,
  6976           de letePState : deletePS tate,
  6977           sa veOrDelete UnSavedPSt ate: saveO rDeleteUnS avedPState ,
  6978           ge tSessionTy pe: getSes sionType,
  6979           se tSessionTy pe: setSes sionType,
  6980           is Measuremen tDrawable:  isMeasure mentDrawab le,
  6981           up dateActive PStateDesc ription :  updateActi vePStateDe scription,
  6982           ho unsfieldTe xtPosition  : hounsfi eldTextPos ition,
  6983           is EditMeasur ement : is EditMeasur ement,
  6984           sh owAndHideS plashWindo w : showAn dHideSplas hWindow,
  6985           po intTextPos ition: poi ntTextPosi tion,
  6986           se tPenToolEn d : setPen ToolEnd,
  6987           is PenToolEnd  : isPenTo olEnd,
  6988           ad dPenMeasur ements: ad dPenMeasur ements,
  6989           ge tPenMeasur ements: ge tPenMeasur ements,
  6990           fi ndPenToDel ete: findP enToDelete ,
  6991           up datePenint oArray: up datePenint oArray,
  6992           ge tPenMeasur ementId: g etPenMeasu rementId,
  6993           se tPenMeasur ementId: s etPenMeasu rementId,
  6994           ud pateMeasur ementPrope rty: udpat eMeasureme ntProperty ,
  6995           se tDefaultSt yleCol: se tDefaultSt yleCol,
  6996           ge tEnumMT: g etEnumMT
  6997       }
  6998  
  6999       return  dicomView er;
  7000   }(dicomVie wer));/**
  7001    * New nod e file
  7002    */
  7003   var dicomV iewer = (f unction(di comViewer)  {
  7004  
  7005       if (di comViewer  === undefi ned) {
  7006           di comViewer  = {};
  7007       }
  7008  
  7009       var li neStatus =  "added";
  7010  
  7011       var ph ysicalUnit sXYDirecti onArray =  ["none", " %", "dB",  "cm", "sec ", "hertz" , "dB/sec" , "cm/sec" , "cm\u00B 2", "cm\u0 0B2/sec",  "cm\u00B3" , "cm\u00B 3/sec", "\ u00B0"];
  7012       
  7013       var me asurementI d = null;
  7014  
  7015       var me asurementT ype = -1;
  7016  
  7017       var me asurementU nits = nul l;
  7018  
  7019       var us erStyle =  {
  7020           li neColor :  "#00FFFF",
  7021           li neWidth :  1,
  7022           fo ntName: "A rial",
  7023           fo ntSize: 12 ,
  7024           te xtColor: " #00FFFF",
  7025           is Bold: fals e,
  7026           is Italic: fa lse,
  7027           is Underlined : false,
  7028           is Strikeout:  false,
  7029           is Fill: fals e,
  7030           fi llColor: " #00FFFF",
  7031           ga ugeLength:  7,
  7032           ga ugeStyle:  "Line",
  7033           pr ecision: 2 ,
  7034           me asurementU nits: "cm" ,
  7035           ar cRadius: 2 0
  7036       };
  7037       
  7038       // Use r Measurem ent Style  key/value  pair
  7039       var us erMeasurem entStyleCo l = {};
  7040  
  7041       var sm oothConfig  = {
  7042           me thod: 'cub ic',
  7043           cl ip: 'perio dic',
  7044           la nczosFilte rSize: 2,
  7045           cu bicTension : 0
  7046         };
  7047  
  7048       /**
  7049        *Set  the user m easurement  style key /value pai r
  7050        */
  7051       functi on setUser Measuremen tCol(measu rementStyl eCol) {
  7052           tr y
  7053           {
  7054                userMeas urementSty leCol = me asurementS tyleCol;
  7055           }
  7056           ca tch(e)
  7057           {  }
  7058       }
  7059       
  7060       /**
  7061        *Set  the user m easurement  style by  type
  7062        */
  7063       functi on setUser Measuremen tStyleByTy pe(type, u seDefault,  styleCol)  {
  7064           tr y
  7065           {
  7066                if (user Measuremen tStyleCol  === undefi ned || use rMeasureme ntStyleCol  === null)  {
  7067                    user Measuremen tStyleCol  = {};
  7068                }
  7069                var meas urementSty le = {
  7070                    useD efault: us eDefault,
  7071                    styl eCol: styl eCol
  7072                };
  7073                
  7074                userMeas urementSty leCol["" +  type + "" ] = measur ementStyle ;
  7075           }
  7076           ca tch(e)
  7077           {  }
  7078       }
  7079  
  7080       functi on isValid PixelSpaci ng(pixelSp acing) {
  7081           if  (pixelSpa cing !== u ndefined & & pixelSpa cing !== n ull) {
  7082                return t rue;
  7083           }
  7084           re turn false ;
  7085       }
  7086  
  7087       functi on drawMea surements( imageUid,  frameIndex , context,  presentat ion, image Renderer)  {
  7088  
  7089                    var  displayMea surement =  false;
  7090                    
  7091           if  (imageUid  === undef ined) {
  7092                throw "d rawMeasure ments: ima geUid is n ull/undefi ned";
  7093           }
  7094           if  (frameInd ex === und efined) {
  7095                throw "d rawMeasure ments : fr ameIndex i s null/und efined";
  7096           }
  7097           va r parentDi v = $('#'  + imageRen derer.pare ntElement) .parent(). closest('d iv').attr( 'id');
  7098           if  (parentDi v === unde fined)
  7099                return;
  7100           va r tempData  = dicomVi ewer.measu rement.get TempData() ;
  7101           if  (parentDi v === dico mViewer.ge tActiveSer iesLayout( ).getSerie sLayoutId( ) && tempD ata) {
  7102                var tool  = dicomVi ewer.mouse Tools.getA ctiveTool( );
  7103                var acti veImageUid  = undefin ed;
  7104                if (tool ) {
  7105                    var  activeImag eRenderer  = tool.get ActiveImag eRenderer( );
  7106                    if(a ctiveImage Renderer)  {
  7107                         activeImag eUid = act iveImageRe nderer.anU IDs.split( "*")[0];
  7108                    }
  7109                }
  7110                if (temp Data.measu reType ===  "linedele te") {
  7111                    var  imageData  = dicomVie wer.measur ement.draw .getImageC oordinates ForMousePo int(tempDa ta, imageR enderer, c ontext);
  7112                    dico mViewer.me asurement. resetMeasu rementFlag ();
  7113                    dico mViewer.me asurement. findLineTo Delete(ima geData, im ageRendere r);
  7114                } else i f (tempDat a.measureT ype === "p ointdelete ") {
  7115                    var  imageData  = dicomVie wer.measur ement.draw .getImageC oordinates ForMousePo int(tempDa ta, imageR enderer, c ontext, pa rentDiv);
  7116                    dico mViewer.me asurement. resetMeasu rementFlag ();
  7117                    dico mViewer.me asurement. findPointT oDelete(im ageData, i mageRender er);
  7118                }else if  (tempData .measureTy pe === "an gledelete" ) {
  7119                    var  imageData  = dicomVie wer.measur ement.draw .getImageC oordinates ForMousePo int(tempDa ta, imageR enderer, c ontext, pa rentDiv);
  7120                    dico mViewer.me asurement. resetMeasu rementFlag ();
  7121                    dico mViewer.me asurement. findAngleT oDelete(im ageData, i mageRender er);
  7122                }else if  (tempData .measureTy pe === "el lipsedelet e") {
  7123                    var  imageData  = dicomVie wer.measur ement.draw .getImageC oordinates ForMousePo int(tempDa ta, imageR enderer, c ontext, pa rentDiv);
  7124                    dico mViewer.me asurement. resetMeasu rementFlag ();
  7125                    dico mViewer.me asurement. findEllips eToDelete( imageData,  imageRend erer);
  7126                }else if  (tempData .measureTy pe === "re ctangledel ete") {
  7127                    var  imageData  = dicomVie wer.measur ement.draw .getImageC oordinates ForMousePo int(tempDa ta, imageR enderer, c ontext, pa rentDiv);
  7128                    dico mViewer.me asurement. resetMeasu rementFlag ();
  7129                    dico mViewer.me asurement. findRectan gleToDelet e(imageDat a, imageRe nderer);
  7130                } else i f (tempDat a.measureT ype === "W indowLevel ROIdelete" ) {
  7131                    var  imageData  = dicomVie wer.measur ement.draw .getImageC oordinates ForMousePo int(tempDa ta, imageR enderer, c ontext, pa rentDiv);
  7132                    dico mViewer.me asurement. resetMeasu rementFlag ();
  7133                } else i f (tempDat a.measureT ype === "t racedelete ") {
  7134                    var  imageData  = dicomVie wer.measur ement.draw .getImageC oordinates ForMousePo int(tempDa ta, imageR enderer, c ontext);
  7135                    dico mViewer.me asurement. resetMeasu rementFlag ();
  7136                    dico mViewer.me asurement. findTraceT oDelete(im ageData, i mageRender er);
  7137                } else i f (tempDat a.measureT ype === "v olumedelet e") {
  7138                    var  imageData  = dicomVie wer.measur ement.draw .getImageC oordinates ForMousePo int(tempDa ta, imageR enderer, c ontext);
  7139                    dico mViewer.me asurement. resetMeasu rementFlag ();
  7140                    dico mViewer.me asurement. findVolume ToDelete(i mageData,  imageRende rer);
  7141                } else i f (tempDat a.measureT ype === "m itralGradi entdelete" ) {
  7142                    var  imageData  = dicomVie wer.measur ement.draw .getImageC oordinates ForMousePo int(tempDa ta, imageR enderer, c ontext);
  7143                    dico mViewer.me asurement. resetMeasu rementFlag ();
  7144                    dico mViewer.me asurement. findMitral ToDelete(i mageData,  imageRende rer);
  7145                } else i f (tempDat a.measureT ype === "p endelete")  {
  7146                    var  imageData  = dicomVie wer.measur ement.draw .getImageC oordinates ForMousePo int(tempDa ta, imageR enderer, c ontext);
  7147                    dico mViewer.me asurement. resetMeasu rementFlag ();
  7148                    dico mViewer.me asurement. findPenToD elete(imag eData, ima geRenderer );
  7149                } else i f (tempDat a.measureT ype === "l ine") {
  7150                    line Status = " added";
  7151                    var  measuremen tResult;
  7152                    var  dataToEdit  = dicomVi ewer.measu rement.get DataToEdit ();
  7153                    if ( dataToEdit  != undefi ned) {
  7154                         dicomViewe r.measurem ent.update Measuremen ts(dataToE dit, image Renderer,  tempData,  context);
  7155                         var editPo int = dico mViewer.me asurement. findNearHa ndleToEdit (tempData. start, ima geRenderer , context,  dataToEdi t); //dico mViewer.me asurement. findNearHa ndleToEdit (tempData. start, ima geRenderer , context,  dataToEdi t);
  7156                         if (editPo int !== un defined) {
  7157                             if (ed itPoint.st art.handle Active) {
  7158                                 te mpData.sta rt.x = edi tPoint.sta rt.x;
  7159                                 te mpData.sta rt.y = edi tPoint.sta rt.y;
  7160                             } else  if (editP oint.end.h andleActiv e) {
  7161                                 te mpData.end .x = editP oint.end.x ;
  7162                                 te mpData.end .y = editP oint.end.y ;
  7163                             }
  7164                             lineSt atus = "mo dified";
  7165                             dicomV iewer.meas urement.up dateMeasur ements(dat aToEdit, i mageRender er, tempDa ta, contex t);
  7166                         }
  7167                    } el se {
  7168                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7169                         imageData. textPositi on = tempD ata.textPo sition;
  7170                         if(activeI mageUid ==  imageUid)  {
  7171                             measur ementResul t = drawLi neMeasurem ent(imageU id, contex t, imageDa ta, presen tation, im ageRendere r);
  7172                         }
  7173                    }
  7174                    if ( dicomViewe r.measurem ent.isLine Measuremen tEnd() &&  lineStatus  === "adde d") {
  7175                         if (measur ementResul t != null)  {
  7176                             sendMe asurement( measuremen tResult.id , measurem entResult. value);
  7177                         }
  7178                         var length OfTemp = p arseFloat( getLengthT ext(tempDa ta))
  7179                         if (length OfTemp > 0 .05) {
  7180                             dicomV iewer.meas urement.ad dMeasureme nts(imageU id, frameI ndex, imag eRenderer,  tempData,  context);
  7181                         }
  7182  
  7183                         var calibr ationData  = getUnitM easurement Map(tempDa ta.studyUi d+"|"+imag eRenderer. seriesInde x+"|"+imag eRenderer. imageIndex +"|"+image Renderer.a nUIDs.spli t("*")[1]) ;
  7184  
  7185                         if(calibra tionData)  {
  7186                             tempDa ta.calibra tionData =  calibrati onData;
  7187                         }
  7188  
  7189                         if (dicomV iewer.tool s.getFlagF or2dLength Calibratio n()) {
  7190                             var im ageData =  dicomViewe r.measurem ent.getIma geDataForM ouseData(t empData, i mageRender er, contex t);
  7191                             var co ordinate =  {
  7192                                 st art: image Data.start ,
  7193                                 en d: imageDa ta.end
  7194                             };
  7195                             dicomV iewer.meas urement.se tCoordinat e(coordina te);
  7196                         }
  7197                    }
  7198                } 
  7199                else if  (tempData. measureTyp e === "ell ipse")
  7200                {
  7201                    line Status = " added";
  7202                    var  measuremen tResult;
  7203                    var  dataToEdit  = dicomVi ewer.measu rement.get DataToEdit ();
  7204                    if ( dataToEdit  != undefi ned) {
  7205                         tempData.m easurement Id = dataT oEdit.arry Index;
  7206                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7207                         dicomViewe r.measurem ent.update EllipseMea surements( dataToEdit , imageRen derer, tem pData, con text);
  7208                         lineStatus  = "modifi ed";
  7209                    } el se {
  7210                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7211                         imageData. textPositi on = tempD ata.textPo sition;
  7212                         if(activeI mageUid ==  imageUid)  {
  7213                             measur ementResul t = drawEl lipseMeasu rement(ima geUid, con text, imag eData, pre sentation,  imageRend erer, unde fined, dic omViewer.m easurement .isLineMea surementEn d() ? fals e : true);
  7214                         }
  7215                    }
  7216                    if ( dicomViewe r.measurem ent.isLine Measuremen tEnd() &&  lineStatus  === "adde d") {                      
  7217                         var length OfTemp = p arseFloat( getLengthT ext(tempDa ta));
  7218                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7219                         imageData. textPositi on = tempD ata.textPo sition;
  7220                         measuremen tResult =  drawEllips eMeasureme nt(imageUi d, context , imageDat a, present ation, ima geRenderer , true, fa lse);               
  7221                         if (length OfTemp > 0 .05)
  7222                             dicomV iewer.meas urement.ad dEllipseMe asurements (imageUid,  frameInde x, imageRe nderer, te mpData, co ntext, mea surementRe sult);
  7223                    }
  7224                } else i f (tempDat a.measureT ype === "r ectangle")  {
  7225                    line Status = " added";
  7226                    var  measuremen tResult;
  7227                    var  dataToEdit  = dicomVi ewer.measu rement.get DataToEdit ();
  7228                    if ( dataToEdit  != undefi ned) {
  7229                         tempData.m easurement Id = dataT oEdit.arry Index;
  7230                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7231                         dicomViewe r.measurem ent.update RectangleM easurement s(dataToEd it, imageR enderer, t empData, c ontext, te mpData.edi tMode);
  7232                         lineStatus  = "modifi ed";
  7233                    } el se {
  7234                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7235                         imageData. textPositi on = tempD ata.textPo sition;
  7236                         if(activeI mageUid ==  imageUid)  {
  7237                             measur ementResul t = drawRe ctangleMea surement(i mageUid, c ontext, im ageData, p resentatio n, imageRe nderer, un defined, d icomViewer .measureme nt.isLineM easurement End() ? fa lse : true );
  7238                         }
  7239                    }
  7240                    if ( dicomViewe r.measurem ent.isLine Measuremen tEnd() &&  lineStatus  === "adde d") {                      
  7241                         var length OfTemp = p arseFloat( getLengthT ext(tempDa ta));
  7242                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7243                         imageData. textPositi on = tempD ata.textPo sition;
  7244                         measuremen tResult =  drawRectan gleMeasure ment(image Uid, conte xt, imageD ata, prese ntation, i mageRender er, true,  false);                
  7245                         if (length OfTemp > 0 .05)
  7246                             dicomV iewer.meas urement.ad dRectangle Measuremen ts(imageUi d, frameIn dex, image Renderer,  tempData,  context, m easurement Result);
  7247                    }
  7248                } else i f (tempDat a.measureT ype === "W indowLevel ROI") {
  7249                    line Status = " added";
  7250                    var  measuremen tResult;
  7251                    var  dataToEdit  = dicomVi ewer.measu rement.get DataToEdit ();
  7252                    if ( dataToEdit  != undefi ned) {
  7253                         tempData.m easurement Id = dataT oEdit.arry Index;
  7254                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7255                         lineStatus  = "modifi ed";
  7256                    } el se {
  7257                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7258                         measuremen tResult =  drawWindow LevelROIMe asurement( imageUid,  context, i mageData,  presentati on, imageR enderer, u ndefined);
  7259                    }
  7260                    if ( dicomViewe r.measurem ent.isLine Measuremen tEnd() &&  lineStatus  === "adde d") {
  7261                         var length OfTemp = p arseFloat( getLengthT ext(tempDa ta));
  7262                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7263                         measuremen tResult =  drawWindow LevelROIMe asurement( imageUid,  context, i mageData,  presentati on, imageR enderer, t rue);
  7264                    }
  7265  
  7266                    if(  !dicomView er.tools.i sShowAnnot ationandMe asurement( )) {
  7267                         return;
  7268                    }
  7269                } else i f (tempDat a.measureT ype === "p oint") {
  7270                    line Status = " added";
  7271                    var  measuremen tResult;
  7272                    var  dataToEdit  = dicomVi ewer.measu rement.get DataToEdit ();
  7273                    if ( dataToEdit  != undefi ned) {
  7274                         dicomViewe r.measurem ent.update Measuremen ts(dataToE dit, image Renderer,  tempData,  context);
  7275                         var editPo int = dico mViewer.me asurement. findNearHa ndleToEdit (tempData. start, ima geRenderer , context,  dataToEdi t);
  7276                         if (editPo int !== un defined) {
  7277                             if (ed itPoint.st art.handle Active) {
  7278                                 te mpData.sta rt.x = edi tPoint.end .x;
  7279                                 te mpData.sta rt.y = edi tPoint.end .y;
  7280                             } else  if (editP oint.end.h andleActiv e) {
  7281                                 te mpData.sta rt.x = edi tPoint.sta rt.x;
  7282                                 te mpData.sta rt.y = edi tPoint.sta rt.y;
  7283                             }
  7284                             lineSt atus = "mo dified";
  7285                         }
  7286                    } el se {                      
  7287                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7288                         imageData. textPositi on = tempD ata.textPo sition;
  7289                         measuremen tResult =  drawPointM easurement (imageUid,  context,  imageData,  presentat ion, image Renderer);
  7290                    }
  7291  
  7292                    if ( dicomViewe r.measurem ent.isLine Measuremen tEnd() &&  lineStatus  === "adde d") {
  7293                         if (measur ementResul t != null)  {
  7294                             sendMe asurement( measuremen tResult.id , measurem entResult. value);
  7295                         }
  7296                         dicomViewe r.measurem ent.addMea surements( imageUid,  frameIndex , imageRen derer, tem pData, con text);
  7297                    }
  7298                } else i f (tempDat a.measureT ype === "t race") {
  7299                    var  dataToEdit  = dicomVi ewer.measu rement.get DataToEdit ();
  7300                    if ( dataToEdit  != undefi ned) {
  7301                         tempData.m easurement Id = dataT oEdit.arry Index;
  7302                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7303                         dicomViewe r.measurem ent.update TraceIntoA rray(tempD ata.end, i mageRender er, contex t, dataToE dit);
  7304                    } el se {
  7305                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7306                         imageData. textPositi on = tempD ata.textPo sition;
  7307                         if(activeI mageUid ==  imageUid)  {
  7308                             var me asurementR esult = dr awTraceMea surement(i mageUid, c ontext, im ageData, p resentatio n, imageRe nderer, fa lse, undef ined, unde fined, dic omViewer.m easurement .isTraceMe asurementE nd() ? tru e : false) ;
  7309                         }
  7310  
  7311                         if (dicomV iewer.meas urement.is LineMeasur ementEnd() ) {
  7312                             lineSt atus = "ad ded";
  7313                             dicomV iewer.meas urement.ad dTraceMeas urements(i mageUid, f rameIndex,  imageRend erer, temp Data, cont ext);
  7314                         }
  7315                    }
  7316                } else i f (tempDat a.measureT ype === "a ngle") {
  7317                    var  dataToEdit  = dicomVi ewer.measu rement.get DataToEdit ();
  7318                    if ( dataToEdit  != undefi ned) {
  7319                         tempData.m easurement Id = dataT oEdit.arry Index;
  7320                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7321                         dicomViewe r.measurem ent.update AngleIntoA rray(tempD ata.end, i mageRender er, contex t, dataToE dit);                      
  7322                    } el se {
  7323                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7324                         imageData. textPositi on = tempD ata.textPo sition;
  7325                         if(activeI mageUid ==  imageUid)  {
  7326                             var me asurementR esult = dr awAngleMea surement(i mageUid, c ontext, im ageData, p resentatio n, imageRe nderer, di comViewer. measuremen t.isAngleM easurement End() ? tr ue : false );
  7327                         }
  7328  
  7329                         if (dicomV iewer.meas urement.is LineMeasur ementEnd() ) {
  7330                             lineSt atus = "ad ded";
  7331                             dicomV iewer.meas urement.ad dAngleMeas urements(i mageUid, f rameIndex,  imageRend erer, temp Data, cont ext);
  7332                         }
  7333                    }
  7334                } else i f (tempDat a.measureT ype === "v olumeeditm ove") {
  7335                    var  dataToEdit  = dicomVi ewer.measu rement.get DataToEdit ();
  7336                    if ( dataToEdit  != undefi ned) {
  7337                         tempData.m easurement Id = dataT oEdit.arry Index;
  7338                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7339                         dicomViewe r.measurem ent.update Volumeinto Array(temp Data.end,  imageRende rer, conte xt, dataTo Edit);
  7340  
  7341                         updateDyna micVolumes (tempData,  imageUid,  imageData , frameInd ex, parent Div, prese ntation, c ontext, im ageRendere r);
  7342                    }
  7343                } else i f (tempDat a.measureT ype === "v olume") {
  7344                    var  imageData  = dicomVie wer.measur ement.getI mageDataFo rMouseData (tempData,  imageRend erer, cont ext);
  7345                    var  measuremen tResult =  drawLineMe asurement( imageUid,  context, i mageData,  presentati on, imageR enderer);
  7346  
  7347                    if ( !dicomView er.measure ment.isVol umeMeasure mentEnd())  {
  7348                         updateDyna micVolumes (tempData,  imageUid,  imageData , frameInd ex, parent Div, prese ntation, c ontext, im ageRendere r);
  7349                    } el se if (dic omViewer.m easurement .isLineMea surementEn d()) {
  7350                         lineStatus  = "added" ;
  7351                         dicomViewe r.measurem ent.addVol umeMeasure ments(imag eUid, fram eIndex, im ageRendere r, tempDat a, context );
  7352                    }
  7353                } else i f (tempDat a.measureT ype === "m itralGradi ent") {
  7354                    var  dataToEdit  = dicomVi ewer.measu rement.get DataToEdit ();
  7355                    if ( dataToEdit  != undefi ned) {
  7356                         tempData.m easurement Id = dataT oEdit.arry Index;
  7357                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7358                         dicomViewe r.measurem ent.update MitralMean Gradientin toArray(te mpData.end , imageRen derer, con text, data ToEdit);                      
  7359                    } el se {
  7360                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7361                         var isMeas urementEnd  = dicomVi ewer.measu rement.isM itralMeanG radientMea surementEn d() ? true  : false;
  7362                         imageData. textPositi on = tempD ata.textPo sition;
  7363                         if(activeI mageUid ==  imageUid)  {
  7364                             if(ima geData.mea surementSu bType ===  "freehand" ) {
  7365                                 dr awFreeHand Measuremen t(imageUid , context,  imageData , presenta tion, imag eRenderer,  false, is Measuremen tEnd, unde fined);
  7366                             } else  {
  7367                                 dr awMitralMe anGradient Measuremen t(imageUid , context,  imageData , presenta tion, imag eRenderer,  false, un defined, i sMeasureme ntEnd);
  7368                             }
  7369                         }
  7370  
  7371                         if (dicomV iewer.meas urement.is LineMeasur ementEnd() ) {
  7372                             lineSt atus = "ad ded";
  7373                             dicomV iewer.meas urement.ad dMitralGra dientMeasu rements(im ageUid, fr ameIndex,  imageRende rer, tempD ata, conte xt);
  7374                         } else {
  7375                             var mi tralMeasur ements = d icomViewer .measureme nt.getMitr alGradient Measuremen ts(imageUi d, frameIn dex);
  7376                             if(mit ralMeasure ments != u ndefined & & mitralMe asurements [tempData. measuremen tIndex] ==  undefined ) displayM easurement  = true;
  7377  
  7378                         }
  7379                    }
  7380                } else i f (tempDat a.measureT ype === "p en") {
  7381                    var  dataToEdit  = dicomVi ewer.measu rement.get DataToEdit ();
  7382                    if ( dataToEdit  != undefi ned) {
  7383                         tempData.m easurement Id = dataT oEdit.arry Index;
  7384                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7385                         dicomViewe r.measurem ent.update PenintoArr ay(tempDat a.end, ima geRenderer , context,  dataToEdi t);
  7386                    } el se {
  7387                         var imageD ata = dico mViewer.me asurement. getImageDa taForMouse Data(tempD ata, image Renderer,  context);
  7388                         var isMeas urementEnd  = dicomVi ewer.measu rement.isP enToolEnd( ) ? true :  false;
  7389                         if(activeI mageUid ==  imageUid)  {
  7390                             if(ima geData.mea surementSu bType ===  "pen") {
  7391                                 dr awPenMeasu rement(ima geUid, con text, imag eData, pre sentation,  imageRend erer, isMe asurementE nd);
  7392                             }
  7393                         }
  7394                         dicomViewe r.measurem ent.addPen Measuremen ts(imageUi d, frameIn dex, image Renderer,  tempData,  context);
  7395                    }
  7396                }
  7397           }
  7398  
  7399           va r measurem ents = dic omViewer.m easurement .getMeasur ements(ima geUid, fra meIndex);
  7400           if  (measurem ents !== u ndefined & & measurem ents.lengt h !== 0) {
  7401                for (var  i = 0; i  < measurem ents.lengt h; i++) {
  7402                    var  data = mea surements[ i];
  7403                    if ( data !== u ndefined)  {
  7404                         if (data.m easureType  === "line ") {
  7405                             var da taToEdit =  dicomView er.measure ment.getDa taToEdit() ;
  7406                             if (da taToEdit ! = undefine d && i !=  dataToEdit .arryIndex ) {
  7407                                 da ta.end.han dleActive  = false;
  7408                                 da ta.start.h andleActiv e = false;
  7409                             }
  7410                             if (di comViewer. measuremen t.isMeasur ementDrawa ble(data.s essionType )) {
  7411                                 dr awLineMeas urement(im ageUid, co ntext, dat a, present ation, ima geRenderer );
  7412                             }
  7413                         } else if  (data.meas ureType == = "point")  {
  7414                             var da taToEdit =  dicomView er.measure ment.getDa taToEdit() ;
  7415                             if(dat aToEdit !=  undefined ) {
  7416                                 if (i != data ToEdit.arr yIndex) {
  7417                                      data.end .handleAct ive = fals e;
  7418                                      data.sta rt.handleA ctive = fa lse;
  7419                                 }  else {
  7420                                      //while  editing po int measur ement, aga in updatin g the posi tion of th e text for  the selec ted point
  7421                                      data.tex tPosition  = dicomVie wer.measur ement.poin tTextPosit ion(data,  imageRende rer);
  7422                                 }
  7423                             }
  7424                             if (di comViewer. measuremen t.isMeasur ementDrawa ble(data.s essionType )) {
  7425                                 dr awPointMea surement(i mageUid, c ontext, da ta, presen tation, im ageRendere r);
  7426                             }
  7427                         }
  7428                    }
  7429                }
  7430           }
  7431           
  7432           va r ellipseM easurement s = dicomV iewer.meas urement.ge tEllipseMe asurements (imageUid,  frameInde x);
  7433           if  (ellipseM easurement s !== unde fined && e llipseMeas urements.l ength !==  0) {
  7434                var meas urementRes ult = unde fined;
  7435                for (var  i = 0; i  < ellipseM easurement s.length;  i++) {
  7436                    meas urements =  ellipseMe asurements [i];
  7437                    var  dataResult X = 0;
  7438                    var  dataResult Y = 0;
  7439                    if ( measuremen ts !== und efined) {                      
  7440                         if (measur ements.mea sureType = == "ellips e") {
  7441                             if (di comViewer. measuremen t.isMeasur ementDrawa ble(measur ements.ses sionType))  {
  7442                                 dr awEllipseM easurement (imageUid,  context,  measuremen ts, presen tation, im ageRendere r, (measur ements.edi tMode) ? u ndefined :  true, mea surements. editMode);
  7443                             }
  7444                         }
  7445                    }
  7446                }
  7447           }
  7448           
  7449           va r rectangl eMeasureme nts = dico mViewer.me asurement. getRectang leMeasurem ents(image Uid, frame Index);
  7450           if  (rectangl eMeasureme nts !== un defined &&  rectangle Measuremen ts.length  !== 0) {
  7451                var meas urementRes ult = unde fined;
  7452                for (var  i = 0; i  < rectangl eMeasureme nts.length ; i++) {
  7453                    meas urements =  rectangle Measuremen ts[i];
  7454                    var  dataResult X = 0;
  7455                    var  dataResult Y = 0;
  7456                    if ( measuremen ts !== und efined) {                      
  7457                         if (measur ements.mea sureType = == "rectan gle") {
  7458                             if (di comViewer. measuremen t.isMeasur ementDrawa ble(measur ements.ses sionType))  {
  7459                                 dr awRectangl eMeasureme nt(imageUi d, context , measurem ents, pres entation,  imageRende rer, (meas urements.e ditMode) ?  undefined  : true, m easurement s.editMode ,measureme nts.editMo de);
  7460                             }
  7461                         }
  7462                    }
  7463                }
  7464           }
  7465  
  7466           va r traceMea surements  = dicomVie wer.measur ement.getT raceMeasur ements(ima geUid, fra meIndex);
  7467  
  7468           if  (traceMea surements  !== undefi ned && tra ceMeasurem ents.lengt h !== 0) {
  7469                var meas urementRes ult = unde fined;
  7470                for (var  i = 0; i  < traceMea surements. length; i+ +) {
  7471                    meas urements =  traceMeas urements[i ];
  7472                    var  dataResult X = 0;
  7473                    var  dataResult Y = 0;
  7474                    if ( measuremen ts !== und efined &&  measuremen ts.length  !== 0) {
  7475                         for (var j  = 0; j <  measuremen ts.length;  j++) {
  7476                             var da ta = measu rements[j] ;
  7477                             if (da ta.measure Type === " trace") {
  7478                                 if  (dicomVie wer.measur ement.isMe asurementD rawable(da ta.session Type)) {
  7479                                      dataResu ltX = pars eInt(dataR esultX) +  parseInt(( data.start .x).toFixe d(0));
  7480                                      dataResu ltY = pars eInt(dataR esultY) +  parseInt(( data.start .y).toFixe d(0));
  7481                                      var aver ageX = (pa rseInt(dat aResultX)  / (j + 1)) .toFixed(0 );
  7482                                      var aver ageY = (pa rseInt(dat aResultY)  / (j + 1)) .toFixed(0 );
  7483                                      var disp lay = fals e;
  7484                                      if (j == = measurem ents.lengt h - 1) dis play = tru e;
  7485                                      measurem entResult  = drawTrac eMeasureme nt(imageUi d, context , data, pr esentation , imageRen derer, dis play, aver ageX, aver ageY, data .editMode) ;
  7486                                 }
  7487                             }
  7488                         }
  7489                    }
  7490                }
  7491                if (meas urementRes ult != und efined)
  7492                    send Measuremen t(measurem entResult. id, measur ementResul t.value);
  7493           }
  7494           
  7495           //  Angle mea surement
  7496            v ar angleMe asurements  = dicomVi ewer.measu rement.get AngleMeasu rements(im ageUid, fr ameIndex);
  7497  
  7498           if  (angleMea surements  !== undefi ned && ang leMeasurem ents.lengt h !== 0) {
  7499                var meas urementRes ult = unde fined;
  7500                for (var  i = 0; i  < angleMea surements. length; i+ +) {
  7501                    meas urements =  angleMeas urements[i ];
  7502                    if ( measuremen ts !== und efined &&  measuremen ts.length  !==0) {
  7503                         for (var j  = 0; j <  measuremen ts.length;  j++) {
  7504                             var da ta = measu rements[j]
  7505                             if (da ta.measure Type === " angle") {
  7506                                 if  (dicomVie wer.measur ement.isMe asurementD rawable(da ta.session Type)) {
  7507                                      measurem entResult  = drawAngl eMeasureme nt(imageUi d, context , data, pr esentation , imageRen derer, dat a.editMode );
  7508                                 }
  7509                             }
  7510                         }
  7511                        
  7512                         for(var iI ndex=0; iI ndex < mea surements. length-1;  iIndex++){
  7513                             var fi rstLine =  measuremen ts[iIndex] ;
  7514                             var se condLine =  measureme nts[iIndex +1];
  7515                             var en dPoint;
  7516                             var ce nterPoint  = {
  7517                                      x:firstL ine.end.x. toFixed(0) ,
  7518                                      y:firstL ine.end.y. toFixed(0)
  7519                                 };
  7520                                 va r startPoi nt = {
  7521                                      x:firstL ine.start. x.toFixed( 0),
  7522                                      y:firstL ine.start. y.toFixed( 0)
  7523                                 };
  7524                             if ((f irstLine.e nd.x.toFix ed(0) == s econdLine. end.x.toFi xed(0))&&
  7525                                      (firstLi ne.end.y.t oFixed(0)  == secondL ine.end.y. toFixed(0) )){
  7526                                 en dPoint = {
  7527                                      x:second Line.start .x.toFixed (0),
  7528                                      y:second Line.start .y.toFixed (0)
  7529                                 };
  7530                             } else {
  7531                                 en dPoint = {
  7532                                      x:second Line.end.x .toFixed(0 ),
  7533                                      y:second Line.end.y .toFixed(0 )
  7534                                 };
  7535                             }
  7536                             var an gleValue =  calculate Angle(star tPoint,end Point,cent erPoint, m easurement s[iIndex]. style);
  7537                             if (di comViewer. measuremen t.isMeasur ementDrawa ble(measur ements.ses sionType))  {
  7538                                 dr awAngleVal ue(context ,firstLine ,secondLin e,imageRen derer,pres entation,a ngleValue, "o");
  7539                             }
  7540                         }
  7541                    }
  7542                }
  7543           }
  7544           
  7545           va r volumeMe asurements  = dicomVi ewer.measu rement.get VolumeMeas urements(i mageUid, f rameIndex) ;
  7546  
  7547           if  (volumeMe asurements  !== undef ined && vo lumeMeasur ements.len gth !== 0)  {
  7548                for (var  i = 0; i  < volumeMe asurements .length; i ++) {
  7549                    meas urements =  volumeMea surements[ i];
  7550                    if ( measuremen ts !== und efined &&  measuremen ts.length  !== 0) {
  7551                         var dataTo Edit = dic omViewer.m easurement .getDataTo Edit();
  7552                         var isQual ifyforEdit  = (dataTo Edit !== u ndefined & & (i === d ataToEdit. arryIndex) );
  7553                         var data;
  7554                         for (var j  = 0; j <  measuremen ts.length;  j++) {
  7555                             data =  measureme nts[j];
  7556                             if (da ta.measure Type === " volume") {
  7557                                 dr awLineWith outMeasure ment(image Uid, conte xt, data,  presentati on, imageR enderer, f alse, isQu alifyforEd it);
  7558                             }
  7559                         }
  7560                         if (!(i ==  volumeMea surements. length - 1  && dicomV iewer.meas urement.is VolumeMeas urementEnd ())) {
  7561                             var fi rstPoint =  {
  7562                                 st art: {
  7563                                      x: measu rements[0] .start.x,
  7564                                      y: measu rements[0] .start.y
  7565                                 },
  7566                                 en d: {
  7567                                      x: measu rements[me asurements .length -  1].end.x,
  7568                                      y: measu rements[me asurements .length -  1].end.y
  7569                                 },
  7570                                 me asureType:  "line",
  7571                                 st yle: data. style
  7572                             };
  7573                             drawLi neWithoutM easurement (imageUid,  context,  firstPoint , presenta tion, imag eRenderer,  true, isQ ualifyforE dit);
  7574                         }
  7575                    }
  7576                }
  7577  
  7578           }
  7579  
  7580           va r mitralMe asurements  = dicomVi ewer.measu rement.get MitralGrad ientMeasur ements(ima geUid, fra meIndex);
  7581  
  7582           if  (mitralMe asurements  !== undef ined && mi tralMeasur ements.len gth !== 0)  {
  7583                var meas urementRes ult = unde fined;
  7584                for (var  i = 0; i  < mitralMe asurements .length; i ++) {
  7585                    meas urements =  mitralMea surements[ i];
  7586                    var  dataResult X = 0;
  7587                    var  dataResult Y = 0;
  7588                    var  dataMitral Gradiant =  0;
  7589                    var  gradiantVa lues = get AvgMitralM eanGradien ts(imageUi d, measure ments);
  7590  
  7591                    if ( measuremen ts !== und efined &&  measuremen ts.length  !== 0) {
  7592                         var freeHa ndPoints =  [];
  7593                         if (measur ements[0]. measureTyp e === "mit ralGradien t" &&
  7594                             measur ements[0]. measuremen tSubType = == "freeha nd") {
  7595                             for (v ar j = 0;  j < measur ements.len gth; j++)  {
  7596                                 va r imageCoo rdinate =  dicomViewe r.measurem ent.getCan vasDataFor ImageData( measuremen ts[j], ima geRenderer );
  7597                                 if (j == 0) {
  7598                                      freeHand Points.pus h([parseIn t(imageCoo rdinate.st art.x),
  7599                                                            parseInt (imageCoor dinate.sta rt.y)]);
  7600                                 }
  7601  
  7602                                 fr eeHandPoin ts.push([p arseInt(im ageCoordin ate.end.x) ,
  7603                                                        p arseInt(im ageCoordin ate.end.y) ]);
  7604                             }
  7605                         }
  7606  
  7607                         for (var j  = 0; j <  measuremen ts.length;  j++) {
  7608                             var da ta = measu rements[j] ;
  7609                             if (da ta.measure Type === " mitralGrad ient") {
  7610                                 va r display  = false;
  7611                                 if  (j === me asurements .length -  1) display  = true;
  7612                                 if (data.meas urementSub Type === " freehand")  {
  7613                                      if (dico mViewer.me asurement. isMeasurem entDrawabl e(data.ses sionType))  {
  7614                                          draw FreeHandMe asurement( imageUid,  context, d ata, prese ntation, i mageRender er, displa y, data.ed itMode, fr eeHandPoin ts);
  7615                                      }
  7616                                 }  else {
  7617                                      if (dico mViewer.me asurement. isMeasurem entDrawabl e(data.ses sionType))  {
  7618                                          meas urementRes ult = draw MitralMean GradientMe asurement( imageUid,  context, d ata, prese ntation, i mageRender er, displa y, gradian tValues, d ata.editMo de);
  7619                                      }
  7620                                 }
  7621  
  7622                                 if (data.meas urementSub Type !== " freehand")  {
  7623                                      if ((i ! = mitralMe asurements .length -1  && j == m easurement s.length -  1 ) ||
  7624                                         (i ==  mitralMea surements. length -1  && j == me asurements .length -  1 && (!dic omViewer.m easurement .isMitralM eanGradien tMeasureme ntEnd() ||  displayMe asurement) )) {
  7625                                          var  firstPoint  = {
  7626                                               start: {
  7627                                                   x: mea surements[ 0].start.x ,
  7628                                                   y: mea surements[ 0].start.y
  7629                                               },
  7630                                               end: {
  7631                                                   x: mea surements[ measuremen ts.length  - 1].end.x ,
  7632                                                   y: mea surements[ measuremen ts.length  - 1].end.y
  7633                                               },
  7634                                               measureTyp e: "line",
  7635                                               style: dat a.style
  7636                                          };
  7637                                          if ( dicomViewe r.measurem ent.isMeas urementDra wable(data .sessionTy pe)) {
  7638                                               drawLineWi thoutMeasu rement(ima geUid, con text, firs tPoint, pr esentation , imageRen derer, tru e, isQuali fyforEdit) ;
  7639                                          }
  7640                                      }
  7641                                 }
  7642                             }
  7643                         }
  7644                    }
  7645                }
  7646  
  7647                if (meas urementRes ult != und efined)
  7648                    send Measuremen t(measurem entResult. id, measur ementResul t.value);
  7649           }
  7650  
  7651           va r penMeasu rement = d icomViewer .measureme nt.getPenM easurement s(imageUid , frameInd ex);
  7652           if (penMeasur ement !==  undefined  && penMeas urement.le ngth !== 0 ) {
  7653                var meas urementRes ult = unde fined;
  7654                for (var  i = 0; i  < penMeasu rement.len gth; i++)  {
  7655                    meas urements =  penMeasur ement[i];
  7656                    var  dataResult X = 0;
  7657                    var  dataResult Y = 0;
  7658  
  7659                    
  7660                    if ( measuremen ts !== und efined &&  measuremen ts.length  !== 0) {
  7661                         var penPoi nts = [];
  7662                         for (var j  = 0; j <  measuremen ts.length;  j++) {
  7663                             var da ta = measu rements[j] ;
  7664                             // upd ating the  selected p roperties  styles for  the pen a nnotation
  7665                             if(mea surements. style !==  undefined)  {
  7666                                 da ta.style =  measureme nts.style;
  7667                             }
  7668                             var di splay = fa lse;
  7669                             if (j  === measur ements.len gth - 1) {
  7670                                 di splay = tr ue;
  7671                             }
  7672                             if(dat a.measurem entSubType  === "pen" ) {
  7673                                 if  (dicomVie wer.measur ement.isMe asurementD rawable(da ta.session Type)) {
  7674                                      drawPenM easurement (imageUid,  context,  data, pres entation,  imageRende rer, data. editMode);
  7675                                 }
  7676                             }
  7677                         }
  7678                    }
  7679                }
  7680           }
  7681  
  7682       }
  7683  
  7684       functi on updateD ynamicVolu mes(tempDa ta, imageU id, imageD ata, frame Index, par entDiv, pr esentation , context,  imageRend erer) {
  7685           te mpData.mea surementCo mplete = t rue;
  7686           va r volumeMe asurements  = dicomVi ewer.measu rement.get VolumeMeas urements(i mageUid, f rameIndex) ;
  7687  
  7688           if  (volumeMe asurements  !== undef ined && vo lumeMeasur ements.len gth !== 0)  {
  7689                var meas urements =  volumeMea surements[ imageData. measuremen tId];
  7690                if (meas urements ! == undefin ed && meas urements.l ength !==  0) {
  7691                    var  lastLineDa ta = measu rements[me asurements .length -  1];
  7692                    if ( imageData. measureTyp e === "vol ume" || im ageData.me asureType  === "volum eeditmove" ) {
  7693                         drawLineWi thoutMeasu rement(ima geUid, con text, imag eData, pre sentation,  imageRend erer, fals e);
  7694                    }
  7695                    var  lastData =  [];
  7696                    if ( tempData.m easurement Complete = == true) {
  7697                         lastData =  {
  7698                             start:  {
  7699                                 x:  measureme nts[0].sta rt.x,
  7700                                 y:  measureme nts[0].sta rt.y
  7701                             },
  7702                             end: {
  7703                                 x:  lastLineD ata.end.x,
  7704                                 y:  lastLineD ata.end.y
  7705                             },
  7706                             measur eType: "li ne"
  7707                         };
  7708                         drawLineWi thoutMeasu rement(ima geUid, con text, last Data, pres entation,  imageRende rer, true) ;
  7709                    }
  7710                    //Fi nd the mid  point bet ween the l ine
  7711                    //[( x_1 + x_2) /2 , (y_1  + y_2)/2]
  7712                    var  midPointX  = (lastDat a.start.x  + lastData .end.x) /  2;
  7713                    var  midPointY  = (lastDat a.start.y  + lastData .end.y) /  2;
  7714                    var  arrLength  = [];
  7715                    var  lengthData  = [];
  7716                    for  (var j = 0 ; j < meas urements.l ength - 1;  j++) {
  7717                         lengthData  = {
  7718                             start:  {
  7719                                 x:  midPointX ,
  7720                                 y:  midPointY
  7721                             },
  7722                             end: {
  7723                                 x:  measureme nts[j].end .x,
  7724                                 y:  measureme nts[j].end .y
  7725                             },
  7726                             measur eType: "li ne"
  7727                         };
  7728                         //drawLine WithoutMea surement(i mageUid, c ontext, le ngthData,  presentati on, imageR enderer,tr ue);
  7729  
  7730                         var value  = getLengt hText(leng thData);
  7731                         arrLength[ j] = parse Int(value. split(" ") [0]);
  7732                    }
  7733                    var  maxIndex =  findIndex OfGreatest (arrLength );
  7734                    leng thData = {
  7735                         start: {
  7736                             x: mid PointX,
  7737                             y: mid PointY
  7738                         },
  7739                         end: {
  7740                             x: mea surements[ maxIndex]. end.x,
  7741                             y: mea surements[ maxIndex]. end.y
  7742                         },
  7743                         measureTyp e: "line"
  7744                    };
  7745                    draw LineWithou tMeasureme nt(imageUi d, context , lengthDa ta, presen tation, im ageRendere r, true);
  7746                    var  point = me asurements [maxIndex] ;
  7747                    var  slope = (l astData.en d.y - last Data.start .y) / (las tData.end. x - lastDa ta.start.x );
  7748                    var  slope2 = ( -1 / slope );
  7749                    var  newAngle =  Math.atan (slope2);
  7750                    var  delta_x_A_ C = 20000  * Math.cos (newAngle) ;
  7751                    var  delta_y_A_ C = 20000  * Math.sin (newAngle) ;
  7752                    var  newX1 = po int.end.x  + delta_x_ A_C;
  7753                    var  newY1 = po int.end.y  + delta_y_ A_C;
  7754  
  7755                    delt a_x_A_C =  -20000 * M ath.cos(ne wAngle);
  7756                    delt a_y_A_C =  -20000 * M ath.sin(ne wAngle);
  7757                    var  newX2 = po int.end.x  + delta_x_ A_C;
  7758                    var  newY2 = po int.end.y  + delta_y_ A_C;
  7759  
  7760  
  7761                    newA ngle = Mat h.atan(slo pe);
  7762                    delt a_x_A_C =  20000 * Ma th.cos(new Angle);
  7763                    delt a_y_A_C =  20000 * Ma th.sin(new Angle);
  7764                    var  newX3 = la stData.end .x + delta _x_A_C;
  7765                    var  newY3 = la stData.end .y + delta _y_A_C;
  7766  
  7767                    delt a_x_A_C =  -20000 * M ath.cos(ne wAngle);
  7768                    delt a_y_A_C =  -20000 * M ath.sin(ne wAngle);
  7769                    var  newX4 = la stData.end .x + delta _x_A_C;
  7770                    var  newY4 = la stData.end .y + delta _y_A_C;
  7771                    var  newInterse ct = getIn tersection Point(newX 1, newY1,
  7772                         newX2, new Y2,
  7773                         newX3, new Y3, newX4,  newY4);
  7774                    if ( newInterse ct === nul l)
  7775                         return;
  7776                    midP ointX = ne wIntersect .x;
  7777                    midP ointY = ne wIntersect .y;
  7778                    var  newData =  {
  7779                         start: {
  7780                             x: mid PointX,
  7781                             y: mid PointY
  7782                         },
  7783                         end: {
  7784                             x: mea surements[ maxIndex]. end.x,
  7785                             y: mea surements[ maxIndex]. end.y
  7786                         },
  7787                         measureTyp e: "line"
  7788                    };
  7789                    draw LineWithou tMeasureme nt(imageUi d, context , newData,  presentat ion, image Renderer,  true);
  7790                    var  firstPoint  = [];
  7791                    var  drawWithXA xis = fals e;
  7792                    if ( Math.abs(m idPointX -  point.end .x) > Math .abs(midPo intY - poi nt.end.y))  {
  7793                         drawWithXA xis = true ;
  7794                    }
  7795  
  7796  
  7797                    var  angle_A_B  = Math.ata n2((newDat a.end.y -  newData.st art.y), (n ewData.end .x - newDa ta.start.x ));
  7798                    var  distance =  -arrLengt h[maxIndex ];
  7799                    var  pointsToBe Sent = {};
  7800                    var  pointIndex  = 0;
  7801                    for  (var iTemp  = 0; iTem p < (2 * a rrLength[m axIndex])  / 10; iTem p++) {
  7802                         var delta_ x_A_C = di stance * M ath.cos(an gle_A_B);
  7803                         var delta_ y_A_C = di stance * M ath.sin(an gle_A_B)
  7804                         var x3 = m idPointX +  delta_x_A _C;
  7805                         var y3 = m idPointY +  delta_y_A _C;
  7806                         var b = y3  - (slope  * x3);
  7807                         var point1  = [];
  7808                         var point2  = [];
  7809                         if (drawWi thXAxis) {
  7810                             point1  = {
  7811                                 x:  (x3 - arr Length[max Index]),
  7812                                 y:  ((slope *  (x3 - arr Length[max Index])) +  b)
  7813                             };
  7814                             point2  = {
  7815                                 x:  (x3 + arr Length[max Index]),
  7816                                 y:  ((slope *  (x3 + arr Length[max Index])) +  b)
  7817                             };
  7818                         } else {
  7819                             point1  = {
  7820                                 x:  ((y3 - ar rLength[ma xIndex] -  b) / slope ),
  7821                                 y:  (y3 - arr Length[max Index])
  7822                             };
  7823                             point2  = {
  7824                                 x:  ((y3 + ar rLength[ma xIndex] -  b) / slope ),
  7825                                 y:  (y3 + arr Length[max Index])
  7826                             };
  7827                         }
  7828                         var inters ectPoint1  = undefine d;
  7829                         var inters ectPoint2  = undefine d;
  7830  
  7831                         for (var j  = 0; j <  measuremen ts.length;  j++) {
  7832  
  7833                             var in tersect =  getInterse ctionPoint (measureme nts[j].sta rt.x, meas urements[j ].start.y,
  7834                                 me asurements [j].end.x,  measureme nts[j].end .y,
  7835                                 x3 , y3, poin t1.x, poin t1.y);
  7836                             if (in tersect !=  null) {
  7837                                 if  (intersec tPoint1 ==  null || i ntersectPo int1 == un defined) i ntersectPo int1 = int ersect;
  7838                                 el se if (int ersectPoin t2 == null  || inters ectPoint2  == undefin ed) inters ectPoint2  = intersec t;
  7839                             }
  7840                             inters ect = getI ntersectio nPoint(mea surements[ j].start.x , measurem ents[j].st art.y,
  7841                                 me asurements [j].end.x,  measureme nts[j].end .y,
  7842                                 x3 , y3, poin t2.x, poin t2.y);
  7843                             if (in tersect !=  null) {
  7844                                 if  (intersec tPoint1 ==  null || i ntersectPo int1 == un defined) i ntersectPo int1 = int ersect;
  7845                                 el se if (int ersectPoin t2 == null  || inters ectPoint2  == undefin ed) inters ectPoint2  = intersec t;
  7846                             }
  7847  
  7848                             if (in tersectPoi nt1 !== nu ll && inte rsectPoint 2 !== null  &&
  7849                                 in tersectPoi nt1 !== un defined &&  intersect Point2 !==  undefined ) {
  7850                                 fi rstPoint =  {
  7851                                      start: {
  7852                                          x: i ntersectPo int1.x,
  7853                                          y: i ntersectPo int1.y
  7854                                      },
  7855                                      end: {
  7856                                          x: i ntersectPo int2.x,
  7857                                          y: i ntersectPo int2.y
  7858                                      },
  7859                                      measureT ype: "line "
  7860                                 };
  7861                                 dr awLineWith outMeasure ment(image Uid, conte xt, firstP oint, pres entation,  imageRende rer, true) ;
  7862                                 po intsToBeSe nt[pointIn dex] = [];
  7863                                 po intsToBeSe nt[pointIn dex][0] =  intersectP oint1;
  7864                                 po intsToBeSe nt[pointIn dex][1] =  intersectP oint2;
  7865                                 po intIndex++ ;
  7866                                 in tersectPoi nt1 = unde fined;
  7867                                 in tersectPoi nt2 = unde fined;
  7868                             }
  7869                         }
  7870  
  7871                         distance =  distance  + 10;
  7872  
  7873                    }
  7874                    var  measuremen tToBeSent  = {};
  7875                    for  (var k = 0 ; k < meas urements.l ength; k++ ) {
  7876                         measuremen tToBeSent[ k] = [];
  7877                         measuremen tToBeSent[ k][0] = me asurements [k].start;
  7878                         measuremen tToBeSent[ k][1] = me asurements [k].end;
  7879                    }
  7880                    var  sendData =  {
  7881                         volumeId:  imageData. measuremen tId,
  7882                         volumePoin ts: measur ementToBeS ent,
  7883                         volumeSegm ents: poin tsToBeSent
  7884                    };
  7885                    send VolumeMeas urements(J SON.string ify(sendDa ta));
  7886                }
  7887           }
  7888       }
  7889  
  7890       functi on getImag eCoordinat esForMouse Point(mous ePoint, im ageRendere r, context ) {
  7891           va r presenta tion = ima geRenderer .presentat ionState;
  7892           if  (imageRen derer ===  undefined)  {
  7893                throw "g etImageCoo rdinatesFo rMousePoin t: imageRe nderer is  null/undef ined";
  7894           }
  7895           if  (imageRen derer.imag ePromise = == undefin ed) {
  7896                throw "g etImageCoo rdinatesFo rMousePoin t: imagePr omise is n ull/undefi ned";
  7897           }
  7898           if  (mousePoi nt == null ) {
  7899                return n ull;
  7900           }
  7901  
  7902           va r imageUid  = undefin ed;
  7903           va r frameInd ex = undef ined;
  7904           im ageRendere r.imagePro mise.then( function(i mage) {
  7905                imageUid  = image.i mageUid;
  7906                frameInd ex = image .frameNumb er;
  7907           }) ;
  7908  
  7909           // var contex t = dicomV iewer.meas urement.ge tImageCont ext(imageU id,frameIn dex);
  7910           if  (context  === undefi ned) {
  7911                throw "g etImageCoo rdinatesFo rMousePoin t: canvas  2d context  is null/u ndefined";
  7912           }
  7913           if  (presenta tion === u ndefined)  {
  7914                throw "g etImageCoo rdinatesFo rMousePoin t: present ation is n ull/undefi ned";
  7915           }
  7916           va r pan = pr esentation .getPan();
  7917           va r imageCor dinate = { };
  7918  
  7919           va r contextP oint = con text.trans formedPoin t(mousePoi nt.x, mous ePoint.y);
  7920  
  7921           im ageCordina te.x = (co ntextPoint .x - pan.x );
  7922           im ageCordina te.y = (co ntextPoint .y - pan.y );
  7923           im ageCordina te.handleA ctive = mo usePoint.h andleActiv e;
  7924  
  7925           re turn image Cordinate;
  7926       }
  7927  
  7928       functi on getMous ePointForI mageCoordi nates(imag eCoordinat e, imageRe nderer, co ntext) {
  7929           va r presenta tion = ima geRenderer .presentat ionState;
  7930           if  (imageRen derer ===  undefined)  {
  7931                throw "g etMousePoi ntForImage Coordinate s: imageRe nderer is  null/undef ined";
  7932           }
  7933           if  (imageRen derer.imag ePromise = == undefin ed) {
  7934                throw "g etMousePoi ntForImage Coordinate s: imagePr omise is n ull/undefi ned";
  7935           }
  7936           if  (imageCoo rdinate ==  null) {
  7937                return n ull;
  7938           }
  7939  
  7940           va r imageUid  = undefin ed;
  7941           va r frameInd ex = undef ined;
  7942           im ageRendere r.imagePro mise.then( function(i mage) {
  7943                imageUid  = image.i mageUid;
  7944                frameInd ex = image .frameNumb er;
  7945           }) ;
  7946  
  7947           //  var conte xt = dicom Viewer.mea surement.g etImageCon text(image Uid,frameI ndex);
  7948           if  (context  === undefi ned) {
  7949                throw "g etMousePoi ntForImage Coordinate s: canvas  2d context  is null/u ndefined";
  7950           }
  7951           if  (presenta tion === u ndefined)  {
  7952                throw "g etMousePoi ntForImage Coordinate s: present ation is n ull/undefi ned";
  7953           }
  7954           va r pan = pr esentation .getPan();
  7955           va r mousePoi nt = {};
  7956           va r contextP oint = con text.mouse Point(pars eFloat(ima geCoordina te.x) + pa n.x, parse Float(imag eCoordinat e.y) + pan .y);
  7957           mo usePoint.x  = context Point.x;
  7958           mo usePoint.y  = context Point.y;
  7959           mo usePoint.h andleActiv e = imageC oordinate. handleActi ve;
  7960  
  7961           re turn mouse Point;
  7962       }
  7963  
  7964       functi on getCanv asCoordina tesForImag eCoordinat es(imageCo ordinate,  imageRende rer) {
  7965           va r presenta tion = ima geRenderer .presentat ionState;
  7966           if  (imageRen derer ===  undefined)  {
  7967                throw "g etMousePoi ntForImage Coordinate s: imageRe nderer is  null/undef ined";
  7968           }
  7969           if  (imageRen derer.imag ePromise = == undefin ed) {
  7970                throw "g etMousePoi ntForImage Coordinate s: imagePr omise is n ull/undefi ned";
  7971           }
  7972           if  (presenta tion === u ndefined)  {
  7973                throw "g etMousePoi ntForImage Coordinate s: present ation is n ull/undefi ned";
  7974           }
  7975           if  (imageCoo rdinate ==  null) {
  7976                return n ull;
  7977           }
  7978  
  7979           va r pan = pr esentation .getPan();
  7980           va r canvasCo ordinates  = {};
  7981           ca nvasCoordi nates.x =  parseFloat (imageCoor dinate.x)  + pan.x;
  7982           ca nvasCoordi nates.y =  parseFloat (imageCoor dinate.y)  + pan.y;
  7983           ca nvasCoordi nates.hand leActive =  imageCoor dinate.han dleActive;
  7984  
  7985           re turn canva sCoordinat es;
  7986       }
  7987  
  7988       functi on drawLin eWithoutMe asurement( imageUid,  context, d ata, prese ntation, i mageRender er, dotted Line, isQu alifyforEd it) {
  7989           va r imageCoo rdinate =  dicomViewe r.measurem ent.getCan vasDataFor ImageData( data, imag eRenderer) ;
  7990           va r scale =  presentati on.getZoom ();
  7991           //  draw the  line
  7992           va r currentT empData =  dicomViewe r.measurem ent.getTem pData();
  7993           if  (isQualif yforEdit = == true &&  currentTe mpData !==  undefined  && curren tTempData. measureTyp e !== null  && curren tTempData. measureTyp e === "vol umeedit" & & (data.en d.handleAc tive || da ta.start.h andleActiv e)) {             
  7994                var radi us = 2 / ( imageRende rer.scaleV alue / sca le);
  7995                context. beginPath( );
  7996                context. strokeStyl e = '#DAA5 20';
  7997                context. arc(imageC oordinate. start.x, i mageCoordi nate.start .y, radius , 0, 2 * M ath.PI, fa lse);
  7998                context. closePath( );
  7999                context. stroke();
  8000           }
  8001  
  8002           co ntext.begi nPath();
  8003           up dateContex tStyle(con text, imag eCoordinat e.style ,f alse, imag eRenderer. scaleValue );
  8004  
  8005           co ntext.move To(imageCo ordinate.s tart.x, im ageCoordin ate.start. y);
  8006           co ntext.line To(imageCo ordinate.e nd.x, imag eCoordinat e.end.y);
  8007  
  8008           if  (dottedLi ne) contex t.setLineD ash([5/sca le, 10/sca le]);
  8009           el se context .setLineDa sh([]);
  8010           co ntext.clos ePath();
  8011           co ntext.stro ke();
  8012       }
  8013  
  8014       functi on drawLin eMeasureme nt(imageUi d, context , data, pr esentation , imageRen derer, edi tValue) {
  8015           va r imageCoo rdinate =  data;
  8016           da ta = dicom Viewer.mea surement.g etCanvasDa taForImage Data(data,  imageRend erer);
  8017           da ta.textPos ition = im ageCoordin ate.textPo sition;
  8018           va r dicomHea der = dico mViewer.he ader.getDi comHeader( imageUid);
  8019           va r usRegion Found = fa lse;
  8020           va r resultTe xt = null;
  8021           va r applyCal ibration =  false;
  8022           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  8023           va r measurem entUnit =  null;
  8024           va r precisio n = parseI nt(data.st yle.precis ion);
  8025  
  8026           ap plyCalibra tion = ( m easurement Unit = get UnitMeasur ementMap(s eriesLayou t.studyUid +"|"+image Renderer.s eriesIndex +"|"+image Renderer.i mageIndex+ "|"+imageR enderer.an UIDs.split ("*")[1])  ) ? true :  false;
  8027  
  8028           if (data.cali brationDat a && data. calibratio nData !==  "undefined ") {
  8029                applyCal ibration =  true; 
  8030                measurem entUnit =   !measurem entUnit ?  measuremen tUnit = {}  : measure mentUnit;
  8031                measurem entUnit.pi xelSpacing  = data.ca librationD ata.pixelS pacing;
  8032                measurem entUnit.pi xelSpacing .unitType  = data.cal ibrationDa ta.unitTyp e;
  8033           }
  8034  
  8035           // set the la st calibra ted image
  8036           se tActiveCal ibratedIma ge(seriesL ayout.stud yUid+"|"+i mageRender er.seriesI ndex+"|"+i mageRender er.imageIn dex+"|"+im ageRendere r.anUIDs.s plit("*")[ 1]);
  8037  
  8038           va r dicomIma geInfo = d icomHeader .imageInfo .measureme nt;
  8039           va r pixelSpa cing = dic omImageInf o ? dicomI mageInfo.p ixelSpacin g : undefi ned;
  8040           va r isCalibe r  = dicom Viewer.too ls.getCurs orType();
  8041  
  8042           if (measureme ntUnit !=  null && ap plyCalibra tion) {
  8043                var valu e = getLen gthUsingPi xelSpacing (imageCoor dinate, me asurementU nit.pixelS pacing, fa lse);
  8044                if (pars eFloat(val ue) > 0.05 ) {
  8045  
  8046                    var  calibrateF lag = (pix elSpacing  == undefin ed ||
  8047                                           (pi xelSpacing .row <= 0  && pixelSp acing.colu mn <= 0))  ? false :  true;
  8048                    resu ltText = g etDisplayL engthText( value, cal ibrateFlag , data.mea surementCo mplete,dat a.style.me asurementU nits, cali brateFlag,  precision );
  8049                } else {
  8050                    retu rn;
  8051                }
  8052           }
  8053           el se if ((is Caliber ==  "calibrat e") || (di comImageIn fo != null  && dicomI mageInfo ! == undefin ed)) {
  8054                if (isVa lidPixelSp acing(pixe lSpacing))  {
  8055                     var  value = g etLengthUs ingPixelSp acing(imag eCoordinat e, pixelSp acing, tru e);
  8056                    if ( parseFloat (value) >  0.05) {
  8057                         resultText  = getDisp layLengthT ext(value,  false, da ta.measure mentComple te,data.st yle.measur ementUnits , undefine d, precisi on);
  8058                    } el se if(pixe lSpacing.r ow <= 0 &&  pixelSpac ing.column  <= 0 && d icomViewer .tools.get FlagFor2dL engthCalib ration() & & data.mea surementSu bType != " 2DLine" &&  data.meas urementSub Type != "A rrow"){
  8059                         value = 1;
  8060                         resultText  = "";
  8061                    } el se if(data .measureme ntSubType  == "2DLine " || data. measuremen tSubType = = "Arrow")  {
  8062                         value = 1;
  8063                         resultText  = "";
  8064                    } el se {
  8065                         return;
  8066                    }
  8067                } else i f((isCalib er === "ca librate"))  {
  8068                    valu e = 1;
  8069                    resu ltText = " ";
  8070                } else i f (dicomIm ageInfo &&  (dicomIma geInfo.usR egions !=  null) && ( dicomImage Info.usReg ions.lengt h > 0)) {
  8071  
  8072                    var  regionSpat ialFormat  = 0;
  8073                    var  physicalUn itsXDirect ion = 0;
  8074                    var  physicalUn itsYDirect ion = 0;
  8075                    var  physicalDe ltaX = 0.0 ;
  8076                    var  physicalDe ltaY = 0.0 ;
  8077  
  8078                    for  (var i = 0 ; i < dico mHeader.im ageInfo.me asurement. usRegions. length; i+ +) {
  8079                         var usRegi on = dicom Header.ima geInfo.mea surement.u sRegions[i ];
  8080  
  8081                         if (((imag eCoordinat e.start.x  <= usRegio n.regionLo cationMaxX 1) && (ima geCoordina te.start.x  >= usRegi on.regionL ocationMin X0)) &&
  8082                             ((imag eCoordinat e.start.y  <= usRegio n.regionLo cationMaxY 1) && (ima geCoordina te.start.y  >= usRegi on.regionL ocationMin Y0)) &&
  8083                             ((imag eCoordinat e.end.x <=  usRegion. regionLoca tionMaxX1)  && (image Coordinate .end.x >=  usRegion.r egionLocat ionMinX0))  &&
  8084                             ((imag eCoordinat e.end.y <=  usRegion. regionLoca tionMaxY1)  && (image Coordinate .end.y >=  usRegion.r egionLocat ionMinY0))  &&
  8085                             (!((us Region.reg ionSpatial Format ==  0) && (usR egion.phys icalUnitsX Direction  == 0) && ( usRegion.p hysicalUni tsYDirecti on == 0))) ) {
  8086  
  8087                             usRegi onFound =  true;
  8088                             region SpatialFor mat = usRe gion.regio nSpatialFo rmat;
  8089                             physic alUnitsXDi rection =  usRegion.p hysicalUni tsXDirecti on;
  8090                             physic alUnitsYDi rection =  usRegion.p hysicalUni tsYDirecti on;
  8091                             physic alDeltaX =  usRegion. physicalDe ltaX;
  8092                             physic alDeltaY =  usRegion. physicalDe ltaY;
  8093                             break;
  8094                         }
  8095                    }
  8096  
  8097                    if ( usRegionFo und) {
  8098  
  8099                         if ((regio nSpatialFo rmat == 1)  && (physi calUnitsXD irection = = 3) && (p hysicalUni tsYDirecti on == 3))  {
  8100  
  8101                             var pi xelSpacing  = {
  8102                                 co lumn: Math .abs(physi calDeltaX)  * 10.0,
  8103                                 ro w: Math.ab s(physical DeltaY) *  10.0,
  8104                             };
  8105  
  8106                             var le ngthInCM =  getLength UsingPixel Spacing(im ageCoordin ate, pixel Spacing, t rue);
  8107  
  8108                             if (im ageCoordin ate.style. measuremen tUnits !=  null) {
  8109                                 if  (imageCoo rdinate.st yle.measur ementUnits  == "mm")  {
  8110                                      lengthIn CM *= 10.0 ;
  8111                                      resultTe xt = "" +  lengthInCM .toFixed(p recision)  + " mm";
  8112                                 }  else if(im ageCoordin ate.style. measuremen tUnits ==  "in") {
  8113                                      resultTe xt = "" +  lengthInCM .toFixed(p recision)  + " in";
  8114                                 }  else {
  8115                                      resultTe xt = "" +  lengthInCM .toFixed(p recision)  + " cm";
  8116                                 }
  8117                             } else  {
  8118                                 if  (lengthIn CM < 0.01)  {
  8119                                      lengthIn CM *= 1000 0.0;
  8120                                      resultTe xt = "" +  lengthInCM .toFixed(p recision)  + " \u00B5 " + "cm";
  8121                                 }  else if (l engthInCM  < 1) {
  8122                                      lengthIn CM *= 10.0 ;
  8123                                      resultTe xt = "" +  lengthInCM .toFixed(p recision)  + " mm";
  8124                                 }  else
  8125                                      resultTe xt = "" +  lengthInCM .toFixed(p recision)  + " cm";
  8126                             }
  8127                         } else {
  8128  
  8129                             var le ngthX = Ma th.abs(ima geCoordina te.end.x -  imageCoor dinate.sta rt.x) * Ma th.abs(phy sicalDelta X);
  8130                             var le ngthY = Ma th.abs(ima geCoordina te.end.y -  imageCoor dinate.sta rt.y) * Ma th.abs(phy sicalDelta Y);
  8131  
  8132                             var un itsX;
  8133                             var un itsY;
  8134                             if ((p hysicalUni tsXDirecti on < 0) ||  (physical UnitsXDire ction > 12 )) {
  8135                                 un itsX = "un known";
  8136                             } else  if ((phys icalUnitsY Direction  < 0) || (p hysicalUni tsYDirecti on > 12))  {
  8137                                 un itsY = "un known";
  8138                             } else  {
  8139                                 un itsX = phy sicalUnits XYDirectio nArray[phy sicalUnits XDirection ];
  8140                                 un itsY = phy sicalUnits XYDirectio nArray[phy sicalUnits YDirection ];
  8141                             }
  8142  
  8143                             if (im ageCoordin ate.measur ementType  == 1) // Y - Axis
  8144                                 re sultText =  "" + leng thY.toFixe d(precisio n) + " " +  unitsY;
  8145                             else / / X-axis
  8146                                 re sultText =  "" + leng thX.toFixe d(precisio n) + " " +  unitsX;
  8147                         }
  8148                    } el se
  8149                         resultText  = getLeng thText(ima geCoordina te);
  8150                } else {
  8151                    resu ltText = g etLengthTe xt(imageCo ordinate);
  8152                }
  8153                var valu e = result Text.split (" ")[0];
  8154                if (pars eFloat(val ue) < 0.05 ) {
  8155                    retu rn;
  8156                }
  8157           }  else {
  8158                resultTe xt = getLe ngthText(i mageCoordi nate);
  8159           }
  8160  
  8161           if  (editValu e === unde fined) {
  8162                var dist  =  Math.s qrt(Math.p ow(data.en d.x - data .start.x,  2) 
  8163                                        + Math .pow(data. end.y - da ta.start.y , 2));
  8164  
  8165                if(data. measuremen tSubType = = "Arrow")  {
  8166                    if ( dist * ima geRenderer .scaleValu e < 10) {
  8167                         return;
  8168                    }
  8169                }
  8170  
  8171                // draw  the line
  8172                context. beginPath( );
  8173                updateCo ntextStyle (context,  data.style , false, i mageRender er.scaleVa lue);
  8174                context. moveTo(dat a.start.x,  data.star t.y);
  8175                context. lineTo(dat a.end.x, d ata.end.y) ;
  8176                context. setLineDas h([]);
  8177                context. closePath( );
  8178                context. stroke();
  8179  
  8180                drawLine Handles(im ageUid, co ntext, dat a, present ation, ima geRenderer );
  8181  
  8182                if(data. measuremen tSubType ! = "2DLine"  && data.m easurement SubType !=  "Arrow")  {
  8183                    draw Measuremen tsLength(c ontext, da ta, imageR enderer, p resentatio n, resultT ext, false );
  8184                }
  8185           }
  8186           //  for repor ting
  8187           if  ((usRegio nFound) &&  (imageCoo rdinate.me asurementI d != null) ) {
  8188                return {
  8189                    id:  imageCoord inate.meas urementId,
  8190                    valu e: resultT ext
  8191                };
  8192           }
  8193  
  8194           re turn null;
  8195       }
  8196  
  8197       functi on drawEll ipseMeasur ement(imag eUid, cont ext, data,  presentat ion, image Renderer,  isEllipseE nd, isEdit Mode) {
  8198           va r imageCoo rdinate =  data;
  8199           va r result =  0;
  8200           da ta = dicom Viewer.mea surement.g etCanvasDa taForImage Data(data,  imageRend erer);
  8201           da ta.textPos ition = im ageCoordin ate.textPo sition;
  8202           va r deltaY =  (data.sta rt.y - dat a.end.y);
  8203           va r deltaX =  (data.end .x - data. start.x);
  8204           if (data.star t.y < data .end.y)
  8205                result =  Math.abs( Math.atan2 (deltaY, d eltaX));
  8206           el se
  8207                result =  Math.abs( Math.atan2 (deltaY, d eltaX)) *  -1;
  8208  
  8209           va r zoom = p resentatio n.getZoom( );
  8210           if  (data !==  undefined ) {
  8211                if (data .first ==  null || da ta.first = = undefine d || !data .isCustomE llipse) {
  8212                    cont ext.setLin eDash([],  []);
  8213                    cont ext.save() ;
  8214                    upda teContextS tyle(conte xt, data.s tyle, fals e, imageRe nderer.sca leValue);
  8215                    // P R file Ell ipse - Com pund graph ic sequenc e
  8216                    draw EllipseWit hinRectang leBounds(c ontext, da ta);
  8217                    if(i sEditMode  == undefin ed || isEd itMode) {
  8218                         var radius  = (4 * im ageRendere r.viewport Height) /  (1000 * im ageRendere r.scaleVal ue) ;
  8219                         context.se tLineDash( []);
  8220                         // draws t he four qu adrant poi nts.
  8221                         drawArcand Line(data. start, und efined, ra dius, true , "#DAA520 ", context );
  8222                         drawArcand Line(data. end, undef ined, radi us, true,  "#DAA520",  context);
  8223                        
  8224                         var third  = {
  8225                             x: dat a.start.x,
  8226                             y: dat a.end.y
  8227                         }
  8228                         var fourth  = {
  8229                             x: dat a.end.x,
  8230                             y: dat a.start.y
  8231                         }
  8232                         drawArcand Line(third , undefine d, radius,  true, "#D AA520", co ntext);
  8233                         drawArcand Line(fourt h, undefin ed, radius , true, "# DAA520", c ontext);
  8234                    }
  8235                    cont ext.restor e();
  8236                } else {
  8237                    // c alculate a nd draw th e four ell ipse quadr ants.
  8238                    draw QuadrantsO fEllipse(d ata, conte xt, imageR enderer.sc aleValue,  zoom, isEd itMode);
  8239                    if(i sEditMode  == undefin ed || isEd itMode) {
  8240                         var radius  = (4 * im ageRendere r.viewport Height) /  (1000 * im ageRendere r.scaleVal ue) ;
  8241                         context.se tLineDash( []);
  8242                         // draws t he four qu adrant poi nts.
  8243                         drawArcand Line(data. first, und efined, ra dius, true , "#DAA520 ", context );
  8244                         drawArcand Line(data. second, un defined, r adius, tru e, "#DAA52 0", contex t);
  8245                         drawArcand Line(data. third, und efined, ra dius, true , "#DAA520 ", context );
  8246                         drawArcand Line(data. fourth, un defined, r adius, tru e, "#DAA52 0", contex t);
  8247                    }
  8248                }
  8249           }
  8250           if (isEllipse End != und efined &&  data.measu rementSubT ype != "el lipse")
  8251           {
  8252                if(isEll ipseEnd)
  8253                {
  8254                    resu ltText = c alculateSt andardDevi ation(imag eUid, cont ext, image Coordinate , presenta tion, imag eRenderer) ;
  8255                    draw Measuremen tsLength(c ontext, da ta, imageR enderer, p resentatio n, resultT ext, false , true);
  8256                    retu rn resultT ext;
  8257                }
  8258                else
  8259                {
  8260                    draw Measuremen tsLength(c ontext, da ta, imageR enderer, p resentatio n, imageCo ordinate.m easurement Result, fa lse, true) ;
  8261                }
  8262           }
  8263           re turn null;
  8264       }
  8265       
  8266       /**
  8267        * dar ws ellipse  with 2 po ints (Comp und graphi c sequence )
  8268        * @pa ram {Type}  context 
  8269        * @pa ram {Type}  data 
  8270        */ 
  8271       functi on drawEll ipseWithin RectangleB ounds(cont ext, data)  {
  8272           co ntext.save ();
  8273           co ntext.begi nPath();
  8274           // Dynamic sc aling
  8275           va r scalex =  1*((data. end.x-data .start.x)/ 2);
  8276           va r scaley =  1*((data. end.y-data .start.y)/ 2);
  8277           sc alex =  sc alex == 0  ? 1 : scal ex;
  8278           sc aley =  sc aley == 0  ? 1 : scal ey;
  8279           co ntext.scal e(scalex,s caley);
  8280           // Create ell ipse
  8281           va r point =  {
  8282                x: (data .start.x/s calex)+1,
  8283                y: (data .start.y/s caley)+1
  8284           }
  8285           co ntext.arc( point.x, p oint.y, 1,  0, 2 * Ma th.PI, fal se);
  8286           // Restore an d draw
  8287           co ntext.rest ore();
  8288           co ntext.clos ePath();
  8289           if  (data.sty le.isFill)  {
  8290                context. fillStyle  = data.sty le.fillCol or;
  8291                context. fill();
  8292           }  else {
  8293                context. strokeStyl e = data.s tyle.lineC olor;
  8294                context. stroke();
  8295           }
  8296       }
  8297  
  8298       /**
  8299        * dra ws Arc or  Line using  given inp uts.
  8300        * @pa ram {Type}  start 
  8301        * @pa ram {Type}  end 
  8302        * @pa ram {Type}  radius 
  8303        * @pa ram {Type}  isArc 
  8304        * @pa ram {Type}  strokeSty le 
  8305        * @pa ram {Type}  context 
  8306        */ 
  8307       functi on drawArc andLine(st art, end,  radius, is Arc, strok eStyle, co ntext) {
  8308           co ntext.begi nPath();
  8309           co ntext.stro keStyle =  strokeStyl e;
  8310           co ntext.move To(start.x , start.y) ;
  8311           if  (isArc) {
  8312                context. arc(start. x, start.y , radius,  0, 2 * Mat h.PI, fals e);
  8313           }  else {
  8314                context. lineTo(end .x, end.y) ;
  8315           }
  8316           co ntext.clos ePath();
  8317           co ntext.stro ke();
  8318       }
  8319  
  8320       /**
  8321        * 
  8322        * @pa ram {Type}  data 
  8323        * @pa ram {Type}  context 
  8324        * @pa ram {Type}  scaleValu
  8325        */ 
  8326       functi on drawQua drantsOfEl lipse(data , context,  scaleValu e, zoom, i sEditMode)  {
  8327           //  draws cro ss line be tween quad rants.
  8328           if (data.isEd itable &&  (isEditMod e == undef ined || is EditMode))  {
  8329                context. setLineDas h([5/zoom] , [5/zoom] );
  8330                drawArca ndLine(dat a.first, d ata.second , undefine d, false,  data.style .lineColor , context) ;
  8331                drawArca ndLine(dat a.fourth,  data.third , undefine d, false,  data.style .lineColor , context) ;
  8332           }
  8333  
  8334           co ntext.setL ineDash([] , []);
  8335           co ntext.save ();
  8336           
  8337           up dateContex tStyle(con text, data .style, fa lse, scale Value);
  8338  
  8339           if  (data.cen ter == nul l || data. center ==  undefined)  {
  8340                // PR fi le Ellipse  - Compund  graphic s equenceata
  8341                data.cen ter = {
  8342                    x: ( data.first .x + data. second.x)  / 2,
  8343                    y: ( data.first .y + data. second.y)  / 2
  8344                }
  8345           }
  8346  
  8347           //  draws the  curve seg ment from  first quad rant to fo urth quadr ant.
  8348           dr awQuadrant (data.firs t, data.fo urth, { q1 : data.thi rd, q2: da ta.second  }, data.ce nter, cont ext);
  8349           
  8350           //  draws the  curve seg ment from  fourth qua drant to s econd quad rant.
  8351           dr awQuadrant (data.four th, data.s econd, { q 1: data.fi rst, q2: d ata.third  }, data.ce nter, cont ext);
  8352           
  8353           //  draws the  curve seg ment from  second qua drant to t hird quadr ant.
  8354           dr awQuadrant (data.seco nd, data.t hird, { q1 : data.fou rth, q2: d ata.first  }, data.ce nter, cont ext);
  8355           
  8356           //  draws the  curve seg ment from  third quad rant to fi rst quadra nt.
  8357           dr awQuadrant (data.thir d, data.fi rst, { q1:  data.seco nd, q2: da ta.fourth  } , data.c enter, con text);
  8358           
  8359           co ntext.rest ore();
  8360       }
  8361  
  8362       /**
  8363        * 
  8364        * @pa ram {Type}  start 
  8365        * @pa ram {Type}  end 
  8366        * @pa ram {Type}  oppositeQ uads 
  8367        * @pa ram {Type}  center 
  8368        * @pa ram {Type}  context 
  8369        * @pa ram {Type}  quadrant 
  8370        */ 
  8371       functi on drawQua drant(star t, end, op positeQuad s, center,  context)  {
  8372           co ntext.setL ineDash([] );
  8373           //  check if  the quadra nts are ci rcular for m.
  8374           if  (isCircul arQuadrant (start, en d, center) ) {
  8375                // draws  circular  curve.
  8376                renderCu rveSegment (0, Math.P I * 0.5, c enter, sta rt, false,  context);
  8377           }  else {
  8378                // draws  two curve  segment b etween sta rting and  ending qua drant.
  8379                
  8380                // calcu late two c enter poin ts and ang les to dra w the curv e
  8381                var quad Info = get QuadrantIn fo(start,  end, oppos iteQuads,  center, co ntext);
  8382                
  8383                var angl e = Math.a bs(quadInf o.r2Angle) ;
  8384                var swap  = quadInf o.isSwappe d;
  8385                var cent er = quadI nfo.c2Pt;
  8386                
  8387                // draws  the first  curve seg ment of a  quadrant.
  8388                var firs tEndPt = r enderCurve Segment(0,  angle, ce nter, swap  ? start :  end, swap  ? false :  true, con text);
  8389                
  8390                angle =  Math.abs(q uadInfo.r1 Angle);
  8391                center =  quadInfo. c1Pt;
  8392                // draws  the secon d curve se gment of a  quadrant.
  8393                var seco ndEndPt =  renderCurv eSegment(0 , angle, c enter, swa p ? end :  start, swa p ? true :  false, co ntext);
  8394                
  8395                // conne cts the mi ssing path  between t wo curve s egments.
  8396                if (firs tEndPt !=  undefined  && secondE ndPt != un defined) {
  8397                    cont ext.moveTo (firstEndP t.x, first EndPt.y);
  8398                    cont ext.quadra ticCurveTo (firstEndP t.x, first EndPt.y, s econdEndPt .x, second EndPt.y);
  8399                    cont ext.stroke ();
  8400                }
  8401           }
  8402       }
  8403  
  8404       /**
  8405        * Ret urns the e ndpoint fo r the draw n curve se gment.
  8406        * @pa ram {Type}  startAngl
  8407        * @pa ram {Type}  endAngle 
  8408        * @pa ram {Type}  center 
  8409        * @pa ram {Type}  quadrant 
  8410        * @pa ram {Type}  isNegativ
  8411        * @pa ram {Type}  context 
  8412        */ 
  8413       functi on renderC urveSegmen t(startAng le, endAng le, center , quadrant , isNegati ve, contex t) {
  8414           co ntext.begi nPath();
  8415           va r point;
  8416           fo r (var i =  startAngl e; i < end Angle; i + = 0.01) {
  8417                point =  rotate(cen ter.x, cen ter.y, qua drant, isN egative ?  -i : i);
  8418                if (i ==  startAngl e) {
  8419                    cont ext.moveTo (point.x,  point.y);
  8420                } else {
  8421                    cont ext.lineTo (point.x,  point.y);
  8422                }
  8423           }
  8424           co ntext.stro ke();
  8425           re turn point ;
  8426       }
  8427  
  8428       functi on checkLo op(isNegat ive, i, en dAngle) {
  8429           re turn isNeg ative ? i  > endAngle  : i < end Angle;
  8430       }
  8431       
  8432       functi on incrLoo p(isNegati ve, i) {
  8433           re turn isNeg ative ? i  - 0.01 : i  + 0.01;
  8434       }
  8435  
  8436       /**
  8437        * Rot ate a poin t to given  radians w ith given  center poi nt.
  8438        * @pa ram {Type}  cx 
  8439        * @pa ram {Type}  cy 
  8440        * @pa ram {Type}  point 
  8441        * @pa ram {Type}  radians 
  8442        */ 
  8443       functi on rotate( cx, cy, po int, radia ns) {
  8444                cos = Ma th.cos(rad ians),
  8445                sin = Ma th.sin(rad ians),
  8446                nx = (co s * (point .x - cx))  + (sin * ( point.y -  cy)) + cx,
  8447                ny = (co s * (point .y - cy))  - (sin * ( point.x -  cx)) + cy;
  8448           re turn { x:  nx, y: ny} ;
  8449       }
  8450  
  8451       /**
  8452        * Che cks whethe r the quad rants are  circular.
  8453        * @pa ram {Type}  start 
  8454        * @pa ram {Type}  end 
  8455        * @pa ram {Type}  center 
  8456        */ 
  8457       functi on isCircu larQuadran t(start, e nd, center ) {
  8458           va r firstPos  = findDSA Value(star t, center) ,
  8459                secondPo s = findDS AValue(end , center);
  8460           if  (Math.abs (secondPos .distance  - firstPos .distance)  <= 2) {
  8461                return t rue;
  8462           }
  8463           re turn false ;
  8464       }
  8465  
  8466       /**
  8467        * Cal culate dis tance, ang le and slo pe values  for two gi ven points .
  8468        * @pa ram {Type}  start 
  8469        * @pa ram {Type}  end 
  8470        */ 
  8471       functi on findDSA Value(star t, end) {
  8472           va r dx = end .x - start .x,
  8473                dy = end .y - start .y,
  8474                distance  = Math.sq rt(Math.po w(dx, 2) +  Math.pow( dy, 2)),
  8475                cosalpha  = dx / di stance,
  8476                angle, s lope;
  8477           sl ope = (end .y - start .y) / (end .x - start .x);
  8478           if  (dy / dis tance < 0)
  8479           {
  8480                angle =  (Math.PI *  2 - Math. acos(cosal pha));
  8481           }
  8482           el se
  8483           {
  8484                angle =  (Math.acos (cosalpha) );
  8485           }
  8486           re turn { dis tance : di stance, an gle : angl e, slope :  slope };
  8487       }
  8488  
  8489       /**
  8490        * Cal culates th e two cent er points  and angles  to draw t he two cur ve segment s of the q uadrants.
  8491        * @pa ram {Type}  start 
  8492        * @pa ram {Type}  end 
  8493        * @pa ram {Type}  oppositeQ uads 
  8494        * @pa ram {Type}  center 
  8495        * @pa ram {Type}  context 
  8496        */ 
  8497       functi on getQuad rantInfo(s tart, end,  oppositeQ uads, cent er, contex t) {
  8498           /*  Refer the  following  pdf for t he calcula tions.
  8499           ht tps://acad emics.rowa n.edu/csm/ department s/math/fac ultystaff/ faculty/os ler/106%20 APPROXIMAT ING%20AN%2 0ELLIPSE%2 0WITH%20FO UR%20CIRCU LAR%20ARCS %20Sept2su bmission%2 0to%20MACE _Rev3a.pdf
  8500           *
  8501           */
  8502           va r quadrant Info = {},
  8503                dx, dy,  slopeDista nce, start Dist, endD ist,
  8504                cosalpha , r1Angle,  r2Angle,  slope, c1P t, c2Pt;
  8505           
  8506           va r startPos  = findDSA Value(cent er, start) ;
  8507           st artDist =  startPos.d istance;
  8508           va r endPos =  findDSAVa lue(center , end);
  8509           en dDist = en dPos.dista nce;
  8510           va r slopePos  = findDSA Value(star t, end);
  8511           sl opeDistanc e = slopeP os.distanc e;
  8512           
  8513           r2 Angle = sl opePos.ang le - Math. PI;
  8514           r1 Angle = Ma th.abs(Mat h.PI - ((M ath.PI * 0 .5) + r2An gle));
  8515           
  8516           va r multipli er = (r2An gle > -Mat h.PI * 0.5  && r2Angl e < Math.P I * 0.5) ?  -1 : 1;
  8517           va r finalDis t = startD ist - endD ist,
  8518                finalSta rtPt = sta rt, finalE ndPt = end ,
  8519                finalSta rtPos = st artPos, fi nalEndPos  = endPos,
  8520                opposite  = opposit eQuads.q1,  isSwapped  = false;
  8521           
  8522           //  Swap the  end points  if the en d point di stance to  center poi nt is grea ter than s tart point  distance.
  8523           if  (endDist  > startDis t) {
  8524                finalDis t = endDis t - startD ist;
  8525                finalSta rtPt = end ;
  8526                finalEnd Pt = start ;
  8527                finalSta rtPos = en dPos;
  8528                finalEnd Pos = star tPos;
  8529                multipli er = -mult iplier;
  8530                opposite  = opposit eQuads.q2;
  8531                isSwappe d= true;
  8532           }
  8533  
  8534           //  find mid  point afte r subtract ing the di fference t o center a long the s lope of st art and en d points.
  8535           va r normaliz edSlopeDis t = (slope Distance -  finalDist ) / 2;
  8536           sl ope = slop ePos.slope ;
  8537           va r midPt =  {
  8538                x: final StartPt.x  + multipli er * (norm alizedSlop eDist / Ma th.sqrt(1  + Math.pow (slope, 2) )),
  8539                y: final StartPt.y  + multipli er * ((slo pe * norma lizedSlope Dist) / Ma th.sqrt(1  + Math.pow (slope, 2) ))
  8540           };
  8541           
  8542           //  find a po int of per pendicular  line to t he slope f rom the ab ove mid po int.
  8543           sl ope = - (1  / slope);
  8544           mu ltiplier =  (r2Angle  > 0 && r2A ngle < Mat h.PI) ? -1  : 1;
  8545           te mpPt = {
  8546                x: midPt .x + multi plier * (s lopeDistan ce / Math. sqrt(1 + M ath.pow(sl ope, 2))),
  8547                y: midPt .y + multi plier * (( slope * sl opeDistanc e) / Math. sqrt(1 + M ath.pow(sl ope, 2)))
  8548           };
  8549           
  8550           //  find the  two center s to draw  the curve  segments.
  8551           va r centers  = findC1an dC2Points( finalStart Pt, finalE ndPt, oppo site, cent er, midPt,  tempPt);
  8552           
  8553           //  find two  angles of  curve segm ents.
  8554           va r centerPo s = findDS AValue(cen ters.c1Pt,  centers.c 2Pt);
  8555           r1 Angle = Ma th.atan((c enterPos.s lope - fin alStartPos .slope) /  ( 1 + (fin alStartPos .slope * c enterPos.s lope)));
  8556           r2 Angle = Ma th.atan((c enterPos.s lope - fin alEndPos.s lope) / (  1 + (final EndPos.slo pe * cente rPos.slope )));
  8557           
  8558           r1 Angle = is NaN(r1Angl e) ? (Math .PI * 0.25 ) : r1Angl e;
  8559           r2 Angle = is NaN(r2Angl e) ? (Math .PI * 0.25 ) : r2Angl e;
  8560  
  8561           qu adrantInfo  = {
  8562               r1Angle:  r1Angle,
  8563               r2Angle:  r2Angle,
  8564               c1Pt: cen ters.c1Pt,
  8565               c2Pt: cen ters.c2Pt,
  8566               isSwapped : isSwappe d
  8567          }
  8568          ret urn quadra ntInfo;
  8569       }
  8570  
  8571       /**
  8572        * Ret urns two c enter poin ts using g iven lines  by findin g its inte rsections.
  8573        * @pa ram {Type}  start 
  8574        * @pa ram {Type}  end 
  8575        * @pa ram {Type}  opposite 
  8576        * @pa ram {Type}  center 
  8577        * @pa ram {Type}  midPt 
  8578        * @pa ram {Type}  tempPt 
  8579        */ 
  8580       functi on findC1a ndC2Points (start, en d, opposit e, center,  midPt, te mpPt) {
  8581           va r c2Pt = f indInterse ctingPt(mi dPt, end,  opposite,  tempPt),
  8582                c1Pt = f indInterse ctingPt(mi dPt, cente r, start,  c2Pt);
  8583           re turn { c1P t : c1Pt,  c2Pt : c2P t };
  8584       }
  8585  
  8586       /**
  8587        * Ret urn the po int of int ersection.
  8588        */ 
  8589       functi on findInt ersectingP t (pt1, pt 2, pt3, pt 4) {
  8590           //  Line AB r epresented  as a1x +  b1y = c1
  8591           va r a1 = pt4 .y - pt1.y ;
  8592           va r b1 = pt1 .x - pt4.x ;
  8593           va r c1 = a1* (pt1.x) +  b1*(pt1.y) ;
  8594  
  8595           //  Line CD r epresented  as a2x +  b2y = c2
  8596           va r a2 = pt3 .y - pt2.y ;
  8597           va r b2 = pt2 .x - pt3.x ;
  8598           va r c2 = a2* (pt2.x)+ b 2*(pt2.y);
  8599  
  8600           va r determin ant = a1*b 2 - a2*b1,
  8601                intersec tingPt;
  8602           if  (determin ant == 0)
  8603           {
  8604                // The l ines are p arallel.
  8605           }
  8606           el se
  8607           {
  8608                intersec tingPt = {
  8609                    x: ( b2*c1 - b1 *c2)/deter minant,
  8610                    y: ( a1*c2 - a2 *c1)/deter minant
  8611                };
  8612           }
  8613           re turn inter sectingPt;
  8614       }
  8615  
  8616       /**
  8617        * To  draw recta ngle measu rement of  hounsfield  and annot ation type s
  8618        * @pa ram {Type}  imageUid 
  8619        * @pa ram {Type}  context 
  8620        * @pa ram {Type}  data 
  8621        * @pa ram {Type}  presentat ion 
  8622        * @pa ram {Type}  imageRend erer 
  8623        * @pa ram {Type}  isRectang leEnd 
  8624        * @pa ram {Type}  isEditMod
  8625        */ 
  8626       functi on drawRec tangleMeas urement(im ageUid, co ntext, dat a, present ation, ima geRenderer , isRectan gleEnd, is EditMode,i sEdit) {
  8627           va r isFill =  data.styl e.isFill;
  8628           up dateContex tStyle(con text, data .style, fa lse, image Renderer.s caleValue,  undefined , isFill);
  8629           va r imageCoo rdinate =  getAndUpda teTextBoun ds(context , data, im ageRendere r);
  8630           da ta = dicom Viewer.mea surement.g etCanvasDa taForImage Data(data,  imageRend erer);
  8631           da ta.textPos ition = im ageCoordin ate.textPo sition;
  8632           va r deltaY =  (data.end .y - data. start.y);
  8633           va r deltaX =  (data.end .x - data. start.x);
  8634  
  8635           va r result =  0;
  8636           if (data.star t.y < data .end.y)
  8637                result =  Math.abs( Math.atan2 (deltaY, d eltaX));
  8638           el se
  8639                result =  Math.abs( Math.atan2 (deltaY, d eltaX)) *  -1;
  8640           
  8641           if  (data !==  undefined ) {
  8642                context. beginPath( );
  8643                //Restor e and draw
  8644                if (data .measureme ntSubType  === "text" ) {
  8645                    cont ext.setLin eDash([4,  4]);
  8646                } else {
  8647                    cont ext.setLin eDash([]);
  8648                }
  8649                //Create  rectangle
  8650                if(!(dat a.measurem entType ==  8 && data .measureme ntSubType  === "text"  && 
  8651                     ((i sRectangle End == und efined &&  isEditMode  == false  && isEdit  == undefin ed) ||
  8652                     (is RectangleE nd == true  && isEdit Mode == fa lse))
  8653                    )) {
  8654                    cont ext.moveTo (data.star t.x, data. start.y);
  8655                    cont ext.lineTo (data.star t.x, data. end.y);
  8656                    cont ext.lineTo (data.end. x, data.en d.y);
  8657                    cont ext.lineTo (data.end. x, data.st art.y);
  8658                    cont ext.closeP ath();
  8659                    if ( isFill) {
  8660                         context.fi ll();
  8661                    } el se {
  8662                         context.st roke();
  8663                    }
  8664                    
  8665                }
  8666  
  8667                context. setLineDas h([]);
  8668                if(isEdi tMode == u ndefined | | isEditMo de) {
  8669                    var  radius = ( 4 * imageR enderer.vi ewportHeig ht) / (100 0 * imageR enderer.sc aleValue)  ;
  8670                    cont ext.lineWi dth = radi us;
  8671                    cont ext.beginP ath();
  8672                    cont ext.stroke Style = "# DAA520";
  8673                    cont ext.arc(da ta.start.x , data.sta rt.y, radi us, 0, 2 *  Math.PI,  false);
  8674                    cont ext.closeP ath();
  8675                    cont ext.stroke ();
  8676  
  8677                    cont ext.beginP ath();
  8678                    cont ext.stroke Style = "# DAA520";
  8679                    cont ext.arc(da ta.start.x , data.end .y, radius , 0, 2 * M ath.PI, fa lse);
  8680                    cont ext.closeP ath();
  8681                    cont ext.stroke ();
  8682  
  8683                    cont ext.beginP ath();
  8684                    cont ext.stroke Style = "# DAA520";
  8685                    cont ext.arc(da ta.end.x,  data.end.y , radius,  0, 2 * Mat h.PI, fals e);
  8686                    cont ext.closeP ath();
  8687                    cont ext.stroke ();
  8688  
  8689                    cont ext.beginP ath();
  8690                    cont ext.stroke Style = "# DAA520";
  8691                    cont ext.arc(da ta.end.x,  data.start .y, radius , 0, 2 * M ath.PI, fa lse);
  8692                    cont ext.closeP ath();
  8693                    cont ext.stroke ();
  8694                }
  8695           }
  8696  
  8697           va r isText =  (data.mea surementSu bType ===  "text") ?  true : fal se;
  8698           if (isRectang leEnd != u ndefined & & data.mea surementSu bType ===  "hounsfiel d")
  8699           {
  8700                if(isRec tangleEnd)
  8701                {
  8702                    resu ltText = c alculateSt andardDevi ation(imag eUid, cont ext, image Coordinate , presenta tion, imag eRenderer) ;
  8703                    draw Measuremen tsLength(c ontext, da ta, imageR enderer, p resentatio n, resultT ext, false , false, f alse, true );
  8704                    retu rn resultT ext;
  8705                }
  8706                else
  8707                {
  8708                    draw Measuremen tsLength(c ontext, da ta, imageR enderer, p resentatio n, imageCo ordinate.m easurement Result, fa lse, false , false, t rue);
  8709                }
  8710           }  else if((i sEdit && i sText) ||  (isRectang leEnd != u ndefined & & isText))  {
  8711                if ((isE dit) || (i sRectangle End && dat a.measurem entText != = undefine d && data. measuremen tText.leng th > 0)) {
  8712                    resu ltText = d ata.measur ementText;
  8713                    draw Measuremen tsLength(c ontext, da ta, imageR enderer, p resentatio n, resultT ext, false , false, t rue);
  8714                }
  8715           }
  8716           re turn null;
  8717       }
  8718  
  8719       functi on drawPoi ntMeasurem ent(imageU id, contex t, data, p resentatio n, imageRe nderer, ed itValue) {
  8720           va r imageCoo rdinate =  data;
  8721           da ta = dicom Viewer.mea surement.g etCanvasDa taForImage Data(data,  imageRend erer);
  8722           da ta.textPos ition = im ageCoordin ate.textPo sition;
  8723           va r scale =  presentati on.getZoom ();
  8724           va r dicomHea der = dico mViewer.he ader.getDi comHeader( imageUid);
  8725  
  8726           va r resultTe xt = null;
  8727           if  (dicomHea der.imageI nfo.measur ement != n ull) {
  8728                if ((dic omHeader.i mageInfo.m easurement .usRegions  != null)  && (dicomH eader.imag eInfo.meas urement.us Regions.le ngth > 0))  {
  8729                    var  usRegionFo und = fals e;
  8730                    var  regionSpat ialFormat  = 0;
  8731                    var  physicalUn itsXDirect ion = 0;
  8732                    var  physicalUn itsYDirect ion = 0;
  8733                    var  roiPosXVal ue = 0.0;
  8734                    var  roiPosYVal ue = 0.0;
  8735                    var  isReferenc ePixelX0Pr esent = fa lse;
  8736                    var  isReferenc ePixelY0Pr esent = fa lse;
  8737  
  8738                    for  (var i = 0 ; i < dico mHeader.im ageInfo.me asurement. usRegions. length; i+ +) {
  8739                         var usRegi on = dicom Header.ima geInfo.mea surement.u sRegions[i ];
  8740  
  8741                         if (((usRe gion.regio nSpatialFo rmat == 2)  || (usReg ion.region SpatialFor mat == 3))  &&
  8742                             ((imag eCoordinat e.start.x  <= usRegio n.regionLo cationMaxX 1) && (ima geCoordina te.start.x  >= usRegi on.regionL ocationMin X0)) &&
  8743                             ((imag eCoordinat e.start.y  <= usRegio n.regionLo cationMaxY 1) && (ima geCoordina te.start.y  >= usRegi on.regionL ocationMin Y0))) {
  8744                             usRegi onFound =  true;
  8745                             region SpatialFor mat = usRe gion.regio nSpatialFo rmat;
  8746                             physic alUnitsXDi rection =  usRegion.p hysicalUni tsXDirecti on;
  8747                             physic alUnitsYDi rection =  usRegion.p hysicalUni tsYDirecti on;
  8748                             isRefe rencePixel X0Present  = usRegion .isReferen cePixelX0P resent;
  8749                             isRefe rencePixel Y0Present  = usRegion .isReferen cePixelY0P resent;
  8750  
  8751                             if (is ReferenceP ixelX0Pres ent) {
  8752                                 ro iPosXValue  = (imageC oordinate. start.x -  (usRegion. regionLoca tionMinX0  + usRegion .reference PixelX0) +  usRegion. referenceP ixelPhysic alValueX)  * usRegion .physicalD eltaX;
  8753                             }
  8754  
  8755                             if (is ReferenceP ixelY0Pres ent) {
  8756  
  8757                                 if  (usRegion .regionSpa tialFormat  == 2)
  8758                                 //  M-Mode
  8759                                      roiPosYV alue = -(( usRegion.r egionLocat ionMinY0 +  usRegion. referenceP ixelY0) -  imageCoord inate.end. y + usRegi on.referen cePixelPhy sicalValue Y) * Math. abs(usRegi on.physica lDeltaY);
  8760                                 el se
  8761                                 //  Spectral
  8762                                      roiPosYV alue = ((u sRegion.re gionLocati onMinY0 +  usRegion.r eferencePi xelY0) - i mageCoordi nate.end.y  + usRegio n.referenc ePixelPhys icalValueY ) * Math.a bs(usRegio n.physical DeltaY);
  8763                             }
  8764  
  8765                             break;
  8766                         }
  8767                    }
  8768  
  8769                    if ( usRegionFo und) {
  8770  
  8771                         var unitsX ;
  8772                         var unitsY ;
  8773                         if ((physi calUnitsXD irection <  0) || (ph ysicalUnit sXDirectio n > 12)) {
  8774                             unitsX  = "unknow n";
  8775                         } else if  ((physical UnitsYDire ction < 0)  || (physi calUnitsYD irection >  12)) {
  8776                             unitsY  = "unknow n";
  8777                         } else {
  8778                             unitsX  = physica lUnitsXYDi rectionArr ay[physica lUnitsXDir ection];
  8779                             unitsY  = physica lUnitsXYDi rectionArr ay[physica lUnitsYDir ection];
  8780                         }
  8781  
  8782                         if ((!isRe ferencePix elX0Presen t) && (isR eferencePi xelY0Prese nt)) {
  8783                             if (im ageCoordin ate.measur ementType  == 1) {
  8784                                 //  Y- Axis
  8785                                 re sultText =  formatMea surementRe sult(roiPo sYValue, u nitsY, ima geCoordina te.measure mentUnits) ;
  8786                             } else  {
  8787                                 re sultText =  formatMea surementRe sult(null,  unitsX, i mageCoordi nate.measu rementUnit s);
  8788                             }
  8789                         } else if  ((isRefere ncePixelX0 Present) & & (!isRefe rencePixel Y0Present) ) {
  8790                             if (im ageCoordin ate.measur ementType  == 1) {
  8791                                 //  Y- Axis
  8792                                 re sultText =  formatMea surementRe sult(null,  unitsY, i mageCoordi nate.measu rementUnit s);
  8793                             } else  {
  8794                                 re sultText =  formatMea surementRe sult(roiPo sXValue, u nitsX, ima geCoordina te.measure mentUnits) ;
  8795                             }
  8796                         } else if  ((!isRefer encePixelX 0Present)  && (!isRef erencePixe lY0Present )) {
  8797                             if (im ageCoordin ate.measur ementType  == 1) {
  8798                                 //  Y- Axis
  8799                                 re sultText =  formatMea surementRe sult(null,  unitsY, i mageCoordi nate.measu rementUnit s);
  8800                             } else  {
  8801                                 re sultText =  formatMea surementRe sult(null,  unitsX, i mageCoordi nate.measu rementUnit s);
  8802                             }
  8803                         } else
  8804                         if (imageC oordinate. measuremen tType == 1 ) {
  8805                             // Y-  Axis
  8806                             result Text = for matMeasure mentResult (roiPosYVa lue, units Y, imageCo ordinate.m easurement Units);
  8807                         } else {
  8808                             result Text = for matMeasure mentResult (roiPosXVa lue, units X, imageCo ordinate.m easurement Units);
  8809                         }
  8810                    } el se {
  8811                         resultText  = "" + (i mageCoordi nate.end.x ).toFixed( 0) + " pix , " + (ima geCoordina te.end.y). toFixed(0)  + " pix";
  8812                    }
  8813                } else {
  8814                    resu ltText = " " + (image Coordinate .end.x).to Fixed(0) +  " pix, "  + (imageCo ordinate.e nd.y).toFi xed(0) + "  pix";
  8815                }
  8816           }  else {
  8817                resultTe xt = "" +  (imageCoor dinate.end .x).toFixe d(0) + " p ix, " + (i mageCoordi nate.end.y ).toFixed( 0) + " pix ";
  8818           }
  8819  
  8820           if  (editValu e === unde fined) {
  8821                // draw  the line
  8822                context. beginPath( );
  8823                updateCo ntextStyle (context,  data.style , false, i mageRender er.scaleVa lue);
  8824                //var re ctSize = 2  / (imageR enderer.sc aleValue /  scale);
  8825                var rect Size = (3  * imageRen derer.view portHeight ) / (1000  * imageRen derer.scal eValue) ;
  8826                //contex t.fillRect (data.end. x, data.en d.y, rectS ize, rectS ize);
  8827                context. arc(data.e nd.x, data .end.y, re ctSize, 0,  2 * Math. PI, false) ;
  8828                if (data .start.han dleActive)
  8829                    cont ext.fillSt yle = '#DA A520';
  8830                else
  8831                    cont ext.fillSt yle = data .style.lin eColor;
  8832                context. fill();
  8833                context. closePath( );
  8834  
  8835                context. stroke();
  8836  
  8837                drawMeas urementsLe ngth(conte xt, data,  imageRende rer, prese ntation, r esultText,  true);
  8838           }
  8839  
  8840           //  for repor ting
  8841           if  ((usRegio nFound) &&  (imageCoo rdinate.me asurementI d != null) ) {
  8842                return {
  8843                    id:  imageCoord inate.meas urementId,
  8844                    valu e: resultT ext
  8845                };
  8846           }
  8847  
  8848           re turn null;
  8849       }
  8850  
  8851       functi on drawTra ceMeasurem ent(imageU id, contex t, data, p resentatio n, imageRe nderer, dr awTraceEnd , averageX , averageY , isEditMo de) {
  8852           va r imageCoo rdinate =  data;
  8853           da ta = dicom Viewer.mea surement.g etCanvasDa taForImage Data(data,  imageRend erer);
  8854           da ta.textPos ition = im ageCoordin ate.textPo sition;
  8855           va r scale =  presentati on.getZoom ();
  8856           va r dicomHea der = dico mViewer.he ader.getDi comHeader( imageUid);
  8857           va r usRegion Found = fa lse;
  8858  
  8859           //  draw the  line
  8860           co ntext.begi nPath();
  8861           if  (isEditMo de == unde fined || i sEditMode)
  8862                context. fillStyle  = '#DAA520 ';
  8863           el se
  8864                context. fillStyle  = data.sty le.lineCol or;
  8865           va r rectSize  = 2 / (im ageRendere r.scaleVal ue / scale );
  8866           // context.fi llRect(dat a.end.x, d ata.end.y,  rectSize,  rectSize) ;
  8867           co ntext.arc( data.start .x, data.s tart.y, re ctSize, 0,  2 * Math. PI, false) ;
  8868           co ntext.clos ePath();
  8869           co ntext.fill ();
  8870           co ntext.begi nPath();
  8871           up dateContex tStyle(con text, data .style, fa lse, image Renderer.s caleValue) ;
  8872           co ntext.move To(data.st art.x, dat a.start.y) ;
  8873           co ntext.line To(data.en d.x, data. end.y);
  8874           co ntext.setL ineDash([5 /scale, 10 /scale]);
  8875           co ntext.clos ePath();
  8876           co ntext.stro ke();
  8877  
  8878           if  (drawTrac eEnd) {
  8879                // Draw  the text
  8880                resultTe xt = "" +  (averageX)  + " pix,  " + (avera geY) + " p ix";
  8881                drawMeas urementsLe ngth(conte xt, data,  imageRende rer, prese ntation, r esultText,  false);
  8882  
  8883                // for r eporting
  8884                if ((usR egionFound ) && (imag eCoordinat e.measurem entId != n ull)) {
  8885                    retu rn {
  8886                         id: imageC oordinate. measuremen tId,
  8887                         value: res ultText
  8888                    };
  8889                }
  8890           }
  8891           re turn null;
  8892       }
  8893  
  8894       // Dra w angle 
  8895       functi on drawAng leMeasurem ent(imageU id, contex t, data, p resentatio n, imageRe nderer, is EditMode)  {
  8896           va r imageCoo rdinate =  data;
  8897           
  8898           da ta = dicom Viewer.mea surement.g etCanvasDa taForImage Data(data,  imageRend erer);
  8899           da ta.textPos ition = im ageCoordin ate.textPo sition;
  8900           va r scale =  presentati on.getZoom ();
  8901           
  8902           //  draw the  line
  8903           co ntext.begi nPath();
  8904           up dateContex tStyle(con text, data .style, fa lse, image Renderer.s caleValue) ;
  8905           va r rectSize  = 2 / (im ageRendere r.scaleVal ue / scale );
  8906           
  8907           if  (data.sta rt.handleA ctive)
  8908                context. fillStyle  = '#DAA520 ';
  8909           el se
  8910                context. fillStyle  = data.sty le.lineCol or;
  8911           co ntext.fill ();
  8912           co ntext.move To(data.st art.x, dat a.start.y) ;
  8913           co ntext.line To(data.en d.x, data. end.y);
  8914           co ntext.setL ineDash([] );
  8915           co ntext.clos ePath();
  8916           co ntext.stro ke();
  8917           if  (isEditMo de == unde fined || i sEditMode)  {
  8918                drawLine Handles(im ageUid, co ntext, dat a, present ation, ima geRenderer );
  8919           }
  8920           re turn null;
  8921       }
  8922       
  8923   /**
  8924    * Calcula tes the an gle (in de gree) betw een two ve ctors poin ting outwa rd from on e center
  8925    *
  8926    * @param  p0 first p oint
  8927    * @param  p1 second  point
  8928    * @param  c center p oint
  8929    */
  8930       functi on calcula teAngle(p0 ,p1,c, sty le) {
  8931           va r p0c = Ma th.sqrt(Ma th.pow(c.x -p0.x,2)+M ath.pow(c. y-p0.y,2)) ; // p0->c  (b)   
  8932           va r p1c = Ma th.sqrt(Ma th.pow(c.x -p1.x,2)+M ath.pow(c. y-p1.y,2)) ; // p1->c  (a)
  8933           va r p0p1 = M ath.sqrt(M ath.pow(p1 .x-p0.x,2) +Math.pow( p1.y-p0.y, 2)); // p0 ->p1 (c)
  8934       
  8935           va r angleRad  = Math.ac os((p1c*p1 c+p0c*p0c- p0p1*p0p1) /(2*p1c*p0 c));
  8936           va r resultDe g = (angle Rad*180)/M ath.PI;
  8937           re turn resul tDeg.toFix ed(parseIn t(style.pr ecision));
  8938       }
  8939           
  8940       functi on drawMit ralMeanGra dientMeasu rement(ima geUid, con text, data , presenta tion, imag eRenderer,  drawTrace End, gadia ntValues,  isEditMode ) {
  8941           va r imageCoo rdinate =  data;
  8942           da ta = dicom Viewer.mea surement.g etCanvasDa taForImage Data(data,  imageRend erer);
  8943           da ta.textPos ition = im ageCoordin ate.textPo sition;
  8944           va r scale =  presentati on.getZoom ();
  8945           va r dicomHea der = dico mViewer.he ader.getDi comHeader( imageUid);
  8946           va r usRegion Found = fa lse;
  8947  
  8948           //  draw the  line
  8949           co ntext.begi nPath();
  8950           if  (isEditMo de == unde fined || i sEditMode)
  8951                context. fillStyle  = '#DAA520 ';
  8952           el se
  8953                context. fillStyle  = data.sty le.lineCol or;
  8954           va r rectSize  = 2 / (im ageRendere r.scaleVal ue / scale );
  8955           // context.fi llRect(dat a.end.x, d ata.end.y,  rectSize,  rectSize) ;
  8956           co ntext.arc( data.start .x, data.s tart.y, re ctSize, 0,  2 * Math. PI, false) ;
  8957           co ntext.clos ePath();
  8958           co ntext.fill ();
  8959           co ntext.begi nPath();
  8960           up dateContex tStyle(con text, data .style, fa lse, image Renderer.s caleValue) ;
  8961           co ntext.move To(data.st art.x, dat a.start.y) ;
  8962           co ntext.line To(data.en d.x, data. end.y);
  8963           co ntext.setL ineDash([5 /scale, 10 /scale]);
  8964           co ntext.clos ePath();
  8965           co ntext.stro ke();
  8966  
  8967           if  (drawTrac eEnd) {
  8968                // Draw  the text
  8969                if (gadi antValues. Unit == "p ix") {
  8970                    resu ltText = " " + (gadia ntValues.P ixelX) + "  pix, " +  (gadiantVa lues.Pixel Y) + " pix ";
  8971                } else {
  8972                    resu ltText = " " + (gadia ntValues.V alue) + "  " + gadian tValues.Un it;
  8973                }
  8974  
  8975                drawMeas urementsLe ngth(conte xt, data,  imageRende rer, prese ntation, r esultText,  false);
  8976  
  8977                // for r eporting
  8978                if (imag eCoordinat e.measurem entId != n ull) {
  8979                    retu rn {
  8980                         id: imageC oordinate. measuremen tId,
  8981                         value: res ultText
  8982                    };
  8983                }
  8984           }
  8985           re turn null;
  8986       }
  8987  
  8988       /**
  8989        * Dra w the free  hand meas urement
  8990        */ 
  8991       functi on drawFre eHandMeasu rement(ima geUid, con text, data , presenta tion,
  8992                                            im ageRendere r, drawTra ceEnd, isE ditMode, m easurement s) {
  8993           tr y
  8994           {
  8995                var imag eCoordinat e = data;
  8996                data = d icomViewer .measureme nt.getCanv asDataForI mageData(d ata, image Renderer);
  8997                var scal e = presen tation.get Zoom();
  8998  
  8999                context. beginPath( );
  9000                if (isEd itMode ==  undefined  || isEditM ode) {
  9001                    cont ext.fillSt yle = '#DA A520';
  9002                } else {
  9003                    cont ext.fillSt yle = data .style.lin eColor;
  9004                }
  9005  
  9006                var rect Size = 2 /  (imageRen derer.scal eValue / s cale);
  9007                context. arc(data.s tart.x, da ta.start.y , rectSize , 0, 2 * M ath.PI, fa lse);
  9008                context. closePath( );
  9009                context. fill();
  9010  
  9011                // Draw  line
  9012                if(measu rements !=  undefined ) {
  9013                    if(m easurement s.length > = 2) {
  9014                         context.be ginPath();
  9015                         context.se tLineDash( []);
  9016                         context.mo veTo.apply (context,  measuremen ts[0]);
  9017  
  9018                         // Draw th e line cur ve
  9019                         var length  = measure ments.leng th;
  9020                         for (var i  = 0; 0 <=  length ?  i < length  : i > len gth; 0 <=  length ? i ++ : i--)  {
  9021                             addCur veSegment( context, i , measurem ents);
  9022                         }
  9023                         var lineJo in = conte xt.lineJoi n;
  9024                         var lineCa p = contex t.lineCap;
  9025                         updateCont extStyle(c ontext, da ta.style,  false, ima geRenderer .scaleValu e);
  9026                         context.li neJoin = ' round';
  9027                         context.li neCap = 'r ound';
  9028                         context.st roke();
  9029                         context.li neJoin = l ineJoin;
  9030                         context.li neCap = li neCap;
  9031                    }
  9032                }
  9033           }
  9034           ca tch(e)
  9035           {  }
  9036       }
  9037  
  9038       /**
  9039        * Dra w pen
  9040        */ 
  9041       functi on drawPen Measuremen t(imageUid , context,  data, pre sentation,
  9042                                            im ageRendere r, isEditM ode) {
  9043           tr y
  9044           {
  9045                var imag eCoordinat e = data;
  9046                data = d icomViewer .measureme nt.getCanv asDataForI mageData(d ata, image Renderer);
  9047                var scal e = presen tation.get Zoom();
  9048                var dico mHeader =  dicomViewe r.header.g etDicomHea der(imageU id);
  9049                var usRe gionFound  = false;
  9050  
  9051                // draw  the line
  9052                context. beginPath( );
  9053                if (isEd itMode ==  undefined  || isEditM ode)
  9054                    cont ext.fillSt yle = '#DA A520';
  9055                else
  9056                    cont ext.fillSt yle = data .style.lin eColor;
  9057                var rect Size = 2 /  (imageRen derer.scal eValue / s cale);
  9058                //contex t.fillRect (data.end. x, data.en d.y, rectS ize, rectS ize);
  9059                context. closePath( );
  9060                context. fill();
  9061                context. beginPath( );
  9062                updateCo ntextStyle (context,  data.style , false, i mageRender er.scaleVa lue);
  9063                context. lineJoin =  'round';
  9064                context. lineCap =  'round';
  9065                context. moveTo(dat a.start.x,  data.star t.y);
  9066                context. lineTo(dat a.end.x, d ata.end.y) ;
  9067                context. setLineDas h([]);
  9068                context. closePath( );
  9069                context. stroke();
  9070           }
  9071           ca tch(e)
  9072           {  }
  9073       }
  9074  
  9075       /**
  9076        * Cal culate the  line dist ance
  9077        * @pa ram {Type}  a - Speci fies the p oint 1
  9078        * @pa ram {Type}  b - Speci fies the p oint 2
  9079        */ 
  9080       functi on distanc e(a, b) {
  9081           re turn Math. sqrt(Math. pow(a[0] -  b[0], 2)  + Math.pow (a[1] - b[ 1], 2));
  9082       }
  9083  
  9084       /**
  9085        * Add  the curve  segment
  9086        */ 
  9087       functi on addCurv eSegment ( context, i , points)  {
  9088           tr y
  9089           {
  9090                var aver ageLineLen gth, du, e nd, pieceC ount, piec eLength, s , start, t , u, _ref,  _ref2, _r ef3;
  9091                s = Smoo th(points,  smoothCon fig);
  9092                averageL ineLength  = 1;
  9093                pieceCou nt = 2;
  9094  
  9095                for (t =  0, _ref =  1 / piece Count; t <  1; t += _ ref) {
  9096                    _ref 2 = [s(i +  t), s(i +  t + 1 / p ieceCount) ], start =  _ref2[0],  end = _re f2[1];
  9097                    piec eLength =  distance(s tart, end) ;
  9098                    du =  averageLi neLength /  pieceLeng th;
  9099                    for  (u = 0, _r ef3 = 1 /  pieceCount ; 0 <= _re f3 ? u < _ ref3 : u >  _ref3; u  += du) {
  9100                         context.li neTo.apply (context,  s(i + t +  u));
  9101                    }
  9102                }
  9103  
  9104                context. lineTo.app ly(context , s(i + 1) );
  9105           }
  9106           ca tch(e)
  9107           {  }
  9108       }
  9109  
  9110       functi on getAvgM itralMeanG radients(i mageUid, m easurement s) {
  9111  
  9112           if  (measurem ents == nu ll || meas urements.l ength == 0 ) {
  9113                return n ull;
  9114           }
  9115  
  9116           va r isSameUn its = true ;
  9117           va r isNanVal  = false;
  9118  
  9119           va r avgGradi ants = {
  9120                Value: 0 ,
  9121                PixelX:  0,
  9122                PixelY:  0,
  9123                Unit: ""
  9124           };
  9125           fo r (var ind ex = 0; in dex < meas urements.l ength; ind ex++) {
  9126                var data  = measure ments[inde x];
  9127                var grad ientVal =  getAvgMitr alMeanGrad ient(image Uid, data) ;
  9128                if (grad ientVal.Un it != "pix ") {
  9129                    grad ientVal.Pi xelX = (da ta.start.x ).toFixed( 0);
  9130                    grad ientVal.Pi xelY = (da ta.start.y ).toFixed( 0);
  9131                } else {
  9132                    isSa meUnits =  false;
  9133                }
  9134  
  9135                if (grad ientVal.Va lue == "N/ A") {
  9136                    isNa nVal = tru e;
  9137                }
  9138  
  9139                avgGradi ants.Pixel X = parseI nt((avgGra diants.Pix elX)) + pa rseInt((gr adientVal. PixelX));
  9140                avgGradi ants.Pixel Y = parseI nt((avgGra diants.Pix elY)) + pa rseInt((gr adientVal. PixelY));
  9141                avgGradi ants.Value  = (isNanV al == fals e ? parseF loat((avgG radiants.V alue).toFi xed(2)) +  parseFloat ((gradient Val.Value) ) : 0);
  9142                avgGradi ants.Unit  = (isSameU nits == fa lse ? "pix " : gradie ntVal.Unit );
  9143           }
  9144  
  9145           av gGradiants .PixelX =  (avgGradia nts.PixelX  / measure ments.leng th).toFixe d(0);
  9146           av gGradiants .PixelY =  (avgGradia nts.PixelY  / measure ments.leng th).toFixe d(0);
  9147           av gGradiants .Value = ( isNanVal = = false ?  (avgGradia nts.Value  / measurem ents.lengt h).toFixed (2) : "N/A  ");
  9148           re turn avgGr adiants;
  9149       }
  9150  
  9151       functi on getAvgM itralMeanG radient(im ageUid, da ta) {
  9152           va r imageCoo rdinate =  data;
  9153           va r dicomHea der = dico mViewer.he ader.getDi comHeader( imageUid);
  9154  
  9155           va r resultTe xt = {};
  9156           if  (dicomHea der.imageI nfo.measur ement != n ull) {
  9157                if ((dic omHeader.i mageInfo.m easurement .usRegions  != null)  && (dicomH eader.imag eInfo.meas urement.us Regions.le ngth > 0))  {
  9158                    var  usRegionFo und = fals e;
  9159                    var  regionSpat ialFormat  = 0;
  9160                    var  physicalUn itsXDirect ion = 0;
  9161                    var  physicalUn itsYDirect ion = 0;
  9162                    var  roiPosXVal ue = 0.0;
  9163                    var  roiPosYVal ue = 0.0;
  9164                    var  isReferenc ePixelX0Pr esent = fa lse;
  9165                    var  isReferenc ePixelY0Pr esent = fa lse;
  9166  
  9167                    for  (var i = 0 ; i < dico mHeader.im ageInfo.me asurement. usRegions. length; i+ +) {
  9168                         var usRegi on = dicom Header.ima geInfo.mea surement.u sRegions[i ];
  9169  
  9170                         if (((usRe gion.regio nSpatialFo rmat == 2)  || (usReg ion.region SpatialFor mat == 3))  &&
  9171                             ((imag eCoordinat e.start.x  <= usRegio n.regionLo cationMaxX 1) && (ima geCoordina te.start.x  >= usRegi on.regionL ocationMin X0)) &&
  9172                             ((imag eCoordinat e.start.y  <= usRegio n.regionLo cationMaxY 1) && (ima geCoordina te.start.y  >= usRegi on.regionL ocationMin Y0))) {
  9173                             usRegi onFound =  true;
  9174                             region SpatialFor mat = usRe gion.regio nSpatialFo rmat;
  9175                             physic alUnitsXDi rection =  usRegion.p hysicalUni tsXDirecti on;
  9176                             physic alUnitsYDi rection =  usRegion.p hysicalUni tsYDirecti on;
  9177                             isRefe rencePixel X0Present  = usRegion .isReferen cePixelX0P resent;
  9178                             isRefe rencePixel Y0Present  = usRegion .isReferen cePixelY0P resent;
  9179  
  9180                             if (is ReferenceP ixelX0Pres ent) {
  9181                                 ro iPosXValue  = (imageC oordinate. start.x -  (usRegion. regionLoca tionMinX0  + usRegion .reference PixelX0) +  usRegion. referenceP ixelPhysic alValueX)  * usRegion .physicalD eltaX;
  9182                             }
  9183  
  9184                             if (is ReferenceP ixelY0Pres ent) {
  9185  
  9186                                 if  (usRegion .regionSpa tialFormat  == 2)
  9187                                 //  M-Mode
  9188                                      roiPosYV alue = -(( usRegion.r egionLocat ionMinY0 +  usRegion. referenceP ixelY0) -  imageCoord inate.star t.y + usRe gion.refer encePixelP hysicalVal ueY) * Mat h.abs(usRe gion.physi calDeltaY) ;
  9189                                 el se
  9190                                 //  Spectral
  9191                                      roiPosYV alue = ((u sRegion.re gionLocati onMinY0 +  usRegion.r eferencePi xelY0) - i mageCoordi nate.start .y + usReg ion.refere ncePixelPh ysicalValu eY) * Math .abs(usReg ion.physic alDeltaY);
  9192                             }
  9193  
  9194                             break;
  9195                         }
  9196                    }
  9197  
  9198                    if ( usRegionFo und) {
  9199  
  9200                         var unitsX ;
  9201                         var unitsY ;
  9202                         if ((physi calUnitsXD irection <  0) || (ph ysicalUnit sXDirectio n > 12)) {
  9203                             unitsX  = "unknow n";
  9204                         } else if  ((physical UnitsYDire ction < 0)  || (physi calUnitsYD irection >  12)) {
  9205                             unitsY  = "unknow n";
  9206                         } else {
  9207                             unitsX  = physica lUnitsXYDi rectionArr ay[physica lUnitsXDir ection];
  9208                             unitsY  = physica lUnitsXYDi rectionArr ay[physica lUnitsYDir ection];
  9209                         }
  9210  
  9211                         if ((!isRe ferencePix elX0Presen t) && (isR eferencePi xelY0Prese nt)) {
  9212                             if (im ageCoordin ate.measur ementType  == 5) // Y - Axis
  9213                                 re turn forma tMitralGra dientMeasu rement(roi PosYValue,  unitsY, i mageCoordi nate.measu rementUnit s);
  9214                             else
  9215                                 re turn forma tMitralGra dientMeasu rement(nul l, unitsX,  imageCoor dinate.mea surementUn its);
  9216                         } else if  ((isRefere ncePixelX0 Present) & & (!isRefe rencePixel Y0Present) ) {
  9217                             if (im ageCoordin ate.measur ementType  == 5) // Y - Axis
  9218                                 re turn forma tMitralGra dientMeasu rement(nul l, unitsY,  imageCoor dinate.mea surementUn its);
  9219                             else
  9220                                 re turn forma tMitralGra dientMeasu rement(roi PosXValue,  unitsX, i mageCoordi nate.measu rementUnit s);
  9221                         } else if  ((!isRefer encePixelX 0Present)  && (!isRef erencePixe lY0Present )) {
  9222                             if (im ageCoordin ate.measur ementType  == 5) // Y - Axis
  9223                                 re turn forma tMitralGra dientMeasu rement(nul l, unitsY,  imageCoor dinate.mea surementUn its);
  9224                             else
  9225                                 re turn forma tMitralGra dientMeasu rement(nul l, unitsX,  imageCoor dinate.mea surementUn its);
  9226                         } else
  9227                         if (imageC oordinate. measuremen tType == 5 ) // Y- Ax is
  9228                             return  formatMit ralGradien tMeasureme nt(roiPosY Value, uni tsY, image Coordinate .measureme ntUnits);
  9229                         else
  9230                             return  formatMit ralGradien tMeasureme nt(roiPosX Value, uni tsX, image Coordinate .measureme ntUnits);
  9231                    } el se {
  9232                    }
  9233                } else {
  9234                }
  9235           }  else {
  9236           }
  9237  
  9238           re sultText.V alue = 0;
  9239           re sultText.P ixelX = (i mageCoordi nate.start .x).toFixe d(0);
  9240           re sultText.P ixelY = (i mageCoordi nate.start .y).toFixe d(0);
  9241           re sultText.U nit = "pix ";
  9242  
  9243           re turn resul tText;
  9244       }
  9245  
  9246       // Det ermine len gth(pixel)  of point  on line fr om midpoin t based on  image zoo m percenta ge
  9247       functi on getLenA sPerZoom(z oomVal)
  9248           {
  9249           //  Check whe ther the t ypof of zo omval and  convert ba ck to floa t to avoid  the viewe r crash
  9250           if (typeof zo omVal == " string"){
  9251                zoomVal  = parseFlo at(zoomVal );
  9252           }
  9253  
  9254           va r zoomValu e = zoomVa l.toFixed( 2);
  9255           va r length =  10;
  9256           if (zoomValue  >= "2.5") {
  9257                             length  = 5;              
  9258                    } el se if(zoom Value < "2 .5" && zoo mValue >=  "1.00"){
  9259                length =  10;
  9260           }  else if(zo omValue <  "1.00" &&  zoomValue  >= "0.80") {
  9261                length =  15;
  9262           }  else if(zo omValue <  "0.80" &&  zoomValue  >= "0.60") {
  9263                length =  20;
  9264           }  else if(zo omValue <  "0.60" &&  zoomValue  >= "0.40") {
  9265                length =  30;
  9266           }  else if(zo omValue <  "0.40" &&  zoomValue  >= "0.20") {
  9267                length =  50;
  9268           }e lse if(zoo mValue < " 0.20" && z oomValue > = "0.10"){
  9269                length =  60;
  9270           }e lse if(zoo mValue < " 0.10"){
  9271                length =  80;
  9272           }
  9273           re turn lengt h;
  9274       }
  9275           
  9276       // Get  point on  angle tool  lines to  draw small  point bet weent them
  9277           fu nction get PointOnLin e(x1,y1,x2 ,y2,zoomVa l, arcRadi us){
  9278           
  9279           //  Determine  line leng ths
  9280           va r xlen = x 2 - x1;
  9281           va r ylen = y 2 - y1;
  9282  
  9283           //  Determine  hypotenus e length 
  9284           va r hlen = M ath.sqrt(M ath.pow(xl en,2) + Ma th.pow(yle n,2));
  9285  
  9286           //  The varia ble identi fying the  length of  the `short ened` line .
  9287           //  In this c ase 10 uni ts.
  9288           va r smallerL en =  arcR adius;
  9289  
  9290           //  Determine  the ratio  between t hey shorte ned value  and the fu ll hypoten use.
  9291           va r ratio =  smallerLen  / hlen;
  9292  
  9293           va r smallerX Len = xlen  * ratio;
  9294           va r smallerY Len = ylen  * ratio;
  9295  
  9296           va r Point ={
  9297                x:x1 + s mallerXLen ,
  9298                y:y1 + s mallerYLen
  9299           };
  9300        retur n Point;
  9301       }
  9302           
  9303      // Draw  Angle val ues, arc a nd angle u nit
  9304       functi on drawAng leValue(co ntext, fir stLine, se condLine,  imageRende rer, prese ntation, r esultText,  angleUnit ){
  9305           va r firstLin eData = di comViewer. measuremen t.getCanva sDataForIm ageData(fi rstLine, i mageRender er);
  9306           va r PointToS tart = get PointOnLin e(firstLin eData.end. x,firstLin eData.end. y,firstLin eData.star t.x,firstL ineData.st art.y,pres entation.z oom, first LineData.s tyle.arcRa dius);
  9307           
  9308           va r secondLi neData = d icomViewer .measureme nt.getCanv asDataForI mageData(s econdLine,  imageRend erer);
  9309           se condLineDa ta.textPos ition = se condLine.t extPositio n;
  9310           //  firstLine Data.end i s always c enter poin t
  9311           va r secondPo intX;
  9312           va r secondPo intY;
  9313           if (firstLine Data.end.x  == second LineData.e nd.x){
  9314                secondPo intX = sec ondLineDat a.start.x;
  9315                secondPo intY = sec ondLineDat a.start.y;
  9316           }e lse{
  9317                secondPo intX = sec ondLineDat a.end.x;
  9318                secondPo intY = sec ondLineDat a.end.y;
  9319           }
  9320           va r PointToE nd = getPo intOnLine( firstLineD ata.end.x, firstLineD ata.end.y, secondPoin tX,secondP ointY,pres entation.z oom, first LineData.s tyle.arcRa dius);
  9321  
  9322           co ntext.save ();
  9323           //  Draw the  small line
  9324           co ntext.begi nPath();
  9325           up dateContex tStyle(con text, firs tLineData. style, fal se, imageR enderer.sc aleValue);
  9326           co ntext.move To(PointTo Start.x, P ointToStar t.y);
  9327           co ntext.line To(PointTo End.x, Poi ntToEnd.y) ;
  9328           co ntext.clos ePath();
  9329           co ntext.stro ke();
  9330           
  9331           //  Draw angl e value  a nd unit
  9332           va r textX =  firstLineD ata.end.x;
  9333           va r textY =  firstLineD ata.end.y;
  9334           va r scale =  presentati on.getZoom ();
  9335           up dateContex tStyle(con text, firs tLineData. style, tru e, imageRe nderer.sca leValue);
  9336           up dateTextBo unds({x: t extX, y: t extY}, res ultText +  "°", cont ext, first LineData,  imageRende rer);
  9337  
  9338           co ntext.tran slate(text X, textY);
  9339           co ntext.rota te(-1 * (p resentatio n.getRotat ion() * Ma th.PI / 18 0));
  9340           if (imageRend erer.isPri nt == true  && presen tation.isF lipHorizon talRequire d){
  9341                if (pres entation.r otation &&  (presenta tion.rotat ion !== 18 0 && prese ntation.or ientation  !== 6) ) {
  9342                    cont ext.scale( 1, -1);
  9343                } else {
  9344                    cont ext.scale( -1, 1);
  9345                } 
  9346           }  else if (p resentatio n.vFlip &&  presentat ion.hFlip)  {
  9347                context. scale(-1,  -1);
  9348           }  else if (p resentatio n.hFlip) {
  9349                context. scale(-1,  1);
  9350           }  else if (p resentatio n.vFlip) {
  9351                context. scale(1, - 1);
  9352           }  else {
  9353                context. scale(1, 1 );
  9354           }
  9355  
  9356           if (!isNaN(re sultText))  {
  9357                var text Width = co ntext.meas ureText(re sultText). width;
  9358                
  9359                //for te xt positio n right, d efault val ue
  9360                var newT extX = 15  / imageRen derer.scal eValue;
  9361                var delY  = 15 / im ageRendere r.scaleVal ue;
  9362                
  9363                //for te xt positio n left, sh ifting it  to left
  9364                if(secon dLineData. textPositi on == "lef t") {
  9365                    newT extX = -ne wTextX;
  9366                }
  9367                //for te xt positio n top, shi fting it t o top
  9368                if(secon dLineData. textPositi on == "top ") {
  9369                    delY  = - delY;
  9370                }
  9371                if(secon dLineData. textPositi on == "top -left") {
  9372                    newT extX = -(3 /2*textWid th + (15 /  imageRend erer.scale Value));
  9373                }
  9374  
  9375                context. textAlign  = "start";
  9376                context. fillText(a ngleUnit,  newTextX,  delY );
  9377                context. textAlign  = "end";
  9378                context. textBaseli ne="top";
  9379                context. fillText("  " + resul tText, new TextX, del Y);
  9380                var widt h = contex t.measureT ext(result Text).widt h;
  9381                var font Size = fir stLineData .style.fon tSize / im ageRendere r.scaleVal ue;
  9382                if (firs tLineData. style.isSt rikeout) {
  9383                    cont ext.moveTo (newTextX,  delY + (f ontSize/2) );
  9384                    cont ext.lineTo (newTextX  - width, d elY + (fon tSize/2));
  9385                    cont ext.stroke ();
  9386                }
  9387                if (firs tLineData. style.isUn derlined)  {
  9388                    cont ext.moveTo (newTextX,  delY + fo ntSize);
  9389                    cont ext.lineTo (newTextX  - width, d elY + font Size);
  9390                    cont ext.stroke ();
  9391                }
  9392           }
  9393           co ntext.rest ore();
  9394       }
  9395  
  9396      // Draw  Lines of  angle meas urement to ol
  9397       functi on drawMea surementsL ength(cont ext, data,  imageRend erer, pres entation,  resultText , isPoint,  isEllipse , isText,  isRect) {
  9398           va r textX;
  9399           va r textY;
  9400           if  (isText)  {
  9401                updateCo ntextStyle (context,  data.style , true, im ageRendere r.scaleVal ue, true);
  9402                var font Size = dat a.style.fo ntSize / i mageRender er.scaleVa lue;
  9403                var widt h = data.e nd.x - dat a.start.x;
  9404                var heig ht = data. end.y - da ta.start.y ;
  9405                if (data .end.x < d ata.start. x) {
  9406                    widt h = data.s tart.x - d ata.end.x;
  9407                } if (da ta.end.y <  data.star t.y) {
  9408                    heig ht = data. start.y -  data.end.y ;
  9409                }
  9410                //Text a nnotation  rectangle  coordinate s
  9411                x1 = Mat h.min(data .start.x,  data.end.x );
  9412                x2 = Mat h.max(data .start.x,  data.end.x );
  9413                y1 = Mat h.min(data .start.y,  data.end.y );
  9414                y2 = Mat h.max(data .start.y,  data.end.y );
  9415                
  9416                if(prese ntation.ro tation ==  90 ||prese ntation.ro tation ==  270) {
  9417                    //sw itching th e width an d height o f the rect angle
  9418                    temp  = width;
  9419                    widt h = height ;
  9420                    heig ht = temp;
  9421                }
  9422                //On the  basis of  orientatio n of the i mage, rend ering the  result tex t starting  at the to p-left cor ner of the  rectangle
  9423                switch(p resentatio n.orientat ion) {
  9424                         case 0 : t extX = x1;  //0 degre e
  9425                                  t extY = y1  + fontSize ;
  9426                                  b reak;
  9427                         case 1 : t extX = x2  - fontSize ; // 270 d egree
  9428                                  t extY = y1;
  9429                                  b reak;
  9430                         case 2 : t extX = x2;  // 180 de gree
  9431                                  t extY = y2  - fontSize ;
  9432                                  b reak;
  9433                         case 3 : t extX = x1  + fontSize ; // 90 de gree
  9434                                  t extY = y2;
  9435                                  b reak;
  9436                         case 4 : t extX = x2;  //0 degre e
  9437                                  t extY = y1  + fontSize ;
  9438                                  b reak;
  9439                         case 5 : t extX = x1  + fontSize ; // 270 d egree
  9440                                  t extY = y1;
  9441                                  b reak;
  9442                         case 6 : t extX = x1;  // 180 de gree
  9443                                  t extY = y2  - fontSize ;
  9444                                  b reak;
  9445                         case 7 : t extX = x2  - fontSize ; // 270 d egree
  9446                                  t extY = y2;
  9447                                }
  9448                
  9449                context. save();
  9450                context. translate( textX, tex tY);
  9451                context. rotate(-1  * (present ation.getR otation()  * Math.PI  / 180));
  9452                if(image Renderer.i sPrint ==  true && pr esentation .isFlipHor izontalReq uired){
  9453                    if ( presentati on.rotatio n && (pres entation.r otation != = 180 && p resentatio n.orientat ion !== 6)  ) {
  9454                         context.sc ale(1, -1) ;
  9455                    } el se {
  9456                         context.sc ale(-1, 1) ;
  9457                    } 
  9458                } else i f (present ation.vFli p && prese ntation.hF lip) {
  9459                    cont ext.scale( -1, -1);
  9460                } else i f (present ation.hFli p) {
  9461                    cont ext.scale( -1, 1);
  9462                } else i f (present ation.vFli p) {
  9463                    cont ext.scale( 1, -1);
  9464                } else {
  9465                    cont ext.scale( 1, 1);
  9466                }
  9467  
  9468                var word s = data.m easurement Text.split ("\n");
  9469                var actu alLineInde x = 0;
  9470                for (var  i = 0; i  < words.le ngth; i++)  {
  9471                    var  prependTex t = "";
  9472                    var  appendText  = "";
  9473                    var  diffX = "" ;
  9474                    var  isAppend =  false;
  9475                    var  lineHeight  = actualL ineIndex *  fontSize;
  9476  
  9477                    if ( words[i] = = "") {
  9478                         continue;
  9479                    } el se {
  9480                         actualLine Index++;
  9481                    }
  9482  
  9483                    if ( lineHeight  > height  - fontSize ) {
  9484                         break;
  9485                    }
  9486  
  9487                    var  textWidth  = context. measureTex t(words[i] );
  9488                    var  perTextWid th = textW idth.width  / words[i ].length;
  9489  
  9490                    diff X =  words .length ?  parseInt(w idth) : 0  ;
  9491                    isAp pend = fal se;
  9492  
  9493                    if ( diffX > pa rseInt(per TextWidth  * 2)) {
  9494                         var sliceI ndex = par seInt(diff X / perTex tWidth);
  9495  
  9496                             // get  the slice  index by  word ends
  9497                             var sp litText =  words[i].s plit(/\s+/ );
  9498                             var pr eviousWord Pos = 0;
  9499                             for(va r k = 0; k  < splitTe xt.length;  k++ ) {
  9500                                 va r currentL ength = (s plitText[k ].length)  + 1;
  9501                                 if (currentLe ngth == sl iceIndex | | previous WordPos ==  sliceInde x) {
  9502                                      sliceInd ex = curre ntLength;
  9503                                      break;
  9504                                 }  else if((p reviousWor dPos + cur rentLength ) >= slice Index ) {
  9505                                      sliceInd ex = previ ousWordPos  == 0 ? sl iceIndex :  previousW ordPos;
  9506                                      break;
  9507                                 }
  9508                                 pr eviousWord Pos += cur rentLength ;
  9509                             }
  9510  
  9511                             var tr immedText  = words[i] .slice(0,  sliceIndex );
  9512                             var tr immedTextW idth = con text.measu reText(tri mmedText);
  9513                             var pe rTextWidth  = trimmed TextWidth. width / tr immedText. length;
  9514  
  9515                             if (tr immedTextW idth.width  > parseIn t(width))  {
  9516                                 di ffX =  tri mmedTextWi dth.width  - parseInt (width);
  9517                                 va r sliceInd ex = parse Int(diffX  / perTextW idth);
  9518                                 va r slicedTe xt = trimm edText.sli ce(sliceIn dex, trimm edText.len gth);
  9519                                 wo rds.splice (i+1, 0, s licedText) ;
  9520                                 sl icedText =  words[i]. slice(trim medText.le ngth, word s[i].lengt h);
  9521                                 wo rds.splice (i+2, 0, s licedText) ;
  9522                                 wo rds[i] = t rimmedText .slice(0,  sliceIndex );
  9523                                 i- -;
  9524                                 ac tualLineIn dex--;
  9525                                 co ntinue;
  9526                             } else  if (trimm edTextWidt h.width <  parseInt(t extWidth.w idth / 4))  {
  9527                                 if  (words[i+ 1] !== und efined) {
  9528                                      words[i+ 1] = words [i] + word s[i+1];
  9529                                      words.sp lice(i, 1) ;
  9530                                      i--;
  9531                                      actualLi neIndex--;
  9532                                      continue ;
  9533                                 }
  9534                             }
  9535                             prepen dText = wo rds[i].sli ce(sliceIn dex, words [i].length );
  9536                             if (i  == words.l ength - 1)  {
  9537                                 wo rds[i] = t rimmedText ;
  9538                                 wo rds.push(p rependText );
  9539                             } else  {
  9540                                 wo rds[i] = t rimmedText ;
  9541                                 wo rds.splice (i+1, 0, p rependText );
  9542                             } 
  9543                    }
  9544                    cont ext.fillTe xt(words[i ], 0, line Height);
  9545                    if ( data.style .isStrikeo ut) {
  9546                         context.mo veTo(0, li neHeight -  5);
  9547                         context.li neTo(0 + t rimmedText Width.widt h, lineHei ght - 5);
  9548                         context.st roke();
  9549                    }
  9550                    if ( data.style .isUnderli ned) {
  9551                         context.mo veTo(0, li neHeight +  5);
  9552                         context.li neTo(0 + t rimmedText Width.widt h, lineHei ght + 5);
  9553                         context.st roke();
  9554                    }
  9555                }
  9556                context. restore();
  9557                return;
  9558           }  else if (i sEllipse | | isRect)  {
  9559                updateCo ntextStyle (context,  data.style , true, im ageRendere r.scaleVal ue);
  9560                var font Size = dat a.style.fo ntSize / i mageRender er.scaleVa lue;
  9561                var text X = (data. start.x +  data.end.x ) / 2;
  9562                var text Y = (data. start.y +  data.end.y ) / 2;
  9563                var delY =0;
  9564                context. save();
  9565                context. translate( textX, tex tY);
  9566                context. rotate(-1  * (present ation.getR otation()  * Math.PI  / 180));
  9567                if(image Renderer.i sPrint ==  true && pr esentation .isFlipHor izontalReq uired){
  9568                    if ( presentati on.rotatio n && (pres entation.r otation != = 180 && p resentatio n.orientat ion !== 6)  ) {
  9569                         context.sc ale(1, -1) ;
  9570                    } el se {
  9571                         context.sc ale(-1, 1) ;
  9572                    } 
  9573                } else i f (present ation.vFli p && prese ntation.hF lip) {
  9574                    cont ext.scale( -1, -1);
  9575                } else i f (present ation.hFli p) {
  9576                    cont ext.scale( -1, 1);
  9577                } else i f (present ation.vFli p) {
  9578                    cont ext.scale( 1, -1);
  9579                } else {
  9580                    cont ext.scale( 1, 1);
  9581                }
  9582                
  9583                //Whethe r it is el lipse or r ectangle t he start a nd end poi nts will b e this
  9584                if(data. first != u ndefined & & data.sec ond != und efined && 
  9585                   data. third != u ndefined & & data.fou rth != und efined) {
  9586                    var  rectangle  = {
  9587                         x1 : Math. min(data.f irst.x, da ta.second. x, data.th ird.x, dat a.fourth.x ),
  9588                         x2 : Math. max(data.f irst.x, da ta.second. x, data.th ird.x, dat a.fourth.x )
  9589                    };
  9590                } else {
  9591                    var  rectangle  = {
  9592                         x1 : Math. min(data.s tart.x, da ta.end.x),
  9593                         x2 : Math. max(data.s tart.x, da ta.end.x)
  9594                    };
  9595                }
  9596  
  9597                textX =  (rectangle .x2 - rect angle.x1)  / 2;
  9598                var text Width = co ntext.meas ureText(te xt).width;
  9599                
  9600                updateTe xtBounds({ x: textX,  y: textY},  resultTex t, context , data, im ageRendere r);
  9601  
  9602                //Switch ing the te xt at the  left side  if it is g oing outsi de the rig ht-end of  the viewpo rt
  9603                if(data. textPositi on == "lef t") {
  9604                    newT extX = -(t extX + 2*t extWidth +  (30 / ima geRenderer .scaleValu e));
  9605                    line X = -textX  - (30 / i mageRender er.scaleVa lue);
  9606                } else {
  9607                    newT extX = tex tX + (30 /  imageRend erer.scale Value);
  9608                    line X = textX;
  9609                }
  9610                
  9611                //Shifti ng the tex t more up  if it is g oing outsi de the bot tom of the  viewport
  9612                if(data. textPositi on == "top ") {
  9613                    delY  = delY -  (30 / imag eRenderer. scaleValue );
  9614                }
  9615                
  9616                if(data. textPositi on == "top -left") {
  9617                    newT extX = -(t extX + 2*t extWidth +  (30 / ima geRenderer .scaleValu e));
  9618                    line X = -textX  - (30 / i mageRender er.scaleVa lue);
  9619                    delY  = delY -  (30 / imag eRenderer. scaleValue );
  9620                }
  9621  
  9622                for(var  iIndex=0;  iIndex < r esultText. length; iI ndex++){
  9623                    var  text = res ultText[iI ndex];
  9624                    cont ext.fillTe xt(" " + t ext, newTe xtX, delY) ;
  9625                    var  width = co ntext.meas ureText(te xt).width;
  9626                    var  fontSize =  data.styl e.fontSize  / imageRe nderer.sca leValue;
  9627                    if ( data.style .isStrikeo ut) {
  9628                         context.mo veTo(newTe xtX, delY  - (fontSiz e/2.5));
  9629                         context.li neTo(newTe xtX + widt h, delY -  (fontSize/ 2.5));
  9630                         context.st roke();
  9631                    }
  9632                    if ( data.style .isUnderli ned) {
  9633                         context.mo veTo(newTe xtX, delY  + 5);
  9634                         context.li neTo(newTe xtX + widt h, delY  + 5);
  9635                         context.st roke();
  9636                    }
  9637                    if(f ontSize <=  15) {
  9638                         delY+= (15  / imageRe nderer.sca leValue);
  9639                    }els e {
  9640                         delY+=font Size;
  9641                    }
  9642                }
  9643                if (resu ltText.len gth > 0) {
  9644                    upda teContextS tyle(conte xt, data.s tyle, fals e, imageRe nderer.sca leValue);
  9645                    cont ext.beginP ath();
  9646                    cont ext.moveTo (lineX, 0) ;
  9647                    cont ext.lineTo (lineX + ( 30 / image Renderer.s caleValue) , 0);
  9648                    cont ext.setLin eDash([2,  2]);
  9649                    cont ext.stroke ();
  9650                }
  9651                context. restore();
  9652                return;
  9653           }  else if (i sPoint) {
  9654                var scal e = presen tation.get Zoom();
  9655                var text X = data.e nd.x;
  9656                var text Y = data.e nd.y;
  9657                updateTe xtBounds({ x: textX,  y: textY},  resultTex t, context , data, im ageRendere r);
  9658                context. save();
  9659                var txtD istance =  4 / (image Renderer.s caleValue  / scale);
  9660                if(prese ntation.ge tOrientati on() % 4 = = 2 || pre sentation. getOrienta tion() % 4  == 1) txt Distance =  -1 * txtD istance;
  9661                context. translate( textX + tx tDistance,  textY - t xtDistance );
  9662                context. rotate(-1  * (present ation.getR otation()  * Math.PI  / 180));
  9663                
  9664                if(image Renderer.i sPrint ==  true && pr esentation .isFlipHor izontalReq uired){
  9665                    if ( presentati on.rotatio n && (pres entation.r otation != = 180 && p resentatio n.orientat ion !== 6)  ) {
  9666                         context.sc ale(1, -1) ;
  9667                    } el se {
  9668                         context.sc ale(-1, 1) ;
  9669                    }
  9670                } else i f (present ation.vFli p && prese ntation.hF lip) {
  9671                    cont ext.scale( -1, -1);
  9672                } else i f (present ation.hFli p) {
  9673                    cont ext.scale( -1, 1);
  9674                } else i f (present ation.vFli p) {
  9675                    cont ext.scale( 1, -1);
  9676                } else {
  9677                    cont ext.scale( 1, 1);
  9678                }
  9679                
  9680                //for te xt positio n top as w ell as rig ht, no nee d to shift
  9681                var newT extX = 0;
  9682                var delY  = 0;
  9683                var text Width = co ntext.meas ureText(te xt).width;
  9684                
  9685                //for te xt positio n left, sh ifting it  to left
  9686                if(data. textPositi on == "lef t") {
  9687                    newT extX = -(3 /2*textWid th + (15 /  imageRend erer.scale Value));
  9688                }
  9689                //for te xt positio n top-left , shifting  it to top -left
  9690                if(data. textPositi on == "top -left") {
  9691                    newT extX = -(3 /2*textWid th + (15 /  imageRend erer.scale Value));
  9692                    delY  = - (15 /  imageRend erer.scale Value);
  9693                }
  9694                context. fillText("  " + resul tText, new TextX, del Y);
  9695                var widt h = contex t.measureT ext(result Text).widt h;
  9696                var font Size = dat a.style.fo ntSize / i mageRender er.scaleVa lue;
  9697                if (data .style.isS trikeout)  {
  9698                    cont ext.moveTo (newTextX,  delY - (f ontSize/2. 5));
  9699                    cont ext.lineTo (newTextX  + width, d elY - (fon tSize/2.5) );
  9700                    cont ext.stroke ();
  9701                }
  9702                if (data .style.isU nderlined)  {
  9703                    cont ext.moveTo (newTextX,  delY + 5) ;
  9704                    cont ext.lineTo (newTextX  + width, d elY + 5);
  9705                    cont ext.stroke ();
  9706                }
  9707                context. restore();
  9708           }  else {
  9709                updateCo ntextStyle (context,  data.style , true, im ageRendere r.scaleVal ue);
  9710                var text X = (data. start.x +  data.end.x ) / 2;
  9711                var atex t = (data. start.x -  data.end.x ) / 2;
  9712                var text Y = (data. start.y +  data.end.y ) / 2;
  9713                var text Width = re sultText.l ength;
  9714                var delY  = 0;
  9715                newTextX  = 0;
  9716                updateTe xtBounds({ x: textX,  y: textY},  resultTex t, context , data, im ageRendere r);
  9717                context. save();
  9718                context. translate( textX, tex tY);
  9719                context. rotate(-1  * (present ation.getR otation()  * Math.PI  / 180));
  9720  
  9721                if(image Renderer.i sPrint ==  true && pr esentation .isFlipHor izontalReq uired){
  9722                    if ( presentati on.rotatio n && (pres entation.r otation != = 180 && p resentatio n.orientat ion !== 6)  ) {
  9723                         context.sc ale(1, -1) ;
  9724                    } el se {
  9725                         context.sc ale(-1, 1) ;
  9726                    } 
  9727                } else i f (present ation.vFli p && prese ntation.hF lip) {
  9728                    cont ext.scale( -1, -1);
  9729                } else i f (present ation.hFli p) {
  9730                    cont ext.scale( -1, 1);
  9731                } else i f (present ation.vFli p) {
  9732                    cont ext.scale( 1, -1);
  9733                } else {
  9734                    cont ext.scale( 1, 1);
  9735                }
  9736  
  9737                //for te xt positio n top as w ell as rig ht, no nee d to shift
  9738                newTextX  = 0;
  9739                delY=0;
  9740                
  9741                //for te xt positio n left as  well as to p-left, sh ifting it  to left si de
  9742                if(data. textPositi on == "lef t" || data .textPosit ion == "to p-left") {
  9743                    newT extX = -(7 *textWidth )/imageRen derer.scal eValue;     
  9744                }
  9745                
  9746                context. fillText("  " + resul tText, new TextX, del Y);
  9747                var widt h = contex t.measureT ext(result Text).widt h;
  9748                var font Size = dat a.style.fo ntSize / i mageRender er.scaleVa lue;
  9749                if (data .style.isS trikeout)  {
  9750                    cont ext.moveTo (newTextX,  delY - (f ontSize/2. 5));
  9751                    cont ext.lineTo (newTextX  + width, d elY - (fon tSize/2.5) );
  9752                    cont ext.stroke ();
  9753                }
  9754                if (data .style.isU nderlined)  {
  9755                    cont ext.moveTo (newTextX,  delY + 5) ;
  9756                    cont ext.lineTo (newTextX  + width, d elY  +5);
  9757                    cont ext.stroke ();
  9758                }
  9759                context. restore();
  9760           }
  9761       }
  9762       
  9763       functi on getInte rsectionPo int(x1, y1 , x2, y2,  x3, y3, x4 , y4) {
  9764           va r d = (x1  - x2) * (y 3 - y4) -  (y1 - y2)  * (x3 - x4 );
  9765           if  (d == 0)  return nul l;
  9766  
  9767           va r xi = ((x 3 - x4) *  (x1 * y2 -  y1 * x2)  - (x1 - x2 ) * (x3 *  y4 - y3 *  x4)) / d;
  9768           va r yi = ((y 3 - y4) *  (x1 * y2 -  y1 * x2)  - (y1 - y2 ) * (x3 *  y4 - y3 *  x4)) / d;
  9769  
  9770  
  9771           if  (xi < Mat h.min(x1,  x2) || xi  > Math.max (x1, x2))  return nul l;
  9772           if  (xi < Mat h.min(x3,  x4) || xi  > Math.max (x3, x4))  return nul l;
  9773  
  9774           re turn {
  9775                x: xi,
  9776                y: yi
  9777           };
  9778       }
  9779  
  9780       functi on formatM easurement Result(res ult, units , desiredU nits) {
  9781  
  9782           if  ((desired Units != n ull) && (u nits == "c m/sec")) {
  9783  
  9784                if (resu lt == null )
  9785                    retu rn "N/A "  + desiredU nits;
  9786  
  9787                if (desi redUnits = = "m/s") {
  9788                    resu lt /= 100. 0;
  9789                    retu rn "" + Ma th.abs(res ult.toFixe d(2)) + "  " + desire dUnits;
  9790                } else i f (desired Units == " mmHg") {
  9791                    resu lt /= 100. 0;
  9792                    resu lt = (resu lt * resul t) * 4.0;
  9793                    retu rn "" + Ma th.abs(res ult.toFixe d(2)) + "  " + desire dUnits;
  9794                }
  9795           }
  9796  
  9797           if  (result = = null)
  9798                return " N/A " + un its;
  9799           el se
  9800                return " " + Math.a bs(result. toFixed(2) ) + " " +  units;
  9801       }
  9802  
  9803       functi on formatM itralGradi entMeasure ment(resul t, units,  desiredUni ts) {
  9804  
  9805           va r gradiant Result = {
  9806                Value: " ",
  9807                Unit: ""
  9808           }
  9809           if  ((desired Units != n ull) && (u nits == "c m/sec")) {
  9810  
  9811                if (resu lt == null ) {
  9812                    grad iantResult .Value = " N/A";
  9813                    grad iantResult .Unit = de siredUnits ;
  9814                    retu rn gradian tResult;
  9815                }
  9816  
  9817                if (desi redUnits = = "m/s") {
  9818                    resu lt /= 100. 0;
  9819                    grad iantResult .Value = r esult.toFi xed(2);
  9820                    grad iantResult .Unit = de siredUnits ;
  9821                    retu rn gradian tResult;
  9822                } else i f (desired Units == " mmHg") {
  9823                    resu lt /= 100. 0;
  9824                    resu lt = (resu lt * resul t) * 4.0;
  9825                    grad iantResult .Value = r esult.toFi xed(2);
  9826                    grad iantResult .Unit = de siredUnits ;
  9827                    retu rn gradian tResult;
  9828                }
  9829           }
  9830  
  9831           if  (result = = null) {
  9832                gradiant Result.Val ue = "N/A" ;
  9833                gradiant Result.Uni t = units;
  9834                return g radiantRes ult;
  9835           }  else {
  9836                gradiant Result.Val ue = Math. abs(result .toFixed(2 ));
  9837                gradiant Result.Uni t = units;
  9838                return g radiantRes ult;
  9839           }
  9840       }
  9841  
  9842       functi on getLeng thText(dat a) {
  9843           va r dx = (da ta.start.x  - data.en d.x);
  9844           va r dy = (da ta.start.y  - data.en d.y);
  9845           va r lengthIn Pixels = M ath.sqrt(d x * dx + d y * dy);
  9846  
  9847           re turn "" +  lengthInPi xels.toFix ed(2) + "  pix";
  9848       }
  9849  
  9850       // not  defined f or empty a rray
  9851       functi on findInd exOfGreate st(element s) {
  9852           va r max = el ements[0];
  9853           va r maxIndex  = 0;
  9854  
  9855           fo r (var i =  1; i < el ements.len gth; i++)  {
  9856                if (elem ents[i] >  max) {
  9857                    maxI ndex = i;
  9858                    max  = elements [i];
  9859                }
  9860           }
  9861           re turn maxIn dex;
  9862       }
  9863  
  9864       functi on getLeng thUsingPix elSpacing( data, pixe lSpacing,  bInCM) {
  9865  
  9866           va r dx = Mat h.abs(data .start.x -  data.end. x);
  9867           va r dy = Mat h.abs(data .start.y -  data.end. y);
  9868  
  9869           dx  *= pixelS pacing.col umn;
  9870           dy  *= pixelS pacing.row ;
  9871  
  9872           va r lengthIn CM = undef ined;
  9873           if  (dx == 0. 0) lengthI nCM = dy;
  9874           el se if (dy  == 0.0) le ngthInCM =  dx;
  9875           el se lengthI nCM = dy /  (Math.sin (Math.atan (dy / dx)) );
  9876  
  9877           if (bInCM)
  9878                lengthIn CM /= 10.0 ;
  9879  
  9880           re turn lengt hInCM;
  9881       }
  9882  
  9883       functi on getDisp layLengthT ext(value,  isCalibra ted, isMea surementCo mpleted, t heUnitType , isOwnerP ixelSpacin g, precisi on) {
  9884           if (dicomView er.tools.g etFlagFor2 dLengthCal ibration()  && !isMea surementCo mpleted){
  9885                return " ";
  9886           }
  9887  
  9888           va r unit = " cm";
  9889           va r resultVa lue = valu e;
  9890           va r unitType  = "";
  9891  
  9892           if (theUnitTy pe != unde fined) {
  9893                unitType  = theUnit Type;
  9894           }  else {
  9895                unitType  = dicomVi ewer.measu rement.get DefaultLin eMeasureme ntUnit();
  9896           }
  9897  
  9898           if  (unitType  == "UNITS _MM" || un itType ==  "mm") {
  9899                unit = " mm";
  9900                resultVa lue = resu ltValue *  10.0;
  9901           }  else if (u nitType ==  "UNITS_IN CHES" || u nitType ==  "in") {
  9902                unit = " in";
  9903                resultVa lue = resu ltValue /  2.54;
  9904           }
  9905  
  9906           un it = " " +  unit + (i sCalibrate d == true  ? " (c*)"  : (isOwner PixelSpaci ng == fals e ? " (c)"  : ""));
  9907           va r resultTe xt = "" +  resultValu e.toFixed( precision)  + unit;
  9908  
  9909           re turn resul tText;
  9910       }
  9911  
  9912       functi on drawLin eHandles(i mageUid, c ontext, da ta, presen tation, im ageRendere r) {
  9913           // console.lo g("Draw li ne handles ");
  9914  
  9915           va r scale =  presentati on.getZoom ();
  9916           if  (data.end .handleAct ive || dat a.start.ha ndleActive ) {
  9917                context. beginPath( );
  9918                context. strokeStyl e = '#DAA5 20';
  9919                var radi us = (4 *  imageRende rer.viewpo rtHeight)  / (1000 *  imageRende rer.scaleV alue) ;
  9920                context. lineWidth  = radius;
  9921                context. arc(data.e nd.x, data .end.y, ra dius, 0, 2  * Math.PI , false);
  9922                context. closePath( );
  9923                context. stroke();
  9924                context. beginPath( );
  9925                context. arc(data.s tart.x, da ta.start.y , radius,  0, 2 * Mat h.PI, fals e);
  9926                context. closePath( );
  9927                context. stroke();
  9928                if (data .measureme ntSubType  != "Arrow" ) {
  9929                    retu rn;
  9930                }
  9931           }  else if(da ta.measure Type == "a ngle") {
  9932                return;
  9933           }
  9934           va r lengthOf Slope = da ta.style.g augeLength ;
  9935           va r gaugeSty le = data. style.gaug eStyle;
  9936           va r slope =  (data.star t.y - data .end.y) /  (data.star t.x - data .end.x);
  9937           va r startHan dle = getH andlePoint (data.star t.x, data. start.y, l engthOfSlo pe, slope)
  9938           va r endHandl e = getHan dlePoint(d ata.end.x,  data.end. y, lengthO fSlope, sl ope)
  9939  
  9940           va r isFill =  (data.sty le.isFill)  ? true :  false;
  9941           up dateContex tStyle(con text, data .style, !i sFill, ima geRenderer .scaleValu e, undefin ed, isFill );
  9942           if (data.meas urementSub Type == "A rrow") {
  9943                drawArro w(context,  data.end. x, data.en d.y, data. start.x, d ata.start. y, imageRe nderer.sca leValue, i sFill);
  9944           }  else if(ga ugeStyle = = "Point")  {
  9945                drawPoin t(context,  imageRend erer, data );
  9946           }  else {
  9947                drawLine (context,  imageRende rer, start Handle, en dHandle);
  9948           }
  9949       }
  9950  
  9951        /**
  9952        * dra w line mea surement
  9953        * @pa ram contex t - specif ies the 2d  context
  9954        * @pa ram imageR enderer -  specifies  the image  render
  9955        * @pa ram startH andle - sp ecifies th e start ha ndle
  9956        * @pa ram endHan dle - spec ifies the  end handle
  9957        */
  9958       functi on drawLin e(context,  imageRend erer, star tHandle, e ndHandle)  {
  9959           //  draw the  line
  9960           co ntext.begi nPath();
  9961           co ntext.move To(startHa ndle[0].x,  startHand le[0].y);
  9962           co ntext.line To(startHa ndle[1].x,  startHand le[1].y);
  9963           co ntext.move To(endHand le[0].x, e ndHandle[0 ].y);
  9964           co ntext.line To(endHand le[1].x, e ndHandle[1 ].y);
  9965           co ntext.clos ePath();
  9966           co ntext.stro ke();
  9967       }
  9968  
  9969       /**
  9970        * dra w point me asurement
  9971        * @pa ram contex t - specif ies the 2d  context
  9972        * @pa ram imageR enderer -  specifies  the image  render
  9973        */ 
  9974       functi on drawPoi nt(context , imageRen derer, dat a) {
  9975           co ntext.begi nPath();
  9976           co ntext.stro keStyle =  data.style .lineColor ;
  9977           va r gaugelen gth = data .style.gau geLength ?  parseInt( data.style .gaugeLeng th) : 3;
  9978           va r radius =  (gaugelen gth * imag eRenderer. viewportHe ight) / (1 000 * imag eRenderer. scaleValue ) ;
  9979           co ntext.line Width = ra dius;
  9980           co ntext.fill Style = da ta.style.l ineColor; 
  9981           co ntext.arc( data.end.x , data.end .y, radius , 0, 2 * M ath.PI, fa lse);
  9982           co ntext.fill ();
  9983           co ntext.clos ePath();
  9984           co ntext.stro ke();
  9985           co ntext.begi nPath();
  9986           co ntext.arc( data.start .x, data.s tart.y, ra dius, 0, 2  * Math.PI , false);
  9987           co ntext.fill ();
  9988           co ntext.clos ePath();
  9989           co ntext.stro ke();
  9990       }
  9991       
  9992        /**
  9993        * dra w arrow
  9994        * @pa ram contex t - specif ies the 2d  context
  9995        * @pa ram x1 - s pecifies t he first p oint
  9996        * @pa ram y1 - s pecifies t he second  point
  9997        * @pa ram x2 - s pecifies t he third p oint 
  9998        * @pa ram y2 - s pecifies t he fourth  point
  9999        * @pa ram y2 -   specified  the fill o ption for  polygon
  10000        */
  10001       functi on drawArr ow(context , x1, y1,  x2, y2, sc aleValue,  isFill) {
  10002           va r ang = Ma th.atan2(y 2-y1,x2-x1 );
  10003           if (ang != 0)  {
  10004                context. beginPath( );
  10005                context. moveTo(x1, y1);
  10006                // defau lt arrow a rray
  10007                var arro w = [[ 2,  0 ], [ -20 , -8 ], [  -20, 8]];
  10008                for(pt i n arrow) {
  10009                    // s caling the  arrow dim ensions wi th respect  to the sc ale value
  10010                    arro w[pt][0] =  arrow[pt] [0]/scaleV alue;
  10011                    arro w[pt][1] =  arrow[pt] [1]/scaleV alue;
  10012                }
  10013                drawFill edPolygon( context, t ranslateSh ape(rotate Shape(arro w, ang),x2 ,y2), isFi ll);
  10014           }
  10015       }
  10016  
  10017        /**
  10018        * fil l arrow po lygon
  10019        * @pa ram contex t - specif ies the 2d  context
  10020        * @pa ram shape  - specifie s the shap e whether  angle or p olygon lik e that.
  10021        * @pa ram isFill  - specifi ed the fil l option f or polygon
  10022        */
  10023       functi on drawFil ledPolygon (context,  shape, isF ill) {
  10024           co ntext.begi nPath();
  10025           co ntext.move To(shape[0 ][0], shap e[0][1]);
  10026           
  10027           fo r(p in sha pe) {
  10028                if (p ==  1) {
  10029                    cont ext.lineTo (shape[p][ 0], shape[ p][1]);
  10030                } else i f (p == 2)  {
  10031                    if ( isFill) {
  10032                         context.li neTo(shape [p][0], sh ape[p][1]) ;
  10033                    } el se {
  10034                         context.mo veTo(shape [p][0], sh ape[p][1]) ;
  10035                    }
  10036                }
  10037           }
  10038                
  10039           co ntext.line To(shape[0 ][0], shap e[0][1]);
  10040           if  (isFill)  {
  10041                context. fill();
  10042           }  else {
  10043                context. stroke();
  10044           }
  10045       }
  10046  
  10047        /**
  10048        * dra w arrow li ke shape
  10049        * @pa ram shape  - specifie s the shap e whether  angle or p olygon lik e that.
  10050        * @pa ram ang -  specifies  the angle
  10051        */
  10052       functi on rotateS hape(shape , ang) {
  10053           va r rv = [];
  10054           fo r(p in sha pe)
  10055                rv.push( rotatePoin t(ang,shap e[p][0],sh ape[p][1]) );
  10056           re turn rv;
  10057       }
  10058       
  10059        /**
  10060        * tra nslate the  shape
  10061        * @pa ram shape  - specifie s the shap e whether  angle or p olygon lik e that.
  10062        * @pa ram x - sp ecifies th e first po int
  10063        * @pa ram y - sp ecifies th e second p oint
  10064        */
  10065       functi on transla teShape(sh ape,x,y) {
  10066           va r rv = [];
  10067           fo r(p in sha pe)
  10068                rv.push( [ shape[p] [0] + x, s hape[p][1]  + y ]);
  10069           re turn rv;
  10070       }
  10071  
  10072        /**
  10073        * rot ate the po int
  10074        * @pa ram ang -  specifies  the angle
  10075        * @pa ram x - sp ecifies th e first po int
  10076        * @pa ram y - sp ecifies th e second p oint.
  10077        */
  10078       functi on rotateP oint(ang,x ,y) {
  10079           re turn [
  10080                (x * Mat h.cos(ang) ) - (y * M ath.sin(an g)),
  10081                (x * Mat h.sin(ang) ) + (y * M ath.cos(an g))
  10082           ];
  10083       }
  10084  
  10085       functi on getHand lePoint(px , py, leng th, slope)  {
  10086           //  if slope  is 0 or un defined, w e can't us e our regu lar formul a
  10087           if  (slope == = 0) {
  10088                return [ {
  10089                    x: p x,
  10090                    y: p y + length
  10091                }, {
  10092                    x: p x,
  10093                    y: p y - length
  10094                }];
  10095           }  else if (s lope === u ndefined)  {
  10096                return [ {
  10097                    x: p x + length ,
  10098                    y: p y
  10099                }, {
  10100                    x: p x - length ,
  10101                    y: p y
  10102                }];
  10103           }  else {
  10104                var m =  -1 / slope ;
  10105                var x1 =  (Math.pow (m, 2) * p x + length  * Math.sq rt(Math.po w(m, 2) +  1) + px) /  (Math.pow (m, 2) + 1 );
  10106                var x2 =  (Math.pow (m, 2) * p x - length  * Math.sq rt(Math.po w(m, 2) +  1) + px) /  (Math.pow (m, 2) + 1 );
  10107                var y1 =  m * (x1 -  px) + py;
  10108                var y2 =  m * (x2 -  px) + py;
  10109                return [ {
  10110                    x: p arseFloat( x1.toFixed (1)),
  10111                    y: p arseFloat( y1.toFixed (1))
  10112                }, {
  10113                    x: p arseFloat( x2.toFixed (1)),
  10114                    y: p arseFloat( y2.toFixed (1))
  10115                }];
  10116           }
  10117       }
  10118  
  10119       functi on setMeas urementTyp e(type, id , units) {
  10120           me asurementT ype = type ;
  10121           me asurementI d = id;
  10122           me asurementU nits = uni ts;
  10123       }
  10124  
  10125       functi on getMeas urementTyp e() {
  10126           re turn {
  10127                measurem entType: m easurement Type,
  10128                measurem entId: mea surementId ,
  10129                measurem entUnits:  measuremen tUnits
  10130           };
  10131       }
  10132       
  10133       //Retu rn true wh en the cin e is playi ng on the  selected v iewport
  10134       functi on isMeasu remntDisab led(){
  10135           va r imageEle ment = doc ument.getE lementById ("playButt on_wrapper ").getElem entsByTagN ame('img') [0];
  10136           va r playerBu ttomImage  = imageEle ment.src;
  10137           if (playerBut tomImage.i ndexOf("st op.png") >  -1 ) {
  10138                return t rue;
  10139           }  else {
  10140              return fal se;  
  10141           }
  10142       }
  10143       
  10144       /**
  10145       * 
  10146       * @par am {Type}  value 
  10147       */ 
  10148       functi on sign(va lue)
  10149       {
  10150           re turn ( val ue >= 0) ?  1 : -1;
  10151       }
  10152       
  10153       /**
  10154       * Calc ulate the  mean value  of the re gion
  10155       * @par am {Type}   
  10156       */ 
  10157       functi on calcula teStandard Deviation( imageUid,  context, d ata, prese ntation, i mageRender er, editVa lue)
  10158       {          
  10159           va r imageCan vas;
  10160           im ageRendere r.imagePro mise.then( function(i mage){
  10161                imageCan vas = imag e;
  10162           }) ;
  10163  
  10164           if (!imageCan vas && dat a.measurem entResult)  {
  10165                return d ata.measur ementResul t;
  10166           }
  10167  
  10168           va r precisio n = parseI nt(data.st yle.precis ion);
  10169           va r displayS tring = [] ;
  10170           va r startX =  Math.min( Math.round (data.star t.x), Math .round(dat a.end.x));
  10171           va r startY =  Math.min( Math.round (data.star t.y), Math .round(dat a.end.y));
  10172           
  10173           va r endX = M ath.max(Ma th.round(d ata.start. x), Math.r ound(data. end.x));
  10174           va r endY = M ath.max(Ma th.round(d ata.start. y), Math.r ound(data. end.y));
  10175           
  10176           va r ptStart  = { x: sta rtX, y: st artY };
  10177           va r ptEnd =  { x: endX,  y: endY } ;       
  10178       
  10179           va r nSgnX =  sign(ptEnd .x - ptSta rt.x);
  10180           va r nSgnY =  sign(ptEnd .y - ptSta rt.y);
  10181           va r numberOf Pixels = 0 ;
  10182       
  10183           va r nAggrega te = 0;
  10184           va r ptDiffer enceX = Ma th.abs(ptE nd.x - ptS tart.x) /  2;
  10185           va r ptDiffer enceY = Ma th.abs(ptE nd.y - ptS tart.y) /  2;
  10186           va r dXOverA  = 0;
  10187                var dYOv erB = 0;
  10188           va r mean = 0 ;
  10189           va r pixelLis t = [];
  10190           va r ptOrigin  =
  10191                {
  10192                x : (ptS tart.x + p tEnd.x) /  2,
  10193                y : (ptS tart.y + p tEnd.y) /  2
  10194                }
  10195       
  10196           //  Calculate  the mean  value
  10197           va r isValidR egion = (p tDifferenc eX > 1 ? t rue : (ptD ifferenceY  > 1 ? tru e : false) );
  10198           va r imageDat a =  dicom Viewer.ima geCache.ge tImageData (imageCanv as, imageR enderer.im ageCanvas. canvasId);
  10199           if (imageCanv as!== unde fined && i mageData ! == undefin ed && isVa lidRegion)
  10200           {
  10201                var nPix elValue;
  10202                for (var  j = ptSta rt.y ; j < = ptEnd.y  ; j += 1 *  nSgnY)
  10203                {
  10204                    for  (var i = p tStart.x ;  i <= ptEn d.x ; i +=  1 * nSgnX )
  10205                    {
  10206                       d XOverA = ( (i - ptOri gin.x) / p tDifferenc eX);
  10207                       d YOverB = ( (j - ptOri gin.y) / p tDifferenc eY);
  10208  
  10209                         nPixelValu e = imageD ata[(image Canvas.col umns * j)  + i];
  10210                         if(nPixelV alue === u ndefined)  {
  10211                              nPixe lValue = i mageCanvas .minPixel;
  10212                         }
  10213  
  10214                         pixelList. push(nPixe lValue);
  10215                         nAggregate  += nPixel Value;
  10216                         numberOfPi xels++;
  10217                    }
  10218                }
  10219  
  10220                var seri esLayout =  dicomView er.getActi veSeriesLa yout();
  10221                var meas urementUni t = null; 
  10222                var pixe lSpacing =  (measurem entUnit =  getUnitMea surementMa p(seriesLa yout.study Uid+"|"+im ageRendere r.seriesIn dex+"|"+im ageRendere r.imageInd ex+"|"+ima geRenderer .anUIDs.sp lit("*")[1 ])) ?measu rementUnit .pixelSpac ing : unde fined;
  10223                
  10224                // Check  for pixel  spacing
  10225                if(pixel Spacing == = undefine d){
  10226                    var  dicomHeade r = dicomV iewer.head er.getDico mHeader(im ageUid);
  10227                    pixe lSpacing =  dicomHead er.imageIn fo.measure ment.pixel Spacing
  10228                }
  10229  
  10230                var unit Type = mea surementUn it ? measu rementUnit .unitType  : undefine d ;
  10231                mean = ( nAggregate  / numberO fPixels).t oFixed(2);
  10232                var stdD evMean = m ean;
  10233                if(prese ntation != = undefine d && prese ntation != = null) {
  10234                    var  slope = pr esentation .lookupObj .rescaleSl ope;
  10235                    var  intercept  = presenta tion.looku pObj.resca leIntercep t;
  10236                    mean  = parseFl oat(mean)  * slope +  intercept;
  10237                }
  10238  
  10239                displayS tring.push ("Area: "+ getEllipse Area(numbe rOfPixels,  pixelSpac ing, unitT ype, data. style.meas urementUni ts, precis ion));
  10240                displayS tring.push ("Avg: "+p arseFloat( mean).toFi xed(precis ion));
  10241                displayS tring.push ("StdDev:  "+getEllip seStdDev(p ixelList,  stdDevMean , numberOf Pixels, pr ecision));    
  10242           }
  10243           re turn displ ayString;
  10244       }
  10245       
  10246       /**
  10247       * To g et the are a string
  10248       * @par am {Type}  numberOfPi xels - No  of pixels  in the sel ected regi on
  10249       */ 
  10250       functi on getElli pseArea(nu mberOfPixe ls, pixelS pacing, un itType, me asurementU nits, prec ision)
  10251       {
  10252           va r pixelSpa cingX = 1. 0;
  10253           va r pixelSpa cingY = 1. 0;
  10254       
  10255           if (pixelSpac ing.column  !== undef ined){
  10256                pixelSpa cingX = pi xelSpacing .column;
  10257           }
  10258           if (pixelSpac ing.row != = undefine d){
  10259                pixelSpa cingX = pi xelSpacing .row;
  10260           }
  10261  
  10262           //  Calculate  the area
  10263           va r area = n umberOfPix els * pixe lSpacingX  * pixelSpa cingY;
  10264           if  (unitType  === undef ined || un itType ===  null ) {
  10265                measurem entUnits =  (measurem entUnits = = 'in') ?  'inches' :  measureme ntUnits;
  10266                unitType  = 'UNITS_ ' + measur ementUnits .toUpperCa se();//dic omViewer.m easurement .getDefaul tLineMeasu rementUnit ();
  10267                area /=  10;
  10268           }
  10269  
  10270           //  Convert t o other un its if nee ded
  10271           va r areaStri ng = "";
  10272           sw itch(unitT ype)
  10273           {
  10274                case  "U NITS_MM":
  10275                    area  = area *  10.0;
  10276                    suff ix = "sqmm ";
  10277                break;
  10278                case "UN ITS_CM":
  10279                     are a /= 10;
  10280                    suff ix = "sqcm ";
  10281                break;
  10282  
  10283                case "UN ITS_INCHES ":
  10284                    area  = (area /  (25.4 * 2 5.4)) * 10 ;
  10285                    suff ix = "sqin ";
  10286                break;
  10287           }
  10288       
  10289           ar eaString =  area.toFi xed(precis ion) + " "  + suffix;     
  10290           re turn areaS tring;
  10291       }
  10292  
  10293       /**
  10294        * Get  the stand ard deviat ion
  10295        * @pa ram {Type}  pixelList  - Pixels  with in th e region
  10296        * @pa ram {Type}  average -  Mean valu e
  10297        * @pa ram {Type}  numberOfP ixels - No  Of pixels
  10298        */ 
  10299       functi on getElli pseStdDev( pixelList,  average,  numberOfPi xels, prec ision)
  10300       {          
  10301           if (pixelList .length >  1)
  10302           {
  10303                var nAgg regateSE =  0;
  10304                pixelLis t.forEach( function(p ixelValue)
  10305                {
  10306                    nAgg regateSE + = ((pixelV alue - ave rage) * (p ixelValue  - average) );
  10307                });
  10308  
  10309                return M ath.sqrt(n AggregateS E / (numbe rOfPixels  - 1)).toFi xed(precis ion);
  10310           }
  10311           re turn 0;
  10312       }
  10313  
  10314        /**
  10315        * To  draw Windo wLevelROI  measuremen t
  10316        * @pa ram {Type}  imageUid 
  10317        * @pa ram {Type}  context 
  10318        * @pa ram {Type}  data 
  10319        * @pa ram {Type}  presentat ion 
  10320        * @pa ram {Type}  imageRend erer 
  10321        */ 
  10322       functi on drawWin dowLevelRO IMeasureme nt(imageUi d, context , data, pr esentation , imageRen derer, isR ectangleEn d, isEnd)  {
  10323           va r imageCoo rdinate =  data;
  10324           da ta = dicom Viewer.mea surement.g etCanvasDa taForImage Data(data,  imageRend erer);
  10325           
  10326           va r deltaY =  (data.end .y - data. start.y);
  10327           va r deltaX =  (data.end .x - data. start.x);
  10328           va r result =  0;
  10329           if (data.star t.y < data .end.y)
  10330                result =  Math.abs( Math.atan2 (deltaY, d eltaX));
  10331           el se
  10332                result =  Math.abs( Math.atan2 (deltaY, d eltaX)) *  -1;
  10333           
  10334           if  (data !==  undefined ) {
  10335                context. save();
  10336                context. beginPath( );
  10337                //Restor e and draw
  10338                context. restore();
  10339                context. strokeStyl e = '#CCCC 66';
  10340                var radi us = (3 *  imageRende rer.viewpo rtHeight)  / (1000 *  imageRende rer.scaleV alue) ;
  10341                context. lineWidth  = radius;
  10342                //Create  rectangle
  10343                context. moveTo(dat a.start.x,  data.star t.y);
  10344                context. lineTo(dat a.start.x,  data.end. y);
  10345                context. lineTo(dat a.end.x, d ata.end.y) ;
  10346                context. lineTo(dat a.end.x, d ata.start. y);
  10347                
  10348                context. closePath( );
  10349                context. stroke();
  10350           }
  10351           
  10352           re turn null;
  10353       }
  10354  
  10355       /**
  10356        * To  get the RO I WindowLe vel values
  10357        * @pa ram {Type}  imageUid 
  10358        * @pa ram {Type}  context 
  10359        * @pa ram {Type}  data 
  10360        * @pa ram {Type}  presentat ion 
  10361        * @pa ram {Type}  imageRend erer 
  10362        */ 
  10363       functi on GetROIW indowLevel Values(ima geUid, con text, data , presenta tion, imag eRenderer)
  10364       {
  10365           va r imageCan vas;
  10366           im ageRendere r.imagePro mise.then( function(i mage){
  10367                imageCan vas = imag e;
  10368           }) ;
  10369  
  10370           va r precisio n = parseI nt(data.st yle.precis ion);
  10371           va r displayS tring = [] ;
  10372           va r startX =  Math.min( Math.round (data.star t.x), Math .round(dat a.end.x));
  10373           va r startY =  Math.min( Math.round (data.star t.y), Math .round(dat a.end.y));
  10374           
  10375           va r endX = M ath.max(Ma th.round(d ata.start. x), Math.r ound(data. end.x));
  10376           va r endY = M ath.max(Ma th.round(d ata.start. y), Math.r ound(data. end.y));
  10377           
  10378           va r ptStart  = { x: sta rtX, y: st artY };
  10379           va r ptEnd =  { x: endX,  y: endY } ;       
  10380  
  10381           va r nSgnX =  sign(ptEnd .x - ptSta rt.x);
  10382           va r nSgnY =  sign(ptEnd .y - ptSta rt.y);
  10383           va r numberOf Pixels = 0 ;
  10384       
  10385           va r nAggrega te = 0;
  10386           va r ptDiffer enceX = Ma th.abs(ptE nd.x - ptS tart.x) /  2;
  10387           va r ptDiffer enceY = Ma th.abs(ptE nd.y - ptS tart.y) /  2;
  10388           va r dXOverA  = 0;
  10389                var dYOv erB = 0;
  10390           va r mean = 0 ;
  10391           va r pixelLis t = [];
  10392           va r ptOrigin  =
  10393                {
  10394                x : (ptS tart.x + p tEnd.x) /  2,
  10395                y : (ptS tart.y + p tEnd.y) /  2
  10396                }
  10397  
  10398           //  Calculate  the mean  value
  10399           va r imageDat a =  dicom Viewer.ima geCache.ge tImageData (imageCanv as, imageR enderer.im ageCanvas. canvasId);
  10400           if (imageCanv as !== und efined &&  imageData  !== undefi ned && ptD ifferenceX  > 1 && pt Difference Y > 1)
  10401           {
  10402                var nPix elValue;
  10403                for (var  j = ptSta rt.y ; j < = ptEnd.y  ; j += 1 *  nSgnY)
  10404                {
  10405                    for  (var i = p tStart.x ;  i <= ptEn d.x ; i +=  1 * nSgnX )
  10406                    {
  10407                       d XOverA = ( (i - ptOri gin.x) / p tDifferenc eX);
  10408                       d YOverB = ( (j - ptOri gin.y) / p tDifferenc eY);
  10409  
  10410                       / / Check wh ether the  pixel is i nside the  selected r egion
  10411                       / /if (dXOve rA * Math. abs(dXOver A) + dYOve rB * Math. abs(dYOver B) <= 1)
  10412                       {
  10413                            //nPixe lValue = c ontext.get ImageData( i, j, 1, 1 ).data[0];                          
  10414                            nPixelV alue = ima geData[(im ageCanvas. columns *  j) + i];
  10415                            if(nPix elValue == = undefine d) {
  10416                                nPi xelValue =  imageCanv as.minPixe l;
  10417                            }
  10418                            pixelLi st.push(nP ixelValue) ;
  10419                            nAggreg ate += nPi xelValue;
  10420                            numberO fPixels++;
  10421                       }
  10422                    }
  10423                }
  10424                
  10425                mean = ( nAggregate  / numberO fPixels).t oFixed(2);
  10426                return {
  10427                    leve l  : parse Int(mean),
  10428                    wind ow : parse Int(getEll ipseStdDev (pixelList , mean, nu mberOfPixe ls, precis ion))
  10429                };
  10430           }
  10431       }
  10432  
  10433       /**
  10434        * get  and updat e the text  bounds
  10435        * @pa ram {Type}  context -  Specifies  the conte xt
  10436        * @pa ram {Type}  data - Sp ecifies th e data
  10437        * @pa ram {Type}  imageRend erer - Spe cifies the  image ren derer
  10438        */ 
  10439       functi on getAndU pdateTextB ounds(cont ext, data,  imageRend erer) {
  10440           tr y
  10441           {
  10442                if(data. measuremen tSubType ! == "text")  {
  10443                    retu rn data;
  10444                }
  10445  
  10446                var heig ht = data. end.y - da ta.start.y ;
  10447                if (data .end.y < d ata.start. y) {
  10448                    heig ht = data. start.y -  data.end.y ;
  10449                }
  10450  
  10451                // To av oid the ex ternal pre sentation  text rende ring
  10452                if(heigh t == 0) {
  10453                    var  fontSize =  15 / imag eRenderer. scaleValue ;
  10454                    var  lineWidth  = data.sty le.lineWid th / image Renderer.s caleValue;
  10455                    data .end.x = d ata.start. x + contex t.measureT ext(data.m easurement Text).widt h + (lineW idth * 2);
  10456                    data .end.y = d ata.start. y + fontSi ze + (line Width * 2) ;
  10457                }
  10458  
  10459                return d ata;
  10460           }
  10461           ca tch(e)
  10462           {  }
  10463  
  10464           re turn data;
  10465       }
  10466       
  10467       /**
  10468        * Get  the user  measuremen t key/valu e pair
  10469        */ 
  10470       functi on getUser Measuremen tCol() {
  10471           re turn userM easurement StyleCol;
  10472       }
  10473  
  10474       /**
  10475        * Get  the user  measuremen t style by  type
  10476        */ 
  10477       functi on getUser Measuremen tStyleByTy pe(type, d efaultType ) {
  10478           if  (jQuery.i sEmptyObje ct(userMea surementSt yleCol) ||  type == u ndefined)  {
  10479                return u serStyle;
  10480           }
  10481           
  10482           if  (defaultT ype !== un defined) {
  10483                type = ( getUseDefa ultValue(d efaultType )) ? ("sys " + type)  : type;
  10484           }  else {
  10485                type = ( userMeasur ementStyle Col[type]. useDefault ) ? ("sys"  + type) :  type;
  10486           }
  10487  
  10488           re turn userM easurement StyleCol[t ype].style Col;
  10489       }
  10490       
  10491       /**
  10492        * Get  useDefaul t value fo r given ty pe
  10493        * @pa ram {Type}   
  10494        */ 
  10495       functi on getUseD efaultValu e(type) {
  10496           if  (jQuery.i sEmptyObje ct(userMea surementSt yleCol) ||  type == u ndefined)  {
  10497                return t rue;
  10498           }
  10499  
  10500           re turn userM easurement StyleCol[t ype].useDe fault;
  10501       }
  10502  
  10503       /**
  10504        * Get  the scout line style
  10505        */ 
  10506       functi on getScou tLineStyle () {
  10507           re turn getUs erMeasurem entStyleBy Type("LBLS COUT");
  10508       }
  10509  
  10510       /**
  10511        * Get  the ruler  style
  10512        */ 
  10513       functi on getRule rStyle() {
  10514           re turn getUs erMeasurem entStyleBy Type("LBLR ULER");
  10515       }
  10516       
  10517       /**
  10518        *Get  the overla y style
  10519        */
  10520       functi on getOver layStyle()  {
  10521           re turn getUs erMeasurem entStyleBy Type("LBLO VERLAY");
  10522       }
  10523       
  10524       /**
  10525        *Get  the orient ation styl e
  10526        */
  10527       functi on getOrie ntationSty le() {
  10528           re turn getUs erMeasurem entStyleBy Type("LBLO RIENTATION ");
  10529       }
  10530       
  10531       functi on updateC ontextStyl e(context,  measureme ntStyle, i sFont, sca leValue, i sText, isF ill) {
  10532           if  (isText | | isFont)  {
  10533                context. fillStyle  = measurem entStyle.t extColor;
  10534           }  else if (i sFill) {
  10535                context. fillStyle  = measurem entStyle.f illColor;
  10536           }  else {
  10537                context. strokeStyl e = measur ementStyle .lineColor ;
  10538           }
  10539  
  10540           va r fontStyl e = "norma l";
  10541           if  (measurem entStyle.i sItalic &&  measureme ntStyle.is Bold) {
  10542                fontStyl e = "itali c bold";
  10543           }  else if (m easurement Style.isIt alic) {
  10544                fontStyl e = "itali c";
  10545           }  else if (m easurement Style.isBo ld) {
  10546                fontStyl e = "bold" ;
  10547           }
  10548           co ntext.line Width = me asurementS tyle.lineW idth / sca leValue;
  10549           co ntext.font  = fontSty le +  " "  + (measure mentStyle. fontSize /  scaleValu e) + "px"  + " " + me asurementS tyle.fontN ame;
  10550       }
  10551  
  10552       functi on updateT extBounds( textPt, te xt, contex t, data, i mageRender er) {
  10553           if (data.imag eData) {
  10554                data.ima geData.tex tBounds =  [];
  10555                data.ima geData.mea surementTe xt = undef ined;
  10556                var pres entation =  imageRend erer.prese ntationSta te;
  10557                if (pres entation)  {
  10558                    var  pan = pres entation.g etPan();
  10559                    var  topLeftPt  = {};
  10560                    var  bottomRigh tPt = {};
  10561                    var  displayTex t = "";
  10562                    var  lineLength  = 1;
  10563                    var  textWidth  = 0;
  10564  
  10565                    if(O bject.prot otype.toSt ring.call( text) ===  '[object A rray]') {
  10566                         lineLength  = text.le ngth;
  10567                         text.forEa ch(functio n(val){
  10568                             displa yText += v al;
  10569                             displa yText += " \r\n";
  10570  
  10571                             var li neTextWidt h = contex t.measureT ext(val).w idth;
  10572                             if(lin eTextWidth  > textWid th) {
  10573                                 te xtWidth =  lineTextWi dth;
  10574                             }
  10575                         });
  10576                         displayTex t = displa yText.trim ();
  10577                    } el se {
  10578                         displayTex t = text;
  10579                         textWidth  = context. measureTex t(displayT ext).width ;
  10580                    }
  10581                    
  10582                    topL eftPt.x =  parseFloat (textPt.x)  - pan.x;
  10583                    topL eftPt.y =  parseFloat (textPt.y)  - pan.y;
  10584                    bott omRightPt. x = topLef tPt.x + te xtWidth;
  10585                    bott omRightPt. y = topLef tPt.y + (d ata.style. fontSize *  lineLengt h);
  10586  
  10587                    data .imageData .textBound s.push(top LeftPt);
  10588                    data .imageData .textBound s.push(bot tomRightPt );
  10589                    data .imageData .measureme ntText = d isplayText ;
  10590                }
  10591           }
  10592       }
  10593  
  10594       dicomV iewer.meas urement.dr aw = {
  10595           dr awMeasurem ents: draw Measuremen ts,
  10596           se tMeasureme ntType: se tMeasureme ntType,
  10597           ge tMeasureme ntType: ge tMeasureme ntType,
  10598           ge tHandlePoi nt: getHan dlePoint,
  10599           ge tMousePoin tForImageC oordinates : getMouse PointForIm ageCoordin ates,
  10600           ge tImageCoor dinatesFor MousePoint : getImage Coordinate sForMouseP oint,
  10601           ge tCanvasCoo rdinatesFo rImageCoor dinates: g etCanvasCo ordinatesF orImageCoo rdinates,
  10602           dr awLineMeas urement: d rawLineMea surement,
  10603           dr awPointMea surement:  drawPointM easurement ,
  10604           se tUserMeasu rementCol:  setUserMe asurementC ol,
  10605           se tUserMeasu rementStyl eByType: s etUserMeas urementSty leByType,
  10606           ge tUserMeasu rementCol:  getUserMe asurementC ol,
  10607           ge tUserMeasu rementStyl eByType: g etUserMeas urementSty leByType,
  10608           ge tScoutLine Style: get ScoutLineS tyle,
  10609           ge tRulerStyl e: getRule rStyle,
  10610           ge tOverlaySt yle: getOv erlayStyle ,
  10611           ge tOrientati onStyle: g etOrientat ionStyle,
  10612           is Measuremnt Disabled:  isMeasurem ntDisabled ,
  10613           dr awWindowLe velROIMeas urement :  drawWindow LevelROIMe asurement,
  10614           Ge tROIWindow LevelValue s : GetROI WindowLeve lValues
  10615       };
  10616  
  10617       return  dicomView er;
  10618   }(dicomVie wer));var  dicomViewe r = (funct ion(dicomV iewer){
  10619           
  10620           if (dicomView er === und efined)
  10621           {
  10622                    dico mViewer =  {};
  10623           }
  10624  
  10625       functi on drawUSR egions(con text,image Info,prese ntation)
  10626       {
  10627           va r usRegion s = imageI nfo.getUSR egions();
  10628           if (usRegions  === undef ined)
  10629           {
  10630                return;
  10631           }
  10632           fo r(var i=0; i<usRegion s.length;i ++)
  10633           {
  10634                drawRegi ons(contex t,usRegion s[i],prese ntation);
  10635           }
  10636       }
  10637  
  10638       functi on drawReg ions(conte xt,region, presentati on)
  10639       {
  10640           va r cordinat es = getRe gionCordin atesInCanv as(region, presentati on);
  10641           
  10642           co ntext.begi nPath();
  10643           co ntext.rect (cordinate s.x0, cord inates.y0,  (cordinat es.x1 - co rdinates.x 0) , (cord inates.y1  - cordinat es.y0));
  10644           co ntext.line Width = 1/ presentati on.getZoom ();
  10645           co ntext.stro keStyle =  'blue';
  10646           co ntext.setL ineDash([1 5]);
  10647           co ntext.stro ke();
  10648       }
  10649  
  10650       functi on getRegi onCordinat esInCanvas (region,pr esentation )
  10651       {
  10652           if (presentat ion === un defined)
  10653           {
  10654                throw "g etRegionCo rdinatesIn Canvas: pr esentation  is null/u ndefined";
  10655           }
  10656           va r pan = pr esentation .getPan();
  10657           va r canvasCo ordinates  = {};
  10658           ca nvasCoordi nates.x0 =  region.re gionLocati onMinX0 +   pan.x;
  10659           ca nvasCoordi nates.x1 =  region.re gionLocati onMaxX1 +   pan.x;
  10660           ca nvasCoordi nates.y0 =  region.re gionLocati onMinY0 +  pan.y;
  10661           ca nvasCoordi nates.y1 =  region.re gionLocati onMaxY1 +  pan.y;
  10662           
  10663           re turn canva sCoordinat es;
  10664       }
  10665  
  10666       dicomV iewer.draw  = {
  10667           us Region : {
  10668                             drawUS Regions :  drawUSRegi ons,
  10669                             drawRe gions : dr awRegions
  10670                }
  10671       };
  10672  
  10673       return  dicomView er;
  10674       
  10675   }(dicomVie wer));/**
  10676    * This mo dule deals  with Imag eLoaders,  loading im ages and c aching ima ges
  10677    */
  10678  
  10679   var dicomV iewer = (f unction(di comViewer)  {
  10680  
  10681       if (di comViewer  === undefi ned) {
  10682           di comViewer  = {};
  10683       }
  10684  
  10685       /**
  10686        * Get  the image  promise
  10687        */
  10688       functi on getImag ePromise(s tudyUid, s eriesIndex , imageUid , frameNum ber, image Type) {
  10689           re turn getIm ageInfo(st udyUid, se riesIndex,  imageUid,  frameNumb er, imageT ype);
  10690       }
  10691  
  10692       // Loa ds an imag e given an  imageUid  and return s a promis e which wi ll resolve
  10693       // to  the loaded  image obj ect or fai l if an er ror occurr ed.  The i mage is
  10694       // sto red in the  cache
  10695       functi on getImag e(studyUid , imageUid , frameNum ber, serie sIndex, im ageType, i ndex) {
  10696           if  (imageUid  === undef ined) {
  10697                throw "g etImage: p arameter i mageUid mu st not be  undefined" ;
  10698           }
  10699  
  10700           va r purgeSer iesIndex =  (index !=  undefined ) ? index  : seriesIn dex;
  10701           va r purgeIma geIndex =  (index !=  undefined)  ? seriesI ndex : und efined;
  10702           if  (dicomVie wer.isSeri esInComple te(studyUi d, purgeSe riesIndex,  purgeImag eIndex)) {
  10703                dicomVie wer.enable CacheData( studyUid,  true);
  10704                dicomVie wer.cacheI mages(stud yUid);
  10705           }
  10706  
  10707           va r imagePro mise = dic omViewer.i mageCache. getImagePr omise(imag eUid + "_"  + frameNu mber);
  10708           if  (imagePro mise !== u ndefined)  {
  10709                return i magePromis e;
  10710           }
  10711  
  10712           im agePromise  = getImag ePromise(s tudyUid, s eriesIndex , imageUid , frameNum ber, image Type);
  10713           if  (imagePro mise === u ndefined)  {
  10714                throw "g etImage: n o image lo ader for i mageUid";
  10715           }
  10716  
  10717           di comViewer. imageCache .putImageP romise(stu dyUid, ima geUid, fra meNumber,  imagePromi se, series Index, ind ex);
  10718           re turn image Promise;
  10719       }
  10720  
  10721       functi on updateI mage(image Canvas, im age, prese ntation) {
  10722           // var presen tation = i mage.prese ntation;
  10723           va r lookUpTa ble = pres entation.g etlookupTa ble();
  10724           im ageCanvas. height = i mage.rows;
  10725           im ageCanvas. width = im age.column s;
  10726           va r context  = imageCan vas.getCon text("2d") ;
  10727           co ntext.setT ransform(1 , 0, 0, 1,  0, 0);
  10728           //  clear the  canvas
  10729           co ntext.fill Style = 'b lack';
  10730           co ntext.fill Rect(0, 0,  image.col umns, imag e.rows);
  10731  
  10732           if  (image.is WLApplied  == false | |
  10733                image.la stAppliedw indowCente r != prese ntation.wi ndowCenter  || 
  10734                image.la stAppliedW indowWidth  != presen tation.win dowWidth |
  10735                image.la stAppliedB rightness  != present ation.brig htness || 
  10736                image.la stAppliedC ontrast !=  presentat ion.contra st || 
  10737                image.la stAppliedI nvert != p resentatio n.invert |
  10738                image.la stAppliedR GBMode !=  presentati on.rgbMode  ||
  10739                image.la stAppliedS harpenLeve l != prese ntation.sh arpen ||
  10740                image.is 6000Overla y != dicom Viewer.too ls.is6000O verlayVisi ble()) {
  10741                    // U pdate the  flags
  10742                    imag e.lastAppl iedwindowC enter = pr esentation .windowCen ter;
  10743                    imag e.lastAppl iedWindowW idth = pre sentation. windowWidt h;
  10744                    imag e.lastAppl iedBrightn ess = pres entation.b rightness;
  10745                    imag e.lastAppl iedContras t = presen tation.con trast;
  10746                    imag e.lastAppl iedInvert  = presenta tion.inver t;
  10747                    imag e.presenta tion.inver t = presen tation.inv ert;
  10748                    imag e.presenta tion.rgbMo de = prese ntation.rg bMode;
  10749                    imag e.lastAppl iedRGBMode  = present ation.rgbM ode;
  10750                    imag e.lastAppl iedWindowL evel = pre sentation. windowLeve l;
  10751                    imag e.is6000Ov erlay = di comViewer. tools.is60 00OverlayV isible();
  10752                    imag e.isWLAppl ied = true ;
  10753                    imag e.presenta tion.sharp en = prese ntation.sh arpen;
  10754                    imag e.lastAppl iedSharpen Level = pr esentation .sharpen;
  10755  
  10756                    // G et the wl  canvas con text
  10757                    imag e.wlCanvas Context.fi llStyle =  'white';
  10758                    imag e.wlCanvas Context.fi llRect(0,0 , image.wl Canvas.wid th, image. wlCanvas.h eight);
  10759                    imag e.wlCanvas Data = ima ge.wlCanva sContext.g etImageDat a(0, 0, im age.wlCanv as.width,  image.wlCa nvas.heigh t);
  10760  
  10761                    var  imageData  = dicomVie wer.imageC ache.getIm ageData(im age, image Canvas.can vasId);
  10762                    if(! imageData)  {
  10763                         imageData  = dicomVie wer.imageC ache.getRa wData(imag e)
  10764                    }
  10765  
  10766                    if ( image.isCo lorImage)  {
  10767                         lookUpTabl e.applyCol orLUT(imag eData, ima ge.wlCanva sData, ima ge.columns , image.ro ws, presen tation.get RGBMode()) ;
  10768                    } el se {
  10769                         lookUpTabl e.applyLUT (imageData , image.wl CanvasData , image.co lumns, ima ge.rows);
  10770  
  10771                         // Apply 6 000 overla y
  10772                         if(dicomVi ewer.tools .is6000Ove rlayVisibl e()) {
  10773                             lookUp Table.appl y6000Overl ay(image,  image.wlCa nvasData);
  10774                         }
  10775                    }
  10776                
  10777                image.wl CanvasCont ext.putIma geData(ima ge.wlCanva sData, 0,  0);
  10778                image.wl CanvasData  = null;
  10779  
  10780                // If ap plysharpen  true then  use sharp en tool
  10781                // Sharp en tool wi ll work on ce the can vas image  is created
  10782                if(image .applyShar pen) {
  10783                    look UpTable.ap plySharpen (image.wlC anvasConte xt, image. wlCanvas.w idth, imag e.wlCanvas .height, i mage.prese ntation.sh arpen);
  10784                }
  10785           }
  10786  
  10787           co ntext.draw Image(imag e.wlCanvas , 0,0, ima ge.columns , image.ro ws, 0, 0,  image.colu mns, image .rows);
  10788       }
  10789  
  10790       functi on getImag eInfo(stud yUid, seri esIndex, i mageUid, f rameNumber ,  imageTy pe) {
  10791           va r deferred  = $.Defer red();
  10792           va r urlParam eters = di comViewer. getImageIn foURl(imag eUid);
  10793           va r deffered Value = un defined;
  10794           va r dicominf o = dicomV iewer.head er.getDico mHeader(im ageUid);
  10795           if  (dicominf o === unde fined) {
  10796                var meta URL = dico mViewer.ur l.getDicom ImageURL(u rlParamete rs);
  10797                var logM essage = " Imageinfo  request ur l : " + me taURL;
  10798                dumpCons oleLogs(LL _DEBUG, un defined, " getImageIn fo ", logM essage);
  10799                if (type of(Worker)  !== "unde fined") {
  10800                    var  workerJob  = {
  10801                         studyUid :  studyUid,
  10802                         seriesInde x : series Index,
  10803                         imageUid :  imageUid,
  10804                         frameNumbe r : frameN umber,
  10805                         deferred :  deferred,
  10806                         urlParamet ers : urlP arameters,
  10807                         url : meta URL,
  10808                         type : "ca che",
  10809                         request :  "DicomInfo ",
  10810                         isProcessi ng : false ,
  10811                         id : "Dico mInfo_" +  imageUid,
  10812                    };
  10813                    doWo rkerQueue( workerJob) ;
  10814                } else {
  10815                    var  def = dico mViewer.he ader.getDi comHeaderI nfo(metaUR L);
  10816                    def. done(funct ion(text)  {
  10817                         var imageT ype = text .imageType ;
  10818                         dicominfo  = new Imag eInfoManag er(text);
  10819                         dicomViewe r.header.p utDicomHea der(imageU id, dicomi nfo);
  10820                         requestIma ge(imageUi d, frameNu mber, dico minfo, url Parameters , deferred , studyUid , seriesIn dex);
  10821                    });
  10822                }
  10823           }  else {
  10824                requestI mage(image Uid, frame Number, di cominfo, u rlParamete rs, deferr ed, studyU id, series Index);
  10825           }
  10826  
  10827           re turn defer red;
  10828       }
  10829  
  10830       functi on process DicomImage (imageUid,  frameNumb er, dicomi nfo, fileC ontent, co mpressDone , seriesIn dex) {
  10831           va r renderIm age;
  10832           if  (compress Done) {
  10833                renderIm age = file Content;
  10834           }  else {
  10835                var read er = new D icomInputS treamReade r();
  10836                reader.r eadDICOMBy tes(fileCo ntent);
  10837                var dico mBuffer =  reader.get InputBuffe r();
  10838                var dico mReader =  reader.get Reader();
  10839                renderIm age = prep areImage(d icominfo,  dicomBuffe r, dicomRe ader);
  10840           }
  10841  
  10842           va r pixelBuf fer = rend erImage.pi xelArray;
  10843           va r minMaxPi xel = rend erImage.mi nMaxPixel;
  10844           va r image =  {
  10845                imageUid : imageUid ,
  10846                frameNum ber: frame Number,
  10847                dicominf o: dicomin fo,
  10848                imageDat a: pixelBu ffer,
  10849                canvas:  null,
  10850                sizeInBy tes: (isCa cheCompres sedImageDa ta ? pixel Buffer.len gth : dico minfo.getF rameSize() ),
  10851                canvasCt x: null,
  10852                presenta tion:  new  Presentat ion(),
  10853                lastAppl iedInvert:  false,
  10854                lastAppl iedRGBMode :0,
  10855                rows: di cominfo.ge tRows(),
  10856                columns:  dicominfo .getColumn s(),
  10857                minPixel : minMaxPi xel.min,
  10858                maxPixel : minMaxPi xel.max,
  10859                invert:  (dicominfo .getPhotom etricInter pretation( ) === "MON OCHROME1"  ? true : f alse),
  10860                isColorI mage: dico minfo.isCo lor(),
  10861                imageTyp e: "image" ,
  10862                isWLAppl ied: false ,
  10863                bitsAllo cated: dic ominfo.get BitsAlloca ted(),
  10864                isCompre ssed: isCa cheCompres sedImageDa ta,
  10865                minMaxPi xel: minMa xPixel,
  10866                isRGBToo lEnabled:  true,
  10867                lastAppl iedWindowL evel: 1,
  10868                is6000Ov erlay: fal se,
  10869                lastAppl iedSharpen Level: 0,
  10870                applySha rpen: isSh owSharpen
  10871           };
  10872  
  10873           /* ********** ********** ********** ********** ********** ********** ********** **
  10874           *  Create the  separate  canvas for  WL
  10875           *  Referred f rom 'corne rstoneDemo ' to impro ve perform ance in IE
  10876           *  http://cha fey.github .io/corner stoneDemo/
  10877           ** ********** ********** ********** ********** ********** ********** ********** **/
  10878           im age.wlCanv as = docum ent.create Element('c anvas');
  10879           im age.wlCanv as.width =  image.col umns;
  10880           im age.wlCanv as.height  = image.ro ws;
  10881           im age.wlCanv asContext  = image.wl Canvas.get Context('2 d');
  10882           im age.wlCanv asContext. fillStyle  = 'white';
  10883           im age.wlCanv asContext. fillRect(0 ,0, image. wlCanvas.w idth, imag e.wlCanvas .height);
  10884           im age.wlCanv asData = n ull;
  10885  
  10886           //  Calculate  the rende r size
  10887           im age.render SizeInByte s = getRen derSize(im age);
  10888           im age.sizeIn Bytes *= 8 ;
  10889  
  10890           //  Update wi ndow level
  10891           up dateWindow Level(imag e);
  10892  
  10893           //  Update th e 6000 ove rlay
  10894           up date6000Ov erlay(imag e, 0, seri esIndex);
  10895  
  10896           re turn image ;
  10897       }
  10898  
  10899       functi on process GeneralIma ge(imageUi d, frameNu mber, dico minfo, ima geObj, def erred) {
  10900           va r brightne ss = 100;
  10901           va r contrast  = 100;
  10902           va r presenta tion = new  Presentat ion();
  10903           va r backgrou dRenderer  = document .createEle ment("canv as");
  10904           va r context  = backgrou dRenderer. getContext ("2d");
  10905  
  10906           pr esentation .setBright nessContra st(brightn ess, contr ast);
  10907           im ageObj.onl oad = func tion () {
  10908                if (wind ow.console ) {
  10909                    var  t0 = getUr lParam("ts ", imageOb j.src).val ue;
  10910                    cons ole.log("I mageUid :  " + imageU id + "_" +  frameNumb er + " \t  Time Elaps ed (ms) :  " + (Date. now() - t0 ));
  10911                }
  10912  
  10913                imageObj .type = "a pplication /jpeg";
  10914                dicominf o.setRows( imageObj.h eight);
  10915                dicominf o.setColum ns(imageOb j.width);
  10916                var size InBytes =  imageObj.h eight * im ageObj.wid th;
  10917                var imag e = {
  10918                    imag eUid: imag eUid,
  10919                    fram eNumber: f rameNumber ,
  10920                    dico minfo: dic ominfo,
  10921                    imag eData: ima geObj,
  10922                    canv as: null,
  10923                    size InBytes: s izeInBytes ,
  10924                    canv asCtx: nul l,
  10925                    pres entation:  presentati on,
  10926                    wind owWidth: 0 ,
  10927                    wind owCenter:  0,
  10928                    brig htness: br ightness,
  10929                    cont rast: cont rast,
  10930                    last AppliedWin dowWidth:  0,
  10931                    last Appliedwin dowCenter:  0,
  10932                    last AppliedBri ghtness: b rightness,
  10933                    last AppliedCon trast: con trast,
  10934                    last AppliedInv ert: false ,
  10935                    rows : imageObj .height,
  10936                    colu mns: image Obj.width,
  10937                    inve rt: false,
  10938                    isCo lorImage:  false,
  10939                    imag eType: "im age",
  10940                    isWL Applied: f alse,
  10941                    isRG BToolEnabl ed: false,
  10942                    last AppliedWin dowLevel:  1
  10943                };
  10944                image.st udyUid = d eferred.st udyUid;
  10945                deferred .resolve(i mage);
  10946           }
  10947       }
  10948       
  10949       functi on request Image(imag eUid, fram eNumber, d icominfo,  urlParamet ers, defer red,  stud yUid, seri esIndex) {
  10950           tr y {
  10951                var t0 =  Date.now( );
  10952                dumpCons oleLogs(LL _DEBUG, un defined, " loader", " Start");
  10953  
  10954                var imag eType  = " ";
  10955                if(dicom info != un defined) {
  10956                    imag eType = di cominfo.im ageInfo.im ageType;
  10957                }
  10958  
  10959                if(defer red) {
  10960                    defe rred.study Uid = stud yUid;
  10961                }
  10962  
  10963                if (imag eType == I MAGETYPE_R ADECHO ||  imageType  == IMAGETY PE_RAD ||  imageType  == null) {
  10964                    if(( dicominfo. imageInfo. numberOfFr ames > 1)  && (dicomi nfo.imageI nfo.modali ty === "US ")) {
  10965                         requestGen eralImage( imageUid,  frameNumbe r, urlPara meters, de ferred, di cominfo);
  10966                    } el se {
  10967                         urlParamet ers = dico mViewer.ge tDicomFram eUrl(image Uid, frame Number);
  10968                         var url =  dicomViewe r.url.getD icomImageU RL(urlPara meters);
  10969                         var logMes sage = "Im ageinfo re quest url  : " + url  + "\n \
  10970                               Imag e request  for => " +  imageUid  + "_" + fr ameNumber;
  10971                         dumpConsol eLogs(LL_D EBUG, unde fined, und efined, lo gMessage);
  10972                         var reques tHeaders =  getImageR equestHead ers(studyU id, series Index, ima geUid);
  10973                         if (typeof (Worker) ! == "undefi ned") {
  10974                             var wo rkerJob =  {
  10975                                 st udyUid : s tudyUid,
  10976                                 se riesIndex:  seriesInd ex,
  10977                                 im ageUid : i mageUid,
  10978                                 fr ameNumber  : frameNum ber,
  10979                                 de ferred : d eferred,
  10980                                 ur l : url,
  10981                                 he aders : re questHeade rs,
  10982                                 di cominfo: d icominfo,
  10983                                 is Decompress ionRequire d: !isCach eCompresse dImageData ,
  10984                                 ty pe : "cach e",
  10985                                 re quest : "I mage",
  10986                                 is Processing  : false,
  10987                                 id  : "Image_ " + imageU id,
  10988                             };
  10989                             doWork erQueue(wo rkerJob);
  10990                         } else {
  10991                             $.ajax ({
  10992                                 ur l: url,
  10993                                 be foreSend:  function(x hr) {
  10994                                      xhr.over rideMimeTy pe("text/p lain; char set=x-user -defined") ;
  10995                                 }
  10996                             })
  10997                             .done( function(d ata) {
  10998                                 va r image =  processDic omImage(im ageUid, fr ameNumber,  dicominfo , data, fa lse);
  10999                                 de ferred.res olve(image );
  11000                             })
  11001                             .fail( function(d ata) {
  11002                                 de ferred.rej ect();
  11003                             })
  11004                             .error (function( xhr, statu s) {
  11005                                 va r descript ion = xhr. statusText  + "\nFail ed to read  the image ." + "\nIm age UID: "  + imageUi d;
  11006                                 se ndViewerSt atusMessag e(xhr.stat us.toStrin g(), descr iption);
  11007                             });
  11008                         }
  11009                         $("#ecgPre ference"). prop("disa bled", tru e);
  11010                    }
  11011                } else i f (imageTy pe == IMAG ETYPE_JPEG ) {
  11012                    requ estGeneral Image(imag eUid, fram eNumber, u rlParamete rs, deferr ed, dicomi nfo);
  11013                } else i f (imageTy pe == IMAG ETYPE_RADP DF) {
  11014                    requ estPdf(ima geUid, fra meNumber,  urlParamet ers);
  11015                } else i f (imageTy pe == IMAG ETYPE_RADE CG) {
  11016                    dico mViewer.lo adEcg(urlP arameters,  "imagevie wer1x1");
  11017                } else i f (imageTy pe == IMAG ETYPE_RADS R || image Type == IM AGETYPE_CD A) {
  11018                    dico mViewer.lo adSR(urlPa rameters,n ull,deferr ed, imageT ype);
  11019                }
  11020           }
  11021           ca tch(e)
  11022           {
  11023                dumpCons oleLogs(LL _ERROR, un defined, u ndefined,  e.message)
  11024           }
  11025           fi nally {
  11026                dumpCons oleLogs(LL _DEBUG, un defined, u ndefined,  "End", (Da te.now() -  t0));
  11027           }
  11028       }
  11029  
  11030       functi on request GeneralIma ge(imageUi d, frameNu mber, urlP arameters, deferred,d icominfo)  {
  11031           ur lParameter s =  dicom Viewer.get JpegFrameU rl(imageUi d, frameNu mber);
  11032           va r url = di comViewer. url.getDic omImageURL (urlParame ters);
  11033           va r logMessa ge = "Imag einfo requ est url :  " + url +  "\n \
  11034                               Imag e request  for => " +  imageUid  + "_" + fr ameNumber;
  11035           du mpConsoleL ogs(LL_DEB UG, undefi ned, "requ estGeneral Image ", l ogMessage) ;
  11036           va r imageObj  = new Ima ge();
  11037           im ageObj.typ e = "appli cation/jpe g";
  11038           ur l += "&ts= " + Date.n ow();
  11039           im ageObj.src  = url;
  11040           pr ocessGener alImage(im ageUid, fr ameNumber,  dicominfo , imageObj , deferred );
  11041  
  11042           $( "#ecgPrefe rence").pr op("disabl ed", true) ;
  11043       }
  11044  
  11045       functi on request Pdf(imageU id, frameN umber, url Parameters ) {
  11046           $( "#ecgPrefe rence").pr op("disabl ed", true) ;
  11047           ur lParameter s =  dicom Viewer.get PdfFrameUr l(imageUid );
  11048           va r url = di comViewer. url.getDic omImageURL (urlParame ters);
  11049           $( "#imagevie wer1x1").e mpty();
  11050           va r pdfDiv =  "<div id= 'pdf' styl e='height: 100%;width :100%'><if rame name= 'pdfviewer 1x1' style ='height:1 00%;width: 100%' src= " + url +  "/></div>" ;
  11051           $( "#imagevie wer1x1").a ppend(pdfD iv);
  11052           do cument.get ElementsBy Name("pdfv iewer1x1") [0].conten tWindow.do cument.bod y.focus();
  11053       }
  11054  
  11055       functi on prepare Image(dico minfo, dic omBuffer,  dicomReade r) {
  11056           va r minMax =  {
  11057                min: dic ominfo.get MinPixelVa lue(),
  11058                max: dic ominfo.get MaxPixelVa lue()
  11059           };
  11060  
  11061           va r isCompre ssed = tru e;
  11062           if  (isCompre ssed) {
  11063                if(!isCa cheCompres sedImageDa ta) {
  11064                    pixe lBuffer =  dicomBuffe r;
  11065                } else {
  11066                    // d ecompress  image
  11067                    pixe lBuffer =  pako.infla te(dicomBu ffer);
  11068  
  11069                    // c onvert to  16 bit arr ay if nece ssary
  11070                    var  bitsAlloca ted = dico minfo.getB itsAllocat ed();
  11071                    if ( bitsAlloca ted == 16)  {
  11072  
  11073                         var arrayS ize8 = pix elBuffer.l ength;
  11074                         var pixelB uffer16 =  new Uint16 Array(arra ySize8 / 2 );
  11075                         var pixelI ndex = 0;
  11076                         for (var i  = 0; i <  arraySize8 ; i += 2)  {
  11077                             pixelB uffer16[pi xelIndex++ ] = (pixel Buffer[i +  1] * 256)  + pixelBu ffer[i];
  11078                         }
  11079                         pixelBuffe r = pixelB uffer16;
  11080                    }
  11081                }
  11082           }  else {
  11083                var bits Allocated  = dicominf o.getBitsA llocated() ;
  11084                var byte sPerPixel  = (bytesPe rPixel ==  8) ? 1 : 2 ;
  11085                var pixe lBuffer =  new Array( dicomBuffe r.length);
  11086                var pixe lIndex = 0 ;
  11087                for (var  i = 0; i  < dicomBuf fer.length ; i += byt esPerPixel ) {
  11088                    pixe lBuffer[pi xelIndex++ ] = dicomR eader.read Number(byt esPerPixel , i);
  11089                }
  11090           }
  11091  
  11092           va r renderIm age = {
  11093                pixelArr ay: pixelB uffer,
  11094                minMaxPi xel: minMa x
  11095           };
  11096  
  11097           re turn rende rImage;
  11098       }
  11099  
  11100       functi on getWind owLevelLim its(minMax Pixel, dic ominfo) {
  11101           va r aRescale Slope = di cominfo.ge tRescaleSl ope();
  11102           va r aRescale Intercept  = dicominf o.getResca leIntercep t();
  11103  
  11104           va r minLevel Value = (m inMaxPixel .min * aRe scaleSlope ) + aResca leIntercep t;
  11105           va r maxLevel Value = (m inMaxPixel .max * aRe scaleSlope ) + aResca leIntercep t;
  11106           va r minWindo wValue = 1 ; // As pe r the Stan dard
  11107           va r maxWindo wValue = ( maxLevelVa lue - minL evelValue)  * 2.0;
  11108  
  11109           re turn {
  11110                wwLimit:  {
  11111                    min:  minWindow Value,
  11112                    max:  maxWindow Value
  11113                },
  11114                wcLimit:  {
  11115                    min:  minLevelV alue,
  11116                    max:  maxLevelV alue
  11117                }
  11118           };
  11119       }
  11120  
  11121       functi on findMin Max(dicomi nfo, pixel Buffer) {
  11122           va r min = 65 536;
  11123           va r max = -6 5536;
  11124           fo r (var i =  0; i < pi xelBuffer. length; i  ++) {
  11125                 var pix el = pixel Buffer[i];
  11126                if(min >  pixel) mi n = pixel;
  11127                if(max <  pixel) ma x = pixel;
  11128           }
  11129           va r minMax =  {
  11130                min: min ,
  11131                max: max
  11132           };
  11133  
  11134           re turn minMa x;
  11135       }
  11136  
  11137       functi on calcula teAutoWind owLevel(di cominfo, m inMaxPixel ) {
  11138           va r aRescale Slope = di cominfo.ge tRescaleSl ope();
  11139           va r aRescale Intercept  = dicominf o.getResca leIntercep t();
  11140           if  (aRescale Slope ===  undefined)  {
  11141                aRescale Slope = 1;
  11142           }
  11143           if  (aRescale Intercept  === undefi ned) {
  11144                aRescale Intercept  = 0;
  11145           }
  11146           va r vMinPixe l = minMax Pixel.min;
  11147           va r vMaxPixe l = minMax Pixel.max;
  11148           if  (dicominf o.getBitsA llocated()  === 16 &&  Math.pow( 2, dicomin fo.getBits Allocated( )-1) < (vM axPixel -  vMinPixel)   ) {
  11149                vMinPixe l = 0 - mi nMaxPixel. min;
  11150                vMaxPixe l = 65536  - minMaxPi xel.max;
  11151           }  else if(vM inPixel == = 0 && vMa xPixel ===  Math.pow( 2, dicomin fo.getBits Allocated( )-1)) {
  11152                vMinPixe l = 0;
  11153                vMaxPixe l = (1 / a RescaleSlo pe) - aRes caleInterc ept;;
  11154           }
  11155  
  11156           va r itsMinLe velRange =  (vMinPixe l * aResca leSlope) +  aRescaleI ntercept;  // Minimum  Level can  be accept ed for thi s image
  11157           va r itsMaxLe velRange =  (vMaxPixe l * aResca leSlope) +  aRescaleI ntercept;  // Maximum  Level can  be accept ed for thi s image
  11158           
  11159           //  Window le vel should  be within  itsMinLev elRange an d itsMaxLe velRange
  11160           va r level =  (itsMinLev elRange +  itsMaxLeve lRange) /  2; // Expe cted Windo w Level
  11161  
  11162           va r theMinWi ndowRange  = 1;  // A s per the  Standard.  Minimum wi dth can be  accepted  for this i mage
  11163           va r theMaxWi ndowRange  = (itsMaxL evelRange  - itsMinLe velRange)  * 2.0; //  Maximum wi dth can be  accepted  for this i mage
  11164           
  11165           //  Window wi dth should  be within  theMinWin dowRange a nd theMaxW indowRange
  11166           va r window =  (theMinWi ndowRange  + theMaxWi ndowRange)  / 2; // E xpected Wi ndow Level
  11167           
  11168           re turn { ww:  parseInt( window), w c: parseIn t(level) } ;
  11169       }
  11170       
  11171       functi on changeN ullToEmpty (value) {
  11172           if  (value ==  undefined  || value  == null) {
  11173                return " ";
  11174           }
  11175           re turn value ;
  11176       }
  11177  
  11178       /**
  11179        * Cal culate the  render si ze
  11180        * @pa ram {Type}  image - S pecifies t he image o bject
  11181        */ 
  11182       functi on getRend erSize(ima ge) {
  11183           tr y
  11184           {
  11185                if(image  == undefi ned || ima ge == null ) {
  11186                    retu rn 0;
  11187                }
  11188  
  11189                if(!imag e.isCompre ssed) {
  11190                    retu rn 0;
  11191                }
  11192  
  11193                var isWL Required =  (image.di cominfo.ge tModality( ) === "US"  ? false :  true);
  11194                var size InBytes =  image.dico minfo.getF rameSize() ;
  11195                var rend erCanvasSi ze = sizeI nBytes;
  11196                var wlCa nvasSize =  (isWLRequ ired ? siz eInBytes :  0);
  11197                var minM axPixel =  (isWLRequi red ? (ima ge.maxPixe l - Math.m in(image.m inPixel, 0 )) + 1 : 0 );
  11198                var rend erSize = ( sizeInByte s / 4);
  11199                var tota lRenderSiz e = 0;
  11200  
  11201                totalRen derSize +=  renderCan vasSize;
  11202                totalRen derSize +=  wlCanvasS ize;
  11203                totalRen derSize +=  minMaxPix el;
  11204                totalRen derSize +=  renderSiz e;
  11205  
  11206                return t otalRender Size;
  11207           }
  11208           ca tch(e)
  11209           {  }
  11210  
  11211           re turn 0;
  11212       }
  11213  
  11214       /**
  11215        * upd ate the wi ndow level
  11216        * @pa ram {Type}  image - S pecifies t he image
  11217        */ 
  11218       functi on updateW indowLevel (image) {
  11219           tr y
  11220           {
  11221                /*
  11222                *  Windo w / Level
  11223                // windo wWidth =>  Window
  11224                // windo wCenter =>  Level
  11225                */
  11226  
  11227                var wind owCenter =  image.dic ominfo.get WindowCent er();
  11228                var wind owWidth =  image.dico minfo.getW indowWidth ();
  11229                var pixe lBuffer =  dicomViewe r.imageCac he.getRawD ata(image) ;
  11230                var dico minfo = im age.dicomi nfo;
  11231                var minM axPixel =  image.minM axPixel;
  11232                var wind owLevelLim its = getW indowLevel Limits(min MaxPixel,  dicominfo) ;
  11233                var inve rt = image .invert;
  11234                var brig htness = 1 00;
  11235                var cont rast = 100 ;
  11236  
  11237                var auto CalWinLvl  = false;
  11238                if (isNa N(windowCe nter) || i sNaN(windo wWidth)) {
  11239                    if ( image.isCo lor) {
  11240                         windowCent er = 128;
  11241                         windowWidt h = 255;
  11242                    } el se {
  11243                         autoCalWin Lvl = true ;
  11244                    }
  11245                } else i f(windowCe nter === 0  && window Width ===  0){
  11246                     aut oCalWinLvl  = true;
  11247                }
  11248  
  11249                if(autoC alWinLvl)  {
  11250                    var  autoWindow Level = {w c: windowC enter, ww:  windowWid th};
  11251                    minM axPixel =  findMinMax (dicominfo , pixelBuf fer);
  11252                    wind owLevelLim its = getW indowLevel Limits(min MaxPixel,  dicominfo) ;
  11253                    auto WindowLeve l = calcul ateAutoWin dowLevel(d icominfo,  minMaxPixe l);
  11254                    wind owCenter =  autoWindo wLevel.wc;
  11255                    wind owWidth =  autoWindow Level.ww;
  11256                }
  11257  
  11258                image.wi ndowWidth  = windowWi dth;
  11259                image.wi ndowCenter  = windowC enter;
  11260                image.br ightness =  brightnes s;
  11261                image.co ntrast = c ontrast;
  11262                image.la stAppliedW indowWidth  = windowW idth;
  11263                image.la stAppliedw indowCente r = window Center;
  11264                image.la stAppliedB rightness  = brightne ss;
  11265                image.la stAppliedC ontrast =  contrast;
  11266                image.pr esentation .setWindow ingdata(wi ndowCenter , windowWi dth);
  11267                image.pr esentation .setWindow Level(dico minfo, min MaxPixel,  invert);
  11268                image.pr esentation .setWindow LevelLimit s(windowLe velLimits) ;
  11269                image.pr esentation .setBright nessContra st(brightn ess, contr ast);
  11270           }
  11271           ca tch(e)
  11272           {  }
  11273       }
  11274  
  11275       /**
  11276        * 
  11277        * @pa ram {Type}  image - S pecifies t he image
  11278        * @pa ram {Type}  overlayIn dex - Spec ifies the  overlay in dex
  11279        */ 
  11280       functi on update6 000Overlay (image, ov erlayIndex , seriesIn dex) {
  11281           tr y
  11282           {
  11283                var dico minfo = im age.dicomi nfo;
  11284                if(!dico minfo) {
  11285                    retu rn;
  11286                }
  11287  
  11288                var imag eInfo = di cominfo.im ageInfo;
  11289                if(!imag eInfo) {
  11290                    retu rn;
  11291                }
  11292  
  11293                var over lays = ima geInfo.ove rlays;
  11294                if(!over lays) {
  11295                    retu rn;
  11296                }
  11297  
  11298                if(overl ayIndex <  0 || overl ayIndex >  overlays.l ength - 1)  {
  11299                    retu rn;
  11300                }
  11301  
  11302                var over lay = over lays[overl ayIndex];
  11303                if(!over lay) {
  11304                    retu rn;
  11305                }
  11306  
  11307                if(!imag e.overlay6 000) {
  11308                    imag e.overlay6 000 = {};
  11309                }
  11310  
  11311                // Check  whether t he 6000 ov erlay data  is alread y processe
  11312                if(image .overlay60 00.overlay Data !== u ndefined)  {
  11313                    retu rn;
  11314                }
  11315  
  11316                // 6000  Overlay ca nvas 
  11317                image.ov erlay6000. column = o verlay.col umns;
  11318                image.ov erlay6000. row = over lay.rows;
  11319                image.ov erlay6000. descriptio n = overla y.descript ion;
  11320                image.ov erlay6000. label = ov erlay.labe l;
  11321                image.ov erlay6000. overlayDat a = undefi ned;
  11322  
  11323                // Updat e the rend er size
  11324                image.re nderSizeIn Bytes += ( overlay.co lumns * ov erlay.rows  * (overla y.bitDepth  / 8));
  11325  
  11326                // Proce ss 6000 ov erlay imag e data
  11327                if (type of(Worker)  !== "unde fined") {
  11328                    var  workerJob  = {
  11329                         image : im age,
  11330                         seriesInde x : series Index,
  11331                         bitsAlloca ted: overl ay.bitDept h,
  11332                         url : dico mViewer.ur l.get6000o verlayUrl( image.imag eUid, imag e.frameNum ber, overl ayIndex),
  11333                         type : "ca che",
  11334                         request :  "overlay60 00",
  11335                         isProcessi ng : false ,
  11336                         id : "over lay6000_"  + image.im ageUid,
  11337                    };
  11338                    doWo rkerQueue( workerJob) ;
  11339                }
  11340           }
  11341           ca tch(e)
  11342           {
  11343                dumpCons oleLogs(LL _ERROR, un defined, " update6000 Overlay ",  e.message );
  11344           }
  11345       }
  11346  
  11347       /**
  11348        * Ref resh the 6 000 overla y
  11349        * @pa ram {Type}  image - s pecifies t he image 
  11350        */ 
  11351       functi on refresh 6000Overla y(image) {
  11352           tr y
  11353           {
  11354                var allV iewports =  dicomView er.viewpor ts.getAllV iewports() ;
  11355                if(allVi ewports == = null ||  allViewpor ts === und efined) {
  11356                    retu rn undefin ed;
  11357                }
  11358  
  11359                $.each(a llViewport s, functio n(key, val ue) {
  11360                    if(v alue.study Uid) {
  11361                         $("#" + va lue.series LayoutId +  " div").e ach(functi on () {
  11362                             var im ageLevelId  = $(this) .attr('id' );
  11363                             var im ageRender  = value.ge tImageRend er(imageLe velId);
  11364                             if (im ageRender)  {
  11365                                 if (imageRend er.imageUi d === imag e.imageUid  && image. is6000Over lay) {
  11366                                      image.is 6000Overla y = false;
  11367                                      imageRen der.render Image(fals e);
  11368                                 }
  11369                             }
  11370                         });
  11371                    }
  11372                });
  11373           }
  11374           ca tch(e)
  11375           {  }
  11376       }
  11377  
  11378       functi on getImag eRequestHe aders(stud yUid, seri esIndex, i mageUid) {
  11379           va r headers  = [];
  11380           he aders["fil epath"] =  dicomViewe r.Series.I mage.getIm ageFilePat h(studyUid , seriesIn dex, image Uid);
  11381           re turn heade rs;
  11382       }
  11383  
  11384       // mod ule export s
  11385       dicomV iewer.requ estImage =  requestIm age;
  11386       dicomV iewer.getI mage = get Image;
  11387       dicomV iewer.upda teImage =  updateImag e;
  11388       dicomV iewer.proc essDicomIm age = proc essDicomIm age;
  11389       dicomV iewer.getI magePromis e = getIma gePromise;
  11390       dicomV iewer.refr esh6000Ove rlay = ref resh6000Ov erlay;
  11391  
  11392       return  dicomView er;
  11393   }(dicomVie wer));/*
  11394    * Mouse T ools Manag er
  11395    */
  11396  
  11397   var dicomV iewer = (f unction(di comViewer) {
  11398           
  11399           if (dicomView er === und efined)
  11400           {
  11401                    dico mViewer =  {};
  11402           }
  11403           
  11404           va r mouseToo ls = {
  11405                    pan  : new Pan( ),
  11406                    zoom  : new Zoo mTool(),
  11407                    wind owLevel :  new Window Level(),
  11408                    line Measure: n ew LineMea surement() ,
  11409                    trac eMeasure:  new TraceM easurement (),
  11410                    volu meMeasure:  new Volum eMeasureme nt(),
  11411                    poin tMeasure:  new PointM easurement (),
  11412           mi tralMeanGr adientMeas ure: new M itralMeanG radientMea surement() ,
  11413           an gleMeasure : new Angl eMeasureme ntTool(),
  11414           el lipseMeasu re: new El lipseMeasu rement(),
  11415           re ctangleMea sure: new  RectangleM easurement (),
  11416           de faultTool:  new Defau ltTool(),
  11417           wi ndowLevelR OI : new W indowLevel ROI(),
  11418           xR efLineSele ctionTool:  new XRefL ineSelecti onTool(),
  11419           li nk: new Li nkTool(),
  11420           sh arpen: new  SharpenTo ol(),
  11421           pe n: new Pen Tool(),
  11422           br ightness:  new Bright ness(),
  11423           co pyAttribut es: new Co pyAttribut es()
  11424           };
  11425           
  11426       var ac tiveTool =  mouseTool s.windowLe vel;
  11427  
  11428       var pr eviousTool  = undefin ed;
  11429  
  11430       var pr eviousCurs or = "defa ult";
  11431  
  11432       var to olName = " WindowLeve l";
  11433  
  11434       functi on getActi veTool() {
  11435           re turn activ eTool;
  11436       }
  11437  
  11438       functi on setActi veTool(too l) {
  11439           if (tool ===  undefined)  {
  11440                throw "a ctive tool  is null/u ndefined";
  11441           }
  11442           ac tiveTool =  tool;
  11443       }
  11444  
  11445       /**
  11446        * Set  the curre nt image t ool as bac kup(previo us)
  11447        * @pa ram {Type}  tool - cu rrent tool
  11448        */
  11449       functi on setPrev iousTool(t ool) {
  11450           if (tool ===  undefined)  {
  11451                throw "p revious to ol is null /undefined ";
  11452           }
  11453           pr eviousTool  = tool;
  11454       }
  11455  
  11456       /**
  11457        * Ret urn the pr eviously s elected to ol
  11458        */
  11459       functi on getPrev iousTool()  {
  11460           re turn previ ousTool;
  11461       }
  11462  
  11463       /**
  11464        * Set  the curre nt cursor  value as b ackup(prev ious)
  11465        * @pa ram {Type}  cursor -  current cu rsor
  11466        */
  11467       functi on setCurs or(cursor)  {
  11468           pr eviousCurs or = curso r;
  11469       }
  11470  
  11471       /**
  11472        * Get  the curso r value
  11473        * @pa ram {Type}  active(1/ undefined)
  11474        * 1 - > return t he current  cursor va lue; undef ined -> re turn the p revious cu rsor value
  11475        */
  11476       functi on getTool Cursor(act ive) {
  11477           if (active) {
  11478                return $ ("#viewpor t_View")[0 ].style.cu rsor;
  11479           }  else {
  11480                return p reviousCur sor;
  11481           }
  11482       }
  11483  
  11484           fu nction get WindowTool ()
  11485           {
  11486                    tool Name = TOO LNAME_WIND OWLEVEL;
  11487                    retu rn mouseTo ols.window Level;
  11488           }
  11489           
  11490       functi on getDefa ultTool()
  11491           {
  11492                    tool Name = TOO LNAME_DEFA ULTTOOL;
  11493                    retu rn mouseTo ols.defaul tTool;
  11494           }
  11495       
  11496           fu nction get PanTool()
  11497           {
  11498                    tool Name = TOO LNAME_PAN;
  11499                    retu rn mouseTo ols.pan;
  11500           }
  11501           
  11502           fu nction get ZoomTool()
  11503           {
  11504                    tool Name = TOO LNAME_ZOOM ;
  11505                    retu rn mouseTo ols.zoom;
  11506           }
  11507           
  11508           fu nction get LinkTool()
  11509           {
  11510                    tool Name = TOO LNAME_LINK ;
  11511                    retu rn mouseTo ols.link;
  11512           }
  11513  
  11514           fu nction get 2DLengthMe asureTool( typeId,mea surementSu btype)
  11515           {
  11516           if  (typeId = = 1) {
  11517                $('#view port_View' ).css('cur sor','url( images/mit rallength. cur), auto ');
  11518           }  else if (t ypeId == 2 ) {
  11519                $('#view port_View' ).css('cur sor','url( images/aor ticlength. cur), auto ');
  11520           }  else if (t ypeId == 3 ) {
  11521                $('#view port_View' ).css('cur sor','url( images/mit ralthickne ss.cur), a uto');
  11522           }  else if(ty peId == 4) {
  11523                $('#view port_View' ).css('cur sor','url( images/ann otateline. cur), auto ');
  11524           }  else if(ty peId == 5) {
  11525                $('#view port_View' ).css('cur sor','url( images/ann otatearrow .cur), aut o');
  11526           }  else {
  11527                $('#view port_View' ).css('cur sor','url( images/mea surelength .cur), aut o');
  11528           }
  11529                    tool Name = "li neMeasurem ent";
  11530           if (measureme ntSubtype  != undefin ed && meas urementSub type != nu ll){
  11531                mouseToo ls.lineMea sure.measu rementData .measureme ntSubType  = measurem entSubtype ;
  11532           }
  11533                    retu rn mouseTo ols.lineMe asure;
  11534           }
  11535           
  11536           fu nction get 2DLengthCa librationT ool()
  11537           {
  11538                    $('# viewport_V iew').css( 'cursor',' url(images /calibrate .cur), aut o');
  11539                    tool Name = "li neMeasurem ent";
  11540                    retu rn mouseTo ols.lineMe asure;
  11541           }
  11542           
  11543           fu nction get 2DPointMea sureTool(t ypeId,meas urementSub type) {
  11544           if  (typeId = = 1) {
  11545                $('#view port_View' ).css('cur sor','url( images/mit ralvelocit y.cur), au to');
  11546           }  else if (t ypeId == 2 ) {
  11547                $('#view port_View' ).css('cur sor','url( images/aor ticregurgi tationvelo city.cur),  auto');
  11548           }  else if (t ypeId == 3 ) {
  11549                $('#view port_View' ).css('cur sor','url( images/aor ticstenosi svelocity. cur), auto ');
  11550           }  else {
  11551                $('#view port_View' ).css('cur sor','url( images/pro be.cur), a uto');
  11552           }
  11553                toolName  = "pointM easurement ";
  11554           if (measureme ntSubtype  != undefin ed && meas urementSub type != nu ll){
  11555                mouseToo ls.pointMe asure.meas urementDat a.measurem entSubType  = measure mentSubtyp e;
  11556           }
  11557                return m ouseTools. pointMeasu re;
  11558           }
  11559           fu nction get TraceMeasu reTool()
  11560           {
  11561           $( '#viewport _View').cs s('cursor' ,'url(imag es/trace.c ur), auto' );
  11562                    tool Name = "tr aceMeasure ment";
  11563                    retu rn mouseTo ols.traceM easure;
  11564           }
  11565           fu nction get VolumeMeas ureTool()
  11566           {
  11567           $( '#viewport _View').cs s('cursor' ,'url(imag es/volume. cur), auto ');
  11568                    tool Name = "vo lumeMeasur ement";
  11569                    retu rn mouseTo ols.volume Measure;
  11570           }
  11571       functi on getMitr alMeanGrad ientMeasur eTool(type Id,measure mentSubtyp e)
  11572           {
  11573           if (typeId ==  1) {
  11574                $('#view port_View' ).css('cur sor','url( images/ann otatefreeh and.cur),  auto');
  11575           }  else {
  11576                $('#view port_View' ).css('cur sor','url( images/mit ralgradien t.cur), au to');
  11577           }
  11578                    tool Name = "mi tralMeanGr adientMeas urement";
  11579           if (measureme ntSubtype  != undefin ed && meas urementSub type != nu ll){
  11580                mouseToo ls.mitralM eanGradien tMeasure.m easurement Data.measu rementSubT ype = meas urementSub type;
  11581           }
  11582                    retu rn mouseTo ols.mitral MeanGradie ntMeasure;
  11583           }
  11584           fu nction get AngleMeasu reTool()
  11585           {
  11586           $( '#viewport _View').cs s('cursor' ,'url(imag es/angle.c ur), auto' );
  11587                    tool Name = "an gleMeasure ment";
  11588                    retu rn mouseTo ols.angleM easure;
  11589           }
  11590       functi on getElli pseMeasure Tool(typeI d,measurem entSubtype )
  11591           {
  11592           if (typeId ==  1) {
  11593                $('#view port_View' ).css('cur sor','url( images/ann otateellip se.cur), a uto');
  11594           }  else {
  11595               $('#viewp ort_View') .css('curs or','url(i mages/elli pse.cur),  auto');
  11596           }
  11597                    tool Name = "el lipseMeasu rement";
  11598           if (measureme ntSubtype  != undefin ed && meas urementSub type != nu ll){
  11599                mouseToo ls.ellipse Measure.me asurementD ata.measur ementSubTy pe = measu rementSubt ype;
  11600           }
  11601                    retu rn mouseTo ols.ellips eMeasure;
  11602           }
  11603       functi on getRect angleMeasu reTool(typ eId,measur ementSubty pe)
  11604       {
  11605           if (typeId ==  1) {
  11606                $('#view port_View' ).css('cur sor','url( images/ann otaterecta ngle.cur),  auto');
  11607           }  else if(ty peId == 2) {
  11608                $('#view port_View' ).css('cur sor','url( images/ann otatetext. cur), auto ');
  11609           }  else {
  11610                $('#view port_View' ).css('cur sor','url( images/rec tangle.cur ), auto');
  11611           }
  11612           to olName = " rectangleM easurement ";
  11613           if (measureme ntSubtype  != undefin ed && meas urementSub type != nu ll){
  11614                mouseToo ls.rectang leMeasure. measuremen tData.meas urementSub Type = mea surementSu btype;
  11615           }
  11616           re turn mouse Tools.rect angleMeasu re;
  11617       }
  11618           fu nction get ToolName()
  11619           {
  11620                    retu rn toolNam e;
  11621           }
  11622  
  11623           fu nction set ToolName(t ool)
  11624           {
  11625                    tool Name = too l;
  11626           }
  11627           
  11628       functi on getWind owToolROI( ) {
  11629           $( '#viewport _View').cs s('cursor' ,'url(imag es/AutoWin dowLevel.c ur), auto' );
  11630           to olName = T OOLNAME_WI NDOWLEVEL_ ROI;
  11631           re turn mouse Tools.wind owLevelROI ;
  11632       }
  11633  
  11634       functi on getXRef LineSelect ionTool()  {
  11635           $( '#viewport _View').cs s('cursor' ,'url(imag es/XReflin e.cur), au to');
  11636           to olName = T OOLNAME_XR EFLINESELE CTIONTOOL;
  11637           re turn mouse Tools.xRef LineSelect ionTool;
  11638       }
  11639       
  11640       functi on getShar penTool()  {
  11641           $( '#viewport _View').cs s('cursor' ,'url(imag es/sharpen .cur), aut o');
  11642           to olName = T OOLNAME_SH ARPENTOOL;
  11643           re turn mouse Tools.shar pen;
  11644       }
  11645  
  11646       /**
  11647        * 
  11648        * get  the pento ol cursor  details
  11649        */ 
  11650       functi on getPenT ool() {
  11651           $( '#viewport _View').cs s('cursor' ,'url(imag es/pen.cur ), auto');
  11652           to olName = T OOLNAME_PE N;
  11653           re turn mouse Tools.pen;
  11654       }
  11655  
  11656       /**
  11657        * 
  11658        * get  the brigh tness curs or details
  11659        */ 
  11660       functi on getBrig htnessCont rastTool()  {
  11661           to olName = T OOLNAME_WI NDOWLEVEL;
  11662           re turn mouse Tools.brig htness;
  11663       }
  11664  
  11665       /**
  11666        * 
  11667        * Get  the Copy  Attributes
  11668        */ 
  11669       functi on getCopy Attributes Tool() {
  11670           $( '#viewport _View').cs s('cursor' ,'url(imag es/copyAtt ribute.cur ), auto');
  11671           to olName = T OOLNAME_CO PYATTRIBUT ES;
  11672           re turn mouse Tools.copy Attributes ;
  11673       }
  11674  
  11675       dicomV iewer.mous eTools = {
  11676                getActiv eTool : ge tActiveToo l,
  11677                setActiv eTool : se tActiveToo l,
  11678                getPrevi ousTool :  getPreviou sTool,
  11679                setPrevi ousTool :  setPreviou sTool,
  11680                getToolC ursor : ge tToolCurso r,
  11681                setCurso r : setCur sor,
  11682                getWindo wTool : ge tWindowToo l,
  11683                getPanTo ol : getPa nTool,
  11684                getZoomT ool : getZ oomTool,
  11685                get2DLen gthMeasure Tool: get2 DLengthMea sureTool,
  11686                get2DPoi ntMeasureT ool: get2D PointMeasu reTool,
  11687                getTrace MeasureToo l : getTra ceMeasureT ool,
  11688                getVolum eMeasureTo ol : getVo lumeMeasur eTool,
  11689                getToolN ame : getT oolName,
  11690                getMitra lMeanGradi entMeasure Tool: getM itralMeanG radientMea sureTool,
  11691                getAngle MeasureToo l: getAngl eMeasureTo ol,
  11692                get2DLen gthCalibra tionTool :  get2DLeng thCalibrat ionTool,
  11693                getEllip seMeasureT ool: getEl lipseMeasu reTool,
  11694                getRecta ngleMeasur eTool: get RectangleM easureTool ,
  11695                getDefau ltTool: ge tDefaultTo ol,
  11696                getWindo wToolROI :  getWindow ToolROI,
  11697                getXRefL ineSelecti onTool: ge tXRefLineS electionTo ol,
  11698                getLinkT ool : getL inkTool,
  11699                setToolN ame : setT oolName,
  11700                getSharp enTool : g etSharpenT ool,
  11701                getPenTo ol : getPe nTool,
  11702                getBrigh tnessContr astTool: g etBrightne ssContrast Tool,
  11703                getCopyA ttributesT ool: getCo pyAttribut esTool
  11704       };
  11705  
  11706   return dic omViewer;
  11707  
  11708   }(dicomVie wer));/**
  11709    * 
  11710    */
  11711   var dicomV iewer = (f unction (d icomViewer ) {
  11712  
  11713       "use s trict";
  11714  
  11715       if(dic omViewer = == undefin ed) {
  11716           di comViewer  = {};
  11717       }
  11718  
  11719       var ov erlayConfi g = null;
  11720  
  11721       var me asurements Config = n ull;
  11722  
  11723       var it emIdCounte r = 100;
  11724  
  11725   function i nitOverlay Config()
  11726   {
  11727           va r url = di comViewer. url.getOve rlayTextUR L();  
  11728           va r req = ne w XMLHttpR equest();
  11729           re q.open('GE T', url, f alse);
  11730           re q.send(nul l);
  11731           if  (req.stat us != 200) throwExcep tion(_exce ption.File LoadFailed );
  11732           {
  11733                    over layConfig  = JSON.par se(req.res ponseText) ;
  11734           }
  11735   }
  11736       
  11737   function g etOverLayV aluesForCo fig(config ,imageinfo )
  11738   {
  11739       var va lueArray =  [];
  11740       
  11741       for(va r key in c onfig)
  11742       {
  11743           sw itch(confi g[key])
  11744           {
  11745                case 'Pa tient_Name ':
  11746                valueArr ay[valueAr ray.length ] = imagei nfo.getPat ientName() ;
  11747                break;
  11748                    
  11749                case 'St udy_Date_T ime':
  11750                valueArr ay[valueAr ray.length ] = imagei nfo.getStu dyDate() +  ' ' + ima geinfo.get StudyTime( );
  11751                break;
  11752                
  11753                case 'Ac cession_Nu mber':
  11754                valueArr ay[valueAr ray.length ] = imagei nfo.getAcc essionNumb er();
  11755                break;
  11756                
  11757                case 'Ma nufacturer ':
  11758                valueArr ay[valueAr ray.length ] = imagei nfo.getMan ufacturer( );
  11759                break;
  11760                    
  11761                case 'Im ageNumber' :
  11762                valueArr ay[valueAr ray.length ] = imagei nfo.getIns tanceNumbe r();
  11763                break;
  11764                
  11765                case 'WC WW':
  11766                valueArr ay[valueAr ray.length ] = 'WCWW' ;
  11767                break;
  11768                
  11769                case 'Sc ale':
  11770                valueArr ay[valueAr ray.length ] = 'Scale ';
  11771                break;
  11772  
  11773                case 'Br ightness':
  11774                valueArr ay[valueAr ray.length ] = 'Brigh tness';
  11775                break;
  11776  
  11777                case 'Co ntrast':
  11778                valueArr ay[valueAr ray.length ] = 'Contr ast';
  11779                break;
  11780  
  11781                case 'Co ntent_Date _Time':
  11782                if(image info.getMo dality() = = "ES") {
  11783                    valu eArray[val ueArray.le ngth] = "C ontent Dat e Time: "  + getForma ttedDateTi me(imagein fo);
  11784                }
  11785                break;
  11786           }
  11787       }
  11788       return  valueArra y;
  11789   }
  11790  
  11791   function g etOverlayC onfig()
  11792   {
  11793           re turn overl ayConfig;
  11794   }
  11795  
  11796   function g etMeasurem entsConfig () {
  11797       return  measureme ntsConfig;
  11798   }
  11799  
  11800   function c reateMeasu rementMenu Item(item)  {
  11801       var li  = $("<li  />")
  11802       li.app end($("<in put type=\ "radio\" o nclick=\"d icomViewer .tools.do2 DMeasureme nt(" + ite m.type + " ,'" + item .id + "',' " + item.u nits + "') \" " +
  11803                  "id=\" measuremen t" + itemI dCounter +  "\" " +
  11804                  "name= \"measurem ent\" valu e=\"" + it emIdCounte r + "\" /> "));
  11805       li.app end($("<la bel for=\" measuremen t" + itemI dCounter +  "\">" + i tem.label  + "</label >"));
  11806       itemId Counter++;
  11807       return  li;
  11808   }
  11809  
  11810   function c reateMeasu rementMenu (name) {
  11811                    var  id = "cont ext-"+ nam e.replace( " ","");
  11812       var me nu = $("<l i class=\" dropdown-s ubmenu\">< a href=\"# \" id = "+ id+" oncli ck=\"\">"  + name + " </a>" + 
  11813                   "<ul  id=\"" + i temIdCount er + "\" c lass=\"dro pdown-menu  dropdown- menu-custo m\" role=\ "menu\" st yle=\"back ground-col or: #999;\ " ></ul></ li>");
  11814       itemId Counter++;
  11815       return  menu;
  11816   }
  11817  
  11818   function a ppendMeasu rements(pa rent, data ) {
  11819  
  11820       if (da ta.items ! = null) {
  11821           va r menu = c reateMeasu rementMenu (data.labe l);
  11822           va r parentMe nu = menu. find("ul") ;
  11823           $. each(data. items, fun ction (ind ex, item)  {
  11824                appendMe asurements (parentMen u, item);
  11825           })
  11826         //   menu.appen dTo(parent );
  11827       } else  {
  11828           va r item = c reateMeasu rementMenu Item(data) ;
  11829           it em.appendT o(parent);
  11830       }
  11831   }
  11832  
  11833   function i nitMeasure mentsConfi g() {
  11834  
  11835       var me asurements  = getMeas urements() ;
  11836       if ((m easurement s == undef ined) || ( measuremen ts == null ) || (meas urements.l ength == 0 ))
  11837           re turn;
  11838  
  11839       $.each (measureme nts, funct ion (index , item) {
  11840           ap pendMeasur ements($(" #contextMe nu"), item );
  11841       })
  11842   }
  11843  
  11844   /**
  11845    * Fortmat  the conte nt date ti me format
  11846    * @param  {Type} ima geinfo 
  11847    */ 
  11848   function g etFormatte dDateTime( imageinfo)  {
  11849       try
  11850       {
  11851           if (isReforma tContentDa teTime) {
  11852                var date  = imagein fo.getCont entDate();
  11853                var time  = imagein fo.getCont entTime();
  11854                if(date)  {
  11855                    var  year = dat e.substr(2 , 2);
  11856                    var  month = da te.substr( 4, 2);
  11857                    var  day = date .substr(6,  2);
  11858                    date  = month +  "-" + day  + "-" + y ear;
  11859                }
  11860                if(time) {
  11861                    var  xx = time. substr(0,  2);
  11862                    var  yy = time. substr(2,  2);
  11863                    var  zz = time. substr(4,  2);
  11864                    time  = xx + ": " + yy + " :" + zz;
  11865                }
  11866                return d ate + ' @  ' + time;
  11867           }  else {
  11868                return i mageinfo.g etContentD ate() + '  @ ' + imag einfo.getC ontentTime ();
  11869           }
  11870       }
  11871       catch( e)
  11872       { }
  11873       
  11874       return  "";
  11875   }
  11876       
  11877   dicomViewe r.overlay  = {
  11878       initOv erlayConfi g: initOve rlayConfig ,
  11879       initMe asurements Config: in itMeasurem entsConfig ,
  11880       getOve rlayConfig :getOverla yConfig,
  11881       getOve rLayValues ForCofig:  getOverLay ValuesForC ofig,
  11882       getMea surementsC onfig:getM easurement sConfig,
  11883   }
  11884  
  11885  
  11886  
  11887   return dic omViewer;
  11888   }(dicomVie wer));/**
  11889    * This mo dule cache  and handl e the secu rity token
  11890    */
  11891  
  11892   var dicomV iewer = (f unction(di comViewer)  {
  11893  
  11894       "use s trict";
  11895  
  11896       if (di comViewer  === undefi ned) {
  11897           di comViewer  = {};
  11898       }
  11899  
  11900       var se curityToke n = null;
  11901  
  11902       /**
  11903        *@par am token
  11904        *set  the securi ty token f rom the ur l to secur ityToken
  11905        */
  11906       functi on setSecu rityToken( token) {
  11907           se curityToke n = token;
  11908       }
  11909  
  11910       /**
  11911        *Get  the securi ty token f rom the se curityToke n variable
  11912        */
  11913       functi on getSecu rityToken( ) {
  11914           re turn secur ityToken;
  11915       }
  11916  
  11917       dicomV iewer.secu rity = {
  11918           se tSecurityT oken: setS ecurityTok en,
  11919           ge tSecurityT oken: getS ecurityTok en
  11920       }
  11921  
  11922       return  dicomView er;
  11923   }(dicomVie wer));var  dicomViewe r = (funct ion (dicom Viewer) {
  11924  
  11925       "use s trict";
  11926  
  11927       if (di comViewer  === undefi ned) {
  11928           di comViewer  = {};
  11929       }
  11930  
  11931       var st udyDetails Holder = { };
  11932       var li stOfStudyU id = [];
  11933       var re OrderedStu dyUidList  = [];
  11934           
  11935           /* *
  11936        *@par am studyDe atils
  11937        *set  the study  details to  the study DetailsHol der variab le
  11938        */
  11939       functi on setStud yDetails(s tudyDeatil s) {
  11940           if  (studyDea tils === u ndefined)  {
  11941                throw "S tduyDeatil s is undef ined";
  11942           }
  11943           va r studyUid  = studyDe atils.stud yUid;
  11944                    stud yDetailsHo lder[study Uid] = stu dyDeatils;
  11945           li stOfStudyU id[listOfS tudyUid.le ngth] = st udyUid;
  11946           ad dOrRemoveR eOrderedSt udyUid(stu dyUid, tru e);
  11947       }
  11948  
  11949       /**
  11950        *Get  the study  detail fro m the stud yDetailsHo lder varia ble
  11951        */
  11952       functi on getStud yDetails(s tudyUid) {
  11953           re turn study DetailsHol der[studyU id];
  11954       }
  11955  
  11956       /**
  11957        *Get  the study  id from th e study de tail
  11958        */
  11959       functi on getStud yId() {
  11960           re turn study DetailsHol der.studyI d;
  11961       }
  11962           
  11963           /* *
  11964        *Get  the study  id from th e study de tail
  11965        */
  11966       functi on getStud yUid() {
  11967           re turn study DetailsHol der.studyU id;
  11968       }
  11969  
  11970       /**
  11971        *@par am seriesI ndex
  11972        *Get  the series  object ba sed on the  series in dex
  11973        */
  11974       functi on getSeri es(studyUi d, seriesI ndex, imag eIndex) {
  11975           if  (seriesIn dex === un defined) {
  11976                throw "S eries Inde x is null/ undefined" ;
  11977           }
  11978  
  11979           va r study =  studyDetai lsHolder[s tudyUid];
  11980           if (study) {
  11981                if(image Index !==  undefined  && study.i sGeneral & & study[0] .imageType  == IMAGET YPE_JPEG & & study[se riesIndex] .numberOfF rames > 1)  {
  11982                    retu rn study[i mageIndex] ;
  11983                } else i f(study.se ries !== u ndefined)  {
  11984                    var  series = s tudy.serie s[seriesIn dex];
  11985                    if(! series &&  study.hasM utiframeIm ages) {
  11986                         series = s tudy.serie s[0];
  11987                    }
  11988  
  11989                    retu rn series;
  11990                } else {
  11991                    retu rn study[s eriesIndex ];
  11992                }
  11993           }
  11994  
  11995           re turn undef ined;
  11996       }
  11997  
  11998       /**
  11999        *Get  the series  count fro m the stud y detail
  12000        */
  12001       functi on getSeri esCount(st udyUid) {
  12002           re turn getSt udyDetails (studyUid) .seriesCou nt;
  12003       }
  12004  
  12005       /**
  12006        *@par am seriesI ndex
  12007        *get  the image  count base d on the s eries inde x
  12008        */
  12009       functi on getImag eCount(stu dyUid,seri esIndex) {
  12010           va r series;
  12011           tr y {
  12012                series =  getSeries (studyUid, seriesInde x);
  12013           }  catch(e) {
  12014                series =  undefined ;
  12015                }
  12016           if ( series ! == undefin ed)
  12017                return s eries.imag eCount;
  12018           el se
  12019                return 0 ;
  12020       }
  12021  
  12022       /**
  12023        *@par am seriesI ndex
  12024        *@par am imageIn dex
  12025        *Get  the image  based on t he series  index and  image inde x
  12026        */
  12027       functi on getImag e(studyUid ,seriesInd ex, imageI ndex) {
  12028  
  12029           if  (imageInd ex === und efined) {
  12030                throw "I mage Index  is null/u ndefined"
  12031           }
  12032           if (getSeries (studyUid, seriesInde x) !== und efined)             
  12033                if(getSe ries(study Uid,series Index).ima ges !== un defined){
  12034                    retu rn getSeri es(studyUi d,seriesIn dex).image s[imageInd ex];
  12035                }else{
  12036                    retu rn getSeri es(studyUi d,seriesIn dex, image Index);
  12037                }
  12038           el se
  12039                return u ndefined;
  12040       }
  12041       /**
  12042        *@par am seriesI ndex
  12043        *@par am imageIn dex
  12044        *Get  all images  of the pa rticular s eries
  12045        */
  12046       functi on getAllI mages(stud yUid, seri esIndex) {
  12047  
  12048           if  (seriesIn dex === un defined) {
  12049                throw "S eries Inde x is null/ undefined"
  12050           }
  12051  
  12052           re turn getSe ries(study Uid, serie sIndex).im ages;
  12053       }
  12054           
  12055           /* function g etSerieInd ex(studyUi d, imageId )
  12056       {
  12057           va r series =  getSeries Count(stud yUid);
  12058           fo r (var key  in series .images)
  12059           {
  12060                if( seri es.images[ key].image Id == imag eId)
  12061                {
  12062                    retu rn key
  12063                }
  12064           }
  12065           
  12066           re turn -1;
  12067       }
  12068   */
  12069           fu nction get ImageIndex (studyUid, seriesInde x, imageUi d)
  12070       {
  12071           va r series =  getSeries (studyUid,  seriesInd ex);
  12072  
  12073            i f(!series) {
  12074                return - 1;
  12075           }
  12076  
  12077           //  Get the n on dicom i mage index  
  12078           if (isDicomSt udy(studyU id) === fa lse && ser ies !== un defined &&  series != = null) {
  12079                if(serie s.imageCou nt == 1) {
  12080                    retu rn 0;
  12081                }
  12082           }
  12083  
  12084           fo r (var key  in series .images)
  12085           {
  12086                if( seri es.images[ key].image Uid == ima geUid)
  12087                {
  12088                    retu rn key
  12089                }
  12090           }
  12091           
  12092           re turn -1;
  12093       }
  12094           
  12095       /**
  12096        *@par am image
  12097        *Get  image id b ased on th e image
  12098        */
  12099       functi on getImag eId(image)  {
  12100           if  (image == = undefine d) {
  12101                throw "i mage is nu ll/undefin ed"
  12102           }
  12103  
  12104           re turn image .imageId;
  12105       }
  12106  
  12107       /**
  12108        *@par am image
  12109        *Get  the frame  count base d on the i mage
  12110        */
  12111       functi on getImag eFrameCoun t(image) {
  12112           if  (image == = undefine d) {
  12113                throw "i mage is nu ll/undefin ed";
  12114           }
  12115           if  (image.nu mberOfFram es !== und efined) {
  12116                if (imag e.numberOf Frames ===  0) {
  12117                    imag e.numberOf Frames +=  1;
  12118                }
  12119                return i mage.numbe rOfFrames;
  12120           }
  12121  
  12122           //  Checking  image info  already c ached or n ot
  12123           va r header =  dicomView er.header. getDicomHe ader(dicom Viewer.Ser ies.Image. getImageUi d(image));
  12124           if  (header = == undefin ed) {
  12125                return u ndefined;
  12126           }
  12127           im age.number OfFrames =  header.ge tNumberOfF rames();
  12128  
  12129  
  12130           if  (image.nu mberOfFram es === und efined) {
  12131                image.nu mberOfFram es = 1;
  12132           }
  12133  
  12134           re turn image .numberOfF rames;
  12135       }
  12136  
  12137       /**
  12138        *@par am seriesI ndex
  12139        *Get  the modali ty based o n the seri es index
  12140        */
  12141       functi on getModa lity(study Uid,series Index) {
  12142           if  (seriesIn dex === un defined) {
  12143                throw "s eriesIndex  is null/u ndefined"
  12144           }
  12145           va r series =  getSeries (studyUid, seriesInde x);
  12146           if (series ==  undefined  )
  12147           {
  12148                return " ";
  12149           }
  12150           re turn serie s.modality ;
  12151       }
  12152  
  12153       functi on getSeri esDescript ion(studyU id, series Index){
  12154           if (studyUid  === undefi ned) retur n "";
  12155           va r series =  getSeries (studyUid, seriesInde x)
  12156           if (series == = undefine d || serie s == null)  {
  12157                return " ";
  12158           }
  12159  
  12160           re turn serie s.descript ion;
  12161       }
  12162       
  12163       /**
  12164        *@par am image
  12165        *get  the instan ce number  based on t he image
  12166        */
  12167       functi on getInst anceNumber (image) {
  12168           if  (image == = undefine d) {
  12169                throw "i mage is nu ll/undefin ed"
  12170           }
  12171           if  (image.in stanceNumb er !== und efined) {
  12172                return i mage.insta nceNumber;
  12173           }
  12174           //  Checking  image info  already c ached or n ot
  12175           va r header =  dicomView er.header. getDicomHe ader(dicom Viewer.Ser ies.Image. getImageUi d(image));
  12176           if  (header = == undefin ed) {
  12177                return u ndefined;
  12178           }
  12179           im age.instan ceNumber =  header.ge tInstanceN umber();
  12180  
  12181           re turn image .instanceN umber;
  12182       }
  12183           
  12184              /**
  12185        *@par am image
  12186        *Get  image id b ased on th e image
  12187        */
  12188       functi on getImag eUid(image ) {
  12189           if  (image == = undefine d) {
  12190                throw "i mage is nu ll/undefin ed"
  12191           }
  12192  
  12193           re turn image .imageUid;
  12194       }
  12195       
  12196       functi on getList OfStudyUid (isResize) {
  12197           if (reOrdered StudyUidLi st !== und efined &&  reOrderedS tudyUidLis t !== null ) {
  12198                if(reOrd eredStudyU idList.len gth > 0 &&  (reOrdere dStudyUidL ist.length  == listOf StudyUid.l ength || i sResize))  {
  12199                    retu rn reOrder edStudyUid List;
  12200                }
  12201           }
  12202  
  12203           re turn listO fStudyUid;
  12204       }
  12205       
  12206       functi on removeS tudyDetail s(studyUid ){
  12207           de lete study DetailsHol der[studyU id];
  12208           va r listOfst udyLength  = listOfSt udyUid.len gth;
  12209           fo r(var inde x = 0;list OfstudyLen gth>index; index++)
  12210           {
  12211                var stud yUidInList  = listOfS tudyUid[in dex]
  12212                if(study Uid === st udyUidInLi st){
  12213                   listO fStudyUid. splice(ind ex,1);
  12214                    addO rRemoveReO rderedStud yUid(study Uid, false );
  12215                    dico mViewer.im ageCache.c learCache( studyUid);
  12216                }
  12217           }
  12218       }
  12219       
  12220       functi on isImage Avilable(s tudyUid, s electedIma geUid){
  12221           if (studyUid  !== undefi ned)
  12222           {
  12223                var seri esCount =  getSeriesC ount(study Uid)
  12224                for(var  index = 0;  seriesCou nt>index;i ndex++){
  12225                    var  allImages  = getAllIm ages(study Uid, index );
  12226                    for( var imageI ndex in al lImages)
  12227                    {
  12228                         var image  = allImage s[imageInd ex];
  12229                         var imageU id = getIm ageUid(ima ge);
  12230                         if(selecte dImageUid  === imageU id)
  12231                         {
  12232                             return  true;
  12233                         }
  12234                    }
  12235                }
  12236           }
  12237           re turn false ;
  12238       }
  12239  
  12240       /**
  12241        * Che ck whether  the given  study is  dicom or n ot
  12242        * @pa ram {Type}  studyUid  - Specifie s the Stud y Uid
  12243        */ 
  12244       functi on isDicom Study(stud yUid) {
  12245           va r isDicom  = false;
  12246           va r studyDet ails = get StudyDetai ls(studyUi d);
  12247           if (studyDeta ils !== un defined) {
  12248                isDicom  = studyDet ails.isDic om;
  12249           }
  12250  
  12251           re turn isDic om;
  12252       }
  12253  
  12254       /**
  12255        * Che ck whether  the given  series is  dicom or  not
  12256        * @pa ram {Type}  studyUid  - Specifie s the Stud y Uid
  12257        * @pa ram {Type}  seriesInd ex - Speci fies the s eries inde x
  12258        */ 
  12259      functio n isDicomS eries(stud yUid, seri esIndex) {
  12260           va r isDicom  = false;
  12261           va r series =  getSeries (studyUid,  seriesInd ex);
  12262           if (series != = undefine d) {
  12263                isDicom  = series.i sDicom;
  12264           }
  12265  
  12266           re turn isDic om;
  12267       }
  12268  
  12269       /**
  12270        * Set  the reord er studyUi ds
  12271        * @pa ram {Type}  reOrdered StudyUids  - Specifie s the reor der studyU ids
  12272        * @pa ram {Type}  isClear -  Flag to c lear the l ist
  12273        */ 
  12274       functi on setReOr deredStudy Uids(reOrd eredStudyU ids, isCle ar) {
  12275           tr y
  12276           {
  12277                if(isCle ar) {
  12278                    reOr deredStudy UidList =  [];
  12279                } else {
  12280                    reOr deredStudy UidList =  reOrderedS tudyUids;
  12281                }
  12282           }
  12283           ca tch(e)
  12284           {  }
  12285       }
  12286  
  12287       /**
  12288        * Add  or remove  the study Uid from t he reorder  list
  12289        * It  will call  while addi ng study w ith an exi sting sess ion or clo se the rev ewport 
  12290        * @pa ram {Type}  studyUid  - Specifie s the stud yUid
  12291        * @pa ram {Type}  isAdd - F lag to add /remove th e studyUid  from arra y
  12292        */ 
  12293       functi on addOrRe moveReOrde redStudyUi d(studyUid , isAdd) {
  12294           tr y
  12295           {
  12296                var inde x = reOrde redStudyUi dList.inde xOf(studyU id);
  12297                if(isAdd  && reOrde redStudyUi dList.leng th > 0 &&  index == - 1) {
  12298                    reOr deredStudy UidList.pu sh(studyUi d);
  12299                } else i f(!isAdd & & index >  -1) {
  12300                    reOr deredStudy UidList.sp lice(index ,1);
  12301                }
  12302           }
  12303           ca tch(e)
  12304           {  }
  12305       }
  12306  
  12307        /**
  12308        * Res et the stu dy details
  12309        */ 
  12310       functi on resetSt udy() {
  12311           re OrderedStu dyUidList  = [];
  12312           li stOfStudyU id = [];
  12313       }
  12314  
  12315       /**
  12316        * Get  the image  Urn
  12317        * @pa ram {Type}  studyUid  - Specifie s the stud y Uid
  12318        * @pa ram {Type}  seriesInd ex - Speci fies the s eries inde x
  12319        * @pa ram {Type}  imageInde x - Specif ies the im age index
  12320        */ 
  12321       functi on getImag eUrn(study Uid, serie sIndex, im ageIndex)  {
  12322           va r image =  getImage(s tudyUid,se riesIndex,  imageInde x);
  12323           if (image) {
  12324                return i mage.image Urn;
  12325           }
  12326  
  12327           re turn undef ined;
  12328       }
  12329  
  12330       functi on getImag eFilePath( studyUid,  seriesInde x, imageUi d) {
  12331           va r series =  getSeries (studyUid,  seriesInd ex);
  12332           if (!series){
  12333                return - 1;
  12334           }
  12335  
  12336           fo r (var key  in series .images) {
  12337                if(serie s.images[k ey].imageU id == imag eUid) {
  12338                    retu rn (!serie s.images.f ilePath) ?  "" : seri es.images. filePath;
  12339                }
  12340           }
  12341  
  12342           re turn -1;
  12343       }
  12344  
  12345       dicomV iewer.setS tudyDetail s = setStu dyDetails;
  12346       dicomV iewer.getS tudyDetail s = getStu dyDetails;
  12347       dicomV iewer.getL istOfStudy Uid = getL istOfStudy Uid;
  12348       dicomV iewer.remo veStudyDet ails = rem oveStudyDe tails;
  12349       dicomV iewer.isIm ageAvilabl e = isImag eAvilable;
  12350       dicomV iewer.isDi comStudy =  isDicomSt udy;
  12351       dicomV iewer.isDi comSeries  = isDicomS eries;
  12352       dicomV iewer.setR eOrderedSt udyUids =  setReOrder edStudyUid s;
  12353       dicomV iewer.rese tStudy = r esetStudy;
  12354       dicomV iewer.Stud y = {
  12355           ge tSeriesCou nt: getSer iesCount,
  12356           ge tStudyId:  getStudyId ,
  12357                getStudy Uid : getS tudyUid
  12358       };
  12359       dicomV iewer.Seri es = {
  12360           ge tSeries: g etSeries,
  12361           ge tImageCoun t: getImag eCount,
  12362           ge tAllImages : getAllIm ages,
  12363           Im age: {
  12364                getImage Index : ge tImageInde x,
  12365                getImage : getImage ,
  12366                             getIma geUid: get ImageUid,
  12367                getImage Id: getIma geId,
  12368                getImage FrameCount : getImage FrameCount ,
  12369                getInsta nceNumber:  getInstan ceNumber,
  12370                getImage Urn : getI mageUrn,
  12371                getImage FilePath :  getImageF ilePath
  12372           },
  12373           ge tModality:  getModali ty,
  12374           ge tSeriesDes cription:g etSeriesDe scription
  12375       };
  12376       
  12377       return  dicomView er;
  12378   }(dicomVie wer));/**
  12379    * Thumbna il creator
  12380    */
  12381   var dicomV iewer = (f unction(di comViewer)  {
  12382  
  12383       "use s trict";
  12384  
  12385       if (di comViewer  === undefi ned) {
  12386           di comViewer  = {};
  12387       }
  12388       var th umbnailPro cessing =  [];
  12389       var th umbnails =  {};
  12390       var sh owCacheInd icatorOnTh umbnail =  false;
  12391       /**
  12392        *Crea te the thu mbnail bas ed on the  image leve l or serie s level
  12393        */
  12394       functi on createT humbnail(s tudyUid) {
  12395           cr eateOrAppe ndThumbnai l(studyUid , 0, true) ;
  12396       }
  12397       /**
  12398        *@par am image
  12399        *@par am modalit y
  12400        *Base d on the m odality it  ill retur n true(US, CR,ES,DX,X A) or fals e
  12401        */
  12402       functi on isImage Thumbnail( image, che ckOnModali ty) {
  12403           if (image !==  undefined  && image  !== null)  {
  12404                if(image .numberOfF rames !==  undefined  && image.n umberOfFra mes !== nu ll) {
  12405                    if(i mage.numbe rOfFrames  > 1) {
  12406                         return tru e;
  12407                    } el se {
  12408                         if (image. modality = == "US" ||
  12409                             image. modality = == "CR" ||
  12410                             image. modality = == "ES" ||
  12411                             image. modality = == "DX" ||
  12412                             image. modality = == "XA" ||
  12413                             image. modality = == "ECG" | |
  12414                             image. modality = == "XC" ||
  12415                             image. modality = == "OP" ||
  12416                             image. modality = == "SC") {
  12417                             return  true;
  12418                         }
  12419                    }
  12420                } else {
  12421                    if ( image.moda lity === " US" ||
  12422                         image.moda lity === " CR" ||
  12423                         image.moda lity === " ES" ||
  12424                         image.moda lity === " DX" ||
  12425                         image.moda lity === " XA" ||
  12426                         image.moda lity === " ECG" ||
  12427                         image.moda lity === " XC" ||
  12428                         image.moda lity === " OP" ||
  12429                         image.moda lity === " SC") {
  12430                         return tru e;
  12431                    }
  12432                }
  12433           }
  12434  
  12435           re turn false ;
  12436       }
  12437  
  12438       /**
  12439        * Che ck whether  the cine  can run or  not
  12440        * @pa ram {Type}  image 
  12441        */ 
  12442       functi on canRunC ine(image)  {
  12443           if (image !==  undefined  && image  !== null)  {
  12444                if(image .numberOfF rames !==  undefined  && image.n umberOfFra mes !== nu ll) {
  12445                    if(i mage.numbe rOfFrames  > 1) {
  12446                         return tru e;
  12447                    }
  12448                }
  12449           }
  12450  
  12451           re turn false ;
  12452       }
  12453  
  12454       /**
  12455        *@par am image
  12456        *@par am modalit y
  12457        *Base d on the m odality it  ill retur n true(US, CR,DR,DX,X A) or fals e
  12458        */
  12459       functi on isSerie sContainsM ultiframe( studyUid,s eriesIndex ) {
  12460           va r numberOf Images = d icomViewer .Series.ge tImageCoun t(studyUid , seriesIn dex);
  12461           fo r(var imag eIndex = 0 ; imageInd ex < numbe rOfImages;  imageInde x++)
  12462           {
  12463                var imag e = dicomV iewer.Seri es.Image.g etImage(st udyUid, se riesIndex,  imageInde x);
  12464                if(isIma geThumbnai l(image,fa lse)) retu rn true;
  12465           }
  12466           re turn false ;
  12467       }
  12468       /**
  12469        *@par am seriesI ndex
  12470        *@par am numberO fimages
  12471        *@par am imageTh umbDiv
  12472        *Usin g the seri esIndex, n umberOfima ges, image ThumbDiv c reate the  image thum bnails
  12473        */
  12474       functi on createI mageThumba il(studyUi d, seriesI ndex, numb erOfimages , imageThu mbDiv, isK eyImageSer ies, tmpSe riesIndex)  {
  12475           fo r (var i =  0; i < nu mberOfimag es; i++) {
  12476                var appe ndThumb =  "_thumb";
  12477                if (isKe yImageSeri es) {
  12478                    appe ndThumb =  "_keythumb ";
  12479                }
  12480                var thum bnailId =  'imageview er_' + dic omViewer.r eplaceDotV alue(study Uid) + "_"  + seriesI ndex + app endThumb +  i;
  12481                var thum bnailStrin g = '<div  id="' + th umbnailId  + '" style ="clear:ri ght; width :auto;back ground:bla ck;margin- right: 5px ; margin-b ottom: 5px ; " class= "default-t humbnail-v iew col-xs -12" oncli ck="loadIm age(event) "></div>';
  12482                if (isKe yImageSeri es) {
  12483                    var  keyThumb =  $("#keyim ageThumbna il_View"). find("#thu mb_" + ima geThumbDiv );
  12484                    keyT humb.appen d(thumbnai lString);
  12485                } else {
  12486                    $("# thumb_" +  imageThumb Div).appen d(thumbnai lString);
  12487                }
  12488                var imag e = dicomV iewer.Seri es.Image.g etImage(st udyUid, se riesIndex,  i);
  12489                var imag eUid = dic omViewer.S eries.Imag e.getImage Uid(image) ;
  12490                var thum b = new Th umbnailRen derer();
  12491                thumb.cr eateImageT humbnail(s tudyUid, i mageUid, t humbnailId , isKeyIma geSeries ?  tmpSeries Index : se riesIndex,  i + 1);
  12492                thumb.se tStudyUid( studyUid);
  12493                addThumb nails(thum bnailId, t humb);
  12494  
  12495                if(thumb nailWidth  == undefin ed ) {
  12496                    thum bnailWidth  = documen t.getEleme ntById(thu mbnailId). offsetWidt h;
  12497                }
  12498           }
  12499       }
  12500       /**
  12501        *@par am selecte dSeriesInd ex
  12502        *Base d on the t humbnail d iv id sele ct the thu mbnail(dis play green  border to  thumbnail )
  12503        */
  12504       functi on selectT humbnail(s electedSer iesIndex)  {
  12505           re moveSelcte dThumbnail ();
  12506           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  12507           va r series =  dicomView er.Series. getSeries( seriesLayo ut.studyUi d, selecte dSeriesInd ex, 0);
  12508           va r appendTh umb = "_th umb";
  12509           if  (series.i skeyImageS eries) {
  12510                selected SeriesInde x = series .seriesInd ex;
  12511                appendTh umb = "_ke ythumb";
  12512           }
  12513           va r thumbnai lId = "#im ageviewer_ " + dicomV iewer.repl aceDotValu e(seriesLa yout.study Uid) + "_"  + selecte dSeriesInd ex + appen dThumb;
  12514           if  (!$(thumb nailId).ha sClass('se lected-thu mbnail-vie w')) {
  12515                $(thumbn ailId).rem oveClass(
  12516                    'def ault-thumb nail-view' ).addClass ('selected -thumbnail -view');
  12517                makeThum bnailVisib le(thumbna ilId);
  12518           }
  12519       }
  12520  
  12521       /**
  12522        *@par am alertTh umbnailSel ection
  12523        *Base d on the t humbnail d iv id diss elect the  thumbnail( display re d border t o thumbnai l)
  12524        */
  12525       functi on alertTh umbnailSel ection(thu mbnailId)  {
  12526           re moveSelcte dThumbnail ();
  12527           if  (!$("#"+t humbnailId ).hasClass ('alert-th umbnail-vi ew')) {
  12528                $("#"+th umbnailId) .removeCla ss(
  12529                'default -thumbnail -view').ad dClass('al ert-thumbn ail-view') ;
  12530           }
  12531       }
  12532  
  12533       /**
  12534        *@par am thumbna ilId
  12535        *@par am thumbna il
  12536        *Uing  the thumb nail div i d as key s toring the  thumbnail  render ob ject as va lue in the  thumbnail s
  12537        */
  12538       functi on addThum bnails(thu mbnailId,  thumbnail)  {
  12539           if  (thumbnai lId === un defined) {
  12540                throw "t humbnailId  should no t be null/ undefined" ;
  12541           }
  12542           if  (thumbnai l === unde fined) {
  12543                throw "t humbnail s hould not  be null/un defined";
  12544           }
  12545           th umbnails[t humbnailId ] = thumbn ail;
  12546       }
  12547       /**
  12548        *@par am selecte dSeriesInd ex
  12549        *@par am imageIn dex
  12550        *Base d on the t humbnail d iv id sele ct the thu mbnail(dis play green  border to  thumbnail ) for imag e level th umbnails
  12551        */
  12552       functi on selectI mageThumbn ail(select edSeriesIn dex, image Index) {
  12553           va r sereiesL ayout = di comViewer. getActiveS eriesLayou t();
  12554           va r studyUid  = sereies Layout.stu dyUid;
  12555           re moveSelcte dThumbnail ();
  12556           va r series =  dicomView er.Series. getSeries( sereiesLay out.studyU id, select edSeriesIn dex, 0);
  12557           va r appendTh umb = "_th umb";
  12558           if  (series.i skeyImageS eries) {
  12559                selected SeriesInde x = series .seriesInd ex;
  12560                appendTh umb = "_ke ythumb";
  12561           }
  12562           va r thumbnai lId = "ima geviewer_"  + dicomVi ewer.repla ceDotValue (studyUid)  + "_" + ( selectedSe riesIndex)  + appendT humb;
  12563           if  (!$(thumb nailId).ha sClass('se lected-thu mbnail-vie w')) {
  12564                var elem ent = docu ment.getEl ementById( thumbnailI d);
  12565                if (elem ent == nul l || eleme nt == unde fined) {
  12566                    thum bnailId =  "imageview er_" + dic omViewer.r eplaceDotV alue(study Uid) + "_"  + (select edSeriesIn dex) + app endThumb +  (imageInd ex);
  12567                }
  12568  
  12569                $("#" +  thumbnailI d).removeC lass(
  12570                    'def ault-thumb nail-view' ).addClass ('selected -thumbnail -view');
  12571  
  12572                makeThum bnailVisib le(thumbna ilId);
  12573           }
  12574       }
  12575       /**
  12576        *@par am thumbna ilId
  12577        *Get  the thumbn ail render  boject ba sed on the  thumnail  id
  12578        */
  12579       functi on getThum bnail(thum bnailId) {
  12580           if  (thumbnai lId === un defined) {
  12581                throw "t humbnailId  should no t be null/ undefined" ;
  12582           }
  12583           re turn thumb nails[thum bnailId];
  12584       }
  12585       
  12586        /**
  12587        *Get  the thumbn ails rende r boject
  12588        */
  12589       functi on getAllT humbnails( ) {
  12590           re turn thumb nails;
  12591       }
  12592  
  12593       functi on removeS elctedThum bnail() {
  12594           $( ".selected -thumbnail -view").re moveClass( 'selected- thumbnail- view')
  12595                .addClas s('default -thumbnail -view');
  12596           $( ".alert-th umbnail-vi ew").remov eClass('al ert-thumbn ail-view')
  12597                .addClas s('default -thumbnail -view');
  12598       }
  12599  
  12600       /**
  12601        * Cal culate the  currently  selected  thumbnail  position w hether the  whole thu mbnail is  visible to  the user.
  12602        * Aut o scroll t he thumbna il if the  thumbnail  is not ful ly visible  to the us er.
  12603        */
  12604       functi on makeThu mbnailVisi ble(elemen tId) {
  12605           
  12606           if  (elementI d.indexOf( "_keythumb ") > -1) {
  12607                $('.nav- tabs a[hre f="#keyima geThumbnai l_View"]') .tab('show ');
  12608           }  else {
  12609                $('.nav- tabs a[hre f="#imageT humbnail_V iew"]').ta b('show');
  12610           }
  12611           
  12612           se tTimeout(f unction(){  adjustThu mbnailScro ll(element Id); }, 30 0);
  12613       }
  12614  
  12615       functi on adjustT humbnailSc roll(eleme ntId) {
  12616           va r element  = document .getElemen tById(elem entId);
  12617           if  (element  === null)  {
  12618                dumpCons oleLogs(LL _WARN, und efined, "a djustThumb nailScroll ", "Thumbn ails eleme nt not fou nd with id : " + elem entId);
  12619                return;
  12620           }
  12621  
  12622           //  Get the s crollbar h eight and  calculate  the bottom
  12623           va r docViewT op = $(win dow).scrol lTop();
  12624           va r docViewB ottom = do cViewTop +  $(window) .height();
  12625  
  12626           //  Get the s elected th umbnail an d get heig ht and cal culate the  bottom
  12627           va r elementT op = $(ele ment).offs et().top;
  12628           va r elementB ottom = el ementTop +  $(element ).height() ;
  12629  
  12630           //  Check whe ther the s elected th umbnail is  aligned i n fully vi sible area .
  12631           va r isFullyV isible = ( docViewTop  <= elemen tTop) && ( docViewBot tom >= ele mentBottom );
  12632  
  12633           //  If the th umbnail is  fully vis ible then  we do not  need to sc roll the v iew. So si mply retur n if it is  true.
  12634           if  (isFullyV isible) {
  12635                return;
  12636           }
  12637  
  12638           //  Get the a lign orien tation. If  the thumb nail is al igned near  to top th en the scr oll will b e fit with  topside.
  12639           //  Otherwise  will choo se to alig n at botto m of the s crollbar.
  12640           va r isTopAli gn = (docV iewTop - e lementTop)  > (elemen tBottom -  docViewBot tom);
  12641           el ement.scro llIntoView (isTopAlig n);
  12642       }
  12643  
  12644       functi on replace DotValue(v alue) {
  12645           re turn value .replace(/ \./g, '');
  12646       }
  12647  
  12648       /**
  12649        * Rep lace all t he special  character s
  12650        * @pa ram {Type}  value - S pecifies t he input
  12651        */ 
  12652       functi on replace SpecialsVa lues(value ) {
  12653           re turn value .replace(/ [^A-Za-z0- 9]/g, '');
  12654       }
  12655  
  12656       functi on resizeT humbnailPa nel() {
  12657           // To resize  the thumbn ail panel  based the  scrool pan el
  12658           va r imageThu mbnailView Element =  $("#imageT humbnail_V iew");
  12659           // height of  image thum bnail view
  12660           va r heightOf ImageThumb nail = ima geThumbnai lViewEleme nt.height( );
  12661           // first stud y level th umbnail 
  12662           va r studyThu mbnailElem ent = imag eThumbnail ViewElemen t.children ();
  12663           va r heightOf StudyThumb nails = 0;
  12664           st udyThumbna ilElement. each(funct ion() {
  12665                var elem entId = th is.id;
  12666                if (elem entId != " " && eleme ntId != un defined) {
  12667                    heig htOfStudyT humbnails  = heightOf StudyThumb nails + $( "#" + elem entId).out erHeight() ;
  12668                }
  12669           }) ;
  12670  
  12671           if  (heightOf StudyThumb nails < he ightOfImag eThumbnail ) {
  12672                myLayout  = $('body ').layout( {
  12673                    west __minSize:  (THUMBNAI L_PANEL_WI DTH - 10)
  12674                });
  12675                var widt hOfThumbna ilPanel =  $("#img"). outerWidth ();
  12676                myLayout .sizePane( "west", TH UMBNAIL_PA NEL_WIDTH  - 10);
  12677                if (widt hOfThumbna ilPanel !=  (THUMBNAI L_PANEL_WI DTH - 10))
  12678                    relo adViewPort ();
  12679           }  else {
  12680                myLayout .sizePane( "west", TH UMBNAIL_PA NEL_WIDTH) ;
  12681           }
  12682  
  12683       }
  12684  
  12685       /**
  12686        * set  the viewp ort series  index,fra me index,i mage index  to an arr ay
  12687        */ 
  12688       functi on setView portProper ty() {
  12689           th umbnailPro cessing= [ ];
  12690           va r pushValu es;
  12691           va r allViewp orts = dic omViewer.v iewports.g etAllViewp orts();
  12692           $. each(allVi ewports, f unction(ke y, value)  {
  12693                if(value .studyUid  !== undefi ned) {
  12694                    push Values = v alue.serie sLayoutId  + "|" + va lue.series Index + "| " +
  12695                                  v alue.scrol lData.imag eIndex + " |" + value .scrollDat a.frameInd ex + "|" +  
  12696                                  v alue.image LayoutDime nsion;
  12697                    thum bnailProce ssing.push (pushValue s);
  12698                }
  12699           }) ;
  12700       }
  12701  
  12702       /**
  12703        * ret urn the cu rrent view port prope rties
  12704        * @pa ram {Type}  seriesLay outId - sp ecifies th e viewport  id
  12705        */ 
  12706       functi on getView portProper ty(seriesL ayoutId) {
  12707           if (thumbnail Processing  != null | | thumbnai lProcessin g != undef ined) {
  12708                for(var  i=0;i<thum bnailProce ssing.leng th;i++) {
  12709                    if(t humbnailPr ocessing[i ].split("| ")[0] == s eriesLayou tId) {
  12710                         return thu mbnailProc essing[i];
  12711                    }
  12712                }
  12713           }
  12714           re turn null;
  12715       }
  12716  
  12717       /**
  12718        * Sho w or Hide  the entire  thumbnail  panel on  Double-Cli ck(hiding) /Click(sho wing)
  12719        */ 
  12720       functi on closeTh umbnailPan el() {
  12721           is CineEnable d(true);
  12722           va r obj = {
  12723                id: "stu dyViewer1x 1"
  12724           }
  12725           va r viewport Element =  $('#viewpo rt_View');
  12726           vi ewportElem ent.width( "100%");
  12727           vi ewportElem ent.height ("100%");
  12728  
  12729           va r seriesLa youtId = u ndefined;
  12730           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  12731           if (seriesLay out !== un defined) {
  12732                seriesLa youtId = s eriesLayou t.getSerie sLayoutId( );
  12733           }
  12734  
  12735           se tViewportP roperty();
  12736  
  12737           // Updating t he Cine ma nager with  the selec ted viewpo rt study i d on the b asis of th e Cine pla yer state
  12738           va r splitedR owAndColum n = studyL ayoutValue .split("x" );
  12739           va r studyRow  = splited RowAndColu mn[0];
  12740           va r studyCol umn = spli tedRowAndC olumn[1];
  12741           fo r (var i =  1; i <= s tudyRow; i ++) {
  12742                for (var  j = 1; j  <= studyCo lumn; j++)  {
  12743                    var  studyDiv =  "studyVie wer" + i +  "x" + j;
  12744                    var  rowCalValu e = layout Map[studyD iv];
  12745                    if ( rowCalValu e == undef ined) {
  12746                         rowCalValu e = "1x1";
  12747                    }
  12748                    var  rcArray =  rowCalValu e.split("x ");
  12749                    dico mViewer.to ols.chanag eWhileDrag (rcArray[0 ], rcArray [1], study Div,true);
  12750                }
  12751           }
  12752           
  12753           is CineEnable d(false);
  12754  
  12755           //  Maintain  the previo us selecti on
  12756           if (seriesLay outId !==  undefined)  {
  12757                dicomVie wer.change Selection( seriesLayo utId);
  12758           }
  12759       }
  12760  
  12761       /**
  12762        * Rem ove the th umbnail co ntext's 
  12763        */ 
  12764       functi on removeT humbnailCo ntext(stud yUid) {
  12765           tr y
  12766           {
  12767                var stud yDetials =  dicomView er.getStud yDetails(s tudyUid);
  12768                if(study Detials != = null &&  studyDetia ls !== und efined) {
  12769                    if(! studyDetia ls.isDicom ) {
  12770                         studyDetia ls.forEach (function( nonDicom)  {
  12771                             if(non Dicom !==  null && no nDicom !==  undefined ){
  12772                                 re moveContex tId(nonDic om.context Id);
  12773                             }
  12774                          });
  12775                    } el se {
  12776                         removeCont extId(stud yDetials.c ontextId);
  12777                    }
  12778                }
  12779           }
  12780           ca tch(e)
  12781           {  }
  12782       }
  12783  
  12784       /**
  12785        * Cre ate or app end the th umbanail
  12786        * @pa ram {Type}  studyUid  - Specifie s the stud y Uid
  12787        * @pa ram {Type}  seriesSta rtingIndex  - Specifi es the sta rting seri es index t o create t he thumbna ils.
  12788        * @pa ram {Type}  isNewThum bnailPanel  - Specifi es the fla g to creat e or appen d the thum bnail pane l.
  12789        */ 
  12790       functi on createO rAppendThu mbnail(stu dyUid, ser iesStartin gIndex, is NewThumbna ilPanel) {
  12791           tr y
  12792           {
  12793                var stud yThumbDivI d = "study _thumb_" +  replaceDo tValue(stu dyUid);
  12794                var stud yThumbnail Div = "<di v id=" + s tudyThumbD ivId + " s tyle='bord er: 3px so lid rgba(9 2, 93, 100 , 0.59);ba ckground:  rgba(152,  153, 158,  0.59);" +  "overflow- x: hidden; overflow-y : hidden;' /><br id=b reak_" + r eplaceDotV alue(study Uid) + ">" ;
  12795                var stud yDetials =  dicomView er.getStud yDetails(s tudyUid);
  12796                var stud yInfoDiv =  "";
  12797                var stud yTime = "" ;
  12798                if(study Detials.da teTime !==  null && s tudyDetial s.dateTime  !== undef ined) {
  12799                    stud yTime = st udyDetials .dateTime. replace("T ", "@")
  12800                }
  12801  
  12802                if (!stu dyDetials. isDicom) {
  12803                    stud yInfoDiv =  "<table s tyle='widt h:100%;'>"  + "<tr>"  + "<td>" +  "<div tit le='" + st udyDetials .procedure  + "'  id= 'studyInfo _" + study Uid + "' s tyle='colo r:white;pa dding-left :4px'>" +  studyDetia ls.procedu re + "<br> " + studyT ime + "<br >" + "</di v>" + "</t d>" + "<td  align='ri ght' style ='vertical -align: to p;'>" + "< span  titl e='close'  style='pad ding-botto m: 8px;' o nclick=dic omViewer.t humbnail.c loseThumbn ail('" + s tudyUid +  "')><img s rc='images /close.png ' style='w idth: 8px; '></img> < /span>" +  "</td>" +  "</tr>" +  "</table>"
  12804                } else {
  12805                    stud yInfoDiv =  "<table s tyle='widt h:100%;'>"  + "<tr>"  + "<td>" +  "<div tit le='" + st udyDetials .procedure  + "' id=' studyInfo_ " + studyU id + "' st yle='color :white;pad ding-left: 4px'>" + s tudyDetial s.procedur e + "<br>"  + studyDe tials.dico mStudyId +  "<br>" +  studyTime  + "</div>"  + "</td>"  + "<td al ign='right ' style='v ertical-al ign: top;' >" + "<spa n title='c lose' styl e='padding -bottom: 8 px;' oncli ck=dicomVi ewer.thumb nail.close Thumbnail( '" + study Uid + "')> <img src=' images/clo se.png' st yle='width : 8px;'></ img> </spa n>" + "</t d>" + "</t r>" + "</t able>"
  12806                }
  12807  
  12808                // Creat e the new  thumbnail  panel
  12809                isNewThu mbnailPane l = (isNew ThumbnailP anel === u ndefined ?  true : is NewThumbna ilPanel);
  12810                if(isNew ThumbnailP anel) {
  12811                    $("# imageThumb nail_View" ).append(s tudyThumbn ailDiv);
  12812                    $("# " + studyT humbDivId) .append(st udyInfoDiv );
  12813                    $("# " + studyT humbDivId) .append("< div id=thu mb_" + stu dyThumbDiv Id + " sty le='paddin g-top: 4px ;padding-l eft: 4px;' />");
  12814                    $("# " + studyT humbDivId) .clone().a ppendTo("# keyimageTh umbnail_Vi ew");
  12815                    $("# keyimageTh umbnail_Vi ew").appen d("<br id= break_" +  replaceDot Value(stud yUid) + "> ");
  12816                }
  12817  
  12818                // Creat e the thum bnails
  12819                var numb erOfSeries  = dicomVi ewer.Study .getSeries Count(stud yUid);
  12820                for (var  seriesInd ex = serie sStartingI ndex; seri esIndex <  numberOfSe ries; seri esIndex++)  {
  12821                    var  series = d icomViewer .Series.ge tSeries(st udyUid, se riesIndex,  0);
  12822                    var  tmpSeriesI ndex;
  12823                    if ( series.isk eyImageSer ies) {
  12824                         tmpSeriesI ndex = ser iesIndex;
  12825                         seriesInde x = series .seriesInd ex;
  12826                    }
  12827                    var  image = di comViewer. Series.Ima ge.getImag e(studyUid , seriesIn dex, 0);
  12828                    var  imageUid =  dicomView er.Series. Image.getI mageUid(im age);
  12829  
  12830                    // G enerate th e thumbnai l id
  12831                    var  appendThum bSuffix =  series.isk eyImageSer ies ? "_ke ythumb" :  "_thumb";
  12832                    var  thumbnailI d = 'image viewer_' +  replaceDo tValue(stu dyUid) + " _" + serie sIndex + a ppendThumb Suffix
  12833                    var  thumbnailS tring = '< div id="'  + thumbnai lId + '" s tyle="clea r:right; w idth:auto; background :black; ma rgin-right : 5px; mar gin-bottom : 5px; " o nclick="lo adImage(ev ent)" clas s="default -thumbnail -view col- xs-12"></d iv>';
  12834  
  12835                    if ( !isBlob(im age.imageT ype)) {
  12836                         var modali ty = dicom Viewer.Ser ies.getMod ality(stud yUid, seri esIndex);
  12837                         var number OfImage =  dicomViewe r.Series.g etImageCou nt(studyUi d, seriesI ndex)
  12838                         var isImag eThumbnail s = isSeri esContains Multiframe (studyUid,  seriesInd ex);
  12839                         if (isImag eThumbnail s) {
  12840                             create ImageThumb ail(studyU id, series Index, num berOfImage , studyThu mbDivId, s eries.iske yImageSeri es, tmpSer iesIndex);
  12841                         } else {
  12842                             if (se ries.iskey ImageSerie s) {
  12843                                var  keyThumb  = $("#keyi mageThumbn ail_View") .find("#th umb_" + st udyThumbDi vId);
  12844                                key Thumb.appe nd(thumbna ilString);
  12845                             } else  {
  12846                                 $( "#thumb_"  + studyThu mbDivId).a ppend(thum bnailStrin g);
  12847                             }
  12848                             var th umb = new  ThumbnailR enderer();
  12849                             thumb. setStudyUi d(studyUid );
  12850                             thumb. createThum bnail(stud yUid, imag eUid, thum bnailId, s eries.iske yImageSeri es ? tmpSe riesIndex  : seriesIn dex);
  12851                             addThu mbnails(th umbnailId,  thumb);
  12852                         }
  12853                    } el se {
  12854                         $("#thumb_ " + studyT humbDivId) .append(th umbnailStr ing);
  12855                         var thumb  = new Thum bnailRende rer();
  12856                         thumb.setS tudyUid(st udyUid);
  12857                         thumb.crea teThumbnai l(studyUid , imageUid , thumbnai lId, serie sIndex);
  12858                         addThumbna ils(thumbn ailId, thu mb);
  12859                    }
  12860                    if ( series.isk eyImageSer ies) {
  12861                         seriesInde x = tmpSer iesIndex;
  12862                    }
  12863                }
  12864           }
  12865           ca tch(e)
  12866           {  }
  12867       }
  12868  
  12869       //This  function  used to cl ose the sp ecific stu dy level t humbnails
  12870       functi on closeTh umbnail(st udyUid) {
  12871           va r numberOf Studies =  dicomViewe r.getListO fStudyUid( ).length;
  12872           va r repacedS tudyUid =  dicomViewe r.replaceD otValue(st udyUid);
  12873           $( "#study_th umb_" + re pacedStudy Uid).remov e();
  12874           $( "#break_"  + repacedS tudyUid).r emove();
  12875           di comViewer. viewports. deleteView portsByThu mbnail(rep acedStudyU id);
  12876  
  12877                // Remov e the cont ext from t he display  context
  12878                removeTh umbnailCon text(study Uid);
  12879  
  12880           di comViewer. removeStud yDetails(s tudyUid);
  12881  
  12882           if  (numberOf Studies ==  1) {
  12883                showOrCl earSession (false);
  12884           }  else if(nu mberOfStud ies > 1) {
  12885                adjustLa yout();
  12886           }
  12887       }
  12888  
  12889       functi on setShow CacheIndic atorOnThum bnail() {
  12890           if (showCache IndicatorO nThumbnail  === true)  showCache IndicatorO nThumbnail  = false;
  12891           el se showCac heIndicato rOnThumbna il = true;
  12892       }
  12893        funct ion isShow CacheIndic atorOnThum bnail() {
  12894           re turn showC acheIndica torOnThumb nail;
  12895       }
  12896       dicomV iewer.thum bnail = {
  12897           cr eateThumbn ail: creat eThumbnail ,
  12898           se lectThumbn ail: selec tThumbnail ,
  12899           al ertThumbna ilSelectio n: alertTh umbnailSel ection,
  12900           se lectImageT humbnail:  selectImag eThumbnail ,
  12901                    remo veSelctedT humbnail:  removeSelc tedThumbna il,
  12902           ge tThumbnail : getThumb nail,
  12903           ge tAllThumbn ails : get AllThumbna ils,
  12904           is ImageThumb nail: isIm ageThumbna il,
  12905           ma keThumbnai lVisible:  makeThumbn ailVisible ,
  12906           cl oseThumbna il: closeT humbnail,
  12907           cl oseThumbna ilPanel: c loseThumbn ailPanel,
  12908           se tShowCache IndicatorO nThumbnail  : setShow CacheIndic atorOnThum bnail,
  12909           is ShowCacheI ndicatorOn Thumbnail  : isShowCa cheIndicat orOnThumbn ail,
  12910           is SeriesCont ainsMultif rame : isS eriesConta insMultifr ame,
  12911           re moveThumbn ailContext  : removeT humbnailCo ntext,
  12912           cr eateOrAppe ndThumbnai l : create OrAppendTh umbnail,
  12913           ge tViewportP roperty :  getViewpor tProperty,
  12914           se tViewportP roperty :  setViewpor tProperty,
  12915           ca nRunCine   : canRunCi ne
  12916       };
  12917       dicomV iewer.resi zeThumbnai lPanel = r esizeThumb nailPanel;
  12918       dicomV iewer.repl aceDotValu e = replac eDotValue;
  12919       dicomV iewer.repl aceSpecial sValues =  replaceSpe cialsValue s;
  12920  
  12921       return  dicomView er;
  12922   }(dicomVie wer));var  dicomViewe r = (funct ion(dicomV iewer){
  12923           
  12924           if (dicomView er === und efined)
  12925           {
  12926                    dico mViewer =  {};
  12927           }
  12928       var is FirstTimeI mageLoad =  true;
  12929       var ov erlayVisib leStatus =  false;
  12930       var sc outLineVis ibleStatus  = true;
  12931       var is 6000Overla y = true;
  12932       var an notationAn dMeasureme ntVisibleS tatus = tr ue;
  12933       var re freshCineM anager = [ ];
  12934       var re freshCineM anagerFull Screen = [ ];
  12935           
  12936           va r flagFor2 dLengthCal ibration =  false;
  12937       var is LengthCali brating =  false;
  12938  
  12939       var is Menusrated ScaleVisib le = false ;
  12940           
  12941           fu nction get FlagFor2dL engthCalib ration(){
  12942                    retu rn flagFor 2dLengthCa libration;
  12943           }
  12944           
  12945           fu nction upd ateStudyLa youtSelect ion(value) {
  12946                    
  12947           }
  12948  
  12949       functi on updateW indowLevel Settings(p resetIndex ) {
  12950                    pres etIndex =  parseInt(p resetIndex );
  12951                     $(" #1").paren t().css("b ackground" ,"");
  12952                     $(" #2").paren t().css("b ackground" ,"");
  12953                     $(" #3").paren t().css("b ackground" ,"");
  12954                     $(" #4").paren t().css("b ackground" ,"");
  12955                     $(" #5").paren t().css("b ackground" ,"");
  12956                     $(" #6").paren t().css("b ackground" ,"");
  12957                     $(" #7").paren t().css("b ackground" ,"");
  12958                     $(" #1_ww_wcCo ntextMenu" ).css("bac kground"," ");
  12959                     $(" #2_ww_wcCo ntextMenu" ).css("bac kground"," ");
  12960                     $(" #3_ww_wcCo ntextMenu" ).css("bac kground"," ");
  12961                     $(" #4_ww_wcCo ntextMenu" ).css("bac kground"," ");
  12962                     $(" #5_ww_wcCo ntextMenu" ).css("bac kground"," ");
  12963                     $(" #6_ww_wcCo ntextMenu" ).css("bac kground"," ");
  12964                     $(" #7_ww_wcCo ntextMenu" ).css("bac kground"," ");
  12965                     
  12966                     swi tch(preset Index) {
  12967                case 1:
  12968                                       $("#"+p resetIndex ).parent() .css("back ground","# 868696");
  12969                                       $("#"+p resetIndex +"_ww_wcCo ntextMenu" ).css("bac kground"," #868696");
  12970                break;
  12971                case 2:
  12972                                       $("#"+p resetIndex ).parent() .css("back ground","# 868696");
  12973                                       $("#"+p resetIndex +"_ww_wcCo ntextMenu" ).css("bac kground"," #868696");
  12974                break;
  12975                case 3:
  12976                                       $("#"+p resetIndex ).parent() .css("back ground","# 868696");
  12977                                       $("#"+p resetIndex +"_ww_wcCo ntextMenu" ).css("bac kground"," #868696");
  12978                break;
  12979                case 4:
  12980                                       $("#"+p resetIndex ).parent() .css("back ground","# 868696");
  12981                                       $("#"+p resetIndex +"_ww_wcCo ntextMenu" ).css("bac kground"," #868696");
  12982                break;
  12983                case 5:
  12984                                       $("#"+p resetIndex ).parent() .css("back ground","# 868696");
  12985                                       $("#"+p resetIndex +"_ww_wcCo ntextMenu" ).css("bac kground"," #868696");
  12986                break;
  12987                case 6:
  12988                                       $("#"+p resetIndex ).parent() .css("back ground","# 868696");
  12989                                       $("#"+p resetIndex +"_ww_wcCo ntextMenu" ).css("bac kground"," #868696");
  12990                break;
  12991                             case 7 :
  12992                                       $("#"+p resetIndex ).parent() .css("back ground","# 868696");
  12993                                       $("#"+p resetIndex +"_ww_wcCo ntextMenu" ).css("bac kground"," #868696");
  12994                break;
  12995                             
  12996                default:
  12997                                       $("#1") .parent(). css("backg round","") ;
  12998                                       $("#2") .parent(). css("backg round","") ;
  12999                                       $("#3") .parent(). css("backg round","") ;
  13000                                       $("#4") .parent(). css("backg round","") ;
  13001                                       $("#5") .parent(). css("backg round","") ;
  13002                                       $("#6") .parent(). css("backg round","") ;
  13003                                       $("#7") .parent(). css("backg round","") ;
  13004                break;
  13005           }
  13006                    
  13007                var seri esLayout =  dicomView er.getActi veSeriesLa yout();
  13008           se riesLayout .preferenc eInfo.setW indowLevel Settings(p resetIndex );
  13009       }
  13010       
  13011       /**
  13012        * Cha nge the ba ckground c olor for t he selecte d zoom men u (i.e mak ing it sel ected)
  13013        * @pa ram {Type}  id - id o f the zoom  type elem ent  
  13014        */ 
  13015       functi on updateZ oomLevelSe ttings(id)  {
  13016           re setZoomToo l();
  13017           va r zoomType  = parseIn t(id.split ("_")[0]);
  13018           // whether it  is custom  zoom or n ot (-1 mea ns custom)
  13019           if (zoomType  !== -1) {
  13020                $("#"+id +"ContextM enu").css( "backgroun d","#86869 6");
  13021                $("#"+id ).parent() .css("back ground","# 868696");
  13022           }  else {
  13023                id = "6_ zoom";
  13024                $("#"+id +"ContextM enu").css( "backgroun d","#86869 6");
  13025                $("#"+id ).parent() .css("back ground","# 868696");
  13026           }
  13027       }
  13028       
  13029  
  13030       functi on isOverl ayVisible( ) {
  13031           re turn overl ayVisibleS tatus; 
  13032       }
  13033  
  13034        funct ion isScou tLineVisib le() {
  13035           re turn scout LineVisibl eStatus; 
  13036       }
  13037  
  13038           fu nction cha ngePreset(  presetInd ex )
  13039           {
  13040                    var  seriesLayo ut = dicom Viewer.get ActiveSeri esLayout() ;
  13041           up dateWindow LevelSetti ngs(preset Index);
  13042           $( "#" + seri esLayout.g etSeriesLa youtId() +  " div").e ach(functi on(){
  13043                                      var imag eLayoutId  = $(this). attr('id') ;
  13044                                      var imag eRender =  seriesLayo ut.getImag eRender(im ageLayoutI d);
  13045                                      if(image Render)
  13046                                               imageRende r.applyPre set(preset Index);
  13047                             });
  13048           }
  13049           
  13050           fu nction inv ert()
  13051           {
  13052           va r cineRunn ing = fals e;
  13053                    var  seriesLayo ut = dicom Viewer.get ActiveSeri esLayout() ;
  13054           if (dicomView er.scroll. isCineRunn ing(series Layout.get SeriesLayo utId())) c ineRunning  = true;
  13055           if (cineRunni ng) stopCi neImage(un defined)
  13056                    $("# " + series Layout.get SeriesLayo utId() + "  div").eac h(function (){
  13057                             var im ageLayoutI d = $(this ).attr('id ');
  13058                
  13059                             var im ageRender  = seriesLa yout.getIm ageRender( imageLayou tId);
  13060                             if(ima geRender){
  13061                    dump ConsoleLog s(LL_DEBUG , undefine d, "invert ", "Applyi ng invert  to Image L ayout id :  " + image LayoutId);
  13062                                      imageRen der.invert ();
  13063                }
  13064                    });
  13065           if (cineRunni ng)
  13066           {
  13067                dicomVie wer.startC ine();
  13068                updatePl ayIcon("pl ay.png","s top.png");
  13069           }
  13070           }
  13071           
  13072           fu nction rot ate()
  13073           {
  13074                    var  seriesLayo ut = dicom Viewer.get ActiveSeri esLayout() ;
  13075           if (isEmbedPd fViewer(se riesLayout .imageType )) {
  13076                dicomVie wer.rotate ();
  13077                return;
  13078           }
  13079  
  13080                    $("# " + series Layout.get SeriesLayo utId() + "  div").eac h(function (){
  13081                             var im ageLayoutI d = $(this ).attr('id ');
  13082                             var im ageRender  = seriesLa yout.getIm ageRender( imageLayou tId);
  13083                             if(ima geRender)
  13084                                      imageRen der.rotate (90);
  13085                    });
  13086           }
  13087           
  13088           fu nction rev ert()
  13089           {
  13090                    var  seriesLayo ut = dicom Viewer.get ActiveSeri esLayout() ;
  13091  
  13092           if (isEmbedPd fViewer(se riesLayout .imageType )) {
  13093                dicomVie wer.revert ();
  13094           }  else if(se riesLayout .imageType  == IMAGET YPE_RADECG ){
  13095                if($("#3 x41Value") [0]) {
  13096                    $("# 3x41Value" )[0].isRev ert = true ;
  13097                }
  13098                dicomVie wer.Refres h();
  13099           }  else {
  13100                //dicomV iewer.seti mageCanvas OfViewPort (seriesLay out.getSer iesLayoutI d());
  13101                seriesLa yout.setFr ameIndex(0 );
  13102                $("#" +  seriesLayo ut.getSeri esLayoutId () + " div ").each(fu nction(){
  13103                    var  imageLayou tId = $(th is).attr(' id');
  13104                    var  imageRende r = series Layout.get ImageRende r(imageLay outId);
  13105                    if(i mageRender  !== undef ined){
  13106                         imageRende r.revert(i mageRender .getCurren tUIDs(), i mageRender .getSeries Index());
  13107                         imageRende r.getPrese ntation(). sharpen =  0;
  13108                    }
  13109                });
  13110                changePr eset("1");
  13111                setZoomL evel(1);
  13112           }
  13113           Re vertRGBToo l();
  13114           }
  13115  
  13116       /**
  13117        * Rev erting the  RGBTool
  13118        */ 
  13119       functi on RevertR GBTool()
  13120       {
  13121           va r isColor  = isColorI mage();
  13122           if (isColor = == true) {
  13123                rgbColor (0);
  13124           }
  13125       }
  13126  
  13127           fu nction doO verLay() {
  13128           ov erlayVisib leStatus =  !overlayV isibleStat us;
  13129           va r allViewp orts = dic omViewer.v iewports.g etAllViewp orts();
  13130           fo r (var key  in allVie wports) {
  13131                var view portTemp =  allViewpo rts[key];
  13132                $("#" +  viewportTe mp.getSeri esLayoutId () + " div ").each(fu nction() {
  13133                    var  imageLayou tId = $(th is).attr(' id');
  13134                    var  imageRende r = viewpo rtTemp.get ImageRende r(imageLay outId);
  13135                    if(i mageRender ) {
  13136                         imageRende r.showOrHi deOverlay( overlayVis ibleStatus );
  13137                    }
  13138                });
  13139           }
  13140           }
  13141  
  13142       /**
  13143        * Ena ble disabl e the scou t line dep ends on th e menu sel ection
  13144        */ 
  13145       functi on doScout Line() {
  13146           sc outLineVis ibleStatus  = !scoutL ineVisible Status;
  13147           va r allViewp orts = dic omViewer.v iewports.g etAllViewp orts();
  13148           va r activevi ewport = d icomViewer .getActive SeriesLayo ut();
  13149  
  13150           if (!activevi ewport) {
  13151                return;
  13152           }
  13153  
  13154           fo r (var key  in allVie wports) {
  13155                var view portTemp =  allViewpo rts[key];
  13156                viewport Temp.refre shViewport s(activevi ewport);
  13157           }
  13158       }
  13159  
  13160       functi on setOver lay(overla yVisible)  {
  13161           ov erlayVisib leStatus =  overlayVi sible;
  13162       }
  13163           
  13164           fu nction cha ngeStudyLa yout(row,  column, is Backup,isR esize)
  13165           {
  13166           is CineEnable d(true);
  13167           if (layoutMap  == undefi ned || lay outMap ==  null) {
  13168                layoutMa p = {};
  13169           }
  13170           se tSelectedS tudyLayout (row, colu mn);
  13171           va r activeVi ewport = d icomViewer .getActive SeriesLayo ut();
  13172           if (isFullScr eenEnabled ) {
  13173                dicomVie wer.setStu dyLayout(1 ,1, active Viewport.g etStudyUid (), active Viewport.s eriesIndex , true);
  13174           }
  13175           el se {
  13176                dicomVie wer.setStu dyLayout(r ow,column,  activeVie wport.getS tudyUid(),  activeVie wport.seri esIndex, i sBackup,is Resize);
  13177           }
  13178           di comViewer. changeSele ction("ima geviewer_s tudyViewer 1x1_1x1");
  13179           ac tiveSeries PDFData =  undefined;
  13180           is PDFActiveS eries = fa lse;
  13181           va r activeVi ewport = d icomViewer .getActive SeriesLayo ut();
  13182  
  13183           if (activeVie wport != n ull && act iveViewpor t !== unde fined && i sEmbedPdfV iewer(acti veViewport .imageType )) {
  13184                dicomVie wer.update Paging(act iveViewpor t.seriesLa youtId);
  13185               }
  13186           }
  13187           
  13188           fu nction cha ngeSeriesL ayout( row  , column  , studyLay out, page)
  13189           {
  13190           is CineEnable d(true);
  13191                    stud yDiv = stu dyLayout = == undefin ed ? page. id : study Layout.id;
  13192                    layo utRow = ro w;
  13193           la youtColumn  = column;
  13194                    if(r ow === und efined ||  row === 0)
  13195                    {
  13196                             row =  1;
  13197                    }
  13198                    if(c olumn ===  undefined  || column  === 0)
  13199                    {
  13200                             column  = 1;
  13201                    }
  13202  
  13203           //  If the us er changes  the serie s level la yout when  the fullsc reen mode  is ON we s et it to O FF to hand le the zoo m, invert  and other  overlay pr operly for  all the i mages.
  13204           if (row > 1 | | column >  1) {
  13205                if(isFul lScreenEna bled) {
  13206                    isFu llScreenEn abled = fa lse;
  13207                }
  13208           }
  13209                    var  newSeriesL ayout = di comViewer. viewports. getViewpor t("imagevi ewer_"+stu dyDiv+"_1x 1");
  13210           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  13211           va r selected LayoutId =  seriesLay out.series LayoutId;
  13212           va r seriesLa youtMaxId  = dicomVie wer.viewpo rts.getSer iesLayoutM axId();
  13213           if (seriesLay outMaxId ! = undefine d) {
  13214                var rowC olumnValue  = seriesL ayoutMaxId .split('_' )[2];
  13215           }
  13216           va r viewport Number = 0 ;
  13217           if (rowColumn Value != u ndefined)  {
  13218                viewport Number = d icomViewer .viewports .getViewpo rtNumber(p arseInt(ro wColumnVal ue.split(' x')[0]), p arseInt(ro wColumnVal ue.split(' x')[1]), s electedLay outId.spli t('_')[2]) ;
  13219           }
  13220           va r imageAnd SeriesInde x = getOrS etReArrang edSeriesPo sitions(ro w, column,  undefined , page);
  13221           la youtMap[st udyDiv] =  row+"x"+co lumn;
  13222           if (seriesLay out.studyU id === new SeriesLayo ut.studyUi d)
  13223                dicomVie wer.setSer iesLayout( seriesLayo ut.studyUi d, row, co lumn, imag eAndSeries Index, nul l, studyDi v);
  13224           el se
  13225                dicomVie wer.setSer iesLayout( newSeriesL ayout.stud yUid, row,  column, 0 , null, st udyDiv);
  13226           is CineEnable d(false);
  13227  
  13228           di comViewer. setReArran gedSeriesP ositions(u ndefined);
  13229           if (seriesLay out !== un defined &&  seriesLay out !== nu ll) {
  13230                var isMu ltiFrame =  dicomView er.thumbna il.isSerie sContainsM ultiframe( seriesLayo ut.studyUi d, seriesL ayout.seri esIndex);
  13231                //If the re is any  duplicate  viewport i n the seri es level l ayout then  updating  the series  layout on  the basis  of the vi eport numb er 
  13232                if(dicom Viewer.vie wports.isD uplicateVi ewport(isM ultiFrame,  isMultiFr ame ? seri esLayout.s crollData. imageIndex  : seriesL ayout.seri esIndex))  {
  13233                    var  viewport =  dicomView er.viewpor ts.getSele ctedViewpo rt(studyDi v, row, co lumn, view portNumber );
  13234                    if(v iewport !=  undefined  || viewpo rt != null ) {
  13235                         seriesLayo ut = viewp ort;
  13236                    }
  13237                }
  13238                dicomVie wer.change Selection( seriesLayo ut.seriesL ayoutId);
  13239                if(page)  {
  13240                    Enab leDisableN extSeriesI mage(dicom Viewer.get ActiveSeri esLayout() );
  13241                }
  13242           }
  13243           ch angeIconSi ze();
  13244       }
  13245           
  13246       functi on chanage WhileDrag(  row , col umn, study Div,isThum bnailClick )
  13247       {
  13248           la youtRow =  row;
  13249           la youtColumn  = column;
  13250           if (row === u ndefined | | row ===  0)
  13251           {
  13252                row = 1;
  13253           }
  13254  
  13255           va r layoutId  = "imagev iewer_"+ s tudyDiv+ " _1x1" /*(r ow) + "x"  + (column) */;
  13256           va r viewport  = dicomVi ewer.viewp orts.getVi ewport(lay outId);
  13257  
  13258           if (column == = undefine d || colum n === 0)
  13259           {
  13260                column =  1;
  13261           }
  13262  
  13263           la youtMap[st udyDiv] =  row+"x"+co lumn;
  13264           va r imagecan vasValue =  dicomView er.getimag eCanvasOfV iewPort(la youtId);
  13265           va r seriesIn dex = 0;
  13266           if (imagecanv asValue !=  undefined )
  13267           {                          
  13268                seriesIn dex = imag ecanvasVal ue.seriesI ndex;
  13269           }
  13270           if (layoutId  === "image viewer_stu dyViewer1x 1_1x1" &&  isFullScre enEnabled  === false)
  13271           {
  13272                seriesIn dex = seri esIndexBac kup;
  13273           }
  13274           if (isFullScr eenEnabled ) {
  13275                dicomVie wer.setSer iesLayout( viewport.s tudyUid, 1 , 1, serie sIndex, nu ll, studyD iv, false, undefined, isThumbnai lClick);
  13276           }  else {
  13277                dicomVie wer.setSer iesLayout( viewport.s tudyUid, r ow, column , seriesIn dex, null,  studyDiv,  false,und efined,isT humbnailCl ick);
  13278           }
  13279       }
  13280           
  13281       /**
  13282        *Chan ge the ima ge layout  by changin g the no o f images i n the acti ve viewpor t for the  selected s eries
  13283        *Poss ible image  layouts -  {1x1, 1x2 , 2x1, 2x2 }
  13284        *@par am {Intege r} row - T otal no of  rows in i mage layou t
  13285        *@par am {Intege r} column  - Total no  of column s in image  layout
  13286        */
  13287           fu nction cha ngeImageLa yout(row,  column, di vId, page)  {
  13288           $( "#playButt on").remov eClass("k- state-disa bled"); // enable the  playbutto n if it is  disabled
  13289           ne xtslideind ex = 0;
  13290                    var  seriesLayo ut = dicom Viewer.get ActiveSeri esLayout() ;
  13291                    seri esLayout.s etImageLay outDimensi on(row + " x" +column );
  13292           va r totalIma geLevelLay out = row  * column;
  13293           va r imageInd ex = serie sLayout.ge tImageInde x();
  13294           va r frameInd ex = serie sLayout.ge tFrameInde x();
  13295           // For gettin g the tota l image co unt for th e selected  series of  active st udy
  13296           va r imageSer ies = dico mViewer.Se ries.getSe ries(serie sLayout.st udyUid, se riesLayout .seriesInd ex);
  13297           //  Checking  whether th e image le vel layout  changes t o like 1 x  2, 2 x 1,  2 x 2
  13298           if (totalImag eLevelLayo ut > 1){
  13299                var stud yUid = ser iesLayout. getStudyUi d();
  13300                var imag eValue = d icomViewer .Series.Im age.getIma ge(studyUi d, seriesL ayout.seri esIndex,im ageIndex);
  13301                seriesLa yout.image Type = ima geValue.im ageType;
  13302                if(image Value != u ndefined){
  13303                    // C hecking wh ether the  respective  image is  multiframe  or not
  13304                    var  isMultifra me = dicom Viewer.thu mbnail.isI mageThumbn ail(imageV alue);
  13305                    var  imageAndFr ameIndex =  isMultifr ame ? seri esLayout.g etFrameInd ex() : ser iesLayout. getImageIn dex();
  13306                    var  totalImage Count = is Multiframe  ? dicomVi ewer.Serie s.Image.ge tImageFram eCount(ima geValue) :  seriesLay out.getIma geCount();
  13307  
  13308                    // F ollowing c alculation  to displa y an image s or frame s to selec ted image  level layo ut based o n thier av ailability  
  13309                    var  difference  = totalIm ageCount -  imageAndF rameIndex;
  13310                    if(( totalImage Count < 4  || totalIm ageCount = == undefin ed) && 
  13311                       ( totalImage LevelLayou t === 4 ||  totalImag eLevelLayo ut > 4)) {
  13312                         imageAndFr ameIndex =  0;
  13313                    }
  13314                    else  if((total ImageCount  < 4 || to talImageCo unt === un defined &&
  13315                              total ImageLevel Layout < 4 ) && image AndFrameIn dex > 0) {
  13316                         imageAndFr ameIndex-- ;
  13317                    }
  13318                    else  if(imageA ndFrameInd ex + 1 ===  totalImag eCount ||  difference  < totalIm ageLevelLa yout){
  13319                         imageAndFr ameIndex =  imageAndF rameIndex  - (totalIm ageLevelLa yout - dif ference);
  13320                    }
  13321  
  13322                    imag eIndex = i sMultifram e ? series Layout.get ImageIndex () : image AndFrameIn dex;
  13323                    fram eIndex = ! isMultifra me ? serie sLayout.ge tFrameInde x() : imag eAndFrameI ndex;
  13324                    if(! isMultifra me) {
  13325                         //Stop the  cine and  disable th e play but ton when t he image c ount for t he active  series is  < 4 and th e image la yout is 2x 2
  13326                         if(imageSe ries.image Count < 4  && seriesL ayout.imag eLayoutDim ension ==  "2x2")
  13327                         {
  13328                             dicomV iewer.tool s.stopCine Image();
  13329                             update PlayIcon(" stop.png",  "play.png ", false,   "#playBut ton");
  13330                             $("#pl ayButton") .addClass( "k-state-d isabled");
  13331                         }
  13332                    }
  13333                }
  13334           }
  13335           if (divId !==  undefined ) {
  13336                dicomVie wer.setIma geLevelLay out(series Layout.stu dyUid, row , column,  seriesLayo ut.getSeri esLayoutId (), series Layout,ser iesLayout. getSeriesI ndex(), im ageIndex,  frameIndex );
  13337           }  else if (p age != und efined) {
  13338                if (page .isMultiFr ame) {
  13339                    dico mViewer.se tImageLeve lLayout(se riesLayout .studyUid,  row, colu mn, series Layout.get SeriesLayo utId(), se riesLayout , page.ser iesIndex,   page.imag eIndex, pa ge.first);
  13340                    seri esLayout.s etImageInd ex(page.im ageIndex);
  13341                    seri esLayout.s etFrameInd ex(page.fi rst);
  13342                } else {
  13343                    dico mViewer.se tImageLeve lLayout(se riesLayout .studyUid,  row, colu mn, series Layout.get SeriesLayo utId(), se riesLayout , page.ser iesIndex,  page.first , seriesLa yout.getFr ameIndex() );
  13344                }
  13345           }
  13346           if (dicomView er.scroll. isCineRunn ing(series Layout.get SeriesLayo utId())) {
  13347                var moda lity = dic omViewer.S eries.getM odality(se riesLayout .getStudyU id(), seri esLayout.g etSeriesIn dex());
  13348                showOrHi deInCineRu nning(moda lity, true );
  13349         }
  13350           En ableDisabl eNextSerie sImage(ser iesLayout) ;
  13351           }
  13352           
  13353           fu nction sho wDicomHead er()
  13354           {
  13355                    var  returnStri ng = "";
  13356           va r imageRen der;
  13357                    var  seriesLayo ut = dicom Viewer.get ActiveSeri esLayout() ;
  13358                    var  layoutId =  seriesLay out.getSer iesLayoutI d();
  13359                    $("# " + layout Id + " div ").each(fu nction(){
  13360                    var  imageLevel Id = $(thi s).attr('i d');
  13361  
  13362                    if(s eriesLayou t.imageTyp e === IMAG ETYPE_RADS R)
  13363                    {
  13364                             imageR ender = se riesLayout .getImageR ender("srR eport")
  13365                             return String = d icomViewer .header.ge tDicomHead erValues(s eriesLayou t.studyUid ,imageRend er.imageUi d);
  13366                    }
  13367                    else  if(series Layout.ima geType ===  IMAGETYPE _RADECG){
  13368                imageRen der = seri esLayout.g etImageRen der("ecgDa ta")
  13369                             return String = d icomViewer .header.ge tDicomHead erValues(s eriesLayou t.studyUid ,imageRend er.imageUi d);
  13370           }e lse
  13371           {
  13372                imageRen der = seri esLayout.g etImageRen der(imageL evelId);
  13373           }
  13374                    if(i mageRender  != undefi ned)
  13375                    {
  13376               
  13377                             var im agePromise Obj = imag eRender.im agePromise ;
  13378                 if(imag ePromiseOb j != undef ined)
  13379                 {
  13380                    var  dicomObjct ;
  13381                    imag ePromiseOb j.then(fun ction(imag e){
  13382                         dicomObjct  = image;
  13383                         returnStri ng = dicom Viewer.hea der.getDic omHeaderVa lues(serie sLayout.st udyUid,dic omObjct.im ageUid);
  13384                         var innerH TMLString  = "<tr><th >Group</th ><th>Eleme nt</th><th >Descripti on</th><th >VR</th><t h align='l eft'>Value </th></tr> ";
  13385                         for ( var  i = 0; i <  returnStr ing.length ; i++)
  13386                         {
  13387                             var ta gString =  returnStri ng[i].tag. replace("( ", "").rep lace(")",  "").split( ",");
  13388                             if(tag String[0]  === "0010"  && tagStr ing[1] ===  "0010"){
  13389                                 in nerHTMLStr ing += '<t r><td>' +  tagString[ 0] + '</td ><td>' + t agString[1 ] + '</td> <td>'
  13390                                      + return String[i]. tagDescrip tion + '</ td><td>' +  returnStr ing[i].vrT ype
  13391                                      + '</td> <td>' + re turnString [i].tagVal ue.replace (/\^/gi, '  ') + '</t d></tr>';
  13392                             }else
  13393                             {
  13394                             innerH TMLString  += '<tr><t d>' + tagS tring[0] +  '</td><td >' + tagSt ring[1] +  '</td><td> '
  13395                                      + return String[i]. tagDescrip tion + '</ td><td>' +  returnStr ing[i].vrT ype
  13396                                      + '</td> <td>' + re turnString [i].tagVal ue + '</td ></tr>';
  13397                             }
  13398                         }
  13399                         $("#dicomH eader").ht ml(innerHT MLString);
  13400                         $("#dicomH eaderAttri butes").di alog('open ');
  13401                         dicomViewe r.pauseCin ePlay(1,tr ue);
  13402                         return fal se;
  13403                    });
  13404                    
  13405                 }
  13406                 else
  13407                 {
  13408                         returnStri ng = dicom Viewer.hea der.getDic omHeaderVa lues(serie sLayout.st udyUid,ima geRender.i mageUid);
  13409                          var inner HTMLString  = "<tr><t h>Group</t h><th>Elem ent</th><t h>Descript ion</th><t h>VR</th>< th align=' left'>Valu e</th></tr >";
  13410                             for (  var i = 0;  i < retur nString.le ngth; i++)
  13411                             {
  13412                                 va r tagStrin g = return String[i]. tag.replac e("(", "") .replace(" )", "").sp lit(",");
  13413                                 if (tagString [0] === "0 010" && ta gString[1]  === "0010 ")
  13414                                 {
  13415                                 in nerHTMLStr ing += '<t r><td>' +  tagString[ 0] + '</td ><td>' + t agString[1 ] + '</td> <td>'
  13416                                      + return String[i]. tagDescrip tion + '</ td><td>' +  returnStr ing[i].vrT ype
  13417                                      + '</td> <td>' + re turnString [i].tagVal ue.replace (/\^/gi, '  ') + '</t d></tr>';
  13418                                 }e lse
  13419                                 {
  13420                                      innerHTM LString +=  '<tr><td> ' + tagStr ing[0] + ' </td><td>'  + tagStri ng[1] + '< /td><td>'
  13421                                               + returnSt ring[i].ta gDescripti on + '</td ><td>' + r eturnStrin g[i].vrTyp e
  13422                                               + '</td><t d>' + retu rnString[i ].tagValue  + '</td>< /tr>';
  13423                                 }
  13424                             }
  13425                             $("#di comHeader" ).html(inn erHTMLStri ng);
  13426                             $("#di comHeaderA ttributes" ).dialog(' open');
  13427                             dicomV iewer.paus eCinePlay( 1,true);
  13428                             return  false;
  13429                 }
  13430                    }
  13431                    });
  13432                    
  13433           }
  13434       
  13435       functi on showIma geData() {
  13436           va r imageRen der;
  13437           va r imageLev elId;
  13438           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  13439           if (seriesLay out.imageT ype === IM AGETYPE_VI DEO || ser iesLayout. imageType  === IMAGET YPE_AUDIO 
  13440               || series Layout.ima geType ===  IMAGETYPE _RADECG ||  seriesLay out.imageT ype === IM AGETYPE_RA DSR ||
  13441               seriesLay out.imageT ype === IM AGETYPE_CD A) {
  13442                if(serie sLayout.im ageType == = IMAGETYP E_RADECG)  {
  13443                    imag eLevelId =  "ecgData" ;
  13444                }
  13445                else if  (seriesLay out.imageT ype === IM AGETYPE_RA DSR || ser iesLayout. imageType  === IMAGET YPE_CDA) {
  13446                    imag eLevelId =  "srReport ";
  13447                }
  13448                else {
  13449                    imag eLevelId =  seriesLay out.imageT ype;
  13450                }
  13451                imageRen der = seri esLayout.g etImageRen der(imageL evelId);
  13452                if(image Render !=  undefined)
  13453                {
  13454                    disp layImageDa ta(seriesL ayout, ima geRender.i mageUid);
  13455                    retu rn true;
  13456                }
  13457           }
  13458           el se {
  13459                var layo utId = ser iesLayout. getSeriesL ayoutId();
  13460                $("#" +  layoutId +  " div").e ach(functi on() {
  13461                    imag eLevelId =  $(this).a ttr('id');
  13462                    imag eRender =  (seriesLay out.getIma geRender(i mageLevelI d) == unde fined) ? 
  13463                                      seriesLa yout.getIm ageRender( imageLevel Id.split(" _")[0]) :  seriesLayo ut.getImag eRender(im ageLevelId );
  13464  
  13465                    if(i mageRender  != undefi ned) {
  13466                         var imageP romiseObj  = imageRen der.imageP romise;
  13467                         if(imagePr omiseObj ! = undefine d) {
  13468                             var di comObjct;
  13469                             imageP romiseObj. then(funct ion(image)  {
  13470                                 di comObjct =  image;
  13471                                 di splayImage Data(serie sLayout, d icomObjct. imageUid);
  13472                                 re turn false ;
  13473                             });
  13474                          }
  13475                         else {
  13476                             displa yImageData (seriesLay out, image Render.ima geUid);
  13477                             return  false;
  13478                         }
  13479                    }
  13480                });
  13481           }
  13482       }
  13483  
  13484       /**
  13485        * Dis play the i mage data  window.
  13486        * @pa ram {Type}  seriesLay out - spec ifies the  series lay out
  13487        * @pa ram {Type}  imageUid  - specifie s the imag e uid
  13488        */ 
  13489       functi on display ImageData( seriesLayo ut, imageU id)
  13490       {
  13491           if (imageUid  == undefin ed) {
  13492                return;
  13493           }
  13494  
  13495           va r def = di comViewer. header.get Metadata(s eriesLayou t.studyUid ,imageUid) ;
  13496           de f.done(fun ction(meta data) {
  13497                $("#imag eMetadata" ).html(met adata);
  13498           }) ;
  13499           $( "#imagingD ata").dial og('open') ;
  13500           di comViewer. pauseCineP lay(1,true );
  13501       }
  13502  
  13503           fu nction set DicomOverL ayFalse(se riesLayout )
  13504           {
  13505           va r layoutId  = seriesL ayout.getS eriesLayou tId();
  13506  
  13507                    $("# " + layout Id + " div ").each(fu nction() {
  13508                             var im ageLevelId  = $(this) .attr('id' );
  13509                             var im ageRender  = seriesLa yout.getIm ageRender( imageLevel Id);
  13510                             if(ima geRender)  {
  13511                    imag eRender.sh owOrHideOv erlay(over layVisible Status);
  13512                             }
  13513                    });
  13514           }
  13515  
  13516           fu nction doW indowLevel (e)
  13517           {
  13518           va r actvieSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  13519           va r imageTyp eOrModalit y = actvie SeriesLayo ut ? actvi eSeriesLay out.imageT ype : unde fined;
  13520           if (imageType OrModality  == IMAGET YPE_JPEG | | imageTyp eOrModalit y == IMAGE TYPE_RADEC HO ||
  13521               imageType OrModality  == "US" )  {
  13522                doBright nessContra st(e);
  13523                return;
  13524           }
  13525  
  13526                    if(e  != undefi ned && e.i d == "7")  {
  13527                             custom WindowLeve l(e.id);
  13528                    }
  13529                    else  if(e == " 7") {
  13530                customWi ndowLevel( e);
  13531           }
  13532                    else  if(e != u ndefined & & e.id !=  "winL")
  13533                    {
  13534                             if(e.i d != undef ined) {
  13535                    dico mViewer.to ols.change Preset(e.i d);
  13536                } else {
  13537                    dico mViewer.to ols.change Preset(e);
  13538                }
  13539                    }
  13540                    else {
  13541                             applyW indowLevel ();
  13542                    }
  13543       }
  13544       
  13545       functi on doSharp en(e)
  13546       {
  13547           re setMenu();    
  13548           $( "#context- sharpen"). css("backg round","#8 68696");
  13549           di comViewer. measuremen t.setDataT oDelete();
  13550           va r tool = d icomViewer .mouseTool s.getActiv eTool();
  13551           to ol.hanleDo ubleClick( );
  13552           $( '#viewport _View').cs s('cursor' ,'url(imag es/sharpen .cur), aut o');
  13553           di comViewer. mouseTools .setActive Tool(dicom Viewer.mou seTools.ge tSharpenTo ol());
  13554  
  13555           //  refresh i mage so th at US regi ons appear
  13556           re freshImage ();
  13557       }
  13558           
  13559       functi on applyWi ndowLevel( )
  13560       {
  13561           re setMenu();
  13562           $( "#context- windowleve l").css("b ackground" ,"#868696" );
  13563           $( "#context- ww_wc").cs s("backgro und","#868 696");
  13564           di comViewer. measuremen t.setDataT oDelete();
  13565           va r tool = d icomViewer .mouseTool s.getActiv eTool();
  13566           to ol.hanleDo ubleClick( );
  13567           $( '#viewport _View').cs s('cursor' ,'url(imag es/brightn ess.cur),  auto');
  13568           di comViewer. mouseTools .setActive Tool(dicom Viewer.mou seTools.ge tWindowToo l());
  13569  
  13570           //  refresh i mage so th at US regi ons appear
  13571           re freshImage ();
  13572       }
  13573  
  13574           fu nction doP an()
  13575           {
  13576                    rese tMenu();
  13577                    $("# context-pa n").css("b ackground" ,"#868696" );
  13578                    dico mViewer.me asurement. setDataToD elete();
  13579                             var to ol = dicom Viewer.mou seTools.ge tActiveToo l();
  13580                             tool.h anleDouble Click();
  13581            $ ('#viewpor t_View').c ss('cursor ','url(ima ges/pan.cu r), auto') ;
  13582                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getP anTool());
  13583  
  13584                // refre sh image s o that US  regions ap pear
  13585                    refr eshImage() ;
  13586       }
  13587           
  13588           fu nction doZ oom(e)
  13589           {
  13590           di comViewer. measuremen t.setDataT oDelete();
  13591           va r tool = d icomViewer .mouseTool s.getActiv eTool();
  13592           to ol.hanleDo ubleClick( );
  13593  
  13594           re setMenu();
  13595  
  13596           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  13597           if (!isEmbedP dfViewer(s eriesLayou t.imageTyp e)) {
  13598                if((seri esLayout.i mageType ! == IMAGETY PE_RADSR)  && (series Layout.ima geType !==  IMAGETYPE _RADECG))  {
  13599                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getZ oomTool()) ;
  13600                    $('# viewport_V iew').css( 'cursor',' url(images /zoom.cur) , auto');
  13601                }
  13602           }
  13603  
  13604                    if(e  === "6_zo om" || (e. id != unde fined && e .id === "6 _zoom"))
  13605                    {
  13606                             var cu stomZoomID  = e;
  13607                             if(e.i d != undef ined)
  13608                                      customZo omID = e.i d;
  13609                             
  13610                changeZo omCustom(c ustomZoomI D);
  13611                             var se riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  13612                seriesLa yout.prefe renceInfo. setZoomLev elSettings (parseInt( customZoom ID));
  13613           } 
  13614                    else  if(e.id ! = undefine d && e.id  !== "zoomB utton")
  13615                    {
  13616                             var va lue = e.id .split("_" )
  13617                             dicomV iewer.tool s.setZoomL evel(parse Int(value[ 0]));
  13618                             var se riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  13619                             series Layout.pre ferenceInf o.setZoomL evelSettin gs(e.id);
  13620           }
  13621           el se if(e.id  == "zoomB utton")
  13622           {
  13623                resetZoo mTool();
  13624                var seri esLayout =  dicomView er.getActi veSeriesLa yout();
  13625                seriesLa yout.prefe renceInfo. setZoomLev elSettings (e.id);
  13626           }
  13627           re freshImage ();
  13628       }
  13629           
  13630           fu nction do2 DLengthMea surement()  {
  13631                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.get2DLen gthMeasure Tool());
  13632  
  13633                // refre sh image s o that US  regions ap pear
  13634                refreshI mage();
  13635           }
  13636       
  13637           fu nction doA ngleMeasur ement() {
  13638                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getAngle MeasureToo l());
  13639  
  13640                // refre sh image s o that US  regions ap pear
  13641                refreshI mage();
  13642           }
  13643           fu nction do2 DPointMeas urement()  {
  13644                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.get2DPoi ntMeasureT ool());
  13645  
  13646                // refre sh image s o that US  regions ap pear
  13647                refreshI mage();
  13648           }
  13649           
  13650           fu nction get TraceMeasu reTool() {
  13651                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getTrace MeasureToo l());
  13652  
  13653                // refre sh image s o that US  regions ap pear
  13654                refreshI mage();
  13655           }
  13656         
  13657           fu nction get VolumeMeas ureTool()  {
  13658                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getVolum eMeasureTo ol());
  13659  
  13660                // refre sh image s o that US  regions ap pear
  13661                refreshI mage();
  13662           }
  13663           
  13664       functi on getMitr alMeanGrad ientMeasur eTool() {
  13665                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getMitra lMeanGradi entMeasure Tool());
  13666  
  13667                // refre sh image s o that US  regions ap pear
  13668                refreshI mage();
  13669           }
  13670           fu nction cha ngeStudyLa youtFromTo ol(type, i sBackup,is Resize)
  13671           {
  13672           if  (isResize  === undef ined || is Resize ===  true) {
  13673                reOrderE xistingStu dyUids();
  13674           }
  13675           is CineEnable d(true);
  13676                    stud yLayoutVal ue = type. id;
  13677           is FullScreen Enabled =  isBackup ?  isBackup  : false;
  13678                    var  colAndRow  = type.id. split("x") ;
  13679                    chan geStudyLay out(colAnd Row[0],col AndRow[1],  isBackup, isResize);
  13680           }
  13681           /* *
  13682           *R eset the C ontext and  toolbar m enus
  13683           ** /
  13684           fu nction res etMenu(isS howKendo){
  13685  
  13686           if (!isShowKe ndo) {
  13687                removeKe ndoButtons ();
  13688                previous eSelectdTo ol = undef ined;
  13689           }
  13690  
  13691                    //co ntext menu s
  13692                    $("# context-pa n").css("b ackground" ,"");
  13693           $( "#context- sharpen"). css("backg round","") ;
  13694           $( "#context- windowleve l").css("b ackground" ,"");
  13695           $( "#context- ww_wc").cs s("backgro und","");
  13696                    $("# context-le ngth").css ("backgrou nd","");
  13697                    $("# context-2d Point").cs s("backgro und","");
  13698                    $("# context-tr ace").css( "backgroun d","");
  13699                    $("# context-vo lume").css ("backgrou nd","");
  13700                    $("# context-le ngth-calib ration").c ss("backgr ound","");
  13701           $( "#context- angle").cs s("backgro und","");
  13702                    $("# context-ho unsfield") .css("back ground","" );
  13703           $( "#context- cacheIndic ator").css ("backgrou nd","");
  13704           $( "#context- hounsfield -ellipse") .css("back ground","" );
  13705           $( "#context- hounsfield -rectangle ").css("ba ckground", "");
  13706           $( "#context- text").css ("backgrou nd","");
  13707           $( "#context- line").css ("backgrou nd","");
  13708           $( "#context- arrow").cs s("backgro und","");
  13709           $( "#context- ellipse"). css("backg round","") ;
  13710           $( "#context- rectangle" ).css("bac kground"," ");
  13711           $( "#context- freehand") .css("back ground","" );
  13712           $( "#measurem ent104").c ss("backgr ound","");
  13713           $( "#measurem ent102").c ss("backgr ound","");
  13714           $( "#measurem ent106").c ss("backgr ound","");
  13715           $( "#measurem ent101").c ss("backgr ound","");
  13716           $( "#measurem ent103").c ss("backgr ound","");
  13717           $( "#measurem ent107").c ss("backgr ound","");
  13718           $( "#measurem ent108").c ss("backgr ound","");
  13719                    //To olbar menu s
  13720                    $("# 0_measurem ent").css( "backgroun d","");
  13721                    $("# 1_measurem ent").css( "backgroun d","");
  13722                    $("# 2_measurem ent").css( "backgroun d","");
  13723                    $("# 3_measurem ent").css( "backgroun d","");
  13724                    $("# 6_measurem ent").css( "backgroun d","");
  13725                    $("# 7_measurem ent").css( "backgroun d","");
  13726           $( "#14_measu rement").c ss("backgr ound","");
  13727           $( "#8_text") .css("back ground","" );
  13728                    $("# 9_line").c ss("backgr ound","");
  13729                    $("# 10_arrow") .css("back ground","" );
  13730                    $("# 11_ellipse ").css("ba ckground", "");
  13731                    $("# 12_rectang le").css(" background ","");
  13732                    $("# 13_freehan d").css("b ackground" ,"");
  13733           $( "#angle_me asurement" ).css("bac kground"," ");
  13734           $( "#15_pen") .css("back ground","" );
  13735           $( "#context- pen").css( "backgroun d","");
  13736           }
  13737           
  13738       /**
  13739       * Rese t the Zoom  Tool butt on backgro und color  for contex t and Tool bar menus
  13740       */
  13741       functi on resetZo omTool()
  13742       {
  13743           // Toolbar me nus
  13744           $( "#0_zoom") .parent(). css("backg round","") ;
  13745           $( "#1_zoom") .parent(). css("backg round","") ;
  13746           $( "#2_zoom") .parent(). css("backg round","") ;
  13747           $( "#3_zoom") .parent(). css("backg round","") ;
  13748           $( "#4_zoom") .parent(). css("backg round","") ;
  13749           $( "#5_zoom") .parent(). css("backg round","") ;
  13750           $( "#6_zoom") .parent(). css("backg round","") ;
  13751           // Context me nus
  13752           $( "#0_zoomCo ntextMenu" ).css("bac kground"," ");
  13753           $( "#1_zoomCo ntextMenu" ).css("bac kground"," ");
  13754           $( "#2_zoomCo ntextMenu" ).css("bac kground"," ");
  13755           $( "#3_zoomCo ntextMenu" ).css("bac kground"," ");
  13756           $( "#6_zoomCo ntextMenu" ).css("bac kground"," ");
  13757       }
  13758  
  13759       /**
  13760       * Comp lete the i ncompleted  previousl y draw sha pe while s electing a ny of the  Measuremen t/Annotati on tool
  13761       */
  13762       functi on complet eShape() {
  13763           va r tool = d icomViewer .mouseTool s.getActiv eTool();
  13764           va r toolName  = dicomVi ewer.mouse Tools.getT oolName();
  13765           if (toolName  === "mitra lMeanGradi entMeasure ment" || t oolName == = "traceMe asurement"  
  13766              || toolNam e === "ang leMeasurem ent") {
  13767                tool.han leDoubleCl ick();
  13768           }
  13769       }
  13770  
  13771       functi on do2DMea surement(t ype, id, u nits) {
  13772           re setMenu(tr ue);
  13773           co mpleteShap e();
  13774           if (type.id ! = undefine d) {
  13775                type = t ype.id.spl it("_")[0] ;
  13776           }  else if(ty pe != 4) {
  13777                dicomVie wer.measur ement.draw .setMeasur ementType( type, id,  units);
  13778           }
  13779           di comViewer. mouseTools .setPrevio usTool(dic omViewer.m ouseTools. getActiveT ool());
  13780           di comViewer. mouseTools .setCursor (dicomView er.mouseTo ols.getToo lCursor(1) );
  13781           if  (type ==  0) {
  13782                isLength Calibratin g = false;
  13783                if(isCal iberEnable d()){
  13784                    isLe ngthCalibr ating = tr ue;
  13785                    cali brationToo lId = type ;
  13786                    Line Measuremen t.prototyp e.setMeasu rementSubT ype("2DLen gth");
  13787                    setC alibration ActiveTool ();
  13788                } else{
  13789                    cali brationToo lId = unde fined;
  13790                    flag For2dLengt hCalibrati on = false ;
  13791                    Line Measuremen t.prototyp e.setMeasu rementSubT ype();
  13792                    if(i d == "mitr alRegurgit ationLengt h") {
  13793                         $("#measur ement102") .css("back ground","# 868696");
  13794                         dicomViewe r.mouseToo ls.setActi veTool(dic omViewer.m ouseTools. get2DLengt hMeasureTo ol(1));
  13795                    } el se if (id  == "aortic Regurgitat ionLength" ){
  13796                         $("#measur ement106") .css("back ground","# 868696");
  13797                         dicomViewe r.mouseToo ls.setActi veTool(dic omViewer.m ouseTools. get2DLengt hMeasureTo ol(2));
  13798                    } el se if (id  == "mitral ValveAnter iorLeaflet Thickness" ) {
  13799                         $("#measur ement101") .css("back ground","# 868696");
  13800                         dicomViewe r.mouseToo ls.setActi veTool(dic omViewer.m ouseTools. get2DLengt hMeasureTo ol(3));
  13801                    } el se {
  13802                         $("#contex t-length") .css("back ground","# 868696");
  13803                         $("#0_meas urement"). css("backg round","#8 68696");
  13804                         dicomViewe r.mouseToo ls.setActi veTool(dic omViewer.m ouseTools. get2DLengt hMeasureTo ol(0,"2DLe ngth"));
  13805                         LineMeasur ement.prot otype.setM easurement SubType("2 DLength");
  13806                    }
  13807                }
  13808           }
  13809           el se if (typ e == 1){
  13810  
  13811                if(id ==  "mitralRe gurgitatio nPeakVeloc ity") {
  13812                    $("# measuremen t103").css ("backgrou nd","#8686 96");
  13813                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DPointMeas ureTool(1) );
  13814                } else i f (id == " aorticRegu rgitationP eakVelocit y"){
  13815                    $("# measuremen t107").css ("backgrou nd","#8686 96");
  13816                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DPointMeas ureTool(2) );
  13817                } else i f (id == " aorticSten osisPeakVe locity") {
  13818                    $("# measuremen t108").css ("backgrou nd","#8686 96");
  13819                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DPointMeas ureTool(3) );
  13820                } else {
  13821                    $("# context-2d Point").cs s("backgro und","#868 696");
  13822                    $("# 1_measurem ent").css( "backgroun d","#86869 6");
  13823                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.get2 DPointMeas ureTool(0) );
  13824                }
  13825                    }
  13826           el se if (typ e == 2) {
  13827                             $("#co ntext-trac e").css("b ackground" ,"#868696" );
  13828                             $("#2_ measuremen t").css("b ackground" ,"#868696" );
  13829                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getTrace MeasureToo l());
  13830                    }
  13831                    else  if (type  == 3) {
  13832                             $("#co ntext-volu me").css(" background ","#868696 ");
  13833                             $("#3_ measuremen t").css("b ackground" ,"#868696" );
  13834                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getVolum eMeasureTo ol());
  13835                    }
  13836           el se if (typ e == "angl e"){
  13837                             $("#co ntext-angl e").css("b ackground" ,"#868696" );
  13838                             $("#an gle_measur ement").cs s("backgro und","#868 696");
  13839                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getAngle MeasureToo l());
  13840                    }
  13841                    else  if (type  == 6) {
  13842                setLengt hCalibrati onFlag(fal se);
  13843                setCalib rationActi veTool();
  13844                LineMeas urement.pr ototype.se tMeasureme ntSubType( );
  13845                    }
  13846                    else  if (type  == 4) {
  13847                             var se riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  13848                var imag eRender =  seriesLayo ut.imageRe nders;
  13849                for (var  key in im ageRender)  {
  13850                    var  render = i mageRender [key];
  13851                                      var fram eIndex = r ender.anUI Ds.split(" *")[1];
  13852                                      dicomVie wer.measur ement.remo veAllMeasu rements(re nder.image Uid, frame Index, ren der);
  13853                    var  tool = dic omViewer.m ouseTools. getActiveT ool();
  13854                    if(t ool != und efined &&  tool != nu ll){
  13855                         SetMenuSel ectionColo r(tool.Too lType);
  13856                    }
  13857                }
  13858                dicomVie wer.measur ement.setD ataToDelet e();
  13859                    }
  13860           el se if (typ e == 5) {
  13861                             $("#me asurement1 04").css(" background ","#868696 ");
  13862                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getMitra lMeanGradi entMeasure Tool(0,"mi tral"));
  13863                MitralMe anGradient Measuremen t.prototyp e.setMeasu rementSubT ype("mitra l");
  13864                    }
  13865           el se if (typ e == 7 ||  type == 14 ) {
  13866                isLength Calibratin g = false;
  13867                if(isCal iberEnable d()){
  13868                    isLe ngthCalibr ating = tr ue;
  13869                    cali brationToo lId = type ;
  13870                    if(t ype == 7)  {
  13871                         EllipseMea surement.p rototype.s etMeasurem entSubType ("hounsfie ld");
  13872                    } el se {
  13873                         RectangleM easurement .prototype .setMeasur ementSubTy pe("hounsf ield");
  13874                    }
  13875                    setC alibration ActiveTool ();
  13876                } 
  13877                else if( type == 7)  {
  13878                    cali brationToo lId = unde fined;
  13879                    $("# context-ho unsfield-e llipse").c ss("backgr ound","#86 8696");
  13880                    $("# 7_measurem ent").css( "backgroun d","#86869 6");
  13881                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getE llipseMeas ureTool(0, "hounsfiel d"));
  13882                    Elli pseMeasure ment.proto type.setMe asurementS ubType("ho unsfield")
  13883                } else i f (type ==  14) {
  13884                    cali brationToo lId = unde fined;
  13885                    $("# context-ho unsfield-r ectangle") .css("back ground","# 868696");
  13886                    $("# 14_measure ment").css ("backgrou nd","#8686 96");
  13887                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getR ectangleMe asureTool( 0,"hounsfi eld"));
  13888                    Rect angleMeasu rement.pro totype.set Measuremen tSubType(" hounsfield ");
  13889                }
  13890  
  13891                    } el se if (typ e == 8) {
  13892                             $("#co ntext-text ").css("ba ckground", "#868696") ;
  13893                             $("#8_ text").css ("backgrou nd","#8686 96");
  13894                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getRecta ngleMeasur eTool(2,"t ext"));
  13895                Rectangl eMeasureme nt.prototy pe.setMeas urementSub Type("text ");
  13896                    } el se if (typ e == 9) {
  13897                flagFor2 dLengthCal ibration =  false;
  13898                             $("#co ntext-line ").css("ba ckground", "#868696") ;
  13899                             $("#9_ line").css ("backgrou nd","#8686 96");
  13900                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.get2DLen gthMeasure Tool(4,"2D Line"));
  13901                LineMeas urement.pr ototype.se tMeasureme ntSubType( "2DLine");
  13902                    } el se if (typ e == 10) {
  13903                flagFor2 dLengthCal ibration =  false;
  13904                             $("#co ntext-arro w").css("b ackground" ,"#868696" );
  13905                             $("#10 _arrow").c ss("backgr ound","#86 8696");
  13906                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.get2DLen gthMeasure Tool(5,"Ar row"));
  13907                LineMeas urement.pr ototype.se tMeasureme ntSubType( "Arrow");
  13908                    } el se if (typ e == 11) {
  13909                             $("#co ntext-elli pse").css( "backgroun d","#86869 6");
  13910                             $("#11 _ellipse") .css("back ground","# 868696");
  13911                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getEllip seMeasureT ool(1,"ell ipse"));
  13912                EllipseM easurement .prototype .setMeasur ementSubTy pe("ellips e");
  13913                    } el se if (typ e == 12) {
  13914                             $("#co ntext-rect angle").cs s("backgro und","#868 696");
  13915                             $("#12 _rectangle ").css("ba ckground", "#868696") ;
  13916                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getRecta ngleMeasur eTool(1));
  13917                Rectangl eMeasureme nt.prototy pe.setMeas urementSub Type("rect angle");
  13918                    } el se if (typ e == 13) {
  13919                             $("#co ntext-free hand").css ("backgrou nd","#8686 96");
  13920                             $("#13 _freehand" ).css("bac kground"," #868696");
  13921                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getMitra lMeanGradi entMeasure Tool(1,"fr eehand"));
  13922                MitralMe anGradient Measuremen t.prototyp e.setMeasu rementSubT ype("freeh and");
  13923                    }
  13924           el se if (typ e == 15) {
  13925                $("#cont ext-pen"). css("backg round","#8 68696");
  13926                $("#15_p en").css(" background ","#868696 ");
  13927                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getPenTo ol());
  13928                PenTool. prototype. setMeasure mentSubTyp e("pen");
  13929           }
  13930                // refre sh image s o that US  regions ap pear
  13931                refreshI mage();
  13932           }
  13933           
  13934           /* *
  13935           *R eset RGB t oolbar men us
  13936           ** /
  13937           fu nction res etRGBMenu( ){
  13938                    //co ntext menu s
  13939                    $("# 0_rgbAllCo ntextMenu" ).css("bac kground"," ");
  13940                    $("# 1_rgbRedCo ntextMenu" ).css("bac kground"," ");
  13941                    $("# 2_rgbGreen ContextMen u").css("b ackground" ,"");
  13942                    $("# 3_rgbBlueC ontextMenu ").css("ba ckground", "");
  13943                    
  13944                    //To olbar menu s
  13945                    $("# 0_rgbAll") .css("back ground","" );
  13946                    $("# 1_rgbRed") .css("back ground","" );
  13947                    $("# 2_rgbGreen ").css("ba ckground", "");
  13948                    $("# 3_rgbBlue" ).css("bac kground"," ");
  13949                    
  13950                    //Ov erflow men us
  13951                    $("# RGBButton_ overflow") .css("back ground","" );
  13952                    $("# 0_rgbAll_o verflow"). css("backg round","") ;
  13953                    $("# 1_rgbRed_o verflow"). css("backg round","") ;
  13954                    $("# 2_rgbGreen _overflow" ).css("bac kground"," ");
  13955                    $("# 3_rgbBlue_ overflow") .css("back ground","" );
  13956                    
  13957           }
  13958           
  13959           fu nction rgb Color(e, i sApplied){
  13960                    var  rgbColorId  = "0";
  13961                    rese tRGBMenu() ;
  13962                    if(e .id != und efined &&  e != undef ined){
  13963                             rgbCol orId = e.i d.split("_ ")[0];                  
  13964                    }els e{
  13965                             rgbCol orId = e;
  13966                    }
  13967                                      
  13968                    if ( rgbColorId  == 1){
  13969                             $("#1_ rgbRedCont extMenu"). css("backg round","#8 68696");
  13970                             $("#1_ rgbRed").c ss("backgr ound","#86 8696");
  13971                    }
  13972           el se if (rgb ColorId ==  2){
  13973                             $("#2_ rgbGreenCo ntextMenu" ).css("bac kground"," #868696");
  13974                             $("#2_ rgbGreen") .css("back ground","# 868696");
  13975                    }
  13976                    else  if (rgbCo lorId == 3 ){
  13977                             $("#3_ rgbBlueCon textMenu") .css("back ground","# 868696");
  13978                             $("#3_ rgbBlue"). css("backg round","#8 68696");
  13979                    }
  13980                    else  {
  13981                             $("#0_ rgbAllCont extMenu"). css("backg round","#8 68696");
  13982                             $("#0_ rgbAll").c ss("backgr ound","#86 8696");                       
  13983                    }
  13984  
  13985           if (isApplied ) {
  13986                return;
  13987           }
  13988                             
  13989                    var  seriesLayo ut = dicom Viewer.get ActiveSeri esLayout() ;
  13990           $( "#" + seri esLayout.g etSeriesLa youtId() +  " div").e ach(functi on()
  13991                {
  13992                    var  imageLevel Id = $(thi s).attr('i d');
  13993                    var  imageRende r = series Layout.get ImageRende r(imageLev elId);
  13994                    if(i mageRender )
  13995                    {                         
  13996                             imageR ender.appl yRGB(parse Int(rgbCol orId));
  13997                    }         
  13998                });
  13999                    
  14000           }
  14001           
  14002           fu nction mov eToPreviou sImage()
  14003           {
  14004                    //Mo ve to prev ious frame /image 
  14005                    dico mViewer.sc roll.moveT oNextOrPre viousImage (false);
  14006                    var  serieLayou t = dicomV iewer.getA ctiveSerie sLayout();
  14007                    var  studyUid =  serieLayo ut.getStud yUid();
  14008                    var  firstImage Frame = $( "#"+serieL ayout.getS eriesLayou tId()+" di v:first"). attr("id") ;
  14009                    var  imageRende r = serieL ayout.getI mageRender (firstImag eFrame);
  14010                    var  currentIma geIndex =  null;
  14011                    var  currentFra meIndex =  null;
  14012                    if(i mageRender  != undefi ned)
  14013                    {
  14014                             var an UIDs = ima geRender.a nUIDs;
  14015                             var re sultArray  = anUIDs.s plit("*");
  14016                             curren tFrameInde x = parseI nt(resultA rray[1]);
  14017                             curren tImageInde x = imageR ender.imag eIndex;
  14018                    }
  14019                    seri eLayout.se tImageInde x(currentI mageIndex) ;
  14020                    seri eLayout.se tFrameInde x(currentF rameIndex) ;
  14021           En ableDisabl eNextSerie sImage(ser ieLayout);
  14022           }
  14023           
  14024           fu nction mov eToNextIma ge()
  14025           {
  14026                    //Mo ve to next  from fram e/image
  14027                    dico mViewer.sc roll.moveT oNextOrPre viousImage (true);
  14028                    var  serieLayou t = dicomV iewer.getA ctiveSerie sLayout();
  14029                    var  studyUid =  serieLayo ut.getStud yUid();
  14030                    var  firstImage Frame = $( "#"+serieL ayout.getS eriesLayou tId()+" di v:first"). attr("id") ;
  14031                    var  imageRende r = serieL ayout.getI mageRender (firstImag eFrame);
  14032                    var  currentIma geIndex =  null;
  14033                    var  currentFra meIndex =  null;
  14034                    if(i mageRender  != undefi ned)
  14035                    {
  14036                             var an UIDs = ima geRender.a nUIDs;
  14037                             var re sultArray  = anUIDs.s plit("*");
  14038                             curren tFrameInde x = parseI nt(resultA rray[1]);
  14039                             curren tImageInde x = imageR ender.imag eIndex;
  14040                    }
  14041                    seri eLayout.se tImageInde x(currentI mageIndex) ;
  14042                    seri eLayout.se tFrameInde x(currentF rameIndex) ;
  14043           En ableDisabl eNextSerie sImage(ser ieLayout);
  14044                    
  14045           }
  14046           fu nction run CineImage( direction)
  14047           {
  14048                    //Ru n images i n cine mod e
  14049                    dico mViewer.sc roll.runCi neImage(di rection);
  14050           }
  14051           fu nction sto pCineImage (direction )
  14052           {
  14053                    //St op images  in cine mo de
  14054                    dico mViewer.sc roll.stopC ineImage(d irection);
  14055           }
  14056       
  14057       functi on doHoriz ontalFilp( )
  14058       {
  14059           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  14060           if (isEmbedPd fViewer(se riesLayout .imageType )) {
  14061                dicomVie wer.flip(t rue);
  14062                return;
  14063           }
  14064  
  14065                    $("# " + series Layout.get SeriesLayo utId() + "  div").eac h(function (){
  14066                             var im ageLevelId  = $(this) .attr('id' );
  14067                             var im ageRender  = seriesLa yout.getIm ageRender( imageLevel Id);
  14068                             if(ima geRender)
  14069                             {
  14070                                      imageRen der.doHori zontalFlip ();
  14071                             }
  14072                    });
  14073       }
  14074       
  14075       functi on doVerti calFilp()
  14076       {
  14077                    rese tMenu();
  14078           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  14079           if (isEmbedPd fViewer(se riesLayout .imageType )) {
  14080                dicomVie wer.flip(f alse);
  14081                return;
  14082           }
  14083  
  14084                    $("# " + series Layout.get SeriesLayo utId() + "  div").eac h(function (){
  14085                             var im ageLevelId  = $(this) .attr('id' );
  14086                             var im ageRender  = seriesLa yout.getIm ageRender( imageLevel Id);
  14087                             if(ima geRender)
  14088                             {
  14089                                      imageRen der.doVert icalFilp() ;
  14090                             }
  14091                    });
  14092       }
  14093       
  14094       functi on setZoom Level(leve l)
  14095       {
  14096           re setZoomToo l();
  14097           va r id = lev el+"_zoom" ;
  14098           if (id === "4 _zoom" ||  id === "5_ zoom") {
  14099                //SR Zoo m tool
  14100                dicomVie wer.zoomSR (id);  
  14101           }  else {
  14102                $("#"+id +"ContextM enu").css( "backgroun d","#86869 6");
  14103                var seri esLayout =  dicomView er.getActi veSeriesLa yout();
  14104                if(serie sLayout.ec gZoomLevel Settings ! == seriesL ayout.pref erenceInfo .zoomLevel Setting) {
  14105                    seri esLayout.e cgZoomLeve lSettings  = seriesLa yout.prefe renceInfo. zoomLevelS etting;
  14106                    if(l evel == 6)  {
  14107                         id = serie sLayout.ec gZoomLevel Settings;
  14108                    }
  14109                }
  14110                seriesLa yout.prefe renceInfo. setZoomLev elSettings (id);
  14111  
  14112                $("#" +  seriesLayo ut.getSeri esLayoutId () + " div ").each(fu nction(){
  14113                    var  imageLevel Id = $(thi s).attr('i d');
  14114                    if(  seriesLayo ut && (ser iesLayout. imageType  === IMAGET YPE_PDF ||  
  14115                                           ser iesLayout. imageType  === IMAGET YPE_TIFF | |
  14116                                           ser iesLayout. imageType  === IMAGET YPE_RADPDF )) {
  14117                         if (imageL evelId ==  undefined  || imageLe velId.inde xOf("image PdfDiv") = = -1) {
  14118                             return  true;
  14119                         }
  14120                         var zoomFa ctor;
  14121                         if(isNaN(l evel)) {
  14122                             zoomFa ctor = (pa rseFloat(l evel.split ("-")[1])) /100;
  14123                             level  = 4;
  14124                         }
  14125                         dicomViewe r.setPdfZo om(level,z oomFactor) ;
  14126                    } el se {
  14127                         if(seriesL ayout.imag eType ===  IMAGETYPE_ RADECG)
  14128                         {
  14129                             imageL evelId = " ecgData";
  14130                             var sp litArray =  seriesLay out.ecgZoo mLevelSett ings.toStr ing().spli t("_");
  14131                             if(spl itArray[0]  == 6 && s plitArray. length > 1  && level  == 6) {
  14132                                lev el = split Array[0] +  "_" + spl itArray[1] ;
  14133                             }
  14134                         }
  14135                         else if(se riesLayout .imageType  === IMAGE TYPE_CDA | | seriesLa yout.image Type === I MAGETYPE_R ADSR) {
  14136                             //HTML  files
  14137                             dicomV iewer.zoom SR(level);
  14138                             return  false;
  14139                         }
  14140                         var imageR ender = se riesLayout .getImageR ender(imag eLevelId);
  14141                         if(imageRe nder)
  14142                         {
  14143                             imageR ender.setZ oomLevel(l evel);
  14144                             var cu stomValue  = 0; 
  14145                             var zo omLevel =  level;
  14146                             if((le vel.toStri ng()).inde xOf("6_zoo m") >=0 )  {
  14147                                 cu stomValue  = parseInt (level.spl it("-")[1] );
  14148                                 zo omLevel =  customValu e > 0 ? 6  : 2;
  14149                             }
  14150  
  14151                             var ec gZoomPrope rty = {
  14152                                 le vel : zoom Level,
  14153                                 cu stomValue  : customVa lue
  14154                             };
  14155                             series Layout.ecg ZoomProper ty = ecgZo omProperty ;
  14156                         }
  14157                    }
  14158                });
  14159           }
  14160           $( "#"+id).pa rent().css ("backgrou nd","#8686 96");
  14161       }
  14162  
  14163       functi on refresh Image() {
  14164           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  14165           $( "#" + seri esLayout.g etSeriesLa youtId() +  " div").e ach(functi on () {
  14166                var imag eLevelId =  $(this).a ttr('id');
  14167                var imag eRender =  seriesLayo ut.getImag eRender(im ageLevelId );
  14168                if (imag eRender) {
  14169                    imag eRender.re nderImage( false);
  14170                }
  14171           }) ;
  14172       }
  14173           
  14174      functio n moveSeri es(increme ntFlag)
  14175       {
  14176           va r seriesLa yout =  di comViewer. getActiveS eriesLayou t();
  14177                    var  studyUid =  seriesLay out.getStu dyUid();
  14178           va r activeSe riesIndex  = parseInt (seriesLay out.series Index);
  14179           va r sereisLa youtId = s eriesLayou t.getSerie sLayoutId( );
  14180           di comViewer. setimageCa nvasOfView Port(serei sLayoutId) ;
  14181           va r numberOf Series = d icomViewer .Study.get SeriesCoun t(studyUid );
  14182           va r imageAnd FrameIndex  = dicomVi ewer.scrol l.getCurre ntImageAnd FrameIndex (increment Flag, seri esLayout);
  14183           va r imageInd ex = image AndFrameIn dex[0];
  14184           va r frameInd ex = image AndFrameIn dex[1];
  14185           va r imageCou nt = dicom Viewer.Ser ies.getIma geCount(st udyUid,act iveSeriesI ndex);
  14186           va r muliFram eImageInde x;
  14187           va r seriesIn dex;
  14188  
  14189           va r imageVal ue = dicom Viewer.Ser ies.Image. getImage(s tudyUid, a ctiveSerie sIndex,ima geIndex);
  14190                    var  framecount  =0;
  14191           if (imageValu e === unde fined) ret urn;
  14192           fr amecount =  dicomView er.Series. Image.getI mageFrameC ount(image Value);
  14193           va r isImageT humbnails  = dicomVie wer.thumbn ail.isSeri esContains Multiframe (studyUid, activeSeri esIndex)
  14194           va r thumbnai lId;
  14195           if  (incremen tFlag)
  14196           {
  14197                if(isIma geThumbnai ls)
  14198                {
  14199                    muli FrameImage Index = pa rseInt(ima geIndex) +  1;
  14200                         seriesInde x = active SeriesInde x;
  14201                    if(m uliFrameIm ageIndex > = imageCou nt){
  14202                         muliFrameI mageIndex  = 0;
  14203                         seriesInde x = series Index +1;
  14204                         if(numberO fSeries == = seriesIn dex)
  14205                             return ;
  14206                         imageCount  = dicomVi ewer.Serie s.getImage Count(stud yUid,serie sIndex);
  14207                    }
  14208                }else
  14209                {
  14210                    muli FrameImage Index = 0;
  14211                    seri esIndex =  activeSeri esIndex +  1;
  14212                }
  14213                if(serie sIndex ==  numberOfSe ries){
  14214                    retu rn;
  14215                }
  14216           }
  14217           el se
  14218           {
  14219                if(isIma geThumbnai ls)
  14220                {
  14221                    muli FrameImage Index = pa rseInt(ima geIndex) -  1;
  14222                    seri esIndex =  activeSeri esIndex;
  14223                    if(m uliFrameIm ageIndex <  0){
  14224                         seriesInde x = series Index -1;
  14225                         if(seriesI ndex === - 1)
  14226                             return ;
  14227                         imageCount  = dicomVi ewer.Serie s.getImage Count(stud yUid,serie sIndex);
  14228                         muliFrameI mageIndex  = imageCou nt -1; 
  14229  
  14230                    }
  14231                }
  14232                else
  14233                {
  14234                    muli FrameImage Index = 0;
  14235                    var  studyDetia ls = dicom Viewer.get StudyDetai ls(studyUi d);
  14236                    if(s tudyDetial s) {
  14237                         var isMult iframe = d icomViewer .thumbnail .isSeriesC ontainsMul tiframe(st udyUid, ac tiveSeries Index - 1) ;
  14238                         if(isMulti frame) {
  14239                             var se ries = dic omViewer.S eries.getS eries(stud yUid, acti veSeriesIn dex - 1);
  14240                             if(ser ies) {
  14241                                 mu liFrameIma geIndex =  (series.im ageCount -  1) < 0 ?  0 : (serie s.imageCou nt - 1);
  14242                             }
  14243                         }
  14244                    }
  14245  
  14246                    seri esIndex =  activeSeri esIndex -  1;
  14247                }
  14248                            
  14249                if(serie sIndex < 0  ) {
  14250                    retu rn;
  14251                }
  14252           }
  14253           se riesLayout .setSeries Index(seri esIndex);
  14254                    imag eValue = d icomViewer .Series.Im age.getIma ge(studyUi d, seriesI ndex,muliF rameImageI ndex);
  14255                    fram ecount =0;
  14256            s eriesLayou t.imageTyp e = imageV alue.image Type;
  14257           if (imageValu e != undef ined) fram ecount = d icomViewer .Series.Im age.getIma geFrameCou nt(imageVa lue);
  14258           va r studyDiv  = getStud yLayoutId( seriesLayo ut.seriesL ayoutId);
  14259           va r imageLay outDisplay Id = "imag eDisplay"+ studyDiv;
  14260           // frame coun t is great er than on e we displ ayin image s based on  the mulfr ame images  in the sa me series
  14261           if (dicomView er.thumbna il.isSerie sContainsM ultiframe( studyUid,s eriesIndex ))
  14262           {
  14263                thumbnai lId = "ima geviewer_" +dicomView er.replace DotValue(s tudyUid)+" _"+(series Index)+"_t humb"+(mul iFrameImag eIndex);
  14264                if(serie sLayout.im ageType != = IMAGETYP E_JPEG) {
  14265                    docu ment.getEl ementById( imageLayou tDisplayId ).style.di splay= 'bl ock';
  14266                }
  14267           }
  14268           el se
  14269           {
  14270                thumbnai lId = "ima geviewer_" +dicomView er.replace DotValue(s tudyUid)+" _"+(series Index)+"_t humb";
  14271                imageCou nt = dicom Viewer.Ser ies.getIma geCount(st udyUid,ser iesIndex);
  14272                if( imag eCount > 1  && series Layout.ima geType !==  IMAGETYPE _JPEG)
  14273                    docu ment.getEl ementById( imageLayou tDisplayId ).style.di splay= 'bl ock';
  14274                else 
  14275                    docu ment.getEl ementById( imageLayou tDisplayId ).style.di splay='non e';
  14276           }
  14277           di splayImage (seriesLay out,series Index,muli FrameImage Index, tru e);
  14278           di comViewer. setStudyTo olBarTools (seriesLay out);
  14279           va r modality  = dicomVi ewer.Serie s.getModal ity(series Layout.stu dyUid, ser iesLayout. seriesInde x);
  14280           if (modality  == "CT") {
  14281                updateKe ndoArrowBu tton($("#w inL_wrappe r"), false );
  14282                dicomVie wer.update Preset(ser iesLayout) ;
  14283           }
  14284           va r thumbnai lRenderer  = dicomVie wer.thumbn ail.getThu mbnail(thu mbnailId);
  14285           //  If the th umbnail is  available  to render er then re turn the m ethod.
  14286           if  (thumbnai lRenderer  == undefin ed)
  14287                {
  14288                         return;
  14289                }
  14290           if (thumbnail Renderer.i mageCountO fSeries==u ndefined)
  14291                thumbnai lRenderer. imageCount OfSeries =  1;
  14292           // Display th e thumbnai l selectio n based on  next or p revious bu ttons
  14293           di comViewer. thumbnail. selectImag eThumbnail (thumbnail Renderer.s eriesIndex ,muliFrame ImageIndex );
  14294                    dico mViewer.sc roll.stopC ineImage(  undefined  );
  14295                    
  14296           if (dicomView er.Series. Image.getI mageFrameC ount(image Value)>1)  {
  14297                dicomVie wer.startC ine();
  14298                updatePl ayIcon("pl ay.png", " stop.png") ;
  14299               } else {
  14300                   dicom Viewer.scr oll.stopCi neImage(un defined);
  14301                   updat ePlayIcon( "stop.png" , "play.pn g");
  14302               }
  14303           va r imageLay out = seri esLayout.g etImageLay outDimensi on().split ("x");
  14304           di comViewer. tools.chan geImageLay out(parseI nt(imageLa yout[0]),p arseInt(im ageLayout[ 1]));
  14305           
  14306           // While manu ally movin g to the n ext/previo us series  with the c ine player , updating  the toolb ar buttons  status
  14307           va r isCinePl ay = dicom Viewer.scr oll.isCine Running(se riesLayout .getSeries LayoutId() );
  14308           sh owOrHideIn CineRunnin g(modality , isCinePl ay, isCine Play);
  14309           if (!isCinePl ay) {
  14310                dicomVie wer.enable OrDisableT ools(modal ity, serie sLayout);
  14311           }
  14312           En ableDisabl eNextSerie sImage(ser iesLayout) ;
  14313           di comViewer. changeSele ction(seri esLayout.s eriesLayou tId);
  14314           di comViewer. setDefault CursorType (modality,  seriesLay out);
  14315       }
  14316  
  14317       
  14318       functi on display Image(seri esLayout,s eriesIndex ,imageInde x, isMoveS eries) {
  14319           va r studyUid  = seriesL ayout.getS tudyUid();
  14320           va r image =  dicomViewe r.Series.I mage.getIm age(studyU id, series Index,imag eIndex);
  14321           va r imageUid  = dicomVi ewer.Serie s.Image.ge tImageUid( image);
  14322           va r imagePro mise = dic omViewer.i mageCache. getImagePr omise(imag eUid+"_"+0 );
  14323           if (imageProm ise === un defined) {
  14324                //TODO c ache
  14325           }
  14326           se riesLayout .setSeries Index(pars eInt(serie sIndex));
  14327           se riesLayout .setImageI ndex(image Index);
  14328           se riesLayout .setFrameI ndex(0);
  14329           se riesLayout .setImageC ount(dicom Viewer.Ser ies.getIma geCount(st udyUid, se riesIndex) );
  14330  
  14331           va r playerBu ttonImage  = $("#play Button_wra pper img") [0].src;
  14332           if ( (dicomVi ewer.scrol l.isToPlay Study(seri esLayout.s eriesLayou tId)) && p layerButto nImage.ind exOf("stop .png") > - 1 ) {
  14333                dicomVie wer.scroll .loadimage s(seriesLa yout,parse Int(series Index),ima geIndex,0) ;
  14334           }  else {
  14335                seriesLa yout.remov eAllImageR enders();
  14336                var imag eLayout =  seriesLayo ut.getImag eLayoutDim ension().s plit("x");
  14337                dicomVie wer.setIma geLevelLay out(studyU id, parseI nt(imageLa yout[0]),  parseInt(i mageLayout [1]), seri esLayout.s eriesLayou tId,series Layout,ser iesIndex,  imageIndex ,0, isMove Series);
  14338          }
  14339       }
  14340  
  14341       functi on firstTi meImageLoa d() {
  14342           if  (isFirstT imeImageLo ad) {
  14343                isFirstT imeImageLo ad = false ;
  14344                return t rue;
  14345           }  else {
  14346                return f alse;
  14347           }
  14348       }
  14349           
  14350           fu nction len gthCalibra tion() {
  14351           $( "#lengthCa librationA lert").htm l('');
  14352           do cument.get ElementByI d("unit"). selectedIn dex = 0;
  14353           do cument.get ElementByI d("calibra teLength") .value = " ";
  14354           do cument.get ElementByI d("applyTo AllImages" ).checked  = false;
  14355           $( "#lengthCa librationA lert").rem oveClass(' alert-dang er');
  14356           $( "#lengthCa librationM odal" ).di alog({ dia logClass:  'no-close'  });
  14357           $( "#lengthCa librationM odal").dia log('open' );
  14358       }
  14359  
  14360       /**
  14361        * Set  the selec ted study  layout
  14362        * @pa ram {Type}  row - Spe cifies the  rows
  14363        * @pa ram {Type}  column -  Specifies  the column s
  14364        * @pa ram {Type}  isWrapper  - Specifi es the ove rflow
  14365        */ 
  14366       functi on setSele ctedStudyL ayout(row,  column, i sWrapper)  {
  14367           tr y
  14368           {
  14369                // Remov e selected  table row s
  14370                var appl ySelectedC ell;
  14371                for(var  rows = 0 ; rows < 9;  rows++ ) {
  14372                    appl ySelectedC ell = $(". tableCell" )[rows];
  14373                    $(ap plySelecte dCell).rem oveClass(" selectedCe ll");
  14374                }
  14375  
  14376                // Apply  selected  table row  and column s
  14377                var cInc  = 0;
  14378                for(var  rows = 0 ; rows < row ; rows++ )  {
  14379                    for( var column s = 0 ;col umns < col umn; colum ns++ ) {
  14380                         applySelec tedCell =  $(".tableC ell")[cInc +columns];
  14381                         $(applySel ectedCell) .addClass( "selectedC ell");
  14382                    }
  14383                    cInc  += 3;
  14384                }
  14385                // Displ ay row and  column te xt
  14386                var stud yId = row  + " x " +  column;
  14387                $('#tabl eDimmensio ns').html( studyId);
  14388           }
  14389           ca tch(e)
  14390           {  }
  14391       }
  14392  
  14393       /**
  14394        * Reo rder the e xising stu dy Uid to  maintain t he visibil e study in  the new s tudy layou t
  14395        */ 
  14396       functi on reOrder ExistingSt udyUids(is Resize) {
  14397           tr y
  14398           {
  14399                // Reset  the exist ing reorde red studyU ids
  14400                dicomVie wer.setReO rderedStud yUids(unde fined, tru e);
  14401  
  14402                var allV iewports =  dicomView er.viewpor ts.getAllV iewports() ;
  14403                if(allVi ewports == = null ||  allViewpor ts === und efined) {
  14404                    retu rn;
  14405                }
  14406  
  14407                var seri esLayouts  = [];
  14408                $.each(a llViewport s, functio n(key, val ue) {
  14409                    if(v alue.study Uid !== un defined ||  isResize)  {
  14410                         seriesLayo uts.push(v alue.serie sLayoutId) ;
  14411                    }
  14412                });
  14413  
  14414                // Sorti ng the ser ies layout  id
  14415                var exis tinngStudy Uids = [];
  14416                if(serie sLayouts.l ength > 0)  {
  14417                    seri esLayouts. sort();
  14418                    seri esLayouts. forEach(fu nction(vie wportId) {
  14419                         var viewpo rt = dicom Viewer.vie wports.get Viewport(v iewportId) ;
  14420                         if(viewpor t != null  && viewpor t != undef ined) {
  14421                             if(vie wport.stud yUid !== u ndefined | | isResize ) {
  14422                                 if (existinng StudyUids. indexOf(vi ewport.stu dyUid) ===  -1){
  14423                                      existinn gStudyUids .push(view port.study Uid);
  14424                                 }
  14425                             }
  14426                         } else if  (isResize)  {
  14427                             if(exi stinngStud yUids.inde xOf(viewpo rt.studyUi d) === -1) {
  14428                                      existinn gStudyUids .push(view port.study Uid);
  14429                             }
  14430                         }
  14431                    });
  14432                }
  14433  
  14434                if(exist inngStudyU ids.length  == 0) {
  14435                    dico mViewer.se tReOrdered StudyUids( undefined,  true);
  14436                }
  14437  
  14438                var stud yUids = di comViewer. getListOfS tudyUid();
  14439                if(study Uids !== u ndefined & & studyUid s !== null ) {
  14440                    stud yUids.forE ach(functi on(studyUi d) {
  14441                         if(existin ngStudyUid s.indexOf( studyUid)  == -1) {
  14442                             existi nngStudyUi ds.push(st udyUid);
  14443                         }
  14444                    });
  14445                }
  14446  
  14447                dicomVie wer.setReO rderedStud yUids(exis tinngStudy Uids, fals e);
  14448           }
  14449           ca tch(e)
  14450           {  }
  14451       }
  14452  
  14453       /**
  14454        * Get  or Set th e rearrang ed series  positions
  14455        * @pa ram {Type}  row - Spe cifies the  Row
  14456        * @pa ram {Type}  column -  Specifies  the Column
  14457        */ 
  14458       functi on getOrSe tReArrange dSeriesPos itions(row , column,  isDoubleCl ick, page)  {
  14459           tr y
  14460           {
  14461                var seri esLayout =  dicomView er.getActi veSeriesLa yout();
  14462                var seri esIndex =  seriesLayo ut.getSeri esIndex();
  14463                var imag eIndex = s eriesLayou t.scrollDa ta.imageIn dex;
  14464                var tota lSeriesLev elLayout =  row * col umn;
  14465                var imag eValue = d icomViewer .Series.Im age.getIma ge(seriesL ayout.stud yUid, seri esIndex, 0 );
  14466                var seri esCount =  dicomViewe r.Study.ge tSeriesCou nt(seriesL ayout.stud yUid);
  14467                var imag eCount = d icomViewer .Series.ge tImageCoun t(seriesLa yout.study Uid, serie sIndex);
  14468                var isMu ltiframe =  dicomView er.thumbna il.isImage Thumbnail( imageValue );
  14469                var imag eAndSeries Index = is Multiframe  ? imageIn dex : seri esIndex;
  14470                var imag eOrSeriesC ount = isM ultiframe  ? imageCou nt : serie sCount;
  14471  
  14472                // Initi alize the  rearranged  series po sition val ues
  14473                var sele ctThumbnai lImageInde x = series Layout.scr ollData.im ageIndex;
  14474                var actu alSeriesIn dex = imag eAndSeries Index;
  14475                var mult iFrameImag eIndex = 0 ;
  14476  
  14477                // Valid ate and as sign the i mage or se ries index
  14478                if(total SeriesLeve lLayout >  1) {
  14479                    var  totalViewp orts = tot alSeriesLe velLayout  + imageAnd SeriesInde x;
  14480                    if(t otalViewpo rts >= ima geOrSeries Count) {
  14481                         imageAndSe riesIndex  = (totalSe riesLevelL ayout > im ageOrSerie sCount ? 0  : imageOr SeriesCoun t - totalS eriesLevel Layout);
  14482                    }
  14483                }
  14484  
  14485                if(isMul tiframe ==  true) {
  14486                    mult iFrameImag eIndex = i mageAndSer iesIndex;
  14487                }
  14488  
  14489                // For m ixed modal ity study,  if one of  the serie s is multi frame and  while chan ging the s eries leve l layout b y selectin g other mo dality ser ies, movin g to the l ast image  for the pr evious mul tiframe se ries
  14490                var seri es = dicom Viewer.Ser ies.getSer ies(series Layout.stu dyUid, ser iesIndex,  0);
  14491                if(serie sLayout.ge tSeriesInd ex() > ima geAndSerie sIndex &&  !series.is keyImageSe ries) {
  14492                    //Ch ecking if  the previo us series  is multifr ame or not
  14493                    var  newImage =  dicomView er.Series. Image.getI mage(serie sLayout.st udyUid, im ageAndSeri esIndex, 0 );
  14494                    var  isImageThu mbnail = d icomViewer .thumbnail .isImageTh umbnail(ne wImage);
  14495                    if(i sImageThum bnail) {
  14496                         //Moving t o the last  image for  the multi frame seri es
  14497                         var imageO rSeries =  dicomViewe r.Series.g etSeries(s eriesLayou t.studyUid , seriesIn dex);
  14498                         multiFrame ImageIndex  = imageOr Series.ima geCount -  1;
  14499                         if(totalSe riesLevelL ayout > 3)  {
  14500                             if(mul tiFrameIma geIndex >=  totalSeri esLevelLay out-1) {
  14501                                 mu ltiFrameIm ageIndex++ ;
  14502                                 mu ltiFrameIm ageIndex =  multiFram eImageInde x - (total SeriesLeve lLayout-1) ;
  14503                             }
  14504                         }
  14505                    }
  14506                }
  14507                
  14508                // Set t he rearran ged series  positions
  14509                dicomVie wer.setReA rrangedSer iesPositio ns (
  14510                {
  14511                    mult iFrameImag eIndex : m ultiFrameI mageIndex,
  14512                    actu alSeriesIn dex : actu alSeriesIn dex,
  14513                    sele ctThumbnai lImageInde x : select ThumbnailI mageIndex,
  14514                    isVi ewPortDoub leClicked  : isDouble Click,
  14515                    page View: page
  14516                });
  14517  
  14518                return ( isMultifra me ? serie sIndex : i mageAndSer iesIndex);
  14519           }
  14520           ca tch(e)
  14521           {  }
  14522  
  14523           re turn undef ined;
  14524       }
  14525       
  14526       /**
  14527        * To  Change the  text of c ontext men u item of  study cach e indicato r
  14528        *  
  14529        */ 
  14530       functi on cacheIn dicator()  {
  14531           re setMenu();
  14532           sh owStudyCac heIndicato r = !showS tudyCacheI ndicator;
  14533           sh owCacheInd icator();
  14534           
  14535           if (showStudy CacheIndic ator) {
  14536                $(".cach eindicator ").text("H ide Cache  Indicator" );
  14537           }  else {
  14538                $(".cach eindicator ").text("S how Cache  Indicator" );
  14539           }
  14540       }
  14541  
  14542       /**
  14543        * Nee d to check  calibrati on values  is present  in the cu rrent imag e
  14544        *  
  14545        */ 
  14546       functi on isCalib erEnabled( render){
  14547           va r studyUid ;
  14548           va r seriesIn dex;
  14549           va r imageInd ex;
  14550           va r frameInd ex;
  14551           va r imageUid ;
  14552           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  14553           if (render &&  seriesLay out) {
  14554                studyUid  = seriesL ayout.getS tudyUid();
  14555                seriesIn dex = rend er.seriesI ndex
  14556                imageInd ex = rende r.imageInd ex
  14557                frameInd ex = (rend er.anUIDs) .split("*" )[1];
  14558                imageUid  = render. imageUid;
  14559           }  else if(se riesLayout ) {
  14560                studyUid  = seriesL ayout.getS tudyUid();
  14561                seriesIn dex = seri esLayout.s eriesIndex
  14562                imageInd ex = serie sLayout.ge tImageInde x()
  14563                frameInd ex = serie sLayout.sc rollData.f rameIndex
  14564                var imag e = dicomV iewer.Seri es.Image.g etImage(st udyUid, se riesIndex,  imageInde x);
  14565                imageUid  = dicomVi ewer.Serie s.Image.ge tImageUid( image);
  14566           }
  14567  
  14568           if (studyUid  != undefin ed && imag eUid != un defined) {
  14569                var cali bratedValu es = getUn itMeasurem entMap(stu dyUid+"|"+ seriesInde x+"|"+imag eIndex+"|" +frameInde x);
  14570                var dico mHeader =  dicomViewe r.header.g etDicomHea der(imageU id);
  14571                if(dicom Header.ima geInfo.mea surement ) {
  14572                    if(d icomHeader .imageInfo .measureme nt.pixelSp acing != n ull && dic omHeader.i mageInfo.m easurement .pixelSpac ing != und efined){
  14573                         if(dicomHe ader.image Info.measu rement.pix elSpacing. row <= 0 & & calibrat edValues = = null){
  14574                             return  true;
  14575                         }
  14576                    }
  14577                } else i f((calibra tedValues  == null) & & (dicomHe ader.image Info == un defined || dicomHeade r.imageInf o.measurem ent == und efined || 
  14578                           dicomHea der.imageI nfo.measur ement == n ull)) {
  14579                    retu rn true;
  14580                }
  14581           }
  14582           re turn false ;
  14583       }
  14584  
  14585       /**
  14586        * To  set the ca libration  tool as ac tiveTool
  14587        *  
  14588        */ 
  14589       functi on setCali brationAct iveTool(){
  14590           re setMenu();
  14591           $( "#context- length-cal ibration") .css("back ground","# 868696");
  14592           $( "#6_measur ement").cs s("backgro und","#868 696");
  14593           fl agFor2dLen gthCalibra tion = tru e;
  14594           di comViewer. mouseTools .setActive Tool(dicom Viewer.mou seTools.ge t2DLengthC alibration Tool());
  14595       }
  14596  
  14597       /**
  14598        * To  get the le ngth calib ration fla g
  14599        *  
  14600        */ 
  14601       functi on getLeng thCalibrat ionFlag(){
  14602           re turn isLen gthCalibra ting;
  14603       }
  14604  
  14605       /**
  14606        * To  set the le ngth calib ration fla g
  14607        *  
  14608        */ 
  14609       functi on setLeng thCalibrat ionFlag(fl ag){
  14610           is LengthCali brating =  flag;
  14611       }
  14612       
  14613       functi on doDefau lt()
  14614           {
  14615           re setMenu();
  14616           $( '#viewport _View').cs s('cursor' , 'default ');
  14617           di comViewer. measuremen t.setDataT oDelete();
  14618           va r tool = d icomViewer .mouseTool s.getActiv eTool();
  14619           to ol.hanleDo ubleClick( );
  14620  
  14621           di comViewer. mouseTools .setActive Tool(dicom Viewer.mou seTools.ge tDefaultTo ol());
  14622           //  refresh i mage so th at US regi ons appear
  14623           re freshImage ();
  14624       }
  14625  
  14626       /**
  14627        * To  set the co ntext menu  and too b ar measure ment item  selection
  14628        *  
  14629        */ 
  14630       functi on SetMenu SelectionC olor(toolN ame){
  14631           va r cursorOb j = docume nt.getElem entById('v iewport_Vi ew');
  14632           va r cursorNa me;
  14633           if (cursorObj  != undefi ned && cur sorObj !=  null){
  14634                cursorNa me = curso rObj.style .cursor;
  14635           }
  14636           if (toolName  == "lineMe asurement" ){
  14637                if(curso rName.inde xOf("image s/calibrat e.cur") >0 ){
  14638                    $("# context-le ngth-calib ration").c ss("backgr ound","#86 8696");
  14639                    $("# 6_measurem ent").css( "backgroun d","#86869 6");
  14640                } else i f(cursorNa me && curs orName.spl it("/")[1] .split("." )[0] == "a nnotatearr ow") {
  14641                    $("# context-ar row").css( "backgroun d","#86869 6");
  14642                    $("# 10_arrow") .css("back ground","# 868696");
  14643                } else i f(cursorNa me && curs orName.spl it("/")[1] .split("." )[0] == "a nnotatelin e") {
  14644                    $("# context-li ne").css(" background ","#868696 ");
  14645                    $("# 9_line").c ss("backgr ound","#86 8696");
  14646                }else {
  14647                    $("# context-le ngth").css ("backgrou nd","#8686 96");
  14648                    $("# 0_measurem ent").css( "backgroun d","#86869 6");
  14649                }
  14650           }  else if(to olName ==  "pointMeas urement"){
  14651                $("#cont ext-2dPoin t").css("b ackground" ,"#868696" );
  14652                $("#1_me asurement" ).css("bac kground"," #868696");
  14653           }  else if(to olName ==  "traceMeas urement" | | toolName  == "mitra lMeanGradi entMeasure ment"){
  14654                if(curso rName && c ursorName. split("/") [1].split( ".")[0] ==  "annotate freehand")  {
  14655                    $("# context-fr eehand").c ss("backgr ound","#86 8696");
  14656                    $("# 13_freehan d").css("b ackground" ,"#868696" );
  14657                } else {
  14658                    $("# context-tr ace").css( "backgroun d","#86869 6");
  14659                    $("# 2_measurem ent").css( "backgroun d","#86869 6");
  14660                }
  14661           }  else if(to olName ==  "volumeMea surement") {
  14662                $("#cont ext-volume ").css("ba ckground", "#868696") ;
  14663                $("#3_me asurement" ).css("bac kground"," #868696");
  14664           }  else if(to olName ==  "angleMeas urement"){
  14665                $("#cont ext-angle" ).css("bac kground"," #868696");
  14666                $("#angl e_measurem ent").css( "backgroun d","#86869 6");
  14667           }  else if(to olName ==  "ellipseMe asurement" ) {
  14668                if( curs orName &&  cursorName .split("/" )[1].split (".")[0] = = "annotat eellipse")  {
  14669                    $("# context-el lipse").cs s("backgro und","#868 696");
  14670                    $("# 11_ellipse ").css("ba ckground", "#868696") ;
  14671                } else {
  14672                    $("# context-ho unsfield-e llipse").c ss("backgr ound","#86 8696");
  14673                    $("# 7_measurem ent").css( "backgroun d","#86869 6");
  14674                }
  14675           }  else if(to olName ==  "rectangle Measuremen t"){
  14676                if( curs orName &&  cursorName .split("/" )[1].split (".")[0] = = "annotat erectangle ") {
  14677                    $("# context-re ctangle"). css("backg round","#8 68696");
  14678                    $("# 12_rectang le").css(" background ","#868696 ");
  14679                } else i f(cursorNa me && curs orName.spl it("/")[1] .split("." )[0] == "a nnotatetex t") {
  14680                    $("# context-te xt").css(" background ","#868696 ");
  14681                    $("# 8_text").c ss("backgr ound","#86 8696");
  14682                } else {
  14683                    $("# context-ho unsfield-r ectangle") .css("back ground","# 868696");
  14684                    $("# 14_measure ment").css ("backgrou nd","#8686 96");
  14685                }
  14686           }
  14687       }
  14688  
  14689        /**
  14690        * To  set the au to window  level
  14691        *  
  14692        */
  14693       functi on doWindo wLevelROI( e){
  14694           di comViewer. measuremen t.setDataT oDelete();
  14695           va r tool = d icomViewer .mouseTool s.getActiv eTool();
  14696           to ol.hanleDo ubleClick( );
  14697           $( '#viewport _View').cs s('cursor' ,'url(imag es/AutoWin dowLevel.c ur), auto' );
  14698           di comViewer. mouseTools .setActive Tool(dicom Viewer.mou seTools.ge tWindowToo lROI());
  14699  
  14700           //  refresh i mage so th at US regi ons appear
  14701           re freshImage ();
  14702       }
  14703  
  14704       /**
  14705        * 
  14706        * Pri nt
  14707        */ 
  14708       functi on doPrint () {
  14709           do PrintLayou t(false);
  14710       }
  14711  
  14712       /**
  14713        * Pri nt
  14714        */ 
  14715       functi on doExpor t() {
  14716           do PrintLayou t(true);
  14717       }
  14718  
  14719       /**
  14720        * Pri nt
  14721        * @pa ram {Type}  isExport  - Specifie s theflag  to export
  14722        */ 
  14723       var pr intOrExpor tWnd = nul l;
  14724       functi on printLa yout(isExp ort) {
  14725           tr y
  14726           {
  14727                var seri esLayout =  dicomView er.getActi veSeriesLa yout();
  14728                if(serie sLayout == = undefine d || serie sLayout == = null) {
  14729                    retu rn;
  14730                }
  14731  
  14732                var isEc g = series Layout.ima geType ===  IMAGETYPE _RADECG ?  true : fal se;
  14733                var isPd f = (isEmb edPdfViewe r(seriesLa yout.image Type)) ? t rue : fals e;
  14734  
  14735                var imag eRender =  isEcg ? se riesLayout .getImageR ender("ecg Data") : 
  14736                seriesLa yout.getIm ageRender( getClicked ViewportId ()) ;
  14737  
  14738                if(isEcg ) {
  14739                    imag eRender =  seriesLayo ut.getImag eRender("e cgData");
  14740                } else i f(isPdf) {
  14741                    imag eRender =  seriesLayo ut.getImag eRender("p dfData");
  14742                } else {
  14743                    imag eRender =  seriesLayo ut.getImag eRender(ge tClickedVi ewportId() ) ? 
  14744                                    seriesLayo ut.getImag eRender(ge tClickedVi ewportId() ) :
  14745                                    seriesLayo ut.getImag eRender(se riesLayout .seriesLay outId+"Ima geLevel0x0 ");
  14746                }
  14747  
  14748                var seri es = dicom Viewer.Ser ies.getSer ies(series Layout.stu dyUid, ser iesLayout. seriesInde x);
  14749                if(serie s === null  || series  === undef ined) {
  14750                    retu rn;
  14751                }
  14752  
  14753                var desc ription =  series.des cription;
  14754                if(descr iption ===  undefined  || descri ption ===  null) {
  14755                    desc ription =  "";
  14756                }
  14757  
  14758                var prin tOption =  $("#PrintZ oomOptions ").val();
  14759                printOpt ion = pars eInt(print Option);
  14760                var imag eDataUrl =  undefined ;
  14761                var isHt ml = false ;
  14762                var font Size = 12. 75;
  14763  
  14764                var prin tContent =  '<!DOCTYP E html>';
  14765                printCon tent += '< head><titl e>';
  14766                printCon tent += (i sExport? " Export" :  "Print") +  " image -  " + descr iption;
  14767                printCon tent += '< /title></h ead>';
  14768                printCon tent += '< body>';
  14769  
  14770                if(image Render) {
  14771  
  14772                    if(i sEcg) {
  14773                         imageDataU rl = image Render.Pre pareECGPri nt(printOp tion)
  14774                         if(!imageD ataUrl) {
  14775                             dumpCo nsoleLogs( LL_ERROR,  undefined,  "printLay out", "Fai led to pri nt the ima ge/report. \nPrint co ntent is e mpty.");
  14776                             return ;
  14777                         }
  14778  
  14779                         var ecgDiv Id = docum ent.getEle mentById(" ecgDataDiv _" + serie sLayout.se riesLayout Id);
  14780                         if(isExpor t) {
  14781                             export Ecg(ecgDiv Id, printC ontent, im ageDataUrl , imageRen der, print Option);
  14782                             return ;
  14783                         }
  14784  
  14785                         if(printOp tion == 1)  {
  14786                             fontSi ze = fontS ize * pars eFloat(ima geRender.t empEcgScal e);
  14787                         }
  14788  
  14789                         printConte nt += "<di v style=fo nt-size:"  + fontSize  + "px>" +  ecgDivId. innerHTML  + "</div>" ;
  14790                         printConte nt += '<im g src="' +  imageData Url + '">' ;
  14791  
  14792                    } el se if(isPd f) {
  14793                         var printI mageIndex  = $("#prin tLayoutMod al")[0].pr intImageIn dex;
  14794                         var imageD ataUrls =  [];
  14795                         $("#printL ayoutModal ")[0].imag eData = {
  14796                             imageD ataUrls :[ ],
  14797                             count: 0
  14798                         };
  14799                        
  14800                         for(var in dex = 0; i ndex< prin tImageInde x.length;  index++) {  
  14801                             var pr intData =  {
  14802                                 is Export: is Export,
  14803                                 pr intContent  : printCo ntent,
  14804                                 to talPages:  printImage Index.leng th,
  14805                                 pr intOption:  printOpti on,
  14806                                 pr intStaus :  true
  14807                             };
  14808  
  14809                             imageD ataUrl = i mageRender .preparePd fPrint(pri ntData, pr intImageIn dex[index] , function (canvas, p rintData){ printPdfCa llback(can vas, print Data)});
  14810                         }
  14811  
  14812                    } el se {
  14813                         var printI mageIndex  = $("#prin tLayoutMod al")[0].pr intImageIn dex;
  14814                         var imageD ataUrls =  [];
  14815  
  14816                         //get the  imagecanve s
  14817                         for(var in dex = 0; i ndex< prin tImageInde x.length;  index++) {
  14818                             var is Multiframe  = dicomVi ewer.thumb nail.isSer iesContain sMultifram e(seriesLa yout.study Uid, serie sLayout.se riesIndex) ;
  14819  
  14820                             var im ageIndex =  printImag eIndex[ind ex]-1;
  14821                             var is Valid = fa lse;
  14822                             if(isM ultiframe  && seriesL ayout.imag eType != I MAGETYPE_R AD) {
  14823                                 im ageIndex =  0; 
  14824                                 is Valid = tr ue;
  14825                             }
  14826                             var im age = dico mViewer.Se ries.Image .getImage( seriesLayo ut.studyUi d, seriesL ayout.seri esIndex, i mageIndex) ;
  14827  
  14828                             if(!im age) {
  14829                                 co ntinue;
  14830                             }
  14831  
  14832                             var im ageCanvasD ata;
  14833                             var im ageUid = i mage.image Uid;
  14834                             if(isV alid) {
  14835                                 va r loadImag eDeferred  = dicomVie wer.getIma ge(seriesL ayout.stud yUid, imag eUid, prin tImageInde x[index]-1 , seriesLa yout.serie sIndex);
  14836                                 lo adImageDef erred.done (function( imageCanva s) {
  14837                                      var logM essage = " Frame Numb er => " +  imageCanva s.frameNum ber + "\n  \
  14838                                                          Series Ind ex => " +  seriesLayo ut.seriesI ndex + "\n  \
  14839                                                          ImageUid = > " + imag eCanvas.im ageUid + " \n \
  14840                                                          ImageIndex  => " + pr intImageIn dex[index] -1;
  14841                                      dumpCons oleLogs(LL _INFO, und efined, "p rintLayout ", logMess age);
  14842                                      imageCan vasData =  imageCanva s;
  14843                                      var defe rred = $.D eferred();
  14844                                      deferred .resolve(i mageCanvas );
  14845                                 }) ;
  14846                             } else  {
  14847                                 va r imagePro mise = dic omViewer.i mageCache. getImagePr omise(imag eUid +"_"+  (0));
  14848  
  14849                                 if (!imagePro mise) {
  14850                                      continue ;
  14851                                 }
  14852  
  14853                                 im agePromise .then(func tion(image ){
  14854                                      imageCan vasData =  image;
  14855                                 }) ;
  14856                             }
  14857  
  14858                             var pr esentation  = imageRe nder.prese ntationSta te ? image Render.pre sentationS tate : ima geCanvasDa ta.present ation;
  14859  
  14860                             if(ima geCanvasDa ta){
  14861                                 va r imageCan vas = docu ment.creat eElement(" canvas");
  14862  
  14863                                 va r dicominf o = imageC anvasData. dicominfo;
  14864                                 if ((dicominf o.imageInf o.numberOf Frames > 1  && dicomi nfo.imageI nfo.modali ty === "US ") || dico minfo.imag eInfo.imag eType ===  IMAGETYPE_ JPEG) {
  14865                                      imageCan vas = imag eCanvasDat a.imageDat a;
  14866                                 }  else {
  14867                                      dicomVie wer.update Image(imag eCanvas,im ageCanvasD ata,presen tation);
  14868                                 }
  14869                                 im ageCanvas. imageCanva sData = im ageCanvasD ata;
  14870                                 im ageDataUrl  = imageRe nder.prepa reLayoutPr int(printO ption, ima geCanvas);
  14871                                 im ageDataUrl s.push(ima geDataUrl) ;
  14872                             }
  14873                         }
  14874  
  14875                         if(!imageD ataUrls.le ngth) {
  14876                             dumpCo nsoleLogs( LL_ERROR,  undefined,  "printLay out", "Fai led to pri nt the ima ge/report. \nPrint co ntent is e mpty.");
  14877                             return ;
  14878                         }
  14879  
  14880                         var imageL ayoutDimen sion = ser iesLayout. imageLayou tDimension ;
  14881                         var dimens ion = imag eLayoutDim ension.spl it("x");
  14882                         var rows =  dimension [0];
  14883                         var column s = dimens ion[1];
  14884  
  14885                         //set the  layout
  14886                         if(imageDa taUrls.len gth !== ro ws * colum ns){
  14887                             var in dex = imag eDataUrls. length > 9  ? 9 :imag eDataUrls. length;
  14888                             switch (index)
  14889                             {
  14890                                 ca se 1:
  14891                                      {
  14892                                          rows  = 1; colu mns = 1; b reak;
  14893                                      }
  14894                                 ca se 2:
  14895                                      {
  14896                                          rows  = 1; colu mns = 2; b reak;
  14897                                      }
  14898                                 ca se 3:
  14899                                      {
  14900                                          rows  = 1; colu mns = 3; b reak;
  14901                                      }
  14902                                 ca se 4:
  14903                                      {
  14904                                          rows  = 2; colu mns = 2; b reak;
  14905                                      }
  14906                                 ca se 5:
  14907                                 ca se 6:
  14908                                      {
  14909                                          rows  = 2; colu mns = 3; b reak;
  14910                                      }
  14911                                 ca se 7:
  14912                                 ca se 8:
  14913                                 ca se 9:
  14914                                      {
  14915                                          rows  = 3; colu mns = 3; b reak;
  14916                                      }
  14917                                 de fault:
  14918                                      {
  14919                                          rows  = 0; colu mns = 0; b reak;
  14920                                          retu rn;
  14921                                      }
  14922                             }
  14923                         }
  14924  
  14925                         printConte nt += '<ta ble>'
  14926                         var index  = 0;
  14927                         for(var ro w = 0; row  < rows; r ow++){
  14928                             printC ontent +=  '<tr>'
  14929                             for(va r col = 0;  col < col umns; col+ +) {
  14930                                 pr intContent  += '<td>< img src="'  + imageDa taUrls[ind ex++] + '" ></td>'
  14931                             }
  14932                             printC ontent +=  '</tr>'
  14933                         }
  14934                         printConte nt += '</t able>'
  14935  
  14936                    }
  14937                } else {
  14938                    if($ ("#" + ser iesLayout. seriesLayo utId)[0].i sHtml) {
  14939                         var htmlId  = $("#" +  seriesLay out.series LayoutId)[ 0].HtmlId;
  14940                         imageDataU rl = docum ent.getEle mentById(h tmlId).inn erHTML;
  14941                         isHtml = t rue;
  14942                         if(printOp tion == 1)  {
  14943                             fontSi ze = parse Float($("# " + htmlId ).css("fon t-size"));
  14944                         }
  14945  
  14946                         if(!imageD ataUrl) {
  14947                             dumpCo nsoleLogs( LL_ERROR,  undefined,  "printLay out", "Fai led to pri nt the ima ge/report. \nPrint co ntent is e mpty.");
  14948                             return ;
  14949                         }
  14950                         if(isExpor t) {
  14951                             export Html($("#"  + seriesL ayout.seri esLayoutId ), printCo ntent);
  14952                             return ;
  14953                         }
  14954                         printConte nt += "<di v style=fo nt-size:"+ fontSize+" px>" + ima geDataUrl  + "</div>" ;
  14955                    }
  14956                }
  14957  
  14958                printCon tent += '< /body>';
  14959                printCon tent += '< /html>';
  14960  
  14961                var prin tDialog =  printOrExp ortWnd;
  14962                if(!prin tDialog) {
  14963                    prin tDialog =  window.ope n('','Prin t','');
  14964                }
  14965  
  14966                if(!isPd f) {
  14967                    prin tDialog.do cument.ope n();
  14968                    prin tDialog.do cument.wri te(printCo ntent);
  14969                    prin tDialog.do cument.clo se();
  14970  
  14971                    if(i sExport) {
  14972                         return;
  14973                    }
  14974  
  14975                    if(i sInternetE xplorer())  {
  14976                         printDialo g.focus();
  14977                         printDialo g.print();
  14978                         printDialo g.close();
  14979                         return;
  14980                    }
  14981  
  14982                    prin tDialog.wi ndow.setTi meout(func tion () {
  14983                         printDialo g.focus();
  14984  
  14985                         if(printDi alog.onaft erprint == = null) {
  14986                             printD ialog.onaf terprint =  function( ) {
  14987                                 pr intDialog. close();
  14988                             };
  14989                         }
  14990                         printDialo g.print();
  14991  
  14992                         if(printDi alog.onaft erprint == = undefine d) {
  14993                             printD ialog.wind ow.setTime out(functi on () {
  14994                                 pr intDialog. close();
  14995                             }, 300 0);  
  14996                         }
  14997                    }, 2 00);
  14998                }
  14999           }
  15000           ca tch(e)
  15001           {  }
  15002       }
  15003  
  15004       functi on printPd fCallback  (printCanv as, printD ata) {
  15005           tr y
  15006           {
  15007                var imag eDataUrl;
  15008                if(print Canvas &&  printCanva s.canvas)  {
  15009                    imag eDataUrl =  printCanv as.canvas. toDataURL( 'image/jpe g', 1.0);
  15010                }
  15011  
  15012                if(image DataUrl) {
  15013                    $("# printLayou tModal")[0 ].imageDat a.imageDat aUrls.push (imageData Url);
  15014                }
  15015  
  15016                if( ++$( "#printLay outModal") [0].imageD ata.count  !== printD ata.totalP ages) {
  15017                    retu rn;
  15018                }
  15019  
  15020                var imag eDataUrls  = $("#prin tLayoutMod al")[0].im ageData.im ageDataUrl s;
  15021                var prin tContent =  printData .printCont ent;
  15022  
  15023                if(!imag eDataUrls. length) {
  15024                    dump ConsoleLog s(LL_ERROR , undefine d, "printL ayout", "F ailed to p rint the i mage/repor t.\nPrint  content is  empty.");
  15025                    retu rn;
  15026                }
  15027  
  15028                printCon tent += '< table>'
  15029                var inde x = 0;
  15030                for(var  row = 0; r ow < image DataUrls.l ength; row ++) {
  15031                    prin tContent + = '<tr>'
  15032                    for( var col =  0; col < 1 ; col++) {
  15033                         printConte nt += '<td ><img src= "' + image DataUrls[i ndex++] +  '"></td>'
  15034                    }
  15035                    prin tContent + = '</tr>'
  15036                }
  15037                printCon tent += '< /table>'
  15038  
  15039                printCon tent += '< /body>';
  15040                printCon tent += '< /html>';
  15041  
  15042                var prin tDialog =  printOrExp ortWnd;
  15043                if(!prin tDialog) {
  15044                    prin tDialog =  window.ope n('','Prin t','');
  15045                }
  15046  
  15047                printDia log.docume nt.open();
  15048                printDia log.docume nt.write(p rintConten t);
  15049                printDia log.docume nt.close() ;
  15050  
  15051                if(print Data.isExp ort) {
  15052                    retu rn;
  15053                }
  15054  
  15055                if(isInt ernetExplo rer()) {
  15056                    prin tDialog.fo cus();
  15057                    prin tDialog.pr int();
  15058                    prin tDialog.cl ose();
  15059                    retu rn;
  15060                }
  15061  
  15062                printDia log.window .setTimeou t(function  () {
  15063                    prin tDialog.fo cus();
  15064  
  15065                    if(p rintDialog .onafterpr int === nu ll) {
  15066                         printDialo g.onafterp rint = fun ction() {
  15067                             printD ialog.clos e();
  15068                         };
  15069                    }
  15070                    prin tDialog.pr int();
  15071  
  15072                    if(p rintDialog .onafterpr int === un defined) {
  15073                         printDialo g.window.s etTimeout( function ( ) {
  15074                             printD ialog.clos e();
  15075                         }, 3000);   
  15076                    }
  15077                }, 200);
  15078           }
  15079           ca tch(e)
  15080           {  }
  15081       }
  15082  
  15083       /**
  15084        * To  Change the  text of c ontext men u item for  link tool
  15085        *
  15086        */
  15087       functi on linkSer ies() {
  15088           re setMenu();
  15089  
  15090           di comViewer. measuremen t.setDataT oDelete();
  15091           va r tool = d icomViewer .mouseTool s.getActiv eTool();
  15092           to ol.hanleDo ubleClick( );
  15093  
  15094           di comViewer. mouseTools .setActive Tool(dicom Viewer.mou seTools.ge tLinkTool( ));
  15095           if  (dicomVie wer.link.i sSeriesLin ked()) {
  15096                var img  = document .getElemen tById('lin kButton'). children[0 ];
  15097                img.src  = 'images/ link.png';
  15098                updateTo olTip($("# linkButton "), "Link" );
  15099                dicomVie wer.link.u nLinkSerie s();
  15100                $('#view port_View' ).css('cur sor', 'def ault');
  15101           }  else {
  15102                $('#view port_View' ).css('cur sor','url( images/lin k.cur), au to');
  15103                dicomVie wer.link.l inkSeries( );
  15104           }
  15105  
  15106           //  refresh i mage so th at US regi ons appear
  15107           re freshImage ();
  15108       }
  15109  
  15110       functi on doXRefL ineSelecti on() {
  15111           tr y
  15112           {
  15113                dicomVie wer.measur ement.setD ataToDelet e();
  15114                var tool  = dicomVi ewer.mouse Tools.getA ctiveTool( );
  15115                tool.han leDoubleCl ick();
  15116  
  15117                dicomVie wer.mouseT ools.setAc tiveTool(d icomViewer .mouseTool s.getXRefL ineSelecti onTool());
  15118                refreshI mage();
  15119           }
  15120           ca tch(e)
  15121           {  }
  15122       }
  15123  
  15124       /**
  15125        *Copy  the prese nation pro perty 
  15126        */ 
  15127       functi on doCopyA ttributes( ) {
  15128           tr y
  15129           {
  15130                dicomVie wer.measur ement.setD ataToDelet e();
  15131                var tool  = dicomVi ewer.mouse Tools.getA ctiveTool( );
  15132                tool.han leDoubleCl ick();
  15133                var acti veSeries =   dicomVie wer.getAct iveSeriesL ayout();
  15134                if(activ eSeries ==  undefined  || active Series ==  null) {
  15135                    retu rn;
  15136                }
  15137  
  15138                var imag eLayoutId  =undefined ;
  15139                $("#" +  activeSeri es.getSeri esLayoutId () + " div ").each(fu nction(){
  15140                    imag eLayoutId  = $(this). attr('id') ;
  15141                });
  15142  
  15143                if(image LayoutId = = undefine d || image LayoutId = = null) {
  15144                    retu rn;
  15145                }
  15146  
  15147                if(activ eSeries.im ageLayoutD imension ! == "1x1")  {
  15148                    imag eLayoutId  = activeSe ries.serie sLayoutId  + "ImageLe vel0x0";
  15149                }
  15150  
  15151                var copy Attributes Data = act iveSeries. getImageRe nder(image LayoutId);
  15152                var tool  = dicomVi ewer.mouse Tools.getC opyAttribu tesTool();
  15153                tool.set CopyAttrib utesData
  15154                (
  15155                    {
  15156                         sourceId:  activeSeri es.getSeri esLayoutId (),
  15157                         data: copy Attributes Data,
  15158                         studyUid:  activeSeri es.studyUi d,
  15159                         imageType:  activeSer ies.imageT ype
  15160                    }
  15161                );
  15162                dicomVie wer.mouseT ools.setAc tiveTool(t ool);
  15163           }
  15164           ca tch(e)
  15165           {  }
  15166       }
  15167  
  15168       /**
  15169        * Sho w/Hide the  annotatio ns/measure ments
  15170        */ 
  15171       functi on doShowH ideAnnotat ionAndMeas urement()  {
  15172           tr y
  15173           {
  15174                annotati onAndMeasu rementVisi bleStatus  = !annotat ionAndMeas urementVis ibleStatus
  15175                annotati onAndMeasu rementVisi bleStatus  ? $("#4_me asurement" ).show() :  $("#4_mea surement") .hide() ;
  15176                var menu InnerText  = annotati onAndMeasu rementVisi bleStatus  ? "Hide An notation /  Measureme nt" : "Sho w Annotati on / Measu rement" ;
  15177                document .getElemen tById("sho wHideAnnot aionAndMes urement"). innerText  = menuInne rText;
  15178                document .getElemen tById("sho wHideAnnot aionAndMes urement_ov erflow").i nnerText =  menuInner Text;
  15179                var allV iewports =  dicomView er.viewpor ts.getAllV iewports() ;
  15180  
  15181                for (var  key in al lViewports ) {
  15182                    var  viewportTe mp = allVi ewports[ke y];
  15183                    $("# " + viewpo rtTemp.get SeriesLayo utId() + "  div").eac h(function () {
  15184                         var imageL ayoutId =  $(this).at tr('id');
  15185                         var imageR ender = vi ewportTemp .getImageR ender(imag eLayoutId) ;
  15186                         if(imageRe nder) {
  15187                             imageR ender.draw DicomImage ();
  15188                         }
  15189                    });
  15190                }
  15191           }
  15192           ca tch(e)
  15193           {  }
  15194       }
  15195  
  15196       /**
  15197        * set  the show/ hide measu rement and  annotatio n flag 
  15198        */ 
  15199       functi on isShowA nnotationa ndMeasurem ent(){
  15200           re turn annot ationAndMe asurementV isibleStat us;
  15201       }
  15202  
  15203       /**
  15204        * Get  the 6000  overlay vi sibility f lag
  15205        */ 
  15206       functi on is6000O verlayVisi ble() {
  15207           re turn is600 0Overlay; 
  15208       }
  15209  
  15210       /**
  15211        * Sho w/Hide the  6000 over lay
  15212        */ 
  15213       functi on doOverL ay6000() {
  15214           is 6000Overla y = !is600 0Overlay;
  15215           va r menuInne rText = (i s6000Overl ay ? "Hide " : "Show" ) + " Over lay 6000";
  15216           do cument.get ElementByI d("showHid eOverlay60 00").inner Text = men uInnerText ;
  15217           do cument.get ElementByI d("showHid eOverlay60 00_overflo w").innerT ext = menu InnerText;    
  15218           va r allViewp orts = dic omViewer.v iewports.g etAllViewp orts();
  15219           fo r (var key  in allVie wports) {
  15220                var view portTemp =  allViewpo rts[key];
  15221                $("#" +  viewportTe mp.getSeri esLayoutId () + " div ").each(fu nction() {
  15222                    var  imageLayou tId = $(th is).attr(' id');
  15223                    var  imageRende r = viewpo rtTemp.get ImageRende r(imageLay outId);
  15224                    if(i mageRender ) {
  15225                         imageRende r.renderIm age(false) ;
  15226                    }
  15227                });
  15228           }
  15229       }
  15230  
  15231       /**
  15232        * Do  Print or E xport imag e/Report 
  15233        * @pa ram {Type}  option -  Specifies  the option
  15234        * @pa ram {Type}  isVerifie d - Specif ies the fl ag to veri fied
  15235        * @pa ram {Type}  isExport  - Specifie s the flag  to export
  15236        */ 
  15237       functi on doPrint OrExport(i sVerified,  isExport,  printReas on) {
  15238           tr y
  15239           {
  15240                if(isVer ified) {
  15241                    $("# printImage Window").d ata("IsExp ort", isEx port);
  15242                    $('# printImage Window').d ata("callb ack", func tion(signa ture, reas on, isExpo rt) {
  15243                         if(hasExpo rtOrPrintP rivilege(r eason)) {
  15244                             Create AndWriteDu mmyPrintOr ExportCont ent(isExpo rt);
  15245                             if(ise SignatureV alidated(s ignature))  {
  15246                                 pr intLayout( isExport);
  15247                             } else  {
  15248                                 up datePrintS tatus("Fai led to ver ify the eS ignature") ;
  15249                                 $( "#alert-pr intImage") .show();
  15250                                 $( "#alert-pr intImage") .removeCla ss('alert- info').add Class('ale rt-danger' );
  15251                                 $( "#alert-pr intImage") .html('Fai led to ver ify the eS ignature') ;
  15252                                 $( "#printLay outModal") .dialog("o pen");
  15253                                 $( "#printIma geWindow") .dialog("o pen");
  15254                                 $( "#reasonFo rPrintImag e").val(re ason);
  15255                             }
  15256                         } else {
  15257                             update PrintStatu s("Failed  to verify  the " + (i sExport ?  "export" :  "print")  + " image  access");
  15258                         }
  15259                    });
  15260                    $('# printImage Window').d ialog('opt ion', 'tit le', (isEx port ? "Ex port" : "P rint"));
  15261                    $("# printImage Window").d ialog("ope n");
  15262                } else i f(printRea son){
  15263                    doVe rifyAndExp ort(printR eason, isE xport);
  15264                } else {
  15265                    prin tLayout(is Export);
  15266                }
  15267           }
  15268           ca tch(e)
  15269           {  }
  15270       }
  15271  
  15272       /**
  15273        * upd ate the pr int/export  status
  15274        */ 
  15275       functi on updateP rintStatus (reason)
  15276       {
  15277           tr y {
  15278                printOrE xportWnd.d ocument.ge tElementBy Id("printE xportStatu s").innerH TML = reas on;
  15279                printOrE xportWnd.w indow.setT imeout(fun ction() {
  15280                    prin tOrExportW nd.close() ;
  15281                    prin tOrExportW nd = null;
  15282                },1000)
  15283           }
  15284           ca tch(e)
  15285           {  }
  15286       }
  15287  
  15288       /**
  15289        * Cre ate the du mmy print  or export  status
  15290        */ 
  15291       functi on CreateA ndWriteDum myPrintOrE xportConte nt(isExpor t) {
  15292           tr y
  15293           {
  15294                if(print OrExportWn d) {
  15295                    prin tOrExportW nd.close() ;
  15296                    prin tOrExportW nd = null;
  15297                }
  15298  
  15299                var prin tContent =  '<!DOCTYP E html>';
  15300                printCon tent += '< head><titl e>';
  15301                printCon tent += (i sExport ?  "Exporting " : "Print ing") + "  Image";
  15302                printCon tent += '< /title></h ead>';
  15303                printCon tent += '< body>';
  15304                printCon tent += "< div id=pri ntExportSt atus style ='backgrou nd:black;c olor:white ;text-alig n:center;f ont-size:l arger;heig ht:95vh;li ne-height: 95vh'>" +  (isExport  ? "Exporti ng" : "Pri nting") +  " Image... " + "</div >";
  15305                printCon tent += '< /body>';
  15306                printCon tent += '< /html>';
  15307                printOrE xportWnd =  window.op en('','_bl ank','');
  15308                printOrE xportWnd.d ocument.op en();
  15309                printOrE xportWnd.d ocument.wr ite(printC ontent);
  15310                printOrE xportWnd.d ocument.cl ose();
  15311  
  15312                // Watch  the windo w close
  15313                var time r = setInt erval(func tion() { 
  15314                    if(p rintOrExpo rtWnd && p rintOrExpo rtWnd.clos ed) {
  15315                         clearInter val(timer) ;
  15316                         printOrExp ortWnd = n ull;
  15317                    }
  15318                }, 1000) ;
  15319           }
  15320           ca tch(e)
  15321           {  }
  15322       }
  15323  
  15324       /**
  15325        * 
  15326        * @pa ram {Type}  reason -  Specifies  the export  reason
  15327        * @pa ram {Type}  option -  Spectifies  the expor t option
  15328        * @pa ram {Type}  isExport  - Specify  the flag t o export
  15329        */ 
  15330       functi on doVerif yAndExport (reason, i sExport) {
  15331           tr y {
  15332                var t0 =  Date.now( );
  15333                dumpCons oleLogs(LL _INFO, und efined, "d oVerifyAnd Export ",  "Start");
  15334                if(hasEx portOrPrin tPrivilege (reason))  {
  15335                    prin tLayout(is Export)
  15336                }
  15337           }
  15338           ca tch(e)
  15339           {
  15340                dicomVie wer.measur ement.show AndHideSpl ashWindow( "error", " Failed to  verify the  print ima ge access" );
  15341                dumpCons oleLogs(LL _ERROR, un defined, " doVerifyAn dExport",  e.message)
  15342           }
  15343           fi nally {
  15344                dumpCons oleLogs(LL _INFO, und efined, "d oVerifyAnd Export ",  "End", (Da te.now() -  t0));
  15345           }
  15346       }
  15347  
  15348       /**
  15349        * Ver ify the eS ignature
  15350        * @pa ram {Type}  signature  - Specifi es the dig ital signa ture
  15351        */ 
  15352       functi on iseSign atureValid ated(signa ture) {
  15353           tr y
  15354           {
  15355                var t0 =  Date.now( );
  15356                dumpCons oleLogs(LL _INFO, und efined, "p rintOrExpo rtImages " , "Start") ;
  15357  
  15358                dicomVie wer.measur ement.show AndHideSpl ashWindow( "show", "V erifying e Signature. ..","dicom Viewer");
  15359                var iseS ignatureVa lid = fals e;
  15360                $.ajax({
  15361                    type : 'GET',
  15362                    url:  dicomView er.Metadat a.eSignatu reUrl(sign ature),
  15363                    data : "",
  15364                    asyn c: false
  15365                })
  15366                .success (function( data) {
  15367                    iseS ignatureVa lid = true ;
  15368                })
  15369                .fail(fu nction(dat a, textSta tus, error Thrown) {
  15370                    dico mViewer.me asurement. showAndHid eSplashWin dow("error ", "Failed  to verify  the eSign ature");
  15371                })
  15372                .error(f unction(da ta, status ) {
  15373                    dico mViewer.me asurement. showAndHid eSplashWin dow("error ", "Failed  to verify  the eSign ature");
  15374                });
  15375  
  15376                return i seSignatur eValid;
  15377           }
  15378           ca tch(e)
  15379           {
  15380                dumpCons oleLogs(LL _ERROR, un defined, u ndefined,  e.message)
  15381           }
  15382           fi nally {
  15383                dumpCons oleLogs(LL _INFO, und efined, un defined, " End", (Dat e.now() -  t0));
  15384           }
  15385  
  15386           re turn false ;
  15387       }
  15388  
  15389       /**
  15390        * Che ck whether  print pri vilege is  there or n ot for the  given pri nt reason
  15391        * @pa ram {Type}  reason -  Specify th e print re ason
  15392        */ 
  15393       functi on hasExpo rtOrPrintP rivilege(r eason) {
  15394           tr y
  15395           {
  15396                var seri esLayout =  dicomView er.getActi veSeriesLa yout();
  15397                if(serie sLayout == = undefine d || serie sLayout == = null) {
  15398                    retu rn false;
  15399                }
  15400  
  15401                var seri esIndex =  undefined;
  15402                var imag eIndex = u ndefined;
  15403                if($("#"  + seriesL ayout.seri esLayoutId )[0].isHtm l) {
  15404                    seri esIndex =  seriesLayo ut.seriesI ndex;
  15405                    imag eIndex = 0 ;
  15406                } else {
  15407  
  15408                    if(i sEmbedPdfV iewer(seri esLayout.i mageType))  {
  15409                         imageRende r = series Layout.get ImageRende r("pdfData ");
  15410                    } el se {
  15411                         imageRende r = series Layout.ima geType ===  IMAGETYPE _RADECG ?  seriesLayo ut.getImag eRender("e cgData") :  seriesLay out.getIma geRender(g etClickedV iewportId( ));
  15412                    }
  15413  
  15414                    if(i mageRender  === undef ined || im ageRender  === null)  {
  15415                         return fal se;
  15416                    }
  15417  
  15418                    seri esIndex =  imageRende r.seriesIn dex;
  15419                    imag eIndex = i mageRender .imageInde x;
  15420                }
  15421  
  15422                var imag eUrn = dic omViewer.S eries.Imag e.getImage Urn(series Layout.stu dyUid, ser iesIndex,  imageIndex );
  15423                if(!imag eUrn) {
  15424                    dump ConsoleLog s(LL_ERROR , undefine d, "hasExp ortOrPrint Privilege" , "Failed  to get ima geUrn");
  15425                    retu rn false;
  15426                }
  15427  
  15428                var hasE xportOrPri ntPrivileg e = false;
  15429                dicomVie wer.measur ement.show AndHideSpl ashWindow( "show", "V erifying p rint image  access... ","dicomVi ewer");
  15430                $.ajax({
  15431                    type : 'GET',
  15432                    url:  dicomView er.getLogE xportUrl() ,
  15433                    data : {reason:  reason, i mageUrn: i mageUrn},
  15434                    asyn c: false
  15435                })
  15436                .success (function( data) {
  15437                    hasE xportOrPri ntPrivileg e = true;
  15438                })
  15439                .fail(fu nction(dat a, textSta tus, error Thrown) {
  15440                    dico mViewer.me asurement. showAndHid eSplashWin dow("error ", "Failed  to verify  the print  image acc ess");
  15441                })
  15442                .error(f unction(da ta, status ) {
  15443                    dico mViewer.me asurement. showAndHid eSplashWin dow("error ", "Failed  to verify  the print  image acc ess");
  15444                });
  15445  
  15446                return h asExportOr PrintPrivi lege;
  15447           }
  15448           ca tch(e)
  15449           {  }
  15450  
  15451           re turn false ;
  15452       }
  15453  
  15454       /**
  15455        * Exp ort the Ht ml elemten ts using h tml to can vas method
  15456        * @pa ram {Type}  divId - s pecifies t he div id
  15457        * @pa ram {Type}  printCont ent - spec ifies the  print cont ent
  15458        */ 
  15459       functi on exportH tml(divId,  printCont ent) {
  15460           tr y
  15461           {
  15462                html2can vas(divId,  {
  15463                    onre ndered: fu nction(can vas) {
  15464                         printConte nt += '<im g src="' +  canvas.to DataURL('i mage/jpeg' , 1.0) + ' ">';
  15465                         printConte nt += '</b ody>';
  15466                         printConte nt += '</h tml>';
  15467                         var printD ialog = pr intOrExpor tWnd;
  15468                         if(!printD ialog) {
  15469                             printD ialog = wi ndow.open( '','Print' ,'');
  15470                         }
  15471                         printDialo g.document .open();
  15472                         printDialo g.document .write(pri ntContent) ;
  15473                         printDialo g.document .close();
  15474                    }
  15475                });
  15476           }
  15477           ca tch(e)
  15478           {  }
  15479       }
  15480  
  15481       /**
  15482        * Exp ort the Ec g image us ing html t o canvas m ethod
  15483        * @pa ram {Type}  ecgDivId  - specifie s the ecg  div id
  15484        * @pa ram {Type}  printCont ent - spec ifies the  print cont ent
  15485        * @pa ram {Type}  imageData Url - spec ifies the  image data  Url
  15486        * @pa ram {Type}  imageRend er - speci fies the i mage rende r object
  15487        * @pa ram {Type}  printOpti on - speci fies the p rint optio n
  15488        */ 
  15489       functi on exportE cg(ecgDivI d, printCo ntent, ima geDataUrl,  imageRend er, printO ption) {
  15490           tr y
  15491           {
  15492                html2can vas(ecgDiv Id, {
  15493                    onre ndered: fu nction(can vas) {
  15494                         var printC anvas = do cument.cre ateElement ("canvas") ;
  15495                         var ecgDat aId = $("# imageEcgCa nvas" + im ageRender. seriesLeve lDivId);
  15496                         var scaleV alue = 1;
  15497                         if(printOp tion == 1)  {
  15498                             scaleV alue = par seFloat(im ageRender. tempEcgSca le);
  15499                         }
  15500  
  15501                         var ecgDat aWidth = i mageRender .ecgData.w idth * sca leValue;
  15502                         var ecgDat aHeight =  imageRende r.ecgData. height * s caleValue;
  15503                         printCanva s.width =  ecgDivId.c lientWidth   > ecgDat aWidth ? e cgDivId.cl ientWidth  : ecgDataW idth;
  15504                         printCanva s.height =  ecgDivId. clientHeig ht + ecgDa taHeight;
  15505                         var printC ontext = p rintCanvas .getContex t('2d');
  15506                         printConte xt.clearRe ct(0,0,pri ntCanvas.w idth,print Canvas.hei ght);
  15507                         printConte xt.fillSty le = 'whit e';
  15508                         printConte xt.fillRec t(0, 0, pr intCanvas. width, pri ntCanvas.h eight);
  15509                         printConte xt.save();
  15510                         var ecgDiv Obj = new  Image();
  15511                         var ecgDat aObj = new  Image();
  15512                         ecgDivObj. src = canv as.toDataU RL('image/ jpeg', 1.0 );
  15513                         ecgDivObj. onload = f unction()  {
  15514                             printC ontext.dra wImage(ecg DivObj, 0,  0);
  15515                             ecgDat aObj.src =  imageData Url;
  15516                             ecgDat aObj.onloa d = functi on() {
  15517                                 pr intContext .drawImage (ecgDataOb j, 0, ecgD ivId.clien tHeight);
  15518                                 pr intContext .restore() ;
  15519                                 pr intContent  += '<img  src="' + p rintCanvas .toDataURL ('image/jp eg', 1.0)  + '">';
  15520                                 pr intContent  += '</bod y>';
  15521                                 pr intContent  += '</htm l>';
  15522                                 va r printDia log = prin tOrExportW nd;
  15523                                 if (!printDia log) {
  15524                                      printDia log = wind ow.open('' ,'Print',' ');
  15525                                 }
  15526                                 pr intDialog. document.o pen();
  15527                                 pr intDialog. document.w rite(print Content);
  15528                                 pr intDialog. document.c lose();
  15529                             }
  15530                         };
  15531                    }
  15532                });
  15533           }
  15534           ca tch(e)
  15535           {  }
  15536       }
  15537  
  15538       /**
  15539        * Ret urns the c urrent mou se cursor  type/name
  15540        */ 
  15541       functi on getCurs orType() {
  15542           tr y
  15543           {
  15544                var curs orObj = do cument.get ElementByI d('viewpor t_View');
  15545                var curs orName;
  15546                if(curso rObj != un defined &&  cursorObj  != null){
  15547                    curs orName = c ursorObj.s tyle.curso r;
  15548                }
  15549  
  15550                if(curso rName != n ull && cur sorName !=  undefined ) {
  15551                    curs orName = ( (cursorNam e = cursor Name.split ("/")[1])  == undefin ed) ? "def ault" : cu rsorName.s plit(".")[ 0];
  15552                }
  15553  
  15554                return c ursorName;
  15555           }
  15556           ca tch(e)
  15557           {  }
  15558       }
  15559  
  15560       /**
  15561        * dra w the mens urated sca le
  15562        */ 
  15563       functi on doMenus ratedScale () {
  15564           tr y
  15565           {
  15566                isMenusr atedScaleV isible = ! isMenusrat edScaleVis ible;
  15567                var menu InnerText  = (isMenus ratedScale Visible ?  "Hide" : " Show") + "  Mensurate d Scale";
  15568                document .getElemen tById("con text-Mensu ratedScale ").innerTe xt = menuI nnerText;
  15569                document .getElemen tById("sho wHideMensu ratedScale ").innerTe xt = menuI nnerText;
  15570                document .getElemen tById("sho wHideMensu ratedScale _overflow" ).innerTex t = menuIn nerText;
  15571                var allV iewports =  dicomView er.viewpor ts.getAllV iewports() ;
  15572                for (var  key in al lViewports ) {
  15573                    var  viewportTe mp = allVi ewports[ke y];
  15574                    $("# " + viewpo rtTemp.get SeriesLayo utId() + "  div").eac h(function () {
  15575                         var imageL ayoutId =  $(this).at tr('id');
  15576                         var imageR ender = vi ewportTemp .getImageR ender(imag eLayoutId) ;
  15577                         if(imageRe nder) {
  15578                             imageR ender.show OrHideOver lay(isMenu sratedScal eVisible,  viewportTe mp.studyUi d);
  15579                         }
  15580                    });
  15581                }
  15582           }
  15583           ca tch(e)
  15584           {  }
  15585       }
  15586  
  15587       /**
  15588        * ret urn the me nusurated  scale valu e
  15589        */ 
  15590       functi on isVisib leMensurat edScale ()  {
  15591           tr y
  15592           {
  15593                return i sMenusrate dScaleVisi ble;
  15594           }
  15595           ca tch(e)
  15596           {  }
  15597       }
  15598       
  15599       /**
  15600        * Mov es to prev ious page
  15601        * @pa ram {Type}
  15602        */ 
  15603       functi on movePre viousPage( ) {
  15604           do PageNaviga tion("prev ");
  15605       }
  15606       
  15607       /**
  15608        * Mov es to next  page
  15609        * @pa ram {Type}
  15610        */ 
  15611       functi on moveNex tPage() {
  15612           do PageNaviga tion("next ");
  15613       }
  15614  
  15615       /**
  15616        * Do  the page n avigation
  15617        * @pa ram {Type}  type - Sp ecidy the  navigation  type 
  15618        */ 
  15619       functi on doPageN avigation( type) {
  15620           tr y
  15621           {
  15622                var navi gation =   getNavigat ionType(ty pe);
  15623                if (navi gation.ind exArrays ! == null &&  navigatio n.indexArr ays !== un defined) {
  15624                    var  length = n avigation. indexArray s.length;
  15625                    var  firstIndex  = navigat ion.indexA rrays[0];
  15626                    var  lastIndex  = navigati on.indexAr rays[lengt h - 1];
  15627                    if ( navigation .isOrderUd pated ===  false) {
  15628                         if(type == = "next")  {
  15629                             var di ff = navig ation.tota lCount - l astIndex -  1;
  15630                             if (di ff <= leng th) {
  15631                                 fi rstIndex =  navigatio n.totalCou nt - lengt h;
  15632                                 la stIndex =  navigation .totalCoun t - 1;
  15633                             } else  {
  15634                                 fi rstIndex + = length;
  15635                                 la stIndex +=  length;
  15636                             }
  15637                         } else {
  15638                             if (fi rstIndex <  length) {
  15639                                 fi rstIndex =  0;
  15640                                 la stIndex =  length - 1 ;
  15641                             } else  {
  15642                                 fi rstIndex - = length;
  15643                                 la stIndex -=  length;
  15644                             }
  15645                         }
  15646                    }
  15647  
  15648                    chan gePageLayo ut(navigat ion, first Index, las tIndex);
  15649                    post PageNaviga tion((type  === "next " ? lastIn dex : firs tIndex), n avigation. totalCount );
  15650                }
  15651           }
  15652           ca tch(e)
  15653           {  }
  15654       }
  15655       
  15656       /**
  15657        * Nav igate thro ugh pages
  15658        */ 
  15659       functi on changeP ageLayout  (navigatio n, firstIn dex, lastI ndex) {
  15660           tr y
  15661           {
  15662                var page  = {
  15663                    type : navigati on.type,
  15664                    firs t: firstIn dex,
  15665                    last : lastInde x,
  15666                    id:  navigation .studyLayo ut,
  15667                    seri esIndex: n avigation. seriesInde x,
  15668                    imag eIndex: na vigation.i mageIndex,
  15669                    isMu ltiFrame:  navigation .isMultiFr ame
  15670                };
  15671                var rowC ol = navig ation.layo ut.split(' x');
  15672                if (navi gation.typ e === "ser ies") {
  15673                    chan geSeriesLa yout(rowCo l[0], rowC ol[1], und efined, pa ge);
  15674                } else i f (navigat ion.type = == "image"  || naviga tion.type  === "frame ") {
  15675                    chan geImageLay out(rowCol [0], rowCo l[1], unde fined, pag e);
  15676                }
  15677  
  15678                // Selec t the thum bnail
  15679                var seri esLayout =  dicomView er.getActi veSeriesLa yout();
  15680                var seri esIndex =  seriesLayo ut.getSeri esIndex();
  15681                var imag eIndex = s eriesLayou t.scrollDa ta.imageIn dex;
  15682  
  15683                dicomVie wer.thumbn ail.select ImageThumb nail(serie sIndex, im ageIndex);
  15684           }
  15685           ca tch(e)
  15686           {  }
  15687       }
  15688       
  15689       /**
  15690        * Ena ble/Disabl e controls  after pag e navigati on
  15691        * @pa ram {Type}
  15692        */ 
  15693       functi on postPag eNavigatio n(index, t otalCount)  {
  15694           if  (index ==  0) {
  15695                showOrHi dePageNavi gation("fi rst");
  15696           }  else if (i ndex == to talCount -  1) {
  15697                showOrHi dePageNavi gation("la st");
  15698           }  else {
  15699                showOrHi dePageNavi gation("sh ow");
  15700           }
  15701       }
  15702       
  15703       /**
  15704        * Get  parameter s for perf orming pag e navigati on
  15705        */ 
  15706       functi on getNavi gationType  (directio n) {
  15707           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  15708           if  (seriesLa yout === u ndefined | | seriesLa yout === n ull) {
  15709                return;
  15710           }
  15711  
  15712           va r selected StudyUid =  seriesLay out.getStu dyUid();
  15713           va r selected SeriesInde x = series Layout.get SeriesInde x();
  15714           va r isMultiF rame = dic omViewer.t humbnail.i sSeriesCon tainsMulti frame(sele ctedStudyU id, select edSeriesIn dex);
  15715           va r seriesLa youtMaxId  = isFullSc reenEnable d ? dicomV iewer.getC urrentSeri esLayoutId s() : dico mViewer.vi ewports.ge tSeriesLay outMaxId() ;
  15716           va r seriesco unt = dico mViewer.St udy.getSer iesCount(s electedStu dyUid);
  15717           va r imagecou nt = dicom Viewer.Ser ies.getIma geCount(se lectedStud yUid, sele ctedSeries Index);
  15718           va r selected ImageIndex  = seriesL ayout.getI mageIndex( );
  15719           va r framecou nt = dicom Viewer.Ser ies.Image. getImageFr ameCount(d icomViewer .Series.Im age.getIma ge(selecte dStudyUid,  selectedS eriesIndex , selected ImageIndex ));
  15720           if (seriesLay outMaxId ! == undefin ed) {
  15721                var rowC olumnValue  = seriesL ayoutMaxId .split('_' )[2];
  15722                var imag eLayoutDim  = seriesL ayout.getI mageLayout Dimension( );
  15723                var stud yLayoutId  = getStudy LayoutId(s eriesLayou t.seriesLa youtId);
  15724                var type , range, l ayout, tot alCount;
  15725                if (isMu ltiFrame)  {
  15726                    if ( rowColumnV alue === " 1x1") {
  15727                         type = "im age";
  15728                         range = "f rame";
  15729                         layout = i mageLayout Dim;
  15730                         totalCount  = frameco unt;
  15731                    } el se {
  15732                         type = "se ries";
  15733                         range = "i mage";
  15734                         layout = r owColumnVa lue;
  15735                         totalCount  = imageco unt;
  15736                    }
  15737                } else i f (rowColu mnValue == = "1x1") {
  15738                    type  = "image" ;
  15739                    rang e = "image ";
  15740                    layo ut = image LayoutDim;
  15741                    tota lCount = i magecount;
  15742                    imag eIndex = - 1;
  15743                } else {
  15744                    type  = "series ";
  15745                    rang e = "serie s";
  15746                    layo ut = rowCo lumnValue;
  15747                    tota lCount = s eriescount ;
  15748                    imag eIndex = - 1;
  15749                }
  15750                var imag eIndex = r ange === " frame" ? s electedIma geIndex :  -1;
  15751                var navi gation = {
  15752                    type : type,
  15753                    inde xArrays: f indIndexRa nge(range) ,
  15754                    tota lCount: to talCount,
  15755                    layo ut: layout ,
  15756                    stud yLayout: s tudyLayout Id,
  15757                    seri esIndex: s electedSer iesIndex,
  15758                    imag eIndex: im ageIndex,
  15759                    isMu ltiFrame:  isMultiFra me,
  15760                    isOr derUdpated : false
  15761                };
  15762                if (navi gation.typ e === "ser ies") {
  15763                    var  index = is MultiFrame  ? selecte dImageInde x : select edSeriesIn dex;
  15764                    var  viewportOr der = chec kViewportO rder(navig ation.inde xArrays, n avigation. indexArray s.length,  index, nav igation.to talCount,  direction) ;
  15765                    navi gation.ind exArrays =  viewportO rder.index Arrays;
  15766                    navi gation.isO rderUdpate d = viewpo rtOrder.is OrderUdpat ed;
  15767                }
  15768  
  15769                return n avigation;
  15770           }
  15771       }
  15772       
  15773        /**
  15774        * Che ck whether  the viewp orts are i n proper o rder
  15775        * @pa ram {Type}  indexArra ys 
  15776        */ 
  15777       functi on checkVi ewportOrde r(indexArr ays, lengt h, selecte dIndex, li mit, direc tion) {
  15778           va r startInd ex = -1;
  15779           va r endIndex  = -1;
  15780           va r isOrderU dpated = f alse;
  15781  
  15782           va r isOutOfO rder = fal se;
  15783           fo r (var i=0 ; i<indexA rrays.leng th-1; i++)  {
  15784                if (Math .abs(index Arrays[i+1 ] - indexA rrays[i])  > 1) {
  15785                    isOu tOfOrder =  true;
  15786                    brea k;
  15787                }
  15788           }
  15789           
  15790           if  (isOutOfO rder) {
  15791                indexArr ays = [];
  15792                if (dire ction ===  "prev") {
  15793                    star tIndex = s electedInd ex - lengt h;
  15794                    endI ndex = sel ectedIndex  - 1;
  15795                    if ( startIndex  < 0) {
  15796                         startIndex ++;
  15797                         endIndex++ ;
  15798                    }
  15799                } else i f (directi on === "ne xt") {
  15800                    star tIndex = s electedInd ex + 1;
  15801                    endI ndex = sel ectedIndex  + length;
  15802                    if ( endIndex = = limit) {
  15803                         startIndex --;
  15804                         endIndex-- ;
  15805                    }
  15806                }
  15807                for (sta rtIndex; s tartIndex  <= endInde x; startIn dex++) {
  15808                    inde xArrays.pu sh(startIn dex);
  15809                }
  15810                isOrderU dpated = t rue;
  15811                return {  indexArra ys : index Arrays, is OrderUdpat ed : isOrd erUdpated  };
  15812           }
  15813           re turn { ind exArrays :  indexArra ys, isOrde rUdpated :  isOrderUd pated };
  15814       }
  15815  
  15816       /**
  15817        * 
  15818        */ 
  15819       functi on doBrigh tnessContr ast(e)
  15820       {
  15821           re setMenu();
  15822           di comViewer. measuremen t.setDataT oDelete();
  15823           va r tool = d icomViewer .mouseTool s.getActiv eTool();
  15824           to ol.hanleDo ubleClick( );
  15825           $( '#viewport _View').cs s('cursor' ,'url(imag es/brightn ess.cur),  auto');
  15826           di comViewer. mouseTools .setActive Tool(dicom Viewer.mou seTools.ge tBrightnes sContrastT ool());
  15827  
  15828           //  refresh i mage so th at US regi ons appear
  15829           re freshImage ();
  15830       }
  15831       
  15832       /**
  15833        * Sho ws measure ment prope rties
  15834        * @pa ram {Type}   
  15835        */ 
  15836       functi on showMea surementPr operties()  {
  15837           $( "#Measurem entPropert iesModal") .dialog('o pen');
  15838       }
  15839       
  15840       /**
  15841        * Sho ws user pr eferences
  15842        * @pa ram {Type}   
  15843        */ 
  15844       functi on showUse rPreferenc es() {
  15845          $(" #content_V iew").find ('.resp-ta b-active') .removeCla ss('resp-t ab-active' ).css({
  15846                'backgro und-color' : '#363636 ',
  15847                'border- color': 'n one'
  15848           }) ;
  15849           $( "#settingP reference" ).modal();
  15850       }
  15851  
  15852       /**
  15853        * 
  15854        * Pri nt
  15855        */ 
  15856       functi on doPrint Layout(isE xport) {
  15857  
  15858           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  15859           $( "#PrintLay outOptions ").val(ser iesLayout. imageLayou tDimension );
  15860  
  15861           va r imageLay outDimensi on = serie sLayout.im ageLayoutD imension;
  15862           va r dimensio n = imageL ayoutDimen sion.split ("x");
  15863           im ageLayoutD imension =  dimension [0] * dime nsion[1];
  15864  
  15865           va r displayT ext;
  15866           va r isMultif rame = dic omViewer.t humbnail.i sSeriesCon tainsMulti frame(seri esLayout.s tudyUid, s eriesLayou t.seriesIn dex);
  15867  
  15868           va r count =  0
  15869           va r pdfRende r;
  15870           va r pdfData;
  15871           if (isEmbedPd fViewer(se riesLayout .imageType )) {
  15872                pdfRende r = series Layout.get ImageRende r("pdfData ");
  15873                if(pdfRe nder) {
  15874                    pdfD ata = pdfR ender.pdfD ata;
  15875                }
  15876           }
  15877  
  15878           if (isMultifr ame) {
  15879                var imag evalue = d icomViewer .Series.Im age.getIma ge(seriesL ayout.stud yUid, seri esLayout.s eriesIndex , seriesLa yout.getIm ageIndex() );
  15880  
  15881                if(image value ) {
  15882                    coun t =  image value.numb erOfFrames ;
  15883                }
  15884           }  else {
  15885                count =  dicomViewe r.Series.g etImageCou nt(seriesL ayout.stud yUid, seri esLayout.s eriesIndex );
  15886           }
  15887  
  15888           co unt = pdfD ata ? pdfD ata.pageCo unt : coun t;
  15889           $( "#PrintIma ge_Range") .addClass( "k-state-d isabled");
  15890           do cument.get ElementByI d('PrintIm age_Range' ).readOnly   =  true;
  15891  
  15892           $( "#printLay outModal") [0].printR angeMax =  1;
  15893           $( "#imageRan geLabel"). hide();
  15894           if (count !==  undefined  && count  > 1) {
  15895                $("#prin tLayoutMod al")[0].pr intRangeMa x = count;
  15896                var coun tStart = 1
  15897                if(!pdfD ata) {
  15898                    $("# imageRange Label").sh ow();
  15899                    $("# PrintImage _Range").r emoveClass ("k-state- disabled") ;
  15900                    docu ment.getEl ementById( 'PrintImag e_Range'). readOnly   = false;
  15901                }
  15902                $("#imag eRangeLabe l").text(" [ " + coun tStart +"  to " + (co unt) + " ] ");
  15903           }
  15904  
  15905           if (seriesLay out.imageT ype == IMA GETYPE_RAD ECG) {
  15906                var imag eRender =  seriesLayo ut.getImag eRender("e cgData");
  15907                if(image Render) {
  15908                    var  imageIndex  = imageRe nder.image Index;
  15909                    disp layText =  (displayTe xt == unde fined) ? ( parseInt(i mageIndex)  + 1) : di splayText  + ", " + ( parseInt(i mageIndex)  + 1);
  15910                }
  15911           }  else if($( "#" + seri esLayout.s eriesLayou tId)[0].is Html) {
  15912                displayT ext = 1;
  15913           }  else if(pd fData) {
  15914                displayT ext = pdfD ata.curren tPageNumbe r;
  15915           }  else {
  15916                $("#" +  seriesLayo ut.getSeri esLayoutId () + " div ").each(fu nction() {
  15917                    var  imageLayou tId = $(th is).attr(' id');
  15918                    var  imageRende r = series Layout.get ImageRende r(imageLay outId);
  15919                    if(i mageRender ) {
  15920                         var imageI ndex;
  15921                         if(isMulti frame && s eriesLayou t.imageTyp e !== IMAG ETYPE_RAD)  {
  15922                             var aU IDs = imag eRender.an UIDs.split ("*");
  15923                             imageI ndex=aUIDs [1];
  15924                         } else {
  15925                             imageI ndex =imag eRender.im ageIndex;
  15926                         }
  15927                         displayTex t = (displ ayText ==  undefined)  ? (parseI nt(imageIn dex) + 1)  : displayT ext + ", "  + (parseI nt(imageIn dex) + 1);
  15928                    }
  15929                });
  15930           }
  15931  
  15932           $( '#printLay outModal') .dialog('o ption', 't itle', (is Export ? " Export lay out" : "Pr int layout "));
  15933           va r innerTex t = $("#pr intLayoutM odalDiv")[ 0].innerHT ML;
  15934           va r findWord  = "print  Options";
  15935           va r replaceS trig = "ex port Optio ns";
  15936  
  15937           if (!isExport ) {
  15938                findWord  = "export  Options";
  15939                replaceS trig = "pr int Option s";
  15940           }
  15941           $( "#printLay outModalDi v")[0].inn erHTML = i nnerText.r eplace(new  RegExp(fi ndWord, "g "), replac eStrig);
  15942           $( "#printLay outModal") .data("isE xport", is Export);
  15943           $( "#PrintIma ge_Range") .val(displ ayText);
  15944           $( "#printLay outModal") .dialog('o pen');
  15945       }
  15946  
  15947           di comViewer. tools = {
  15948                firstTim eImageLoad  : firstTi meImageLoa d,
  15949                             doZoom  : doZoom,
  15950                             doPan  : doPan,
  15951                             do2DLe ngthMeasur ement: do2 DLengthMea surement,
  15952                             do2DPo intMeasure ment: do2D PointMeasu rement,
  15953                doAngleM easurement : doAngleM easurement ,
  15954                             do2DMe asurement:  do2DMeasu rement,
  15955                             doWind owLevel :  doWindowLe vel,
  15956                             rgbCol or : rgbCo lor,
  15957                             setDic omOverLayF alse : set DicomOverL ayFalse,
  15958                             showDi comHeader  : showDico mHeader,
  15959                showImag eData : sh owImageDat a,
  15960                             change ImageLayou t : change ImageLayou t,
  15961                             change SeriesLayo ut : chang eSeriesLay out,
  15962                             change StudyLayou t : change StudyLayou t,
  15963                             doOver Lay : doOv erLay,
  15964                doScoutL ine : doSc outLine,
  15965                             revert  : revert,
  15966                             rotate  : rotate,
  15967                             invert  : invert,
  15968                doHorizo ntalFilp :  doHorizon talFilp,
  15969                doVertic alFilp : d oVerticalF ilp,
  15970                             change Preset : c hangePrese t,
  15971                             moveTo PreviousIm age : move ToPrevious Image,
  15972                             moveTo NextImage  : moveToNe xtImage,
  15973                runCineI mage : run CineImage,
  15974                stopCine Image : st opCineImag e,
  15975                moveSeri es : moveS eries,
  15976                setZoomL evel : set ZoomLevel,
  15977                updateWi ndowLevelS ettings :  updateWind owLevelSet tings,
  15978                isOverla yVisible :  isOverlay Visible,
  15979                isScoutL ineVisible  : isScout LineVisibl e,
  15980                setOverl ay : setOv erlay,
  15981                             chanag eWhileDrag  : chanage WhileDrag,
  15982                             change StudyLayou tFromTool:  changeStu dyLayoutFr omTool,
  15983                             update ZoomLevelS ettings: u pdateZoomL evelSettin gs,
  15984                             getFla gFor2dLeng thCalibrat ion : getF lagFor2dLe ngthCalibr ation,
  15985                             length Calibratio n : length Calibratio n,
  15986                setSelec tedStudyLa yout : set SelectedSt udyLayout,
  15987                reOrderE xistingStu dyUids: re OrderExist ingStudyUi ds,
  15988                getOrSet ReArranged SeriesPosi tions : ge tOrSetReAr rangedSeri esPosition s,
  15989                applyWin dowLevel :  applyWind owLevel,
  15990                cacheInd icator : c acheIndica tor,
  15991                rgbColor  : rgbColo r,
  15992                resetRGB Menu : res etRGBMenu,
  15993                isCalibe rEnabled :  isCaliber Enabled,
  15994                setCalib rationActi veTool : s etCalibrat ionActiveT ool,
  15995                getLengt hCalibrati onFlag : g etLengthCa librationF lag,
  15996                setLengt hCalibrati onFlag : s etLengthCa librationF lag,
  15997                doDefaul t : doDefa ult,
  15998                SetMenuS electionCo lor : SetM enuSelecti onColor,
  15999                doWindow LevelROI :  doWindowL evelROI,
  16000                doPrint  : doPrint,
  16001                linkSeri es: linkSe ries,
  16002                doXRefLi neSelectio n : doXRef LineSelect ion,
  16003                doCopyAt tributes:  doCopyAttr ibutes,
  16004                doShowHi deAnnotati onAndMeasu rement : d oShowHideA nnotationA ndMeasurem ent,
  16005                isShowAn notationan dMeasureme nt : isSho wAnnotatio nandMeasur ement,
  16006                doOverLa y6000 : do OverLay600 0,
  16007                is6000Ov erlayVisib le : is600 0OverlayVi sible,
  16008                doPrintO rExport :  doPrintOrE xport,
  16009                doExport  : doExpor t,
  16010                doSharpe n : doShar pen,
  16011                getCurso rType : ge tCursorTyp e,
  16012                doMenusr atedScale  : doMenusr atedScale,
  16013                isVisibl eMensurate dScale : i sVisibleMe nsuratedSc ale,
  16014                movePrev iousPage:  movePrevio usPage,
  16015                moveNext Page: move NextPage,
  16016                doBright nessContra st : doBri ghtnessCon trast,
  16017                showMeas urementPro perties: s howMeasure mentProper ties,
  16018                showUser Preference s: showUse rPreferenc es,
  16019                resetZoo mTool: res etZoomTool ,
  16020                printLay out: print Layout,
  16021                printPdf Callback:  printPdfCa llback
  16022           };
  16023           
  16024           re turn dicom Viewer;
  16025           
  16026   }(dicomVie wer));var  dicomViewe r = (funct ion (dicom Viewer) {
  16027  
  16028       "use s trict";
  16029  
  16030       if(dic omViewer = == undefin ed) {
  16031           di comViewer  = {};
  16032       }
  16033       
  16034       //var  baseURL =  "http://ra v-pentap-l t:9000/api /v1/";
  16035       
  16036       functi on getStud yDetailURL ( urlParam eters )
  16037       {
  16038           if (urlParame ters == un defined)
  16039           {
  16040                    thro w "Study U RL: URL Pa rameters a re empty/n ull";
  16041           }        
  16042           re turn baseU RL+"studie s?"+$.para m(urlParam eters);        
  16043       }
  16044       
  16045       functi on getOver layTextURL ()
  16046       {
  16047           re turn baseU RL+"config ?Parameter =TextOverl ay";
  16048       }
  16049       
  16050       functi on getMeas urementsUR L() {
  16051           re turn baseU RL + "conf ig?Paramet er=measure ments";
  16052       }
  16053  
  16054       functi on getView erVersionU RL() {
  16055           re turn baseV iewerURL +  "version" ;
  16056       }
  16057  
  16058       functi on getDico mImageURL( urlParamet ers)
  16059       {
  16060           if (urlParame ters == un defined)
  16061           {
  16062                    thro w "Dicom I mage URL:  URL Parame ters are e mpty/null" ;
  16063           }
  16064           re turn baseU RL+"images ?"+$.param (urlParame ters);
  16065       }
  16066       
  16067           fu nction get DicomImage MetadataUR L(urlParam eters)
  16068       {
  16069           if (urlParame ters == un defined)
  16070           {
  16071                    thro w "Dicom I mage URL:  URL Parame ters are e mpty/null" ;
  16072           }
  16073           re turn baseV iewerURL+" metadata?" +$.param(u rlParamete rs);
  16074       }
  16075           
  16076       functi on getRefe renceLineU RL(urlPara meters)
  16077       {
  16078           if (urlParame ters == un defined)
  16079           {
  16080                    thro w "Dicom I mage URL:  URL Parame ters are e mpty/null" ;
  16081           }
  16082           re turn baseU RL+"xrefli nes?"+$.pa ram(urlPar ameters);
  16083       }
  16084       
  16085       functi on getRele aseHistory Url()
  16086       {            
  16087           re turn baseV iewerURL+" releasehis tory";
  16088       }
  16089           
  16090       functi on getMess ageHistory Url()
  16091       {            
  16092                    retu rn baseVie werURL+"ev ents";
  16093       }
  16094  
  16095       /**
  16096        * Get  the Remov e Context  Url
  16097        * @pa ram {Type}  sessionId  - Spectif y the sess ion id
  16098        */ 
  16099       functi on getRemo veContextU rl(session Id)
  16100       {
  16101           va r baseUrl  = baseURL. split("/v" );
  16102           va r url = ba seUrl[0]+" /vix/sessi on/"+sessi onId+"/con text";
  16103           re turn url;
  16104       }
  16105  
  16106       /**
  16107        * PSt ate Url (P resentatio n State)
  16108        */ 
  16109       functi on getPSta teUrl(cont extId) {
  16110           va r n = dico mViewer.ge tWindowLoc ationUrl() .indexOf(" &");
  16111           va r url = ba seURL+"con text/pstat e?"+ "Cont extId="+de codeURICom ponent(con textId)+di comViewer. getWindowL ocationUrl ().substri ng(n);
  16112           re turn url;
  16113       }
  16114  
  16115       /**
  16116        * Get  the 6000  overlay ur l
  16117        * @pa ram {Type}  imageUid  - Specifie s the imag e uid
  16118        * @pa ram {Type}  frameNumb er - Speci fies the i mage numbe r
  16119        * @pa ram {Type}  overlayIn dex - Spec ifies the  overlay in dex
  16120        */ 
  16121       functi on get6000 overlayUrl (imageUid,  frameNumb er, overla yIndex) {
  16122           va r urlParam eters =
  16123           {
  16124                Format :  "Overlay" ,
  16125                ImageUid  : imageUi d,
  16126                FrameNum ber : fram eNumber,
  16127                Transfor m : "Dicom ",
  16128                Security Token : di comViewer. security.g etSecurity Token(),
  16129           };
  16130  
  16131           re turn baseU RL+"images ?"+$.param (urlParame ters);
  16132       }
  16133  
  16134       dicomV iewer.url  = {
  16135                    getS tudyDetail URL : getS tudyDetail URL,
  16136                    getO verlayText URL: getOv erlayTextU RL,
  16137                    getM easurement sURL: getM easurement sURL,
  16138                    getD icomImageU RL : getDi comImageUR L,
  16139                    getR eferenceLi neURL: get ReferenceL ineURL,
  16140                    getV iewerVersi onURL: get ViewerVers ionURL,
  16141                getRelea seHistoryU rl : getRe leaseHisto ryUrl,
  16142                             getMes sageHistor yUrl : get MessageHis toryUrl,
  16143                             getDic omImageMet adataURL :  getDicomI mageMetada taURL,
  16144                getRemov eContextUr l : getRem oveContext Url,
  16145                getPStat eUrl : get PStateUrl,
  16146                get6000o verlayUrl  : get6000o verlayUrl
  16147       };
  16148       
  16149       return  dicomView er;
  16150   }(dicomVie wer));/**
  16151    * New nod e file
  16152    */
  16153  
  16154   var dicomV iewer = (f unction (d icomViewer ) {
  16155  
  16156       if (di comViewer  === undefi ned) {
  16157           di comViewer  = {};
  16158       }
  16159  
  16160       var CI NERUN = 0;
  16161       var CI NEPAUSE =  1;
  16162       var im ageIndexNu mber = 0;
  16163           
  16164       var st udyLevelMa p = [];
  16165  
  16166       var ci neManager  = {}; // M anage the  cine opter ations
  16167           
  16168       var pr eviousStud yLayout =  "";
  16169       
  16170       var pr eviousSave AndLoadToo lLayout =  "";
  16171  
  16172       var cu rrentLayOu tId = "";
  16173       
  16174       var fu llScreenCi neManager  = {};
  16175       var re sizeCineMa nager = {} ;
  16176       var re peatCineMa nager = {} ;
  16177           
  16178       var se riesLayout Map = new  Map();
  16179       var co lumnSize =  1;
  16180  
  16181       var vi ewportHead erWidth;
  16182  
  16183       var pr eferenceLi st = [ "gr idtype", " gridcolor" , "leadfor mat", "gai n", "signa lthickness "];
  16184  
  16185       //cont ain viewpo rt div id  as key and  imageCanv as as valu
  16186       var im ageCanvasO fViewPorts  = {};
  16187       var im ageCanvasO fBackupVie wPorts = { };
  16188       var al lViewports Temp = und efined;
  16189       var ac tiveSeries LayoutTemp  = undefin ed;
  16190       var cu rrentSerie sLayoutIds  = undefin ed;
  16191  
  16192       var vi ewHeight =  0;
  16193       var ac tiveSeries Layout = n ull; //For  mouse too ls like ww /wc , pan  and zoom
  16194  
  16195       var pl ayStudy =  false; //  if it is t rue play w hole study  in cine,  if false p lay single  image set  in cine
  16196       var te mpHeight =  0;
  16197       var mu ltiFrameIm ageIndex =  0;
  16198       var se lectThumbn ailImageIn dex = unde fined;
  16199       var ac tualSeries Index = 0;
  16200       var is ViewPortDo ubleClicke d = false;
  16201       var pa geView = u ndefined;
  16202       var re peatSeries Index = -1 ;
  16203       var re peatImageI ndex = -1;
  16204       
  16205       functi on createV iewport(ro w, column, studyLayou tId,studyU id) {
  16206           va r imageLay outMenu =  null;
  16207           va r viewport String = ' <table id= table'+stu dyLayoutId +' style=" width:100% ;height:10 0%;">';
  16208           fo r (var i =  0; i < ro w; i++) {
  16209                viewport String +=  '<tr style ="height:'  + (100 /  row) + '%; ">';
  16210                var clea r = "clear :both;";
  16211                for (var  int2 = 0;  int2 < co lumn; int2 ++) {
  16212                    view portString  += '<td s tyle="widt h:' + (100  / column) + '%;heigh t:' + (100  / row)+ ' %;padding- left:5px;" >';
  16213                    view portString  += '<div  id="imagev iewer_'+st udyLayoutI d + "_"  +  (i + 1) +  'x' + (in t2 + 1) +  '"style="w idth:100%; height:100 %;float:le ft;backgro und-color: black;posi tion:relat ive' + cle ar + '"  c lass="disa bleSelecti on" tabind ex="0">';
  16214                    clea r = "";
  16215                    view portString  += '</td> ';
  16216                }
  16217                viewport String +=  '</tr>';
  16218           }
  16219           vi ewportStri ng += '</t able>';
  16220           if (studyLayo utId != un defined)
  16221           {
  16222                var stud yLayoutEle ment = $(" #"+studyLa youtId);
  16223                studyLay outElement .empty();
  16224                var stud yInformati ondiv = "s tudyInfo"+ studyLayou tId;
  16225                var stud yUidAndDat eTime = "s tudyUidDat eTime"+stu dyLayoutId ;
  16226                var seri esLayoutMe nu = "menu SL"+studyL ayoutId;
  16227                var imag eLayoutMen u = "menuI L"+studyLa youtId;
  16228                var save Annotation sButton =  "saveButto n_"+studyL ayoutId;
  16229                var save Annotation sMenu = "s aveMenuSL" +studyLayo utId;
  16230                var load Annotation sButton =  "loadButto n_"+studyL ayoutId;
  16231                var load Annotation sMenu = "l oadMenuIL" +studyLayo utId;
  16232                var imag eLayoutDis playId = " imageDispl ay"+studyL ayoutId;
  16233                var seri esLayoutDi splayId =  "seriesDis play"+stud yLayoutId;
  16234                var tabl eWidth = $ ("#viewpor tTable").w idth();
  16235                viewport HeaderWidt h = (table Width/colu mnSize )-  215;
  16236                var imag eLevelSele ctionId =  "imageLeve lSelection _"+studyLa youtId;
  16237                var seri esLevelSel ectionId =  "seriesLe velSelecti on_"+study LayoutId;
  16238                var tabl eid = "tab le_"+study LayoutId;
  16239                var view portToolba rId = "sav eAndLoad_" +studyLayo utId;
  16240                var save Id = "save _"+studyLa youtId;
  16241                var edit AndSaveId  = "editAnd Save_"+stu dyLayoutId ;
  16242                if(viewp ortHeaderW idth<10) {
  16243                    view portHeader Width =10;
  16244                }
  16245  
  16246                var stud yInformati on = "<tab le id=tabl e"+studyIn formationd iv+" style ='width:99 %;cursor:  default;/* background :rgba(152,  153, 158,  0.59);*/' >"
  16247                                          +"<t r>"
  16248                                          +"<t d id="+tab leid+" sty le ='width :"+viewpor tHeaderWid th+"px'>"
  16249                                               +"<div id= "+studyInf ormationdi v+" style= 'color: wh ite;paddin g-left: 5p x;width: " +viewportH eaderWidth +"px;white -space: no wrap;overf low: hidde n;text-ove rflow: ell ipsis'></d iv>"
  16250                                               +"<div id= "+studyUid AndDateTim e+" style= 'color: wh ite;paddin g-left: 5p x;font-siz e:10px;wid th: "+view portHeader Width+"px; white-spac e: nowrap; overflow:  hidden;tex t-overflow : ellipsis '></div>"
  16251                                          +"</ td>"
  16252                                               +"<td id=" +viewportT oolbarId+"  align='le ft' style= 'display:n one;backgr ound: tran sparent;wi dth: 65px; height:32p x'></td>"
  16253                                          +"<t d align='r ight' styl e='width:  62px;'>"
  16254                                               +"<div id= "+imageLay outDisplay Id+" style ='display: none;'>"
  16255                                                   +"<ul  id="+image LayoutMenu +" style=' width: 60p x;backgrou nd: transp arent; bor der-color:  transpare nt;'>"
  16256                                                       +" <li >"
  16257                                                            +'<img s rc="images /imageLeve l.png" id= '+imageLev elSelectio nId+'>'
  16258                                                                     +"<ul>"
  16259                                                                     +"<li oncl ick='dicom Viewer.too ls.changeI mageLayout (1,1,"+stu dyLayoutId +")'><img  src='image s/1x1.png' ></li>"
  16260                                                                     +"<li oncl ick='dicom Viewer.too ls.changeI mageLayout (1,2,"+stu dyLayoutId +")'><img  src='image s/1x2.png' ></li>"
  16261                                                                     +"<li oncl ick='dicom Viewer.too ls.changeI mageLayout (2,1,"+stu dyLayoutId +")'><img  src='image s/2x1.png' ></li>"
  16262                                                                     +"<li oncl ick='dicom Viewer.too ls.changeI mageLayout (2,2,"+stu dyLayoutId +")'><img  src='image s/2x2.png' ></li>"
  16263                                                                +"</ ul>"
  16264                                                       +" </li>"
  16265                                                   +"</ul >"
  16266                                               +"</div>"
  16267                                          +"</ td>"
  16268                                          +"<t d align='r ight' styl e='width:  62px;'>"
  16269                                               +"<div id= "+seriesLa youtDispla yId+" styl e='display :none;'>"
  16270                                                   +"<ul  id='"+seri esLayoutMe nu+"'style ='width: 6 0px;backgr ound: tran sparent; b order-colo r: transpa rent;'>"
  16271                                                       +" <li>"
  16272                                                            +"<img s rc='images /2x2.png'  id="+serie sLevelSele ctionId+"> "
  16273                                                                +"<u l>"
  16274                +"<li id  = '"+seri esLayoutDi splayId+"_ 1x1' oncli ck='dicomV iewer.tool s.changeSe riesLayout (1,1,"+stu dyLayoutId +")'><img  src='image s/1x1.png' ></li>"
  16275                +"<li id  = '"+seri esLayoutDi splayId+"_ 1x2' oncli ck='dicomV iewer.tool s.changeSe riesLayout (1,2,"+stu dyLayoutId +")'><img  src='image s/1x2.png' ></li>"
  16276                +"<li id  = '"+seri esLayoutDi splayId+"_ 2x1' oncli ck='dicomV iewer.tool s.changeSe riesLayout (2,1,"+stu dyLayoutId +")'><img  src='image s/2x1.png' ></li>"
  16277                +"<li id  = '"+seri esLayoutDi splayId+"_ 2x2' oncli ck='dicomV iewer.tool s.changeSe riesLayout (2,2,"+stu dyLayoutId +")'><img  src='image s/2x2.png' ></li>"
  16278                +"<li id  = '"+seri esLayoutDi splayId+"_ custom' on click='cha ngeCustom( "+studyLay outId+")'> Custom</li >"
  16279                                                                +"</ ul>"
  16280                                                       +" </li>"
  16281                                                   +"</ul >"
  16282                                               +"</div>"
  16283                                          +"</ td>"
  16284                                          +"<t d align='r ight' styl e='width:  12px;'>"
  16285                                               +"<span id ='"+studyL ayoutId+"_ close' tit le='close'  style='pa dding-righ t: 5px;vis ibility:hi dden' oncl ick=closeS tudy('"+st udyLayoutI d+"')><img  src='imag es/close.p ng' style= 'width: 12 px;'></spa n>"
  16286                                          +"</ td>"
  16287                                          +"</ tr>"
  16288                                          +"</ table>"
  16289  
  16290                studyLay outElement .append(st udyInforma tion);
  16291                if(study Uid !== un defined){
  16292                    docu ment.getEl ementById( imageLayou tDisplayId ).style.di splay='blo ck';
  16293                    docu ment.getEl ementById( seriesLayo utDisplayI d).style.d isplay='bl ock';
  16294                     doc ument.getE lementById (viewportT oolbarId). style.disp lay='block ';
  16295                } else i f(studyUid  == undefi ned){
  16296                    docu ment.getEl ementById( viewportTo olbarId).s tyle.displ ay='none';
  16297                }
  16298                $("#"+se riesLayout Menu).kend oMenu();
  16299                $("#"+im ageLayoutM enu).kendo Menu();
  16300                studyUid  == undefi ned ? "" :  ((studyUi d == null)  ? "" : cr eateSaveAn dLoadPStat eGUI(viewp ortToolbar Id,studyUi d,studyLay outId));
  16301  
  16302                updateTo olTip($("# "+imageLay outMenu),  "Image Lev el Layout" , "top");
  16303                updateTo olTip($("# "+seriesLa youtMenu),  "Series L evel Layou t", "top") ;
  16304                $(".k-it em").css(" border-col or", "tran sparent");
  16305                studyLay outElement .append(vi ewportStri ng);
  16306                var heig htOfStudyI nfo = $("# table"+stu dyInformat iondiv).ou terHeight( );
  16307                var heig htOfStudyL ayout = st udyLayoutE lement.hei ght();
  16308                if(study LayoutId = == "studyV iewer1x1") {
  16309                    temp Height = h eightOfStu dyLayout;
  16310                }else
  16311                {
  16312                    heig htOfStudyL ayout = te mpHeight;
  16313                    stud yLayoutEle ment.heigh t(tempHeig ht);
  16314                }
  16315  
  16316                var widt h = docume nt.getElem entById(im ageLevelSe lectionId) .clientWid th;
  16317                var widt h2 = docum ent.getEle mentById(s eriesLevel SelectionI d).clientW idth;
  16318  
  16319                if(width  && width2  ) {
  16320                   if(wi dth2>30)
  16321                         setIconSiz e(width2-6 ); 
  16322                    else
  16323                         setIconSiz e(width2);  
  16324                }
  16325                changeIc onSize(stu dyLayoutId );
  16326                viewHeig ht = (heig htOfStudyL ayout-heig htOfStudyI nfo);
  16327                var even Row = stud yLayoutEle ment.paren t().closes t('tr').cs s('border- top-width' );
  16328                if(evenR ow !== "0p x"){
  16329                    view Height = ( heightOfSt udyLayout- heightOfSt udyInfo)-2 ;
  16330                }
  16331  
  16332                $("#tabl e"+studyLa youtId).he ight(viewH eight-3/*( heightOfSt udyLayout- heightOfSt udyInfo)-3 */);
  16333           }e lse{
  16334                    $("# viewport_V iew").html (viewportS tring);
  16335           }
  16336           va r tableWid th =  stud yLayoutEle ment.width ();
  16337           $( "#table"+s tudyLayout Id).width( tableWidth -5);
  16338           $( "#menuIL"+ studyLayou tId).child ren().addC lass("k-st ate-disabl ed");
  16339       }
  16340           
  16341       functi on createS tudyViewpo rt(row, co lumn) {
  16342           co lumnSize =  column;
  16343           st udyLevelMa p = new Ar ray();
  16344           $( "#viewport _View").em pty();
  16345           va r viewport String = ' <table id= "viewportT able" styl e="width:1 00%;height :100%;">';
  16346           fo r (var i =  0; i < ro w; i++) {
  16347                viewport String +=  '<tr style ="height:'  + (100 /  row) + '%" >';
  16348                var clea r = "clear :both;";
  16349                for (var  int2 = 0;  int2 < co lumn; int2 ++) {
  16350                    view portString  += '<td s tyle="widt h:' + (100  / column) + '%;heigh t:' + (100  / row)+ ' %;">';
  16351                    stud yLevelMap. push('stud yViewer' +  (i + 1) +  'x' + (in t2 + 1));
  16352                    view portString  += '<div  id="studyV iewer' + ( i + 1) + ' x' + (int2  + 1) + '" style="wid th:100%;he ight:100%; float:left ;' + clear  + '"  cla ss="disabl eSelection " tabindex ="0"></div >';
  16353                    clea r = "";
  16354                    view portString  += '</td> ';
  16355                }
  16356                viewport String +=  '</tr>';
  16357           }
  16358           vi ewportStri ng += '</t able>';
  16359           $( "#viewport _View").ht ml(viewpor tString);
  16360           va r tableWid th = $("#v iewportTab le").width ();
  16361           $( "#viewport Table").he ight($("#v iewport_Vi ew").heigh t());
  16362           $( "#viewport Table tr:n th-child(e ven)").css ("border-t op","2px s olid black ");
  16363           $( "#viewport Table td:n th-child(e ven)").css ("border-l eft","2px  solid blac k");
  16364           $( "#viewport Table tr:n th-child(o dd)").css( "border-to p","2px so lid black" );
  16365           $( "#viewport Table td:n th-child(o dd)").css( "border-le ft","2px s olid black ");
  16366       }
  16367  
  16368       functi on loadStu dyInNextVi ewport(stu dyUid, dis playSettin gs) {
  16369           va r seriesIn dex = 0;
  16370           va r studyUid s = dicomV iewer.getL istOfStudy Uid();
  16371           va r listOfSt udy = stud yUids.leng th - 1;
  16372           if ((studyUid  !== undef ined) && ( listOfStud y <= 3) )
  16373           {
  16374                var arra y = studyL evelMap;
  16375                var isMu ltiFrame =  dicomView er.thumbna il.isSerie sContainsM ultiframe( studyUid,  seriesInde x);
  16376                if(!isMu ltiFrame & & getimage CanvasOfVi ewPort("im ageviewer_ "+array[li stOfStudy] +"_" + 1 +  "x" + 1)  != undefin ed){
  16377                    seri esIndex =  getimageCa nvasOfView Port("imag eviewer_"+ array[list OfStudy]+" _" + 1 + " x" + 1).se riesIndex;
  16378                    imag eIndexNumb er = getim ageCanvasO fViewPort( "imageview er_"+array [listOfStu dy]+"_" +  1 + "x" +  1).imageIn dex;
  16379                }
  16380                else
  16381                {
  16382                    seri esIndex =  0;
  16383                }
  16384  
  16385                // Apply  the displ ay setting s
  16386                var seri esLayoutRo ws = 1;
  16387                var seri esLayoutCo lumns = 1;
  16388                if(displ aySettings  !== undef ined){
  16389                    seri esLayoutRo ws = parse Int(displa ySettings. Rows);
  16390                    seri esLayoutCo lumns = pa rseInt(dis playSettin gs.Columns );
  16391                }
  16392  
  16393                setSerie sLayout(st udyUid, se riesLayout Rows, seri esLayoutCo lumns, ser iesIndex,
  16394                                 un defined ,a rray[listO fStudy],un defined, t rue);
  16395           }
  16396       }
  16397  
  16398       functi on refresh StudyLayou t(){
  16399           va r seriesIn dex = 0;
  16400           va r row = 1;
  16401           va r column =  1;
  16402           va r studyUid s = dicomV iewer.getL istOfStudy Uid();
  16403           va r array =  studyUids. length;
  16404           if (studyUids  !== undef ined)
  16405           {
  16406                if(array  === 2) co lumn = 2;
  16407                if(array  === 3) ro w = 2;
  16408  
  16409                createSt udyViewpor t(row,colu mn);
  16410                for(var  index = 0;  index<arr ay;index++ )
  16411                {
  16412                    var  studyUid =  studyUids [index];
  16413                    var  isMultiFra me = dicom Viewer.thu mbnail.isS eriesConta insMultifr ame(studyU id, series Index);
  16414                    if(! isMultiFra me && geti mageCanvas OfViewPort ("imagevie wer_"+arra y[index]+" _" + 1 + " x" + 1) !=  undefined ){
  16415                         seriesInde x = getima geCanvasOf ViewPort(" imageviewe r_"+array[ index]+"_"  + 1 + "x"  + 1).seri esIndex;
  16416                         imageIndex Number = g etimageCan vasOfViewP ort("image viewer_"+a rray[index ]+"_" + 1  + "x" + 1) .imageInde x;
  16417                    }
  16418                    else
  16419                    {
  16420                         seriesInde x = 0;
  16421                    }
  16422                    setS eriesLayou t(studyUid , 1, 1, se riesIndex,  undefined  ,studyLev elMap[inde x],undefin ed);
  16423                }
  16424           }
  16425       }
  16426  
  16427       functi on setStud yLayout(ro w, column,  selectedS tudyUid, s eriesIndex , isBackup ,isResize,  displaySe ttings, is FullScreen Resize){
  16428           se riesIndex  = (seriesI ndex ? ser iesIndex :  0);
  16429           ro w = (row ?  row : 1);
  16430           co lumn = (co lumn ? col umn : 1);
  16431  
  16432           //  Create vi ewport
  16433           cr eateStudyV iewport(ro w, column) ;
  16434  
  16435           va r array =  studyLevel Map;
  16436           va r studyUid s = dicomV iewer.getL istOfStudy Uid(isResi ze);
  16437           fo r(var inde x = 0; ind ex<array.l ength;inde x++)
  16438           {
  16439                var stud yUid = und efined;
  16440                if(selec tedStudyUi d && array .length ==  1) {
  16441                    stud yUid = sel ectedStudy Uid;
  16442                } else {
  16443                    stud yUid = stu dyUids[ind ex];
  16444                }
  16445  
  16446                // get a nd set the  series la yout setti ngs by stu dy
  16447                var seri esLayout =  { Rows: 1 , Columns:  1 };
  16448                if(displ aySettings ) {
  16449                    if(O bject.prot otype.toSt ring.call( displaySet tings) ==  '[object A rray]') {
  16450                         var studyD isplaySett ings = dis playSettin gs.filter( function(o ) {return  o.studyUid  === study Uid;})[0];
  16451                         if(studyDi splaySetti ngs) {
  16452                             series Layout.Row s = parseI nt(studyDi splaySetti ngs.Rows);
  16453                             series Layout.Col umns = par seInt(stud yDisplaySe ttings.Col umns);
  16454                         }
  16455                    } el se {
  16456                         seriesLayo ut.Rows =  parseInt(d isplaySett ings.Rows) ;
  16457                         seriesLayo ut.Columns  = parseIn t(displayS ettings.Co lumns);
  16458                    }
  16459                }
  16460  
  16461                seriesLa yout = get OrUpdateSe riesLayout (studyUid,  seriesLay out.Rows,  seriesLayo ut.Columns , false);
  16462  
  16463                var isMu ltiFrame =  dicomView er.thumbna il.isSerie sContainsM ultiframe( studyUid,  seriesInde x);
  16464                if(!isMu ltiFrame & & getimage CanvasOfVi ewPort("im ageviewer_ "+array[in dex]+"_" +  1 + "x" +  1) != und efined) {
  16465                    seri esIndex =  getimageCa nvasOfView Port("imag eviewer_"+ array[inde x]+"_" + 1  + "x" + 1 ).seriesIn dex;
  16466                    imag eIndexNumb er = getim ageCanvasO fViewPort( "imageview er_"+array [index]+"_ " + 1 + "x " + 1).ima geIndex;
  16467                } else {
  16468                    seri esIndex =  0;
  16469                }
  16470  
  16471                if(study Uid === un defined) {
  16472                    setS eriesLayou t(studyUid , 1, 1, se riesIndex,  isBackup  ,array[ind ex],isResi ze, false) ;
  16473                } else {
  16474                    setS eriesLayou t(studyUid , seriesLa yout.Rows,  seriesLay out.Column s, seriesI ndex, isBa ckup, arra y[index],i sResize, f alse, unde fined, isF ullScreenR esize);
  16475                }
  16476           }
  16477  
  16478           //  Remove th e duplicat e view por ts
  16479           Re moveDuplic ateViewpor ts();
  16480       }
  16481  
  16482       /**
  16483        * Rem ove the du plicate vi ew ports
  16484        */ 
  16485       functi on RemoveD uplicateVi ewports()  {
  16486           tr y
  16487           {
  16488                if(isFul lScreenEna bled == tr ue) {
  16489                    retu rn;
  16490                }
  16491  
  16492                var allV iewports =  dicomView er.viewpor ts.getAllV iewports() ;
  16493                if(allVi ewports == = null ||  allViewpor ts === und efined) {
  16494                    retu rn;
  16495                }
  16496  
  16497                // Parse  the view  ports
  16498                $.each(a llViewport s, functio n(key, val ue) {
  16499                    if(v alue.study Uid !== un defined) {
  16500                         // Remove  the view p ort
  16501                         var studyV iewportId  = getStudy LayoutId(v alue.serie sLayoutId) ;
  16502                         if(studyLe velMap.ind exOf(study ViewportId ) == -1) {
  16503                             dicomV iewer.view ports.remo veViewport sByStudyLa yout(study ViewportId ); 
  16504                             dicomV iewer.remo veimageCan vasOfAllVi ewPorts(st udyViewpor tId);
  16505                         }
  16506                    }
  16507                });
  16508           }
  16509           ca tch(e)
  16510           {  }
  16511       }
  16512  
  16513       /**
  16514       * Chec k whether  the study  is in full  screen mo de
  16515       */ 
  16516       functi on IsFullS creenMode( )
  16517       {
  16518           va r currentS tudyLayout  = studyLa youtValue. split("x") ;
  16519           va r rows = c urrentStud yLayout[0] ;
  16520           va r columns  = currentS tudyLayout [1];
  16521           if ((parseInt (rows) ==  1 && parse Int(column s) == 1) | | isFullSc reenEnable d) {
  16522                return t rue;
  16523           }
  16524  
  16525           re turn false ;
  16526       }
  16527  
  16528       /**
  16529        * Get  or update  the serie s layout f or the stu dy
  16530        * @pa ram {Type}  studyUid  - Study Ui d
  16531        * @pa ram {Type}  rows - Ro ws
  16532        * @pa ram {Type}  columns -  Columns
  16533        * @pa ram {Type}  isUpdate  - Update o r Get flag
  16534        */ 
  16535       functi on getOrUp dateSeries Layout(stu dyUid, row s, columns , isUpdate ){
  16536           //  Maintain  the defaul t values
  16537           va r layout =
  16538                {
  16539                    Rows : rows,
  16540                    Colu mns: colum ns
  16541                };
  16542  
  16543           tr y
  16544           {
  16545                if((stud yUid === u ndefined & & !isUpdat e) || isFu llScreenEn abled){
  16546                    retu rn layout;
  16547                }
  16548  
  16549                // Remov e the key
  16550                if(isUpd ate){
  16551                    if(s eriesLayou tMap.has(s tudyUid)){
  16552                         layout = s eriesLayou tMap.get(s tudyUid);
  16553                         layout.Row s = rows;
  16554                         layout.Col umns = col umns;
  16555                    } el se {
  16556                         // Set the  layout
  16557                         if(studyUi d != undef ined){
  16558                             series LayoutMap. set(studyU id, layout );
  16559                         }
  16560                    }
  16561  
  16562                    retu rn layout;
  16563                }
  16564  
  16565                // Get t he layout
  16566                layout =  seriesLay outMap.get (studyUid) ;
  16567                if(layou t === unde fined){
  16568                    layo ut = {
  16569                         Rows: rows ,
  16570                         Columns: c olumns
  16571                    };
  16572  
  16573                    // S et the lay out 
  16574                    seri esLayoutMa p.set(stud yUid, layo ut);
  16575                }
  16576  
  16577                return l ayout;
  16578           }
  16579           ca tch(e)
  16580           {  }
  16581  
  16582           re turn layou t;
  16583       }
  16584  
  16585       /**
  16586        * Che king wheth er the giv en study i s multi-mo dality or  not.
  16587        * @pa ram {Type}  studyUid  - Study Ui d
  16588        * @pa ram {Type}  seriesInd ex - new s eries inde x
  16589        */
  16590       functi on isMixed Modality(s tudyUid, s eriesIndex ) {
  16591           va r activeSe riesIndex  = dicomVie wer.getAct iveSeriesL ayout().se riesIndex;
  16592           if (activeSer iesIndex ! == undefin ed) {
  16593                var acti veModality  = dicomVi ewer.Serie s.getModal ity(studyU id, active SeriesInde x);
  16594                var newM odality =  dicomViewe r.Series.g etSeries(s tudyUid, s eriesIndex ).modality ;
  16595                if(activ eModality  !== newMod ality) {
  16596                    retu rn true;
  16597                }
  16598           }
  16599           re turn false ;
  16600       }
  16601  
  16602       /* Loa d the dico m images i n viewport s*/
  16603       functi on setSeri esLayout(s tudyUid, r ow, column , seriesIn dexValue,
  16604                                    isBackup,  studyViewp ortId,isRe size, isSe riesLayout UpdationRe quired,isT humbnailCl ick, isFul lScreenRes ize) {
  16605           if  (row ===  undefined  || column  === undefi ned) {
  16606                row = 1;
  16607                column =  1;
  16608           }
  16609           va r backupLa youtId = " ";
  16610           if (isResize  === undefi ned || isR esize ===  false)
  16611           {
  16612                if (isBa ckup === u ndefined | | isBackup  === null)  {
  16613  
  16614                    // U pdate the  series lay out
  16615                    if(i sSeriesLay outUpdatio nRequired  == true){
  16616                         getOrUpdat eSeriesLay out(studyU id, row, c olumn, fal se);
  16617                    }els e if(isSer iesLayoutU pdationReq uired ===  undefined) {
  16618                         getOrUpdat eSeriesLay out(studyU id, row, c olumn, tru e);
  16619                    }
  16620  
  16621                    var  viewports  = dicomVie wer.viewpo rts.getAll Viewports( );
  16622                    for( var key in  viewports ){
  16623                         if(dicomVi ewer.getim ageCanvasO fViewPort( key) !== u ndefined)
  16624                         {
  16625                             var ca nvasTemp =  Object.cr eate(dicom Viewer.get imageCanva sOfViewPor t(key));
  16626                             dicomV iewer.seti mageCanvas OfBackupVi ewPort(key ,canvasTem p);
  16627                         }
  16628                    }
  16629  
  16630                    for  (var key i n cineMana ger)
  16631                    {
  16632                         var studyL ayoutId =  key.split( "_")[1];
  16633                         if(studyVi ewportId = = studyLay outId){
  16634                             resize CineManage r[key] = J SON.parse( JSON.strin gify(cineM anager[key ]));
  16635                             clearI nterval(ci neManager[ key].timer );
  16636                             delete  cineManag er[key];
  16637                         }
  16638                    }
  16639  
  16640                    if ( pageView ! == undefin ed && page View !== n ull) {
  16641                         dicomViewe r.viewport s.getBacku pImageLayo uts(studyV iewportId,  row, colu mn);
  16642                    }
  16643  
  16644                    dico mViewer.vi ewports.ba ckupViewab leViewport sBySeriesI ndex(study ViewportId );
  16645                    dico mViewer.vi ewports.re moveViewpo rtsByStudy Layout(stu dyViewport Id); 
  16646                    dico mViewer.re moveimageC anvasOfAll ViewPorts( studyViewp ortId);
  16647                    dico mViewer.vi ewports.ad dSeriesLay outMaxId(" imageviewe r_"+studyV iewportId+ "_" + row  + "x" + co lumn, stud yViewportI d);
  16648                    dico mViewer.me asurement. setMeasure mentBroken (false);
  16649                } 
  16650           }  else if(di comViewer. getActiveS eriesLayou t() !== nu ll && dico mViewer.ge tActiveSer iesLayout( ) !== unde fined) {
  16651                backupLa youtId = d icomViewer .getActive SeriesLayo ut().getSe riesLayout Id();
  16652           }
  16653           
  16654           cr eateViewpo rt(row, co lumn, stud yViewportI d,studyUid );
  16655           
  16656           va r seriesIn dex = 0;
  16657           if (seriesInd exValue !=  undefined )
  16658           {
  16659                seriesIn dex = seri esIndexVal ue;
  16660           }
  16661           va r imageInd ex = 0;
  16662           va r frameInd ex = 0;
  16663           va r imageLay out = "";
  16664           va r layoutId  = "";
  16665           va r duplicat eSeriesInd ex = 0;
  16666           if (isResize  === undefi ned || isR esize ===  false)
  16667           {
  16668                if(study Uid !== un defined)
  16669                {
  16670                    if(s eriesIndex Value ===  undefined)
  16671                    {
  16672                         if(dicomVi ewer.getAc tiveSeries Layout() ! = undefine d ){
  16673                             series Index = di comViewer. getActiveS eriesLayou t().getSer iesIndex() ;
  16674                             imageI ndex = dic omViewer.g etActiveSe riesLayout ().getImag eIndex();
  16675                         }
  16676                         if(seriesI ndex === u ndefined)  seriesInde x = 0;
  16677                         if(imageIn dex === un defined) i mageIndex  = 0;
  16678                    }els e
  16679                    {
  16680                         seriesInde x = series IndexValue ;
  16681                         if(dicomVi ewer.getAc tiveSeries Layout() = == undefin ed || dico mViewer.ge tActiveSer iesLayout( ) === null )
  16682                         {
  16683                             imageI ndex = 0;
  16684                         }
  16685                         else {
  16686                             //Whil e changing  the serie s layout,  if any mix ed modalit y(multifra me should  be there)  then getti ng the ima ge index f rom the gl obal commo n variable
  16687                             if(isM ixedModali ty(studyUi d, seriesI ndex)) {
  16688                                 im ageIndex =  multiFram eImageInde x;
  16689                             } else  {
  16690                                 im ageIndex =  dicomView er.getActi veSeriesLa yout().get ImageIndex ();
  16691                             }
  16692                             if(ima geIndex == = undefine d) imageIn dex = 0;
  16693                             if(stu dyUid !==  undefined)
  16694                             {
  16695                                 va r imageVal ue = dicom Viewer.Ser ies.Image. getImage(s tudyUid,se riesIndex, imageIndex ); 
  16696                                 if (!dicomVie wer.thumbn ail.isImag eThumbnail (imageValu e))
  16697                                 {
  16698                                      imageInd ex = 0;
  16699                                 }
  16700                             }
  16701                         }
  16702                    }
  16703                }
  16704                
  16705                if (page View !== u ndefined & & pageView  !== null)  {
  16706                    if ( pageView.t ype === "s eries") {
  16707                         if (pageVi ew.isMulti Frame) {
  16708                             series Index = pa geView.ser iesIndex;
  16709                             imageI ndex = pag eView.firs t;
  16710                         } else {
  16711                             series Index = pa geView.fir st;
  16712                             imageI ndex = 0;
  16713                         }
  16714                        
  16715                    } el se if (pag eView.type  === "imag e") {
  16716                         seriesInde x = pageVi ew.seriesI ndex;
  16717                         imageIndex  = pageVie w.first;
  16718                    }
  16719                } else i f(actualSe riesIndex  == imageIn dex){
  16720                    /* a ssign mult iFrameImag eIndex val ue to imag eIndex to  provide th e
  16721                    star ting point  when chan ging the l ayout */
  16722                    imag eIndex = m ultiFrameI mageIndex;
  16723                }
  16724  
  16725                currentS eriesLayou tIds = "im ageviewer_ "+studyVie wportId+"_ " + row +  "x" + colu mn;
  16726                if (isBa ckup !== u ndefined & & isBackup  !== null  && studyUi d !== unde fined)
  16727                {
  16728                    layo utId = "im ageviewer_ "+ studyVi ewportId+  "_" + (1)  + "x" + (1 );
  16729                    if(i sBackup == = true &&  isFullScre enResize ! == true)
  16730                    {
  16731                         currentLay OutId = ge tActiveSer iesLayout( ).getSerie sLayoutId( );
  16732                         if(current LayOutId ! == layoutI d)
  16733                         {
  16734                             viewpo rt = dicom Viewer.vie wports.get Viewport(l ayoutId).c opy(); 
  16735                             if(vie wport !==  undefined)
  16736                             {
  16737                                 di comViewer. viewports. removeView port(layou tId)
  16738                                 di comViewer. viewports. addBackupV iewport(la youtId,vie wport.copy ());
  16739  
  16740                                 vi ewport = d icomViewer .viewports .getViewpo rt(current LayOutId). copy();
  16741                                 di comViewer. viewports. removeView port(curre ntLayOutId )
  16742                                 di comViewer. viewports. addBackupV iewport(cu rrentLayOu tId,viewpo rt.copy()) ;
  16743                                 vi ewport.ser iesLayoutI d = layout Id;
  16744                                 di comViewer. viewports. addViewpor t(layoutId , viewport ); 
  16745  
  16746                                 va r tmpCanva s = dicomV iewer.geti mageCanvas OfViewPort (layoutId) ;
  16747                                 if (tmpCanvas  !== undef ined)
  16748                                 {
  16749                                      var canv asTemp = O bject.crea te(tmpCanv as);
  16750                                      dicomVie wer.setima geCanvasOf BackupView Port(layou tId,canvas Temp);
  16751                                      dicomVie wer.remove imageCanva sOfViewPor t(layoutId );
  16752                                 }
  16753                                 tm pCanvas =  dicomViewe r.getimage CanvasOfVi ewPort(cur rentLayOut Id);
  16754                                 if (tmpCanvas  !== undef ined)
  16755                                 {
  16756                                      var canv asTemp = O bject.crea te(tmpCanv as);
  16757                                      dicomVie wer.setima geCanvasOf BackupView Port(curre ntLayOutId ,canvasTem p);
  16758                                      dicomVie wer.setima geCanvasOf ViewPort(l ayoutId,Ob ject.creat e(canvasTe mp));
  16759                                      dicomVie wer.remove imageCanva sOfViewPor t(currentL ayOutId);
  16760                                 }
  16761  
  16762                                 if (cineManag er[layoutI d] !== und efined)
  16763                                 {
  16764                                      fullScre enCineMana ger[layout Id] = JSON .parse(JSO N.stringif y(cineMana ger[layout Id])); 
  16765                                       clearIn terval(cin eManager[l ayoutId].t imer);
  16766                                       delete  cineManage r[layoutId ];
  16767                                 }
  16768                                 if (cineManag er[current LayOutId]  !== undefi ned)
  16769                                 {
  16770                                      cineMana ger[layout Id] = JSON .parse(JSO N.stringif y(cineMana ger[curren tLayOutId] ));
  16771                                      clearInt erval(cine Manager[la youtId].ti mer);
  16772                                      delete c ineManager [currentLa yOutId];
  16773                                 }
  16774                             }
  16775                         }
  16776                    }els e if(curre ntLayOutId  !== layou tId && isF ullScreenR esize !==  true)
  16777                    { 
  16778                         var backup viewport =  dicomView er.viewpor ts.getView port(layou tId).copy( );
  16779                         if(backupv iewport != = undefine d && curre ntLayOutId  !== "imag eviewer_st udyViewer1 x1_1x1" &&  currentLa yOutId !==  "")
  16780                         {
  16781                             backup viewport.u pdateImage RendersTo( backupview port.serie sLayoutId, currentLay OutId);
  16782                             backup viewport.s eriesLayou tId = curr entLayOutI d;
  16783                             dicomV iewer.view ports.addV iewport(cu rrentLayOu tId, backu pviewport. copy()); 
  16784                             dicomV iewer.view ports.remo veBackupVi ewport(cur rentLayOut Id);
  16785  
  16786                             backup viewport =  dicomView er.viewpor ts.getBack upViewport (layoutId) ;
  16787                             if(bac kupviewpor t !== unde fined) {
  16788                                 di comViewer. viewports. addViewpor t(layoutId , backupvi ewport.cop y()); 
  16789                                 di comViewer. viewports. removeBack upViewport (layoutId) ;
  16790                             } else  {
  16791                                 ba ckupviewpo rt = dicom Viewer.vie wports.get Viewport(l ayoutId).c opy();
  16792                                 di comViewer. viewports. addViewpor t(layoutId , backupvi ewport.cop y()); 
  16793                                 di comViewer. viewports. removeBack upViewport (layoutId) ;
  16794                             }
  16795                             dicomV iewer.view ports.addV iewport(la youtId, ba ckupviewpo rt.copy())
  16796                             dicomV iewer.view ports.remo veBackupVi ewport(lay outId);
  16797  
  16798                             var tm pCanvas =  dicomViewe r.getimage CanvasOfVi ewPort(lay outId);
  16799                             if(tmp Canvas !==  undefined )
  16800                             {
  16801                                 va r canvasTe mp = Objec t.create(t mpCanvas);
  16802                                 di comViewer. removeimag eCanvasOfB ackupViewP ort(curren tLayOutId) ;
  16803                                 di comViewer. setimageCa nvasOfView Port(curre ntLayOutId ,canvasTem p);
  16804                             }
  16805                             tmpCan vas = dico mViewer.ge timageCanv asOfBackup ViewPort(l ayoutId);
  16806                             if(tmp Canvas !==  undefined )
  16807                             {
  16808                                 va r canvasTe mp = Objec t.create(t mpCanvas);
  16809                                 di comViewer. removeimag eCanvasOfB ackupViewP ort(layout Id);
  16810                                 di comViewer. setimageCa nvasOfView Port(layou tId,canvas Temp);
  16811                             }
  16812  
  16813                             if(cin eManager[l ayoutId] ! == undefin ed)
  16814                             {
  16815                                 ci neManager[ currentLay OutId] = J SON.parse( JSON.strin gify(cineM anager[lay outId]));
  16816                                 if (studyLayo utValue != = "1x1" &&  currentLa yOutId !==  undefined  && curren tLayOutId  !== ""){
  16817                                      if(cineM anager[cur rentLayOut Id] !== un defined){
  16818                                           if( cineManage r[currentL ayOutId].p layStudy ! == undefin ed){
  16819                                                repeatCin eManager[c urrentLayO utId] = JS ON.parse(J SON.string ify(cineMa nager[curr entLayOutI d]));
  16820                                           }
  16821                                      }
  16822                                 }
  16823                             }else
  16824                             {
  16825                                 de lete cineM anager[cur rentLayOut Id];
  16826                             }
  16827                             delete   cineMana ger[layout Id];
  16828  
  16829                             if(ful lScreenCin eManager[l ayoutId] ! == undefin ed)
  16830                             {
  16831                                 ci neManager[ layoutId]  = JSON.par se(JSON.st ringify(fu llScreenCi neManager[ layoutId]) );
  16832                             }else
  16833                             {
  16834                                 de lete cineM anager[lay outId];
  16835                             }
  16836                             delete   fullScre enCineMana ger[curren tLayOutId] ;
  16837                             delete   fullScre enCineMana ger[layout Id];
  16838                             backup LayoutId =  currentLa yOutId;
  16839                             curren tLayOutId  = "";
  16840                         }
  16841                    } el se if(curr entLayOutI d == layou tId && isF ullScreenR esize !==  true){
  16842                         if(cineMan ager[layou tId] !== u ndefined)
  16843                             {
  16844                                 ci neManager[ currentLay OutId] = J SON.parse( JSON.strin gify(cineM anager[lay outId]));
  16845                                 if (studyLayo utValue != = "1x1" &&  currentLa yOutId !==  undefined  && curren tLayOutId  !== ""){
  16846                                      if(cineM anager[cur rentLayOut Id] !== un defined){
  16847                                           if( cineManage r[currentL ayOutId].p layStudy ! == undefin ed){
  16848                                                repeatCin eManager[c urrentLayO utId] = JS ON.parse(J SON.string ify(cineMa nager[curr entLayOutI d]));
  16849                                           }
  16850                                      }
  16851                                 }
  16852                             }
  16853                    }
  16854                }
  16855           }
  16856           va r viewport Property =  undefined ;
  16857           va r pageView portIndex  = 0;
  16858           fo r (var i =  0; i < ro w; i++) {
  16859                for (var  int2 = 0;  int2 < co lumn; int2 ++) {
  16860                    layo utId = "im ageviewer_ "+ studyVi ewportId+  "_" + (i +  1) + "x"  + (int2 +  1);
  16861                    var  imageLayou tDimension   = undefi ned;
  16862                    if(i sThumbnail Click) {
  16863                         viewportPr operty = d icomViewer .thumbnail .getViewpo rtProperty (layoutId) ;
  16864                         if(viewpor tProperty  != null) {
  16865                             series Index = vi ewportProp erty.split ("|")[1];
  16866                             imageI ndex = vie wportPrope rty.split( "|")[2];
  16867                             frameI ndex = vie wportPrope rty.split( "|")[3];
  16868                             imageL ayoutDimen sion = vie wportPrope rty.split( "|")[4];
  16869                         } else {
  16870                             isThum bnailClick  = false;
  16871                         }
  16872                    }
  16873                    var  imageValue  = undefin ed;
  16874                    if(d uplicateSe riesIndex  == 0) {
  16875                         imageValue  = dicomVi ewer.Serie s.Image.ge tImage(stu dyUid,seri esIndex,im ageIndex);
  16876                    }
  16877  
  16878                    
  16879                    if(b ackupLayou tId === "" ) backupLa youtId = l ayoutId;
  16880                     var  viewport  = dicomVie wer.viewpo rts.getVie wport(layo utId);
  16881                    if(v iewport != = undefine d && viewp ort !== nu ll){
  16882                         if(viewpor t.studyUid  === undef ined && st udyViewpor tId !== un defined){
  16883                             var im ageLayoutD isplayId =  "imageDis play" + st udyViewpor tId;
  16884                             docume nt.getElem entById(im ageLayoutD isplayId). style.disp lay='none' ;
  16885  
  16886                             var vi ewportTool barId = "S aveAndLoad _"+ studyV iewportId;
  16887                             if(doc ument.getE lementById (viewportT oolbarId)  !== null & & document .getElemen tById(view portToolba rId) !== u ndefined)  {
  16888                                doc ument.getE lementById (viewportT oolbarId). style.disp lay='none' ;
  16889                             }
  16890                         }
  16891                    }
  16892  
  16893                     if  (imageValu e !== unde fined && v iewport == = undefine d || viewp ort === nu ll)
  16894                     {
  16895                          var isIma geThumbnai l = dicomV iewer.thum bnail.isIm ageThumbna il(imageVa lue);
  16896                          if(isImag eThumbnail ){
  16897                             viewpo rt = dicom Viewer.vie wports.get BackupView portBySeri esIndex(st udyUid+"_" +imageInde x);
  16898                              dicom Viewer.vie wports.rem oveBackupV iewportByS eriesIndex (studyUid+ "_"+imageI ndex);
  16899                          }
  16900                          else{
  16901                              viewp ort = dico mViewer.vi ewports.ge tBackupVie wportBySer iesIndex(s tudyUid+"_ "+seriesIn dex);
  16902                              dicom Viewer.vie wports.rem oveBackupV iewportByS eriesIndex (studyUid+ "_"+series Index);
  16903                          }
  16904                          if (viewp ort !== un defined &&  viewport  !== null){
  16905                             if(dic omViewer.g etimageCan vasOfBacku pViewPort( viewport.s eriesLayou tId) != un defined){
  16906                                 ca nvasTemp =  Object.cr eate(dicom Viewer.get imageCanva sOfBackupV iewPort(vi ewport.ser iesLayoutI d));
  16907                                 di comViewer. removeimag eCanvasOfB ackupViewP ort(viewpo rt.seriesL ayoutId);   
  16908                                 di comViewer. setimageCa nvasOfView Port(layou tId,canvas Temp);
  16909                             }
  16910                              if(re sizeCineMa nager[view port.serie sLayoutId]  !== undef ined)
  16911                                 ci neManager[ layoutId]  = JSON.par se(JSON.st ringify(re sizeCineMa nager[view port.serie sLayoutId] )); 
  16912                              viewp ort.series LayoutId =  layoutId;
  16913                              dicom Viewer.vie wports.add Viewport(v iewport.se riesLayout Id, viewpo rt);
  16914                          }
  16915                     }
  16916  
  16917                    if(i mageValue  == undefin ed && (vie wport == u ndefined | | viewport  == null)  && studyUi d != undef ined) {
  16918                         var layout  = dicomVi ewer.viewp orts.getDu plicateVie wportByInd ex(duplica teSeriesIn dex, layou tId.split( '_')[1]);
  16919                         if(layout  != undefin ed && layo ut != null ) {
  16920                             series Index = la yout.getSe riesIndex( );
  16921                             imageI ndex = lay out.getIma geIndex();
  16922                             frameI ndex = lay out.getFra meIndex();
  16923                             imageV alue = dic omViewer.S eries.Imag e.getImage (studyUid,  seriesInd ex, imageI ndex);
  16924                         }
  16925                         duplicateS eriesIndex ++;
  16926                    }
  16927  
  16928                    if(v iewport !=  undefined  && viewpo rt != null  && pageVi ew != null  && pageVi ew != unde fined && i sBackup == = null) {
  16929                         viewport.s etImageLay outDimensi on(dicomVi ewer.viewp orts.getVi ewportImag eLayout(vi ewport.ser iesIndex,  pageViewpo rtIndex++) );
  16930                    }
  16931  
  16932                     if  (viewport  === undefi ned || vie wport ===  null)
  16933                     {
  16934                         viewport =  new Serie sLevelLayo ut(layoutI d);
  16935                         viewport.s etStudyUid (studyUid) ;
  16936                         viewport.s eriesLayou tId = layo utId;
  16937                         if(imageVa lue !== un defined)
  16938                         {
  16939                             viewpo rt.setSeri esIndex(se riesIndex) ;
  16940                             viewpo rt.setImag eIndex(ima geIndex);
  16941                             viewpo rt.setFram eIndex(fra meIndex);
  16942                         }
  16943                         else
  16944                         {
  16945                             viewpo rt.setSeri esIndex(un defined);
  16946                             viewpo rt.setImag eIndex(und efined);
  16947                             viewpo rt.setFram eIndex(und efined);
  16948                         }
  16949                         var imageL ayout = "1 x1";
  16950                          if(viewpo rt != unde fined && v iewport !=  null && p ageView !=  null && p ageView !=  undefined  && isBack up === nul l) {
  16951                              image Layout = d icomViewer .viewports .getViewpo rtImageLay out(series Index, pag eViewportI ndex++);
  16952                          }
  16953  
  16954                         viewport.s etImageLay outDimensi on(imageLa yout);
  16955                         dicomViewe r.viewport s.addViewp ort(viewpo rt.seriesL ayoutId, v iewport);
  16956                    }
  16957                     if( isThumbnai lClick) {
  16958                         viewport.i mageLayout Dimension  = imageLay outDimensi on;
  16959                     }
  16960                    imag eLayout =  viewport.g etImageLay outDimensi on().split ("x");
  16961                    // I nitialize  the ECG pr eference d etails.
  16962                    var  activeSeri esLayout =  dicomView er.getActi veSeriesLa yout();
  16963                    var  preference Info;
  16964                    if(a ctiveSerie sLayout &&  activeSer iesLayout. preference Info) {
  16965                         preference Info = act iveSeriesL ayout.pref erenceInfo ;
  16966                    } el se {
  16967                         preference Info = new  Preferenc eInfo();
  16968                         preference Info.init( );
  16969                    }
  16970  
  16971                    view port.setPr eferenceIn fo(prefere nceInfo);
  16972                    Appl yDisplaySe ttings(stu dyUid, pre ferenceInf o, seriesI ndex);
  16973                    var  isSeriesHa sMultiFram e = dicomV iewer.thum bnail.isSe riesContai nsMultifra me(studyUi d, seriesI ndex);
  16974                    if(i sSeriesHas MultiFrame  == true)  {
  16975                         setImageLe velLayout( studyUid,  parseInt(i mageLayout [0]), pars eInt(image Layout[1]) , layoutId , viewport , viewport .seriesInd ex, viewpo rt.scrollD ata.imageI ndex, view port.scrol lData.fram eIndex, tr ue);
  16976                     }
  16977                    else  {
  16978                         setImageLe velLayout( studyUid,  parseInt(i mageLayout [0]), pars eInt(image Layout[1]) , layoutId , viewport , viewport .seriesInd ex, 0, vie wport.scro llData.fra meIndex, t rue);
  16979                     }
  16980                    if(i mageValue  !== undefi ned)
  16981                    {
  16982                         $("#" + la youtId).mo usedown(se lectViewpo rt); 
  16983                         $("#" + la youtId).mo useover(fo cusActiveL ayout);
  16984                         $("#" + la youtId).ke ydown(keyT oMoveNextO rPreviousI mage); 
  16985                    }
  16986                    $("# " + layout Id).bind(' mousewheel  DOMMouseS croll', sc roll);
  16987                    $("# " + layout Id).on("dr agover", a llowDrop);
  16988                    $("# " + layout Id).on("dr op", serie sDrop);
  16989                    $("# " + layout Id).click( selectView port);
  16990                    if(s tudyUid != = undefine d && image Value !==  undefined)
  16991                    {
  16992                         seriesInde x = viewpo rt.getSeri esIndex();
  16993                         imageIndex  = viewpor t.getImage Index();
  16994                         frameIndex  = viewpor t.getFrame Index();
  16995                         if(studyUi d !== unde fined && s eriesIndex  !== undef ined && im ageIndex ! == undefin ed) {
  16996                            var ima geCount =  dicomViewe r.Series.g etImageCou nt(studyUi d, seriesI ndex);
  16997                             if( (d icomViewer .thumbnail .isImageTh umbnail(im ageValue)  ||
  16998                                  d icomViewer .thumbnail .isSeriesC ontainsMul tiframe(st udyUid, se riesIndex) ) && image Count >= 1  ) {
  16999                                var  frameCoun t = dicomV iewer.Seri es.Image.g etImageFra meCount(di comViewer. Series.Ima ge.getImag e(studyUid , seriesIn dex, image Index));
  17000                                 vi ewport.pro gressbar.u pdateImage Position(f rameCount,  frameInde x);
  17001                                 fr ameIndex =  0;
  17002                                 if (imageInde x < imageC ount-1 ||  isSeriesHa sMultiFram e) {
  17003                                      imageInd ex++;
  17004                                 }  else {
  17005                                      //If it  is the las t image of  the serie s then mov ing to the  next seri es with fi rst image
  17006                                      imageInd ex = 0;
  17007                                      seriesIn dex++;
  17008                                 }
  17009                             } else  {
  17010                                 vi ewport.pro gressbar.u pdateImage Position(i mageCount,  imageInde x);  
  17011                                 im ageIndex =  0;
  17012                                 fr ameIndex =  0;
  17013                                 se riesIndex+ +;
  17014                             }
  17015                         }
  17016  
  17017                         if(duplica teSeriesIn dex > 0) {
  17018                             series Index = di comViewer. Study.getS eriesCount (studyUid)  + duplica teSeriesIn dex;
  17019                         }
  17020                    }
  17021                                                                   
  17022                }
  17023           }
  17024  
  17025           if (pageView  != undefin ed && page View != nu ll && isBa ckup === n ull ) {
  17026                dicomVie wer.viewpo rts.delete ViewportIm ageLayouts ();
  17027           }
  17028  
  17029           if (isBackup  === undefi ned || isB ackup ===  null)
  17030           {
  17031                dicomVie wer.remove imageCanva sOfAllBack upViewPort s(studyVie wportId);
  17032                for (var  key in re sizeCineMa nager){
  17033                    var  studyLayou tId = key. split("_") [1];
  17034                    if(s tudyViewpo rtId == st udyLayoutI d){
  17035                         delete res izeCineMan ager[key];
  17036                    }
  17037                }
  17038                dicomVie wer.viewpo rts.remove AllBackupV iewportByS eriesIndex (studyView portId);
  17039           }
  17040           if (isBackup  === undefi ned || isB ackup ===  null || is Backup ===  false)
  17041           {
  17042                for(var  layoutId i n cineMana ger)
  17043                {
  17044                    var  studyLayou tId = layo utId.split ("_")[1];
  17045                    if ( cineManage r[layoutId ] !== unde fined && s tudyViewpo rtId == st udyLayoutI d) 
  17046                    {
  17047                         if (cineMa nager[layo utId].time r == null)
  17048                         {
  17049                             update PlayIcon(" stop.png", "play.png" );
  17050                         } else
  17051                         {
  17052                             var pa rentElemen t = $("#pl ayBackward ").parent( ).css("bac kground"," ");
  17053                             var pa rentElemen t = $("#pl ayForward" ).parent() .css("back ground","# 868696");
  17054                             $("#"+  layoutId) .trigger(" click"); 
  17055                             update PlayIcon(" play.png", "stop.png" );
  17056                             if(isC ineEnabled ())
  17057                             {
  17058                                 va r obj = {} ;
  17059                                 ob j.id =  "p layButton"
  17060                                 va r seriesLa yout = dic omViewer.v iewports.g etViewport (layoutId) ;
  17061                                 if (cineManag er[layoutI d].playStu dy == true ){
  17062                                      seriesLa yout.serie sIndex = 0 ;
  17063                                      seriesLa yout.scrol lData.imag eIndex = 0 ;
  17064                                 }
  17065  
  17066                                 di comViewer. setActiveS eriesLayou t(seriesLa yout);
  17067                                 up datePlayIc on("stop.p ng","play. png");
  17068                                 pl ayCineImag e(obj,unde fined);
  17069                             }
  17070                         }
  17071                    }
  17072                }
  17073                $("#"+ b ackupLayou tId).trigg er("click" ); 
  17074                                
  17075           }e lse
  17076           {
  17077                 
  17078                if (cine Manager[la youtId] != = undefine d) 
  17079                {
  17080                    if ( cineManage r[layoutId ].timer ==  null)
  17081                    {
  17082                         updatePlay Icon("stop .png","pla y.png");
  17083                    } el se
  17084                    {
  17085                         var parent Element =  $("#playBa ckward").p arent().cs s("backgro und","");
  17086                         var parent Element =  $("#playFo rward").pa rent().css ("backgrou nd","#8686 96");
  17087                         $("#"+ lay outId).tri gger("clic k");
  17088                         updatePlay Icon("play .png","sto p.png");
  17089                         if(isCineE nabled())
  17090                         {
  17091                             var ob j = {};
  17092                             obj.id  =  "playB utton"
  17093                             playCi neImage(ob j);
  17094                             playCi neImage(ob j);
  17095                         }
  17096                    }
  17097                }
  17098                changeSe lection(la youtId);
  17099           }
  17100            a utoCinePla y();
  17101       }
  17102  
  17103       functi on focusAc tiveLayout (event) {
  17104           $( "#" + getA ctiveSerie sLayout(). seriesLayo utId).focu s();
  17105       }
  17106  
  17107       /**
  17108        * To  create the  custom/em bed pdf vi ewer
  17109        * @pa ram {Type}  image - T o specifie s the imag e info
  17110        * @pa ram {Type}  viewport  - To speci fies the v iewport de tails
  17111        * @pa ram {Type}  render -  To specifi es the ima ge render
  17112        * @pa ram {Type}  seriesLev elDiv - To  specifies  the serie s layout D iv ID
  17113        */ 
  17114       functi on createP DFRender(i mage,viewp ort,render er,seriesL evelDiv) {
  17115           va r urlParam eters = di comViewer. getPdfFram eUrl(image .imageUid) ;
  17116           if (urlParame ters.Frame Number !==  undefined ) {
  17117                urlParam eters.Fram eNumber =  undefined;
  17118           }
  17119  
  17120           va r isPdfVie wer = isEm bedPdfView er(image.i mageType)  ? false :  true;
  17121           va r pdfData  = isPdfVie wer ? "pdf " : "pdfDa ta";
  17122           va r url = di comViewer. url.getDic omImageURL (urlParame ters);
  17123           vi ewport.add ImageRende r(pdfData,  renderer) ;
  17124  
  17125           if (isPdfView er) {
  17126                var pdfU rl = "pdfv iewer1x1";
  17127                var pdfD iv = "<div  id='pdf'  style='hei ght:100%;w idth:100%' ><iframe i d='pdfview er1x1' nam e='pdfview er1x1' sty le='height :100%;widt h:100%' sr c="+url+"  onload='th is.focus() '/></div>"
  17128                $("#"+se riesLevelD iv).empty( );
  17129                $("#"+se riesLevelD iv).append (pdfDiv);
  17130                $("#" +  pdfUrl).bi nd('mousew heel DOMMo useScroll' , scroll);
  17131                $("#" +  pdfUrl).mo usedown(se lectViewpo rt); 
  17132                $("#" +  pdfUrl).mo useover(fo cusActiveL ayout);
  17133                $("#" +  pdfUrl).ke ydown(keyT oMoveNextO rPreviousI mage); 
  17134  
  17135                $("#" +  pdfUrl).on ("dragover ", allowDr op);
  17136                $("#" +  pdfUrl).on ("drop", s eriesDrop) ;
  17137                $("#" +  pdfUrl).cl ick(select Viewport);
  17138                bringToF rontPdf(se riesLevelD iv, viewpo rt.imageTy pe);
  17139           }  else {
  17140                dicomVie wer.create PDF(url, s eriesLevel Div);
  17141           }
  17142       }
  17143  
  17144       functi on setImag eLevelLayo ut(studyUi d, row, co lumn, seri esLevelDiv , viewport , seriesIn dex, image Index, fra meIndex, i sMoveSerie s) {
  17145           va r isSingle FrameUS =  false;
  17146           if (studyUid  !== undefi ned && ser iesIndex ! == undefin ed && isMo veSeries = = true){
  17147                // set t he row and  column fo r series,  when image  count as  1
  17148                var imag eCount = 0 ;
  17149                var fram eCount = 0 ;
  17150                imageCou nt = dicom Viewer.Ser ies.getIma geCount(st udyUid, se riesIndex) ;
  17151                frameCou nt = dicom Viewer.Ser ies.Image. getImageFr ameCount(d icomViewer .Series.Im age.getIma ge(studyUi d, seriesI ndex, imag eIndex));
  17152                imageCou nt = dicom Viewer.thu mbnail.isS eriesConta insMultifr ame(studyU id, series Index) ? f rameCount  : imageCou nt;
  17153  
  17154                if(image Count == 1 ) {
  17155                    row  = 1; colum n = 1;
  17156                    isSi ngleFrameU S = true;
  17157                }
  17158           }
  17159  
  17160           $( "#" + seri esLevelDiv ).empty();
  17161           va r imageLev elName = s eriesLevel Div + "Ima geLevel";
  17162           va r appendSt ring = "<t able style ='width:10 0%;height: 99%;'>";
  17163           fo r (var i =  0; i < ro w; i++) {
  17164                appendSt ring += "< tr style=' height:" +  (100 / ro w) + "%;'> ";
  17165                for (var  j = 0; j  < column;  j++) {
  17166                    var  tableDataI d = imageL evelName +  i + "x" +  j + "id";
  17167                    appe ndString + = "<td id= " +tableDa taId+ " st yle='width :" + ((100  / column) ) + "%;hei ght:" + (( 100 / row) ) + "%;'>" ;
  17168                    appe ndString =  appendStr ing + "<di v id=" + i mageLevelN ame + i +  "x" + j +  " style='h eight:98%; width:99%; '></div>";
  17169                    appe ndString + = "</td>";
  17170                }
  17171                appendSt ring += "< /tr>";
  17172           }
  17173           ap pendString  += "</tab le>";
  17174           $( "#" + seri esLevelDiv ).html(app endString) ;
  17175           $( "#" + seri esLevelDiv ).addClass ('default- view');
  17176           va r defaultI mageLayout Id = image LevelName  + "0x0";
  17177           $( "#"+defaul tImageLayo utId+"id") .removeCla ss('defaul t-view');
  17178           up dateSpinne rLocation( seriesLeve lDiv);
  17179  
  17180           va r progress bar = new  ViewportPr ogreeBar(s eriesLevel Div);
  17181           di comViewer. cacheIndic ator.addCa cheIndicat or(progres sbar);
  17182           vi ewport.set Progressba r(progress bar);
  17183           di comViewer. progress.s etSpinnerD ata(progre ssbar);
  17184           if  (studyUid  === undef ined) retu rn;
  17185           if (seriesInd ex === und efined) re turn;
  17186           va r imageSer ies = dico mViewer.Se ries.getSe ries(study Uid,series Index);
  17187           // check the  series is  available  based on s eries inde x if not a vailable i t ill retu rn
  17188           if  (imageSer ies == und efined) {
  17189                return;
  17190           }
  17191           va r spinner  = dicomVie wer.progre ss.createA ndGetSpinn er(seriesL evelDiv);
  17192           di comViewer. progress.p utSpinner( seriesLeve lDiv, spin ner);
  17193                    
  17194           // For storin g the pres entation v alues of t he altered  image(es)
  17195           va r updatedC anvasPrese ntation =  undefined;
  17196           va r isPresen tationUpda tionRequir ed = true;
  17197           if  (row ===  1 && colum n === 1) {
  17198                var imag e = dicomV iewer.Seri es.Image.g etImage(st udyUid, se riesIndex,  imageInde x);
  17199                var anUI Ds = dicom Viewer.Ser ies.Image. getImageUi d(image) +  "*" + (fr ameIndex++ )
  17200                var defa ultImageLa youtId = i mageLevelN ame + "0x0 ";
  17201                $("#"+de faultImage LayoutId+" id").remov eClass('de fault-view ');
  17202                var rend erer = und efined;
  17203                renderer  = viewpor t.getImage Render(vie wport.seri esLayoutId + "ImageLe vel0x0");
  17204  
  17205                //checki ng the ava ilabilty f or the ren dered imag e as well  as its pre sentation  values, if  the rende red image  is altered  then only  fetch and  store its  presentat ion values
  17206                if((rend erer != nu ll || rend erer != un defined) & & renderer .presentat ionState ! = undefine d){
  17207                    if(i sPresentat ionUpdatio nRequired)  {
  17208                         updatedCan vasPresent ation = re nderer.pre sentationS tate;
  17209                         updatedCan vasPresent ation.zoom  = rendere r.scaleVal ue;
  17210                         isPresenta tionUpdati onRequired  = false;
  17211                    }
  17212                }
  17213                renderer  = new Ima geRenderer (defaultIm ageLayoutI d,seriesLe velDiv);
  17214                renderer .init(anUI Ds, series Index, ima geIndex);
  17215  
  17216                if(image .modality  === "US" & & !isSingl eFrameUS)
  17217                    view port.setIm ageType(IM AGETYPE_RA DECHO);
  17218                else
  17219                    view port.setIm ageType(im age.imageT ype);
  17220                if(image .imageType  == IMAGET YPE_RAD ||  image.ima geType ==  IMAGETYPE_ RADECHO ||  image.ima geType ===  IMAGETYPE _JPEG)
  17221                {
  17222                    view port.addIm ageRender( defaultIma geLayoutId , renderer );
  17223                    
  17224                }
  17225                var imag eUid = dic omViewer.S eries.Imag e.getImage Uid(image) ;
  17226                var head er = dicom Viewer.hea der.getDic omHeader(i mageUid);
  17227                var imag ePromise =  undefined ;
  17228  
  17229                if (head er) {
  17230                    var  imageType  = image.im ageType;
  17231                    if ( imageType  == IMAGETY PE_RADECHO  || imageT ype == IMA GETYPE_RAD  || image. imageType  === IMAGET YPE_JPEG)  {
  17232                         disableOrE nableDicom Tools(fals e);
  17233  
  17234                         if(image.m odality ==  "CT") {
  17235                             update KendoArrow Button($(" #winL_wrap per"), fal se);
  17236                         }
  17237                         imagePromi se = dicom Viewer.ima geCache.ge tImageProm ise(imageU id +"_"+ ( frameIndex  - 1));
  17238                         if (imageP romise ===  undefined ) {
  17239  
  17240                             if (di comViewer. thumbnail. isSeriesCo ntainsMult iframe(stu dyUid, ser iesIndex))  {
  17241                                 im agePromise  = dicomVi ewer.getIm age(studyU id, imageU id, frameI ndex - 1,  imageIndex , imageTyp e, seriesI ndex);
  17242                             } else  {
  17243                                 im agePromise  = dicomVi ewer.getIm age(studyU id, imageU id, frameI ndex - 1,  seriesInde x, imageTy pe);
  17244                             }
  17245  
  17246                         }
  17247                         var imageC anvas = nu ll;
  17248                         imagePromi se.then(fu nction(ima ge) {
  17249                             imageC anvas = im age;
  17250                         });
  17251  
  17252                         //On first  time when  the viewe r is rende ring the i mage, upda tedCanvasP resentatio n will be  undefined
  17253                         if(updated CanvasPres entation ! = null &&  updatedCan vasPresent ation != u ndefined)  {
  17254                             if(ima geCanvas ! = null &&  imageCanva s != undef ined) {
  17255                                 if (imageCanv as.present ation.pres entationMo de == "MAG NIFY") {
  17256                                      updatedC anvasPrese ntation.pr esentation Mode = "MA GNIFY";
  17257                                 }
  17258  
  17259                                 im ageCanvas. presentati on = updat edCanvasPr esentation ;
  17260                             }
  17261                         }
  17262                         //get the  imageCanva s value ba sed on the  viewport  id
  17263                         var imageC anvasValue  = imageCa nvasOfView Ports[seri esLevelDiv ];
  17264                         /* selecte d thumbnai l image sh oud have i mageCanvas Value
  17265                         other imag es we are  doing inde fined for  imageCanva sValue to  avoid
  17266                         the duplic ation in t he view po rt*/
  17267                         if(selectT humbnailIm ageIndex ! == undefin ed && sele ctThumbnai lImageInde x != image Index){
  17268                             imageC anvasValue  = undefin ed;
  17269                         }
  17270                         /*when the  imageCanv asValue is  undefines  or alread y added im ageCanvas  is not equ al to curr ent imagea Canvas(ide ntify usin g image id ) we are a dding the  new imageC anvas to t he object( view port  div id as  key and im ageCanvas  as value)* /
  17271                         if (imageC anvasValue  == undefi ned && ima geCanvas ! == null) {
  17272                             /*Addi ng the new  imageCanv as value t o object b ased on vi ewport id  as key*/
  17273                             imageC anvas.seri esIndex =  seriesInde x;
  17274                             imageC anvas.imag eIndex = i mageIndex;
  17275                             setima geCanvasOf ViewPort(s eriesLevel Div, image Canvas);
  17276                             render er.loadIma geRenderer (imageProm ise, image Canvas, st udyUid);
  17277                             render er.present ationState .windowLev el = image Canvas.las tAppliedWi ndowLevel;
  17278                         } else {
  17279                             if(ima geCanvasVa lue != und efined &&  imageCanva s != null) {
  17280                             /*imag eCanvas is  alreday a vilable in  same imag e of same  viewport i f image id  present i n the imag eCanvasVal ue is not  maching wi th the ima ge we are  updating t he image p romised ba sed on sel cted user  image
  17281                         when drag  the image  thumbnail  we can mai ntain the  current im age of the  series on  viewport* /
  17282                             if ( i mageCanvas Value.imag eUid != im age.imageU id || imag eCanvas.fr ameNumber  != imageCa nvasValue. frameNumbe r) {
  17283                                 va r imagePro miseVal =  dicomViewe r.imageCac he.getImag ePromise(i mageCanvas Value.imag eUid +"_"+  (imageCan vasValue.f rameNumber ));
  17284                                 if  (imagePro miseVal !=  undefined ) {
  17285                                      imagePro mise = ima gePromiseV al;
  17286                                 }
  17287                             }
  17288                                 if (imageCanv as.present ation) {
  17289                                      imageCan vasValue.p resentatio n = imageC anvas.pres entation;
  17290                                 }
  17291                                 re nderer.loa dImageRend erer(image Promise, i mageCanvas Value);
  17292                                 re nderer.pre sentationS tate.windo wLevel = i mageCanvas .lastAppli edWindowLe vel;
  17293                                 im ageUid = i mageCanvas Value.imag eUid;
  17294                             }
  17295                         }
  17296                    }
  17297                }
  17298                if(image .imageType  == IMAGET YPE_RADECH O) {
  17299                    var  imageCount Flag = fal se;
  17300                    var  isMultiFra me = dicom Viewer.thu mbnail.isS eriesConta insMultifr ame(studyU id, series Index);
  17301                    if(i sMultiFram e){
  17302                         for (var i  = 0; i <  dicomViewe r.Study.ge tSeriesCou nt(studyUi d); i++){
  17303                             for (v ar j = 0;  j < dicomV iewer.Seri es.getImag eCount(stu dyUid, i);  j++){
  17304                               var  image = di comViewer. Series.Ima ge.getImag e(studyUid ,i,j);
  17305                               var  multiFrame Count = di comViewer. Series.Ima ge.getImag eFrameCoun t(image);
  17306                               if(m ultiFrameC ount > 1){
  17307                                  i mageCountF lag = true ;
  17308                                  b reak;
  17309                               }
  17310                             }
  17311                         }
  17312                         disableToo lbarForUsI mages(true );
  17313                    } el se{
  17314                         for (var i  = 0; i <  dicomViewe r.Study.ge tSeriesCou nt(studyUi d); i++){
  17315                             var im ageCount =  dicomView er.Series. getImageCo unt(studyU id, i);
  17316                             if(ima geCount >  1){
  17317                                ima geCountFla g = true;
  17318                                bre ak;
  17319                             }
  17320                         }
  17321                         disableToo lbarForUsI mages(fals e);
  17322                    }
  17323                                      
  17324                    enab leOrDisabl eNavigatio nTools(ima geCountFla g);
  17325                    disa bleOrEnabl eDicomTool s(false);
  17326                }else if  (image.im ageType ==  IMAGETYPE _RADPDF) {
  17327                    crea tePDFRende r(image,vi ewport,ren derer,seri esLevelDiv );
  17328                    } el se if (ima ge.imageTy pe == IMAG ETYPE_RADE CG) {
  17329                         viewport.a ddImageRen der("ecgDa ta", rende rer);
  17330                         var urlPar ameters =  dicomViewe r.getJpegF rameUrl(im ageUid, 0) ;
  17331                       d icomViewer .loadEcg(u rlParamete rs,seriesL evelDiv);
  17332                    } el se if (ima ge.imageTy pe === IMA GETYPE_RAD SR || imag e.imageTyp e === IMAG ETYPE_CDA)  {
  17333                         viewport.a ddImageRen der("srRep ort", rend erer);
  17334                         var urlPar ameters =  dicomViewe r.getImage InfoURl(im ageUid);
  17335                         imagePromi se = dicom Viewer.ima geCache.ge tImageProm ise(imageU id +"_"+ ( frameIndex  - 1));
  17336                         if (imageP romise ===  undefined ) {
  17337                             if (di comViewer. thumbnail. isSeriesCo ntainsMult iframe(stu dyUid, ser iesIndex))  {
  17338                                 im agePromise  = dicomVi ewer.getIm age(studyU id, imageU id, frameI ndex - 1,  imageIndex , image.im ageType, s eriesIndex );
  17339                             } else  {
  17340                                 im agePromise  = dicomVi ewer.getIm age(studyU id, imageU id, frameI ndex - 1,  seriesInde x, image.i mageType);
  17341                             }
  17342  
  17343                         }   
  17344                         dicomViewe r.loadSR(u rlParamete rs, series LevelDiv,  imagePromi se, image. imageType) ;
  17345                    } el se if (ima ge.imageTy pe === IMA GETYPE_JPE G) {
  17346                         disableToo lBarForNon Dicom();
  17347                    } el se if (isB lob(image. imageType) ) {
  17348                         if (image. imageType  === IMAGET YPE_VIDEO)  {
  17349                             viewpo rt.addImag eRender(im age.imageT ype, rende rer);
  17350                             var vi deoUrls =  dicomViewe r.getVideo Urls(image .imageUid) ;
  17351                             for (i  = 0; i <  videoUrls. length; i+ +) {
  17352                                 vi deoUrls[i] .url = dic omViewer.u rl.getDico mImageURL( videoUrls[ i].urlPara meters);
  17353                             }
  17354                             dicomV iewer.load VideoPlaye r(videoUrl s, seriesL evelDiv);
  17355                         } else if  (image.ima geType ===  IMAGETYPE _AUDIO) {
  17356                             viewpo rt.addImag eRender(im age.imageT ype, rende rer);
  17357                             var au dioURLObje ct = dicom Viewer.get AudioUrl(i mage.image Uid);
  17358                             var au dioURL = d icomViewer .url.getDi comImageUR L(audioURL Object);
  17359                             dicomV iewer.load Player(aud ioURL, ser iesLevelDi v, "mp3");
  17360                         } else if  (image.ima geType ===  IMAGETYPE _PDF || im age.imageT ype === IM AGETYPE_TI FF) {
  17361                             create PDFRender( image,view port,rende rer,series LevelDiv);
  17362                         } else { / / unknown  image
  17363                             var he ight = $(" #" + serie sLevelDiv) .height();
  17364                             var pd fDiv = "<d iv id='pdf ' style='h eight:" +  height + " px;line-he ight:" + h eight + "p x;backgrou nd:white'  align='cen ter'>Unkno wn Type</d iv>"
  17365                             $("#"  + seriesLe velDiv).em pty();
  17366                             $("#"  + seriesLe velDiv).ap pend(pdfDi v);
  17367                         }
  17368                    } el se if(imag e.modality =='US') {
  17369                         disableToo lbarForUsI mages(fals e);
  17370                    }
  17371                
  17372                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  17373                var stud yLayoutId  = getStudy LayoutId(s eriesLevel Div);
  17374                var stud yInformati ondiv = "s tudyInfo"+ studyLayou tId;
  17375                if(study Details.pr ocedure == = null ||  studyDetai ls.procedu re === ""  ||studyDet ails.proce dure.lengt h ===0){
  17376                    $("# "+studyInf ormationdi v).html("& nbsp");
  17377                }else{
  17378                    $("# "+studyInf ormationdi v).html(st udyDetails .procedure );
  17379                    upda teToolTip( $("#"+stud yInformati ondiv), st udyDetails .procedure , "top");
  17380                }
  17381  
  17382                var stud yTime = "" ;
  17383                var stud yId = "";
  17384                if(study Details.da teTime !==  null && s tudyDetail s.dateTime  !== undef ined) {
  17385                    stud yTime = st udyDetails .dateTime. replace("T ", "@");
  17386                }
  17387                
  17388                if(study Details.di comStudyId  !== null  && studyDe tails.dico mStudyId ! == undefin ed) {
  17389                    stud yId = stud yDetails.d icomStudyI d;
  17390                }
  17391  
  17392                if(study Time !== " " || study Id !== "")  {
  17393                    var  studyDispl ayText = ( studyId != = "" ? stu dyId +", "  + studyTi me : study Time);
  17394                    $("# studyUidDa teTime"+st udyLayoutI d).html(st udyDisplay Text);
  17395                    upda teToolTip( $("#studyU idDateTime "+studyLay outId), st udyDisplay Text, "top ");
  17396                }
  17397  
  17398                imageInd ex = getIm ageIndexFo rImageUid( studyUid,s eriesIndex , imageUid );
  17399                progress bar.setSer iesInfo(st udyUid, se riesIndex,  imageInde x, frameIn dex - 1);
  17400                if (imag eIndex ==  undefined)
  17401                    imag eIndex = 0 ;
  17402                $("#"+de faultImage LayoutId+" id").remov eClass('de fault-view ');
  17403           }  else {
  17404                for (var  i = 0; i  < row; i++ ) {
  17405                    for  (var j = 0 ; j < colu mn; j++) {
  17406                         if (dicomV iewer.Seri es.getSeri es(studyUi d, seriesI ndex)) {
  17407                             var im ageLayoutI d = imageL evelName +  i + "x" +  j;
  17408                             var fr amecount =  0;
  17409                             var im age = dico mViewer.Se ries.Image .getImage( studyUid,  seriesInde x, imageIn dex);
  17410                             $("#"+ imageLayou tId+"id"). addClass(' default-vi ew');
  17411                             if (!i mage) {
  17412                                 co ntinue;
  17413                             }
  17414                             frameC ount = dic omViewer.S eries.Imag e.getImage FrameCount (image);
  17415                             if (!( frameCount  > frameIn dex)) {
  17416                                 if (!dicomVie wer.thumbn ail.isImag eThumbnail (image))
  17417                                 {
  17418                                      imageInd ex++;
  17419                                 }
  17420                                 fr ameIndex =  0;
  17421                                 im age = dico mViewer.Se ries.Image .getImage( studyUid,  seriesInde x, imageIn dex);
  17422                             }
  17423                             if(ima ge) {
  17424                                 va r anUIDs =  dicomView er.Series. Image.getI mageUid(im age) + "*"  + (frameI ndex++)
  17425                                 va r renderer  = undefin ed;
  17426                                 re nderer = v iewport.ge tImageRend er(viewpor t.seriesLa youtId+ "I mageLevel" + i + "x"  + j);
  17427                                 // checking t he availab ilty for t he rendere d image as  well as i ts present ation valu es, if the  rendered  image is a ltered the n only fet ch and sto re its pre sentation  values
  17428                                 if ((renderer  != null | | renderer  != undefi ned) && re nderer.pre sentationS tate != un defined) {
  17429                                      if(isPre sentationU pdationReq uired) {
  17430                                          upda tedCanvasP resentatio n = render er.present ationState ;
  17431                                          upda tedCanvasP resentatio n.zoom = r enderer.sc aleValue;
  17432                                          isPr esentation UpdationRe quired = f alse;
  17433                                      }
  17434                                 }
  17435  
  17436                                 re nderer = n ew ImageRe nderer(ima geLayoutId ,seriesLev elDiv);
  17437                                 re nderer.ini t(anUIDs,  seriesInde x, imageIn dex);
  17438                                 vi ewport.add ImageRende r(imageLev elName + i  + "x" + j , renderer );
  17439  
  17440                                 va r imageUid  = dicomVi ewer.Serie s.Image.ge tImageUid( image);
  17441                                 va r header =  dicomView er.header. getDicomHe ader(image Uid);
  17442                                 va r imagePro mise = und efined;
  17443                                 if (header) {
  17444                                      imagePro mise = dic omViewer.i mageCache. getImagePr omise(imag eUid +"_"+  (frameInd ex - 1));
  17445                                      if (imag ePromise = == undefin ed) {
  17446                                          if ( dicomViewe r.thumbnai l.isSeries ContainsMu ltiframe(s tudyUid, s eriesIndex )) {
  17447                                               imagePromi se = dicom Viewer.get Image(stud yUid, imag eUid, fram eIndex - 1 , imageInd ex, image. imageType,  seriesInd ex);
  17448                                          } el se {
  17449                                               imagePromi se = dicom Viewer.get Image(stud yUid, imag eUid, fram eIndex - 1 , seriesIn dex, image .imageType );
  17450                                          }
  17451  
  17452                                      }
  17453                                      var imag eCanvasVal ue = null;
  17454                                      imagePro mise.then( function(i mage) {
  17455                                          imag eCanvasVal ue = image ;
  17456                                      });
  17457                                      
  17458                                      //On fir st time wh en the vie wer is ren dering the  image, up datedCanva sPresentat ion will b e undefine d
  17459                                      if(updat edCanvasPr esentation  != null & & updatedC anvasPrese ntation !=  undefined  && imageC anvasValue  != null)  {
  17460                                          if(i mageCanvas Value.pres entation.p resentatio nMode == " MAGNIFY")  {
  17461                                               updatedCan vasPresent ation.pres entationMo de = "MAGN IFY";
  17462                                          }
  17463                                          imag eCanvasVal ue.lastApp liedWindow Width = up datedCanva sPresentat ion.window Width;
  17464                                          imag eCanvasVal ue.lastApp liedwindow Center = u pdatedCanv asPresenta tion.windo wCenter;
  17465                                          imag eCanvasVal ue.lastApp liedBright ness = upd atedCanvas Presentati on.brightn ess;
  17466                                          imag eCanvasVal ue.lastApp liedContra st = updat edCanvasPr esentation .contrast;
  17467                                          imag eCanvasVal ue.present ation = up datedCanva sPresentat ion;
  17468                                          imag eCanvasVal ue.lastApp liedWindow Level = up datedCanva sPresentat ion.window Level;
  17469                                      }
  17470  
  17471                                      if(image CanvasValu e == null  || imageCa nvasValue  == undefin ed || imag eCanvasVal ue == ""){
  17472                                          rend erer.loadI mageRender er(imagePr omise);
  17473                                      }
  17474                                      else{
  17475                                          rend erer.loadI mageRender er(imagePr omise, ima geCanvasVa lue);
  17476                                      }
  17477  
  17478                                      if(isPre sentationU pdationReq uired &&
  17479                                         updat edCanvasPr esentation  === undef ined) {
  17480                                          upda tedCanvasP resentatio n = jQuery .extend(tr ue, {}, re nderer.pre sentationS tate);
  17481                                          if(i mageCanvas Value !==  null && im ageCanvasV alue !== u ndefined)  {
  17482                                               updatedCan vasPresent ation.zoom  = imageCa nvasValue. presentati on.zoom;
  17483                                          }
  17484                                          isPr esentation UpdationRe quired = f alse;
  17485                                      }
  17486  
  17487                                      if (colu mn > 1 ||  row > 1) {
  17488                                          dico mViewer.to ols.setDic omOverLayF alse(viewp ort);
  17489                                      }
  17490                                 }
  17491  
  17492                                 im ageIndex =  getImageI ndexForIma geUid(stud yUid, seri esIndex, i mageUid);
  17493                                 pr ogressbar. setSeriesI nfo(studyU id, series Index, ima geIndex, f rameIndex  - 1);
  17494                             }
  17495                         }
  17496                    }
  17497                }
  17498           }
  17499       }
  17500  
  17501       functi on getImag eIndexForI mageUid(st udyUid,ser iesIndex,  imageUid)  {
  17502           va r series =  dicomView er.Series. getSeries( studyUid,s eriesIndex );
  17503           fo r (var i =  0; i < di comViewer. Series.get ImageCount (studyUid, seriesInde x); i++) {
  17504                if (imag eUid === d icomViewer .Series.Im age.getIma ge(studyUi d,seriesIn dex, i).im ageUid) {
  17505                    retu rn i;
  17506                }
  17507           }
  17508       }
  17509  
  17510       /**
  17511        * Sel ection the  preferenc e saved in formation  to the ECG  preferenc e.
  17512        */
  17513       functi on updateP referenceV alues() {
  17514           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  17515           va r render ;
  17516           $( "#" + seri esLayout.g etSeriesLa youtId() +  " div").e ach(functi on() {
  17517                var imag eLayoutId  = $(this). attr('id') ;
  17518                render =  seriesLay out.getIma geRender(i mageLayout Id);
  17519                return;
  17520           }) ;
  17521           
  17522           va r windowAt tr = serie sLayout.pr eferenceIn fo.windowL evelSettin gs;
  17523           if (render &&  render.pr esentation State){
  17524                windowAt tr = rende r.presenta tionState. windowLeve l;
  17525           }
  17526           
  17527           va r zoomAttr  = seriesL ayout.pref erenceInfo .zoomLevel Setting;
  17528           if (render &&  render.pr esentation State) {
  17529                zoomAttr  = render. presentati onState.zo omLevel+"_ zoom";
  17530           }
  17531           
  17532           //  Update Wi ndow level  settings  preference  informati on
  17533           di comViewer. tools.upda teWindowLe velSetting s(windowAt tr);
  17534           di comViewer. tools.upda teZoomLeve lSettings( zoomAttr);
  17535           if  (seriesLa yout.prefe renceInfo  === undefi ned || ser iesLayout. preference Info === n ull || 
  17536                seriesLa yout.prefe renceInfo. preference Data === u ndefined | | seriesLa yout.prefe renceInfo. preference Data === n ull)
  17537           {
  17538                return;
  17539           }
  17540           if (seriesLay out.imageT ype === IM AGETYPE_RA DECG){
  17541                resetCon textMenuSe lection();
  17542                for(var  preference Id in pref erenceList )
  17543                {
  17544                    swit ch(prefere nceList[pr eferenceId ])
  17545                    {
  17546                         case "grid type":
  17547                             if (se riesLayout .preferenc eInfo.pref erenceData .gridType  !== undefi ned) {
  17548                                 $( "#"+series Layout.pre ferenceInf o.preferen ceData.gri dType).par ent().css( "backgroun d","#86869 6");
  17549                             }
  17550                         break;
  17551                         case "grid color":
  17552                             if (se riesLayout .preferenc eInfo.pref erenceData .gridColor  !== undef ined) {
  17553                                 $( "#"+series Layout.pre ferenceInf o.preferen ceData.gri dColor).pa rent().css ("backgrou nd","#8686 96");
  17554                             }
  17555                         break;
  17556                         case "lead format":
  17557                             if (se riesLayout .preferenc eInfo.pref erenceData .leadForma t !== unde fined) {
  17558                                 $( "#"+series Layout.pre ferenceInf o.preferen ceData.lea dFormat).p arent().cs s("backgro und","#868 696");
  17559                             }
  17560                         break;
  17561                         case "gain ":
  17562                             if (se riesLayout .preferenc eInfo.pref erenceData .gain !==  undefined)  {
  17563                                 $( "#"+series Layout.pre ferenceInf o.preferen ceData.gai n).parent( ).css("bac kground"," #868696");
  17564                             }
  17565                         break;
  17566                         case "sign althicknes s":
  17567                             if (se riesLayout .preferenc eInfo.pref erenceData .signalThi ckness !==  undefined ) {
  17568                                 $( "#"+series Layout.pre ferenceInf o.preferen ceData.sig nalThickne ss).parent ().css("ba ckground", "#868696") ;
  17569                             }
  17570                         break;
  17571                    }
  17572                }
  17573           }
  17574       }
  17575  
  17576       functi on resetCo ntextMenuS election()  {
  17577           $( "#none").p arent().cs s("backgro und","");
  17578           $( "#onemm"). parent().c ss("backgr ound","");
  17579           $( "#fivemm") .parent(). css("backg round","") ;
  17580  
  17581           $( "#redGrid" ).parent() .css("back ground","" );
  17582           $( "#greenGri d").parent ().css("ba ckground", "");
  17583           $( "#blueGrid ").parent( ).css("bac kground"," ");
  17584           $( "#blackGri d").parent ().css("ba ckground", "");
  17585           $( "#greyGrid ").parent( ).css("bac kground"," ");
  17586  
  17587           $( "#threebyf our").pare nt().css(" background ","");
  17588           $( "#threebyf ourplusone ").parent( ).css("bac kground"," ");
  17589           $( "#threebyf ourplusthr ee").paren t().css("b ackground" ,"");
  17590           $( "#sixbytwo ").parent( ).css("bac kground"," ");
  17591           $( "#twelveby one").pare nt().css(" background ","");
  17592           $( "#averagec omplex").p arent().cs s("backgro und","");
  17593  
  17594           $( "#fivemmga in").paren t().css("b ackground" ,"");
  17595           $( "#tenmmgai n").parent ().css("ba ckground", "");
  17596           $( "#twentymm gain").par ent().css( "backgroun d","");
  17597           $( "#fourtymm gain").par ent().css( "backgroun d","");
  17598  
  17599           $( "#onethick ness").par ent().css( "backgroun d","");
  17600           $( "#twothick ness").par ent().css( "backgroun d","");
  17601           $( "#threethi ckness").p arent().cs s("backgro und","");
  17602       }
  17603  
  17604       /**
  17605        * Ena ble or dis able the n avigation  tools
  17606        * @pa ram {Type}  imageCoun tFlag - Sp ecifies th e image co unt
  17607        * @pa ram {Type}  seriesLay out - Spec ifies the  active ser ies layout
  17608        */ 
  17609       functi on enableO rDisableNa vigationTo ols(imageC ountFlag,s eriesLayou t) {
  17610           va r image =  null;
  17611           va r studyDet ails ;
  17612           if (seriesLay out) {
  17613              image = di comViewer. Series.Ima ge.getImag e(seriesLa yout.study Uid, serie sLayout.se riesIndex,  seriesLay out.scroll Data.image Index);
  17614                studyDet ails = dic omViewer.g etStudyDet ails(serie sLayout.st udyUid);
  17615           }
  17616  
  17617           $( "#repeteOp tion").sho w();
  17618           $( "#repeteOp tion_overf low").show ();
  17619  
  17620           if (imageCoun tFlag) {
  17621                playerTo olBarEleme nt.hide();
  17622                imageNav igationToo lBarElemen t.hide();
  17623                pdfToolB arElement. hide();
  17624                tiffTool BarElement .hide();
  17625                playerFi ledSetElem ent.hide() ;
  17626                imageFil edSetEleme nt.hide();
  17627                pdfFiled SetElement .hide();
  17628                tiffFile dSetElemen t.hide();
  17629                if(image  && image. numberOfFr ames >1 &&  image.ima geType ==  IMAGETYPE_ JPEG){
  17630                    tiff ToolBarEle ment.show( );
  17631                    tiff FiledSetEl ement.show ();
  17632                } else{
  17633                    play erToolBarE lement.sho w();
  17634                    imag eNavigatio nToolBarEl ement.show ();
  17635                    play erFiledSet Element.sh ow();
  17636                    imag eFiledSetE lement.sho w();
  17637                }
  17638           }  else {
  17639                playerTo olBarEleme nt.hide();
  17640                imageNav igationToo lBarElemen t.hide();
  17641                pdfToolB arElement. hide();
  17642                tiffTool BarElement .hide();
  17643                playerFi ledSetElem ent.hide() ;
  17644                imageFil edSetEleme nt.hide();
  17645                pdfFiled SetElement .hide();
  17646                tiffFile dSetElemen t.hide();
  17647                pageFile dSetElemen t.hide();
  17648                if(image  && isEmbe dPdfViewer (image.ima geType)) {
  17649                    dico mViewer.up datePaging (seriesLay out.series layoutId);
  17650                } else i f(image &&  image.ima geType ==  IMAGETYPE_ JPEG && st udyDetails .seriesCou nt > 1){
  17651                    tiff ToolBarEle ment.show( );
  17652                    tiff FiledSetEl ement.show ();
  17653                } else i f(studyDet ails && st udyDetails .seriesCou nt > 1 &&  image.imag eType !==  IMAGETYPE_ PDF && ima ge.imageTy pe !== IMA GETYPE_RAD PDF && ima ge.imageTy pe !== IMA GETYPE_TIF F) {
  17654                    if(i mage.image Type == IM AGETYPE_RA DECG) {
  17655                         imageNavig ationToolB arElement. show();
  17656                         imageFiled SetElement .show();
  17657                    }
  17658                    else  if(image. imageType= = IMAGETYP E_VIDEO){
  17659                         playerFile dSetElemen t.hide();
  17660                         imageFiled SetElement .show();
  17661                         $("#repete Option").h ide();
  17662                         $("#repete Option_ove rflow").hi de();
  17663                         imageNavig ationToolB arElement. show();
  17664                    }
  17665                    else  {
  17666                         playerTool BarElement .show();
  17667                         imageNavig ationToolB arElement. show();
  17668                         playerFile dSetElemen t.show();
  17669                         imageFiled SetElement .show();
  17670                    }
  17671                    Enab leDisableN extSeriesI mage(serie sLayout);
  17672                }
  17673                disableA llToolbarI cons();
  17674           }
  17675       }
  17676  
  17677       functi on selectV iewport(ev ent, study Uid) {
  17678           if  (event.ty pe ==  "mo usedown")  {
  17679                return;
  17680           }
  17681  
  17682           va r elementI d = event. currentTar get.id;
  17683           if (dicomView er.measure ment.isMea surementBr oken()) {
  17684                dicomVie wer.measur ement.setM easurement Broken(fal se);
  17685                event.pr eventDefau lt();
  17686           }
  17687  
  17688           /*  Select th e layout i n the view  port whic h is selec ted in the  thumbnail  only
  17689           af ter changi ng the ser ies level  layout */
  17690           va r backseri eslayoutid  = dicomVi ewer.getAc tiveSeries Layout();
  17691           if (backserie slayoutid  != undefin ed && actu alSeriesIn dex != 0)  {
  17692                elementI d = backse rieslayout id.getSeri esLayoutId ();
  17693           }
  17694           if  (elementI d === "")  {
  17695                return;
  17696           }
  17697           if (isViewPor tDoubleCli cked){
  17698                elementI d = event. currentTar get.id;
  17699           }
  17700  
  17701           $( "#" + elem entId).foc us();
  17702           va r studyDiv  = getStud yLayoutId( elementId) ;        
  17703           if (previousS tudyLayout  != "" ||  previousSa veAndLoadT oolLayout  != "") {
  17704                if(docum ent.getEle mentById(p reviousSav eAndLoadTo olLayout)  !== null &
  17705                   docum ent.getEle mentById(p reviousSav eAndLoadTo olLayout)  !== undefi ned) {
  17706                   docum ent.getEle mentById(p reviousSav eAndLoadTo olLayout). style.disp lay='none' ;
  17707                }
  17708           }
  17709           pr eviousSave AndLoadToo lLayout =  "saveAndLo ad_"+study Div;
  17710           pr eviousStud yLayout =  "#menuIL"+ studyDiv
  17711           va r seriesLa yout = dic omViewer.v iewports.g etViewport (elementId );
  17712           sh owAndHideK endoTools( seriesLayo ut);
  17713           if (seriesLay out == und efined) {
  17714                return;
  17715           }
  17716           if (seriesLay out.imageT ype === IM AGETYPE_RA DECG || se riesLayout .imageType  === IMAGE TYPE_RADPD F
  17717               || series Layout.ima geType ===  IMAGETYPE _RADSR ||  seriesLayo ut.imageTy pe === IMA GETYPE_CDA ) {
  17718                $("#menu IL"+studyD iv).childr en().addCl ass("k-sta te-disable d");
  17719                if(docum ent.getEle mentById(p reviousSav eAndLoadTo olLayout)  !== null &
  17720                   docum ent.getEle mentById(p reviousSav eAndLoadTo olLayout)  !== undefi ned) {
  17721                    docu ment.getEl ementById( previousSa veAndLoadT oolLayout) .style.dis play='none ';
  17722                }
  17723           }  else {
  17724                $("#menu IL"+studyD iv).childr en().remov eClass("k- state-disa bled");
  17725                if(serie sLayout.im ageType != = undefine d) {
  17726                    if(d ocument.ge tElementBy Id(previou sSaveAndLo adToolLayo ut) !== nu ll && 
  17727                       d ocument.ge tElementBy Id(previou sSaveAndLo adToolLayo ut) !== un defined) {
  17728                         document.g etElementB yId(previo usSaveAndL oadToolLay out).style .display=' block';
  17729                    }
  17730                }
  17731           }
  17732  
  17733           //  If the Vi ewport is  already fo cused then  no need t o focus ag ain.
  17734           if  ($("#" +  elementId) .hasClass( 'selected- view')) {
  17735                // Page  navigation  enable an d disable
  17736                if(serie sLayout.ge tSeriesInd ex() !== u ndefined & & seriesLa yout.getSe riesIndex( ) !== null ) {
  17737                    var  imageValue  = dicomVi ewer.Serie s.Image.ge tImage(ser iesLayout. getStudyUi d(),series Layout.get SeriesInde x(),0);
  17738                    var  isImageThu mbnails =  dicomViewe r.thumbnai l.isImageT humbnail(i mageValue) ;
  17739  
  17740                    if(i sImageThum bnails) {
  17741                         var imageI ndex = ser iesLayout. scrollData .imageInde x;
  17742                         // set the  actual se lected thu mbnail ima ge index v alue
  17743                         if(selectT humbnailIm ageIndex ! == undefin ed && sele ctThumbnai lImageInde x != image Index) {
  17744                             imageI ndex = sel ectThumbna ilImageInd ex;
  17745                         }
  17746                         dicomViewe r.thumbnai l.selectIm ageThumbna il(seriesL ayout.getS eriesIndex (), imageI ndex);
  17747                    } el se {
  17748                         dicomViewe r.thumbnai l.selectTh umbnail(se riesLayout .getSeries Index());
  17749                    }
  17750                }
  17751  
  17752                //Need t o enable o r disable  the toolba r options  based on t he image t ype.
  17753                if(serie sLayout != = null &&  seriesLayo ut !== und efined){
  17754                    var  selectedSt udyUid = s eriesLayou t.getStudy Uid();
  17755                    var  selectedSe riesIndex  = seriesLa yout.getSe riesIndex( );
  17756                    if(s electedStu dyUid !==  undefined  && selecte dSeriesInd ex !== und efined){
  17757                         var modali ty = dicom Viewer.Ser ies.getMod ality(sele ctedStudyU id, select edSeriesIn dex);
  17758                         var isCine Play = isC ineRunning (seriesLay out.getSer iesLayoutI d());
  17759                         if(!isCine Play) {
  17760                             enable OrDisableT ools(modal ity, serie sLayout);
  17761                             if(eve nt.which = = 1 && dic omViewer.m ouseTools. getToolNam e() == TOO LNAME_DEFA ULTTOOL){
  17762                                 se tDefaultCu rsorType(m odality, s eriesLayou t);
  17763                             }
  17764                         }
  17765                         else {
  17766                             showOr HideInCine Running(mo dality, is CinePlay);
  17767                             change ToolbarIco n($("#over layButton" ), "overla y.png", "o verlay.png ", false);
  17768                             change ToolbarIco n($("#dico mheaderBut ton_wrappe r"), "head er.png", " header.png ", false);
  17769                         }
  17770                    }
  17771                }
  17772  
  17773                EnableDi sableRefer enceLineMe nu(seriesL ayout);
  17774                updatePr eferenceVa lues();
  17775                return;
  17776           }
  17777  
  17778           se tActiveSer iesLayout( seriesLayo ut);
  17779           
  17780           //  Page navi gation ena ble and di sable
  17781           if (seriesLay out !== nu ll && seri esLayout ! == undefin ed) {
  17782                var tmpS tudyUID =  seriesLayo ut.getStud yUid();
  17783                var tmpS eriesIndex  = seriesL ayout.getS eriesIndex ();
  17784                var tmpI mageUID =  seriesLayo ut.getDefa ultRendere rImageUid( );
  17785                if(tmpSt udyUID !==  null && t mpStudyUID  !== undef ined && tm pSeriesInd ex !== und efined) {
  17786                    var  imageCount Flag = fal se;
  17787                    var  isImageAva ilable =   dicomViewe r.isImageA vilable(tm pStudyUID,  tmpImageU ID)
  17788                    var  isMultiFra me = dicom Viewer.thu mbnail.isS eriesConta insMultifr ame(tmpStu dyUID, tmp SeriesInde x);
  17789                    var  multiFrame IncCount =  0;
  17790                    if(i sMultiFram e) {
  17791                         for (var i  = 0; i <  dicomViewe r.Study.ge tSeriesCou nt(tmpStud yUID); i++ ) {
  17792                             for (v ar j = 0;  j < dicomV iewer.Seri es.getImag eCount(tmp StudyUID,  i); j++) {
  17793                               var  image = di comViewer. Series.Ima ge.getImag e(tmpStudy UID,i,j);
  17794                               var  multiFrame Count = di comViewer. Series.Ima ge.getImag eFrameCoun t(image);
  17795                                 mu ltiFrameCo unt == 1 ?  ++multiFr ameIncCoun t : "";
  17796                                 if (multiFram eCount > 1  || multiF rameIncCou nt > 1){
  17797                                      imageCou ntFlag = t rue;
  17798                                      break;
  17799                                 }
  17800                             }
  17801                         }
  17802                    } el se if(isIm ageAvailab le && !isM ultiFrame)  {
  17803                         multiFrame IncCount =  0;
  17804                         for (var i  = 0; i <  dicomViewe r.Study.ge tSeriesCou nt(tmpStud yUID); i++ ) {
  17805                             var im ageCount =  dicomView er.Series. getImageCo unt(tmpStu dyUID, i);
  17806                             imageC ount == 1  ? ++multiF rameIncCou nt : "";
  17807                             if(ima geCount >  1 || multi FrameIncCo unt > 1) {
  17808                                 im ageCountFl ag = true;
  17809                                 br eak;
  17810                             }
  17811                         }
  17812                    }
  17813                    enab leOrDisabl eNavigatio nTools(ima geCountFla g,seriesLa yout);
  17814                } else {
  17815                    enab leOrDisabl eNavigatio nTools(0);
  17816                    disa bleAllTool barIcons() ;
  17817                }
  17818           }
  17819           up datePrefer enceValues ();
  17820           $( "#" + seri esLayout.g etSeriesLa youtId() +  " div").e ach(functi on() {
  17821                var imag eLevelId =  $(this).a ttr('id');
  17822                var imag eRender =  seriesLayo ut.getImag eRender(im ageLevelId );
  17823                if(image Render) {
  17824                    if(i mageRender .imageProm ise=== und efined) {
  17825                         return;
  17826                    }
  17827                    imag eRender.im agePromise .then(func tion(image ) {
  17828                         dicomViewe r.showCine Rate(image .dicominfo .cineRate) ;
  17829                    });
  17830                }
  17831                return f alse;
  17832           }) ;
  17833           if (cineManag er[seriesL ayout.seri esLayoutId ] !== unde fined) {
  17834                if(cineM anager[ser iesLayout. seriesLayo utId].time r == null)  {
  17835                    upda tePlayIcon ("stop.png ", "play.p ng", undef ined, unde fined, cin eManager[s eriesLayou t.seriesLa youtId].pl ayStudy);
  17836                } else {
  17837                    var  parentElem ent = $("# playBackwa rd").paren t().css("b ackground" ,"");
  17838                    var  parentElem ent = $("# playForwar d").parent ().css("ba ckground", "#868696") ;
  17839                    upda tePlayIcon ("play.png ","stop.pn g",undefin ed,undefin ed,cineMan ager[serie sLayout.se riesLayout Id].playSt udy);
  17840                }
  17841                if (cine Manager[se riesLayout .seriesLay outId].dir ection) {
  17842                    var  parentElem ent = $("# playBackwa rd").paren t().css("b ackground" ,"");
  17843                    var  parentElem ent = $("# playForwar d").parent ().css("ba ckground", "#868696") ;
  17844                } else {
  17845                    var  parentElem ent = $("# playForwar d").parent ().css("ba ckground", "");
  17846                    var  parentElem ent = $("# playBackwa rd").paren t().css("b ackground" ,"#868696" );
  17847                }
  17848                showCine Rate(cineM anager[ser iesLayout. seriesLayo utId].cine Rate);
  17849                if(cineM anager[ser iesLayout. seriesLayo utId].play Study) {
  17850                    var  repeatButt onImage =  document.g etElementB yId("repet eOption"). getElement sByTagName ('img')[0] ;
  17851                    var  repeteOpti on_overflo w = $("#re peteOption _overflow" );
  17852                    var  imageSrc =  repeatBut tonImage.s rc;
  17853                    var  repateOpti onButton =  $("#repet eOption");
  17854                    if ( imageSrc.i ndexOf("re peat.png")  > -1) {
  17855                         repeatButt onImage.sr c = imageS rc.replace ("repeat.p ng", "repe teActive.p ng");
  17856                         updateTool Tip(repate OptionButt on, "Repea t Series") ;
  17857                         updateImag eOverflow( repeteOpti on_overflo w, "images /repeat.pn g", "image s/repeteAc tive.png",  false);
  17858                    }
  17859                } else {
  17860                    var  repeatButt onImage =  document.g etElementB yId("repet eOption"). getElement sByTagName ('img')[0] ;
  17861                    var  repeteOpti on_overflo w = $("#re peteOption _overflow" );
  17862                    var  imageSrc =  repeatBut tonImage.s rc;
  17863                    var  repateOpti onButton =  $("#repet eOption");
  17864                    if(i mageSrc.in dexOf("rep eteActive. png") > -1 ) {
  17865                         repeatButt onImage.sr c = imageS rc.replace ("repeteAc tive.png",  "repeat.p ng");
  17866                         updateTool Tip(repate OptionButt on, "Repea t Study");
  17867                         updateImag eOverflow( repeteOpti on_overflo w, "images /repeteAct ive.png",  "images/re peat.png",  true);
  17868                    }
  17869                }
  17870           }  else {
  17871                if (canP layCine(se riesLayout .imageType )) {
  17872                    var  playBy = d icomViewer .configura tion.cine. getCinePla yBy();
  17873                    cine playBy(pla yBy);
  17874                }
  17875                updatePl ayIcon("st op.png","p lay.png");
  17876           }
  17877           va r viewport ElementIds  = dicomVi ewer.viewp orts.getVi ewportIds( );
  17878           $( ".selected -view").re moveClass( 'selected- view').add Class('def ault-view' );
  17879           $( "#" + elem entId).rem oveClass(' default-vi ew').addCl ass('selec ted-view') ;
  17880           va r seriesIn dex = seri esLayout.g etSeriesIn dex();
  17881           if (studyUid  === undefi ned)
  17882                studyUid  = seriesL ayout.getS tudyUid();
  17883           if (studyUid  === undefi ned || (se riesLayout .seriesInd ex == unde fined && s eriesLayou t.imageTyp e == undef ined)) {
  17884                dicomVie wer.thumbn ail.remove SelctedThu mbnail();
  17885                disableA llToolbarI cons();
  17886                setDefau ltCursorTy pe(undefin ed, series Layout);
  17887                $('#imag eDisplay'+  studyDiv) .hide();
  17888                return;
  17889           }
  17890           if (seriesLay out.getSer iesIndex()  === undef ined) {
  17891                setStudy ToolBarToo ls(seriesL ayout);
  17892                return;
  17893           }
  17894           va r modality  = dicomVi ewer.Serie s.getModal ity(studyU id,seriesI ndex);
  17895           va r imageVal ue = dicom Viewer.Ser ies.Image. getImage(s tudyUid,se riesIndex, 0);
  17896           va r isImageT humbnails  = dicomVie wer.thumbn ail.isImag eThumbnail (imageValu e);
  17897           if (isImageTh umbnails)  {
  17898                var imag eIndex = s eriesLayou t.scrollDa ta.imageIn dex;
  17899                // set t he actual  selected t humbnail i mage index  value
  17900                if(selec tThumbnail ImageIndex  !== undef ined && se lectThumbn ailImageIn dex != ima geIndex) {
  17901                    imag eIndex = s electThumb nailImageI ndex;
  17902                }
  17903                dicomVie wer.thumbn ail.select ImageThumb nail(serie sIndex, im ageIndex);
  17904           }  else {
  17905                dicomVie wer.getAct iveSeriesL ayout().se tStudyUid( studyUid);
  17906                // set t he actual  selected t humbnail i mage index  value
  17907                if(actua lSeriesInd ex != 0) {
  17908                    seri esIndex =  actualSeri esIndex;
  17909                }
  17910                dicomVie wer.thumbn ail.select Thumbnail( seriesInde x);
  17911                seriesIn dex = seri esLayout.g etSeriesIn dex();
  17912           }
  17913  
  17914           // link
  17915           di comViewer. link.updat eLinkMenu( );
  17916  
  17917           if  (dicomVie wer.link.g etLinkTool Active())  {
  17918                if (even t.which ==  1 && !dic omViewer.l ink.isSeri esLinked() ) {
  17919                    dico mViewer.li nk.linkSer ies();
  17920                }
  17921           }
  17922  
  17923           if  (dicomVie wer.link.i sSeriesLin ked()) {
  17924                var img  = document .getElemen tById('lin kButton'). children[0 ];
  17925                document .getElemen tById('lin kButton_ov erflow').c hildren[0] .src = 'im ages/unlin k.png';
  17926                img.src  = 'images/ unlink.png ';
  17927                updateTo olTip($("# linkButton "), "UnLin k");
  17928           }  else {
  17929                var img  = document .getElemen tById('lin kButton'). children[0 ];
  17930                document .getElemen tById('lin kButton_ov erflow').c hildren[0] .src = 'im ages/link. png';
  17931                img.src  = 'images/ link.png';
  17932                updateTo olTip($("# linkButton "), "Link" );
  17933           }
  17934  
  17935           di comViewer. viewports. refreshVie wports(ser iesLayout) ;
  17936           se tStudyTool BarTools(s eriesLayou t);
  17937           se tDefaultCu rsorType(m odality, s eriesLayou t, event);
  17938           en ableOrDisa bleTools(m odality, s eriesLayou t);
  17939           if (actualSer iesIndex ! = 0 && isI mageThumbn ails == fa lse) {
  17940                seriesIn dex = actu alSeriesIn dex;
  17941           }
  17942           if (imageInde x == undef ined) {
  17943                imageInd ex = serie sLayout.ge tImageInde x();
  17944           }
  17945           up dateThumbn ailSelecti on(undefin ed, series Index, ima geIndex,st udyUid);
  17946           if (isCineRun ning(serie sLayout.ge tSeriesLay outId()))  {
  17947               showOrHid eInCineRun ning(modal ity, true) ;
  17948           }
  17949           va r imageUid  = seriesL ayout.getD efaultRend ererImageU id();
  17950           va r imageInd ex = dicom Viewer.Ser ies.Image. getImageIn dex(studyU id,seriesI ndex,image Uid)
  17951           va r image =  dicomViewe r.Series.I mage.getIm age(studyU id ,series Index, ima geIndex);
  17952  
  17953           if (image !==  undefined  && image  !== null){
  17954                if((dico mViewer.Se ries.Image .getImageF rameCount( image)>1)  || dicomVi ewer.Serie s.getImage Count(seri esLayout.g etStudyUid (), series Layout.get SeriesInde x()) > 1)  {
  17955                      if (isCineRun ning(serie sLayout.ge tSeriesLay outId()))  {
  17956                           dicomVie wer.startC ine();
  17957                           updatePl ayIcon("pl ay.png","s top.png");
  17958                      }
  17959                } else {
  17960                    if ( dicomViewe r.isDicomS tudy(serie sLayout.ge tStudyUid( ))) {
  17961                         dicomViewe r.scroll.s topCineIma ge(undefin ed);
  17962                         updatePlay Icon("stop .png", "pl ay.png");
  17963                    }
  17964                }
  17965           }
  17966  
  17967           do cument.get ElementByI d(studyDiv  + '_close ').style.v isibility  = "visible ";
  17968  
  17969           va r imageLay out = seri esLayout.g etImageLay outDimensi on().split ("x");
  17970           di comViewer. tools.chan geImageLay out(parseI nt(imageLa yout[0]),p arseInt(im ageLayout[ 1]));
  17971           En ableDisabl eReference LineMenu(s eriesLayou t);
  17972           En ableDisabl eNextSerie sImage(ser iesLayout) ;
  17973  
  17974       }
  17975  
  17976       /**
  17977        * Ena ble/Disabl e the cros s referenc e line dep ends on th e Image pl ane
  17978        */ 
  17979       functi on EnableD isableRefe renceLineM enu(series Layout)
  17980       {
  17981           va r studyuid  = seriesL ayout.getS tudyUid();
  17982           va r studyDet ials = dic omViewer.g etStudyDet ails(study uid);
  17983           if (studyDeti als !== nu ll && stud yDetials ! == undefin ed) {
  17984                if(study Detials.is XRefLineFo und) {
  17985                    $("# scoutLine" ).show();  //cross re ference li ne
  17986                    $("# scoutLine_ overflow") .show(); / /cross ref erence lin e
  17987                    docu ment.getEl ementById( "context-l ink-crossR efLineSele ctor").sty le.display  = "block"
  17988                    $("# context-li nk-menu"). show();
  17989                } else {
  17990                    $("# scoutLine" ).hide();  //cross re ference li ne
  17991                    $("# scoutLine_ overflow") .hide(); / /cross ref erence lin e
  17992                    docu ment.getEl ementById( "context-l ink-crossR efLineSele ctor").sty le.display  = "none"
  17993                    $("# context-li nk-menu"). hide();
  17994                }
  17995           }
  17996       }
  17997  
  17998       functi on setStud yToolBarTo ols(series Layout)
  17999       {
  18000           va r studyDiv  = getStud yLayoutId( seriesLayo ut.seriesL ayoutId);
  18001           va r imageLay outDisplay Id = "imag eDisplay"+ studyDiv;
  18002           va r seriesLa youtDispla yId = "ser iesDisplay "+studyDiv ;
  18003  
  18004           if (seriesLay out.getStu dyUid() != = undefine d && serie sLayout.ge tSeriesInd ex() !== u ndefined & & seriesLa yout.getIm ageIndex()  !== undef ined)
  18005           {
  18006                var stud yDetails =  dicomView er.getStud yDetails(s eriesLayou t.studyUid );
  18007                if(study Details.is Dicom == t rue) {
  18008                    $("# context-co pyAttribut es").show( );
  18009                    $("l i.copyAttr ibutesPref erence").s how();
  18010                }
  18011  
  18012                document .getElemen tById(seri esLayoutDi splayId).s tyle.displ ay= 'block ';
  18013                var imag eCount = 0 ;
  18014                if (seri esLayout.g etImageInd ex() != un defined)
  18015                {
  18016                    imag eCount = d icomViewer .Series.ge tImageCoun t(seriesLa yout.getSt udyUid(),s eriesLayou t.getSerie sIndex());
  18017                    var  frameCount  = dicomVi ewer.Serie s.Image.ge tImageFram eCount(dic omViewer.S eries.Imag e.getImage (seriesLay out.getStu dyUid(), s eriesLayou t.getSerie sIndex(),  seriesLayo ut.getImag eIndex())) ;
  18018                    imag eCount = d icomViewer .thumbnail .isSeriesC ontainsMul tiframe(se riesLayout .getStudyU id(), seri esLayout.g etSeriesIn dex()) ? f rameCount  : imageCou nt;
  18019                }
  18020  
  18021                if( imag eCount > 1 ) {
  18022                    docu ment.getEl ementById( imageLayou tDisplayId ).style.di splay= 'bl ock';
  18023                } else {
  18024                    docu ment.getEl ementById( imageLayou tDisplayId ).style.di splay='non e';
  18025                }
  18026  
  18027                changeIc onSize();
  18028           }
  18029           el se
  18030           {
  18031                document .getElemen tById(imag eLayoutDis playId).st yle.displa y= 'none';
  18032                $("li.co pyAttribut esPreferen ce").hide( );
  18033           }
  18034       }
  18035       functi on isToolS upportByIm ageType(mo dality, im ageType,se riesLayout )
  18036       {
  18037           va r cursorTy pe = dicom Viewer.too ls.getCurs orType();
  18038           if  (imageTyp e === IMAG ETYPE_RADS R || image Type === I MAGETYPE_R ADPDF || i mageType = == IMAGETY PE_RADECG  || imageTy pe === IMA GETYPE_CDA ) {
  18039                return f alse;
  18040           }
  18041           va r toolName  = dicomVi ewer.mouse Tools.getT oolName();
  18042           va r activeTo ol;
  18043            a ctiveTool  = (activeT ool = dico mViewer.mo useTools.g etActiveTo ol().measu rementData ) ? active Tool.measu rementSubT ype : unde fined;
  18044  
  18045           if (toolName  === "XRefL ineSelecti onTool"){
  18046                var stud yDetials =  dicomView er.getStud yDetails(s eriesLayou t.studyUid );
  18047                if(study Detials != = null &&  studyDetia ls !== und efined &&  studyDetia ls.isXRefL ineFound)  {
  18048                    dico mViewer.to ols.doXRef LineSelect ion();
  18049                    retu rn true;
  18050                }
  18051                return f alse;
  18052           }
  18053  
  18054           if (imageType  === IMAGE TYPE_RADEC HO || imag eType ===  IMAGETYPE_ JPEG)
  18055           {
  18056                if(toolN ame === TO OLNAME_PAN ){
  18057                    $('# viewport_V iew').css( 'cursor',' url(images /pan.cur),  auto');
  18058                    var  obj= {id:" pan"}
  18059                    dico mViewer.to ols.doPan( obj)
  18060                    retu rn true;
  18061                }
  18062                if(toolN ame === TO OLNAME_ZOO M){
  18063                 $('#vie wport_View ').css('cu rsor','url (images/zo om.cur), a uto');
  18064                    var  obj= {id:" zoomButton "}
  18065                    dico mViewer.to ols.doZoom (seriesLay out.prefer enceInfo.z oomLevelSe tting);
  18066                    retu rn true;
  18067                }
  18068                if(toolN ame === TO OLNAME_WIN DOWLEVEL){
  18069                    dico mViewer.to ols.doBrig htnessCont rast();
  18070                    retu rn true;
  18071                }
  18072           }
  18073           if (imageType  === IMAGE TYPE_RAD)
  18074           {
  18075                if(toolN ame === TO OLNAME_WIN DOWLEVEL){
  18076                    $('# viewport_V iew').css( 'cursor',' url(images /brightnes s.cur), au to');
  18077                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getW indowTool( ));
  18078                    retu rn true;
  18079                }
  18080                if(toolN ame === TO OLNAME_WIN DOWLEVEL_R OI){
  18081                    $('# viewport_V iew').css( 'cursor',' url(images /AutoWindo wLevel.cur ), auto');
  18082                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getW indowToolR OI());
  18083                    retu rn true;
  18084                }
  18085                if(toolN ame === TO OLNAME_ZOO M){
  18086                    $('# viewport_V iew').css( 'cursor',' url(images /zoom.cur) , auto');
  18087                    var  obj= {id:" zoomButton "}
  18088                    dico mViewer.to ols.doZoom (seriesLay out.prefer enceInfo.z oomLevelSe tting);
  18089                    retu rn true;
  18090                }
  18091                if(toolN ame === TO OLNAME_PAN ){
  18092                    $('# viewport_V iew').css( 'cursor',' url(images /pan.cur),  auto');
  18093                    var  obj= {id:" pan"}
  18094                    dico mViewer.to ols.doPan( obj)
  18095                    retu rn true;
  18096                }
  18097                if(toolN ame === TO OLNAME_LIN K){
  18098                    if(d icomViewer .link.getL inkToolAct ive()){
  18099                         $('#viewpo rt_View'). css('curso r','url(im ages/link. cur), auto ');
  18100                         dicomViewe r.mouseToo ls.setActi veTool(dic omViewer.m ouseTools. getLinkToo l());
  18101                    } el se {
  18102                         $('#viewpo rt_View'). css('curso r', 'defau lt');
  18103                    }
  18104                    retu rn true;
  18105                }
  18106           }
  18107           if (toolName  === "lineM easurement "){
  18108                if((curs orType !=  "default"  && cursorT ype == "an notatearro w") || (cu rsorType== "default"  && activeT ool=="Arro w")) {
  18109                    var  obj= {id:" 10_arrow"}
  18110                    dico mViewer.to ols.do2DMe asurement( obj);
  18111                } else i f((cursorT ype != "de fault" &&  cursorType  == "annot ateline")  || 
  18112                           (cursorT ype=="defa ult" && ac tiveTool== "2DLine"))  {
  18113                    var  obj= {id:" 9_line"}
  18114                    dico mViewer.to ols.do2DMe asurement( obj);
  18115                } else i f(cursorTy pe != "def ault" && c ursorType  == "mitral length" &&  modality  == "US") {
  18116                    dico mViewer.to ols.do2DMe asurement( 0,"mitralR egurgitati onLength", "cm");
  18117                } else i f(cursorTy pe != "def ault" && c ursorType  == "aortic length" &&  modality  == "US") {
  18118                    dico mViewer.to ols.do2DMe asurement( 0,"aorticR egurgitati onLength", "cm");
  18119                } else i f(cursorTy pe != "def ault" && c ursorType  == "mitral thickness"  && modali ty == "US" ) {
  18120                    dico mViewer.to ols.do2DMe asurement( 0,"mitralV alveAnteri orLeafletT hickness", "mm");
  18121                } else {
  18122                    $('# viewport_V iew').css( 'cursor',' url(images /measuremn et.png), a uto');
  18123                    var  obj= {id:" 0_measurem ent"}
  18124                    dico mViewer.to ols.do2DMe asurement( obj)
  18125                }
  18126                return t rue;
  18127           }
  18128           if (toolName  === "point Measuremen t"){
  18129                if(curso rType != " default" & & cursorTy pe == "mit ralvelocit y" && moda lity == "U S") {
  18130                    dico mViewer.to ols.do2DMe asurement( 1,"mitralR egurgitati onPeakVelo city","m/s ");
  18131                } else i f(cursorTy pe != "def ault" && c ursorType  == "aortic regurgitat ionvelocit y" && moda lity == "U S") {
  18132                    dico mViewer.to ols.do2DMe asurement( 1,"aorticR egurgitati onPeakVelo city","m/s ");
  18133                } else i f(cursorTy pe != "def ault" && c ursorType  == "aortic stenosisve locity" &&  modality  == "US") {
  18134                    var  obj= {type :1}
  18135                    dico mViewer.to ols.do2DMe asurement( 1,"aorticS tenosisPea kVelocity" ,"m/s");
  18136                } else {
  18137                    $('# viewport_V iew').css( 'cursor',' url(images /measuremn et.png), a uto');
  18138                    var  obj= {id:" 1_measurem ent"}
  18139                    dico mViewer.to ols.do2DMe asurement( obj);
  18140                }
  18141                return t rue;
  18142           }
  18143           if (modality  === "US" & & toolName  === "trac eMeasureme nt"){
  18144                $('#view port_View' ).css('cur sor','url( images/mea suremnet.p ng), auto' );
  18145                var obj=  {id:"2_me asurement" }
  18146                dicomVie wer.tools. do2DMeasur ement(obj)
  18147                return t rue;
  18148           }
  18149           if (toolName  === "mitra lMeanGradi entMeasure ment"){
  18150                if((curs orType !=  "default"  && cursorT ype == "an notatefree hand") ||  (cursorTyp e=="defaul t" && acti veTool ==  "freehand" )) {
  18151                   var o bj= {id:"1 3_freehand "}
  18152                    dico mViewer.to ols.do2DMe asurement( obj)
  18153                    retu rn true;
  18154                } else i f(cursorTy pe != "def ault" && c ursorType  == "mitral gradient"  && modalit y == "US") {
  18155                    dico mViewer.to ols.do2DMe asurement( 5,"mitralS tenosisMea nGradient" ,"mmHg");
  18156                    retu rn true;
  18157                }
  18158           }
  18159           if (toolName  === "angle Measuremen t"){
  18160                $('#view port_View' ).css('cur sor','url( images/mea suremnet.p ng), auto' );
  18161                var obj=  {id:"angl e_measurem ent"}
  18162                dicomVie wer.tools. do2DMeasur ement(obj)
  18163                return t rue;
  18164           }
  18165  
  18166           if (toolName  == "rectan gleMeasure ment"){
  18167                if((curs orType !=  "default"  && cursorT ype == "an notaterect angle") ||  (cursorTy pe=="defau lt" && act iveTool ==  "rectangl e")) {
  18168                    var  obj= {id:" 12_rectang le"}
  18169                    dico mViewer.to ols.do2DMe asurement( obj);
  18170                    retu rn true;
  18171                } else i f((cursorT ype != "de fault" &&  cursorType  == "annot atetext")  || (cursor Type=="def ault" && a ctiveTool  == "text") ) {
  18172                    var  obj= {id:" 8_text"}
  18173                    dico mViewer.to ols.do2DMe asurement( obj);
  18174                    retu rn true;
  18175                } else i f(modality  === "CT")  {
  18176                    var  obj= {id:" 14_measure ment"}
  18177                    dico mViewer.to ols.do2DMe asurement( obj);
  18178                    retu rn true;
  18179                } else {
  18180                    var  obj= {id:" 12_rectang le"}
  18181                    dico mViewer.to ols.do2DMe asurement( obj);
  18182                    retu rn true;
  18183                }
  18184           }
  18185  
  18186                    if(t oolName == = "ellipse Measuremen t"){
  18187                if((curs orType !=  "default"  && cursorT ype == "an notateelli pse") || ( cursorType =="default " && activ eTool == " ellipse"))  {
  18188                    var  obj= {id:" 11_ellipse "}
  18189                    dico mViewer.to ols.do2DMe asurement( obj);
  18190                    retu rn true;
  18191                }
  18192                else if( modality = == "CT") {
  18193                    var  obj= {id:" 7_measurem ent"}
  18194                    dico mViewer.to ols.do2DMe asurement( obj);
  18195                    retu rn true;
  18196                } else {
  18197                    var  obj= {id:" 11_ellipse "}
  18198                    dico mViewer.to ols.do2DMe asurement( obj);
  18199                    retu rn true;
  18200                }
  18201           }
  18202           if (toolName  === "pen")  {
  18203                var obj=  {id:"15_p en"};
  18204                dicomVie wer.tools. do2DMeasur ement(obj) ;
  18205                return t rue;
  18206           }
  18207           re turn false ;
  18208       }
  18209  
  18210       /**
  18211        * Han dle the de fault tool  copy attr ibutes or  default
  18212        */ 
  18213       functi on handleD efaultTool (isDicom,  seriesLayo ut, event)  {
  18214           tr y
  18215           {
  18216                var rese tDefault =  false;
  18217                if(dicom Viewer.mou seTools.ge tToolName( ) === TOOL NAME_COPYA TTRIBUTES  && event.w hich == 1)  {
  18218                    var  tool = dic omViewer.m ouseTools. getActiveT ool();
  18219                    var  data = too l.getCopyA ttributesD ata();
  18220                    if(s eriesLayou t.studyUid  === data. studyUid)  {
  18221                         tool.setAc tiveImageR enderer(se riesLayout .getImageR ender(seri esLayout.s eriesLayou tId + "Ima geLevel0x0 "));
  18222                         tool.hanle MouseDown( );
  18223                    } el se {
  18224                         tool.setCo pyAttribut esData(und efined);
  18225                         resetDefau lt = true;
  18226                    }
  18227                } else {
  18228                    rese tDefault =  true;
  18229                }
  18230  
  18231                if(isDic om && rese tDefault)  {
  18232                    $('# viewport_V iew').css( 'cursor',' url(images /brightnes s.cur), au to');
  18233                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getW indowTool( ));
  18234                } else i f(resetDef ault) {
  18235                    $('# viewport_V iew').css( 'cursor',' url(images /brightnes s.cur), au to');
  18236                    dico mViewer.mo useTools.s etActiveTo ol(dicomVi ewer.mouse Tools.getB rightnessC ontrastToo l());
  18237                }
  18238           }
  18239           ca tch(e)
  18240           {  }
  18241       }
  18242  
  18243       functi on setDefa ultCursorT ype(modali ty, series Layout, ev ent){
  18244           if (seriesLay out.studyU id && seri esLayout.s eriesIndex  != undefi ned) {
  18245                if(modal ity == und efined &&  seriesLayo ut.imageTy pe !== IMA GETYPE_JPE G) {
  18246                    $('# viewport_V iew').css( 'cursor',  'default') ;
  18247                } else i f(!isToolS upportByIm ageType(mo dality, se riesLayout .imageType , seriesLa yout)) {
  18248                    if(( modality = = "US") ||  (seriesLa yout.image Type === I MAGETYPE_J PEG) || (s eriesLayou t.imageTyp e === IMAG ETYPE_RADE CHO)) {
  18249                         handleDefa ultTool(fa lse, serie sLayout, e vent);
  18250                    } el se if (isB lob(series Layout.ima geType) ||  
  18251                                ser iesLayout. imageType  === IMAGET YPE_RADSR  || 
  18252                                ser iesLayout. imageType  === IMAGET YPE_CDA) {
  18253                         $('#viewpo rt_View'). css('curso r', 'defau lt');
  18254                    } el se if(seri esLayout.i mageType = == IMAGETY PE_RAD) {
  18255                         handleDefa ultTool(tr ue, series Layout, ev ent);
  18256                    }
  18257  
  18258                    //wh enever cin e is runni ng in repe at study m ode the ac tive mouse  tool shou ld be defa ult tool
  18259                    if ( dicomViewe r.scroll.i sCineRunni ng(seriesL ayout.seri esLayoutId ) && isToP layStudy(s eriesLayou t.seriesLa youtId)) {
  18260                             dicomV iewer.tool s.doDefaul t();
  18261                    }
  18262                }
  18263           }  else {
  18264                dicomVie wer.tools. doDefault( );
  18265           }
  18266       }
  18267       
  18268       functi on enableO rDisableTo ols(modali ty, series Layout) {
  18269           if (modality  == "ECG" | | seriesLa yout.image Type === I MAGETYPE_R ADECG || s eriesLayou t.imageTyp e === IMAG ETYPE_RADP DF) {
  18270                enableOr DisableNav igationToo ls(0,serie sLayout)
  18271                $("#ecgP reference" ).prop("di sabled",fa lse);
  18272                $("#ecgP reference" ).css("bac kground-co lor","");
  18273                disableO rEnableDic omTools(tr ue);
  18274                             enable OrDisableT oolsForECG ();
  18275                if(serie sLayout.im ageType == =IMAGETYPE _RADPDF) {
  18276                    disb aleToolFor ECGPDF();
  18277                    var  element =  document.g etElements ByName("pd fviewer1x1 ");
  18278                    if(e lement !==  null) {
  18279                         var window  = element [0];
  18280                         if(window  !== undefi ned && win dow.conten tWindow.do cument.bod y !== null ) {
  18281                             window .contentWi ndow.docum ent.body.f ocus();
  18282                         }
  18283                    }
  18284                }
  18285                //enable ToolsForNo nDicom();
  18286           }  else if(mo dality ===  "CT"){
  18287                disableO rEnableToo lbarForCTI mages();
  18288           }  else if(mo dality ==  "US" && se riesLayout .imageType  === IMAGE TYPE_RADEC HO) {
  18289                var imag eCountFlag  = false;
  18290                var stud yUID = ser iesLayout. getStudyUi d();
  18291                var seri esIndex =  seriesLayo ut.getSeri esIndex();
  18292                var isMu ltiFrame =  dicomView er.thumbna il.isSerie sContainsM ultiframe( studyUID,  seriesInde x);
  18293                if(isMul tiFrame){
  18294                         for (var i  = 0; i <  dicomViewe r.Study.ge tSeriesCou nt(studyUI D); i++){
  18295                             for (v ar j = 0;  j < dicomV iewer.Seri es.getImag eCount(stu dyUID, i);  j++){
  18296                               var  image = di comViewer. Series.Ima ge.getImag e(studyUID ,i,j);
  18297                               var  multiFrame Count = di comViewer. Series.Ima ge.getImag eFrameCoun t(image);
  18298                               if(m ultiFrameC ount >= 1) {
  18299                                  i mageCountF lag = true ;
  18300                                    break;
  18301                               }
  18302                             }
  18303                         }
  18304                    disa bleToolbar ForUsImage s(true);
  18305                } else{
  18306                    for  (var i = 0 ; i < dico mViewer.St udy.getSer iesCount(s tudyUID);  i++){
  18307                         var imageC ount = dic omViewer.S eries.getI mageCount( studyUID,  i);
  18308                         if(imageCo unt > 1){
  18309                            imageCo untFlag =  true;
  18310                            break;    
  18311                         }
  18312                    }
  18313                    disa bleToolbar ForUsImage s(false);
  18314                }
  18315                             
  18316                enableOr DisableNav igationToo ls(imageCo untFlag,se riesLayout );
  18317           }  else if (m odality == = "SR" ||  modality = == "CDA" | | seriesLa yout.image Type === I MAGETYPE_R ADSR || se riesLayout .imageType  === IMAGE TYPE_CDA)  {
  18318                enableOr DisableNav igationToo ls(0,serie sLayout);
  18319                disableO rEnableSRT ools();
  18320                $("#dico mheaderBut ton_wrappe r").remove Class("k-s tate-disab led");
  18321                $("#refr eshButton" ).removeCl ass("k-sta te-disable d");
  18322                $('#winL _wrapper') .addClass( 'k-state-d isabled');
  18323                if(modal ity === "C DA" || ser iesLayout. imageType  === IMAGET YPE_CDA) {
  18324                    $("# dicomImage Header").h ide();
  18325                    $("# dicomImage Header_ove rflow").hi de(); //Di com Header  Overflow
  18326                }
  18327                else {
  18328                    $("# dicomImage Header").s how();
  18329                    $("# dicomImage Header_ove rflow").sh ow(); //Di com Header  Overflow
  18330                }
  18331           }  else if( s eriesLayou t.imageTyp e === IMAG ETYPE_JPEG ){ 
  18332                disableT oolBarForN onDicom();
  18333           }  else if(is Blob(serie sLayout.im ageType)){
  18334                disableT oolForBlob (true);
  18335           }  else if(se riesLayout .imageType  === IMAGE TYPE_RAD){   
  18336                $("#ecgP reference" ).prop("di sabled",tr ue);
  18337                $("#ecgP reference" ).css("bac kground-co lor","blac k");
  18338                disableO rEnableDic omTools(fa lse);
  18339                enableOr DisableNav igationToo ls(true, s eriesLayou t);
  18340           }
  18341           if (seriesLay out && isE mbedPdfVie wer(series Layout.ima geType)) {
  18342                $("#zoom Button_wra pper").rem oveClass(" k-state-di sabled");
  18343                $("#flip VButton"). removeClas s("k-state -disabled" );
  18344                $("#flip HButton"). removeClas s("k-state -disabled" );
  18345                $("#rota teButton") .removeCla ss("k-stat e-disabled ");
  18346                $("#refr eshButton" ).removeCl ass("k-sta te-disable d");
  18347                $("#zoom Button_ove rflow").sh ow();
  18348                $("#zoom Button_ove rflow").ad dClass("k- state-disa bled");
  18349                $("#flip VButton_ov erflow").s how();
  18350                $("#flip HButton_ov erflow").s how();
  18351                $("#rota teButton_o verflow"). show();
  18352                $("#refr eshButton_ overflow") .show();
  18353           }
  18354       }
  18355       
  18356       functi on allowDr op(event)  {
  18357           va r viewport Object = d icomViewer .viewports .getViewpo rt(event.c urrentTarg et.id);
  18358           if (viewportO bject !==  undefined  && viewpor tObject.ge tStudyUid( ) != undef ined && vi ewportObje ct.getStud yUid() !=  dragThumbn ailStudyUi d){
  18359                return;
  18360           }
  18361           ev ent.preven tDefault() ;
  18362       }
  18363  
  18364       functi on seriesD rop(event)  { 
  18365           di comViewer. measuremen t.setMeasu rementBrok en(false);
  18366           va r dragThum imageUid =  event.ori ginalEvent .dataTrans fer.getDat a("text");
  18367           va r thumbnai lRenderer  = dicomVie wer.thumbn ail.getThu mbnail($(' #' + dragT humimageUi d).parent( ).attr('id '));
  18368           va r studyUid  = thumbna ilRenderer .getStudyU id();
  18369           va r currentS eriesLayou tId = even t.currentT arget.id;
  18370           va r checkVie wport = di comViewer. viewports. checkVewpo rtAvailabl e(currentS eriesLayou tId, study Uid);
  18371           va r isUpdate ViewportHe ight = fal se;
  18372           if ( (dicomVi ewer.viewp orts.getVi ewport(cur rentSeries LayoutId)) .studyUid  == undefin ed) {
  18373                isUpdate ViewportHe ight = tru e;
  18374           }
  18375  
  18376           if (!checkVie wport)
  18377           {
  18378                return;
  18379           }
  18380           dr agThumbnai lStudyUid  = undefine d;
  18381           ev ent.preven tDefault() ;
  18382  
  18383           //  Change th e viewport  selection  if the cu rrent and  target vie wports are  mismatchi ng 
  18384           va r activeVi ewportStud yId = dico mViewer.ge tActiveSer iesLayout( ).getStudy Uid();
  18385           if (activeVie wportStudy Id !== und efined &&  activeView portStudyI d !== null ) {
  18386                if(activ eViewportS tudyId !==  studyUid)  {
  18387                    chan geSelectio n(currentS eriesLayou tId);
  18388                }
  18389           }
  18390  
  18391           va r seriesId  = event.t arget.id;
  18392           if  (event.ta rget.previ ousSibling )
  18393           {
  18394                var pare ntElemet =  $('#' + e vent.targe t.previous Sibling.id ).parent()
  18395                if(paren tElemet[0] === undefi ned)
  18396                {
  18397                    seri esId = eve nt.current Target.id;
  18398                }
  18399                else
  18400                {
  18401                    seri esId = get ParentElem ent($('#'  + event.ta rget.previ ousSibling .id), 'div ');
  18402                }
  18403           }
  18404           va r studyUid  = thumbna ilRenderer .getStudyU id();
  18405           va r seriesLa yout = dic omViewer.v iewports.g etViewport (seriesId) ;
  18406  
  18407           if  (!seriesL ayout)
  18408           {
  18409                var pare ntElemet =  $('#' + s eriesId).p arent();
  18410                if(paren tElemet[0] === undefi ned)
  18411                {
  18412                    seri esId = eve nt.current Target.id;
  18413                }else{
  18414                    seri esId = get ParentElem ent($('#'  + seriesId ), 'div');
  18415                }
  18416                seriesLa yout = dic omViewer.v iewports.g etViewport (seriesId) ;
  18417           }
  18418           if (seriesLay out === un defined)
  18419           {
  18420  
  18421               seriesId  = dicomVie wer.getAct iveSeriesL ayout().ge tSeriesLay outId();
  18422                seriesLa yout = dic omViewer.v iewports.g etViewport (seriesId) ;
  18423           }
  18424           se riesLayout .setStudyU id(studyUi d);
  18425           se riesLayout .isDragAnd Drop = tru e;
  18426           /* When we dr ag and dro p the imag e removing  the value */
  18427           im ageCanvasO fViewPorts [seriesLay out.series LayoutId]  = undefine d;
  18428           va r seriesNo  = thumbna ilRenderer .seriesInd ex;
  18429           va r imageNum ber = thum bnailRende rer.imageC ountOfSeri es;
  18430           // Check the  number is  available  while drag  and drop  the  thumb nail
  18431           // Number is  undefined  while drag  and drop  the series  thumbnail
  18432           if  (imageNum ber == und efined) {
  18433                imageNum ber = 0;
  18434                imageInd exNumber =  0;
  18435           }  else {
  18436                //number  is availa ble while  drag and d rop the im age level  thumbnail
  18437                imageNum ber = imag eNumber -  1;
  18438                imageInd exNumber =  imageNumb er;
  18439           }
  18440           va r image =  dicomViewe r.Series.I mage.getIm age(studyU id ,series No, imageN umber);
  18441           if (image !==  undefined )
  18442           {
  18443                $("#" +  currentSer iesLayoutI d).mousedo wn(selectV iewport); 
  18444                $("#" +  currentSer iesLayoutI d).mouseov er(focusAc tiveLayout );
  18445                $("#" +  currentSer iesLayoutI d).unbind( 'keydown') ;
  18446                $("#" +  currentSer iesLayoutI d).keydown (keyToMove NextOrPrev iousImage)
  18447           }
  18448           va r imageUid  = dicomVi ewer.Serie s.Image.ge tImageUid( image);
  18449           va r imagePro mise = dic omViewer.i mageCache. getImagePr omise(imag eUid +"_"+  0);
  18450           if  (dicomVie wer.isSeri esInComple te(studyUi d, seriesN o)) {
  18451                dicomVie wer.enable CacheData( studyUid,  true);
  18452                dicomVie wer.cacheI mages(stud yUid);
  18453           }
  18454  
  18455           va r isSameSe ries = fal se;
  18456           va r isMultiF rame = dic omViewer.t humbnail.i sSeriesCon tainsMulti frame(stud yUid, seri esLayout.s eriesIndex );
  18457           if (!isMultiF rame) {
  18458                if(serie sLayout.se riesIndex  == parseIn t(seriesNo )) {
  18459                    isSa meSeries =  true;
  18460                } else {
  18461                    dico mViewer.vi ewports.re moveDuplic ateViewpor tsBySeries Index(seri esLayout.s eriesLayou tId.split( '_')[0] +  "_" + seri esLayout.s eriesLayou tId.split( '_')[1] +  "_" + seri esLayout.s eriesIndex );
  18462                }
  18463           }  else {
  18464                if(serie sLayout.sc rollData.i mageIndex  == parseIn t(imageNum ber)) {
  18465                    isSa meSeries =  true;
  18466                } else {
  18467                    dico mViewer.vi ewports.re moveDuplic ateViewpor tsBySeries Index(seri esLayout.s eriesLayou tId.split( '_')[0] +  "_" + seri esLayout.s eriesLayou tId.split( '_')[1] +  "_" + seri esLayout.s crollData. imageIndex );
  18468                }
  18469           }
  18470  
  18471           se riesLayout .setSeries Index(pars eInt(serie sNo));
  18472           se riesLayout .setImageI ndex(parse Int(imageI ndexNumber ));
  18473           se riesLayout .setFrameI ndex(0);
  18474           se riesLayout .removeAll ImageRende rs();
  18475  
  18476           // Update the  view port  height if  viewport  is empty
  18477           if  (isUpdate ViewportHe ight) {
  18478                var imag e = dicomV iewer.Seri es.Image.g etImage(se riesLayout .studyUid,  seriesLay out.series Index, ser iesLayout. scrollData .imageInde x);
  18479                viewport Height(cur rentSeries LayoutId,i mage.image Type);
  18480                var view portId = c urrentSeri esLayoutId .split("_" )[1];
  18481                createSa veAndLoadP StateGUI(" saveAndLoa d_"+viewpo rtId, seri esLayout.s tudyUid, v iewportId) ;
  18482           }
  18483  
  18484           se riesLayout .setImageC ount(dicom Viewer.Ser ies.getIma geCount(st udyUid, se riesNo));
  18485           va r imageLay out = seri esLayout.g etImageLay outDimensi on().split ("x");
  18486           se tImageLeve lLayout(st udyUid, pa rseInt(ima geLayout[0 ]), parseI nt(imageLa yout[1]),  seriesId,  seriesLayo ut, series No, imageN umber, 0,  true);
  18487           if (dicomView er.viewpor ts.isDupli cateViewpo rt(isMulti Frame, isM ultiFrame  ? imageNum ber : seri esNo) && ! isSameSeri es) {
  18488                dicomVie wer.viewpo rts.addDup licateView portsBySer iesIndex(s eriesLayou t.seriesLa youtId.spl it('_')[0]  + "_" + s eriesLayou t.seriesLa youtId.spl it('_')[1]  + "_" + ( isMultiFra me ? image Number : s eriesNo),  seriesLayo ut);
  18489           }
  18490  
  18491           va r viewport ElementIds  = dicomVi ewer.viewp orts.getVi ewportIds( );
  18492           fo r (var i =  0; i < vi ewportElem entIds.len gth; i++)  {
  18493                $("#" +  viewportEl ementIds[i ]).removeC lass('sele cted-view' ).addClass ('default- view');
  18494           }
  18495           $( "#" + seri esId).trig ger("click ",[studyUi d]);
  18496           ch angeIconSi ze();
  18497           di comViewer. scroll.sto pCineImage (undefined );
  18498           ch angePlayDi rection();  // functi on has imp lemented i n viewer.c shtml
  18499           va r modality  = dicomVi ewer.Serie s.getModal ity(studyU id, series No);
  18500           if ((dicomVie wer.Series .Image.get ImageFrame Count(imag e)>1) && ( modality = == "US" ||  modality  === "XA")) {
  18501                 dicomVi ewer.start Cine();
  18502                updatePl ayIcon("pl ay.png", " stop.png") ;
  18503               }else{
  18504                  dicomV iewer.scro ll.stopCin eImage(und efined);
  18505                  update PlayIcon(" stop.png",  "play.png ");
  18506          }
  18507  
  18508           // Toggling t he state o f the Next  and Previ ous Image/ Series But ton on mou se wheel c lick
  18509           En ableDisabl eNextSerie sImage(ser iesLayout) ;
  18510           up datePreset (seriesLay out);
  18511       }
  18512  
  18513        /**
  18514        * cha nge the pr eset for W L and Zoom
  18515        * @pa ram {Type}  seriesLay out - it s pecifies t he active  series
  18516        */ 
  18517       functi on updateP reset(seri esLayout)  {
  18518           va r layoutId  = seriesL ayout.seri esLayoutId +"ImageLev el0x0";
  18519           va r render =  seriesLay out.imageR enders[lay outId];
  18520           if (render != undefined  && render  != null &&
  18521               render.pr esentation State != u ndefined &
  18522               render.pr esentation State != n ull) {
  18523  
  18524                var pres et = (rend er.present ationState ).windowLe vel;
  18525                dicomVie wer.tools. updateWind owLevelSet tings(pres et);
  18526           }
  18527           el se if(seri esLayout & & seriesLa yout.image Type === I MAGETYPE_R ADECG)
  18528           {
  18529                var pref erenceInfo  = seriesL ayout.pref erenceInfo ;
  18530                var zoom settings =  preferenc eInfo.zoom LevelSetti ng;
  18531                zoomsett ings = zoo msettings  ? zoomsett ings.split ("_")[0] :  2 ;
  18532                dicomVie wer.tools. setZoomLev el(parseIn t(zoomsett ings));
  18533           }
  18534       }
  18535  
  18536       functi on loadIma geFromThum bnail(seri esNo, imag eNumber) {
  18537           di comViewer. measuremen t.setMeasu rementBrok en(false);  
  18538                    var  seriesLayo ut = getAc tiveSeries Layout();
  18539                    var  studyUid =  seriesLay out.getStu dyUid();
  18540           im ageCanvasO fViewPorts [seriesLay out.series LayoutId]  = undefine d;
  18541           if  (imageNum ber === un defined) {
  18542                imageNum ber = 0;
  18543                imageInd exNumber =  0;
  18544           }  else {
  18545                //number  is availa ble while  drag and d rop the im age level  thumbnail
  18546                imageNum ber = imag eNumber -  1;
  18547                imageInd exNumber =  imageNumb er;
  18548           }
  18549           va r image =  dicomViewe r.Series.I mage.getIm age(studyU id, series No, imageN umber)
  18550           va r imageUid  = dicomVi ewer.Serie s.Image.ge tImageUid( image);
  18551           va r isMultiF rame = dic omViewer.t humbnail.i sSeriesCon tainsMulti frame(stud yUid, seri esLayout.s eriesIndex );
  18552           va r isSameSe ries = fal se;
  18553           if (!isMultiF rame) {
  18554                if(serie sLayout.se riesIndex  == parseIn t(seriesNo )) {
  18555                    isSa meSeries =  true;
  18556                } else {
  18557                    dico mViewer.vi ewports.re moveDuplic ateViewpor tsBySeries Index(seri esLayout.s eriesLayou tId.split( '_')[0] +  "_" + seri esLayout.s eriesLayou tId.split( '_')[1] +  "_" + seri esLayout.s eriesIndex );
  18558                }
  18559           }  else {
  18560                if(serie sLayout.sc rollData.i mageIndex  == parseIn t(imageNum ber)) {
  18561                    isSa meSeries =  true;
  18562                } else {
  18563                    dico mViewer.vi ewports.re moveDuplic ateViewpor tsBySeries Index(seri esLayout.s eriesLayou tId.split( '_')[0] +  "_" + seri esLayout.s eriesLayou tId.split( '_')[1] +  "_" + seri esLayout.s crollData. imageIndex );
  18564                }
  18565           }
  18566  
  18567           se riesLayout .setSeries Index(pars eInt(serie sNo));
  18568           se riesLayout .setImageI ndex(parse Int(imageI ndexNumber ));
  18569           se riesLayout .setFrameI ndex(0);
  18570           se riesLayout .removeAll ImageRende rs();
  18571           se riesLayout .setImageC ount(dicom Viewer.Ser ies.getIma geCount(st udyUid, se riesNo));
  18572           va r imageLay out = seri esLayout.g etImageLay outDimensi on().split ("x");
  18573           se tImageLeve lLayout(se riesLayout .studyUid,  parseInt( imageLayou t[0]), par seInt(imag eLayout[1] ), seriesL ayout.seri esLayoutId , seriesLa yout, seri esNo, imag eNumber, 0 , true);
  18574           up datePreset (seriesLay out);
  18575           if (dicomView er.viewpor ts.isDupli cateViewpo rt(isMulti Frame, isM ultiFrame  ? imageNum ber : seri esNo) && ! isSameSeri es) {
  18576                dicomVie wer.viewpo rts.addDup licateView portsBySer iesIndex(s eriesLayou t.seriesLa youtId.spl it('_')[0]  + "_" + s eriesLayou t.seriesLa youtId.spl it('_')[1]  + "_" + ( isMultiFra me ? image Number : s eriesNo),  seriesLayo ut);
  18577           }
  18578            
  18579           va r viewport ElementIds  = dicomVi ewer.viewp orts.getVi ewportIds( );
  18580           fo r (var i =  0; i < vi ewportElem entIds.len gth; i++)  {
  18581                $("#" +  viewportEl ementIds[i ]).removeC lass('sele cted-view' ).addClass ('default- view');
  18582           }
  18583           $( "#" + seri esLayout.s eriesLayou tId).trigg er("click" ,[studyUid ]);
  18584           if (image !==  undefined )
  18585           {
  18586                $("#" +  seriesLayo ut.seriesL ayoutId).m ousedown(s electViewp ort); 
  18587                $("#" +  seriesLayo ut.seriesL ayoutId).m ouseover(f ocusActive Layout);
  18588                $("#" +  seriesLayo ut.seriesL ayoutId).u nbind('key down');
  18589                $("#" +  seriesLayo ut.seriesL ayoutId).k eydown(key ToMoveNext OrPrevious Image); 
  18590           }
  18591           di comViewer. scroll.sto pCineImage (undefined );
  18592           ch angePlayDi rection();
  18593           va r imagePro mise = dic omViewer.i mageCache. getImagePr omise(imag eUid +"_"+  0);
  18594           if (image.ima geType !==  IMAGETYPE _JPEG && ! isBlob(ima ge.imageTy pe)){
  18595                if (dico mViewer.is SeriesInCo mplete(stu dyUid, ser iesNo)) {
  18596                    dico mViewer.en ableCacheD ata(studyU id, true);
  18597                    dico mViewer.ca cheImages( studyUid);
  18598                }
  18599           }
  18600       }
  18601  
  18602       functi on getPare ntElement( child, par entTag) {
  18603           va r parent =  child.par ent();
  18604           if  (parent[0 ].tagName  === parent Tag.toUppe rCase()) {
  18605                return p arent.attr ('id');
  18606           }  else {
  18607                return g etParentEl ement(pare nt, parent Tag);
  18608           }
  18609       }
  18610  
  18611       functi on setActi veSeriesLa yout(serie sLayout) {
  18612           if  (seriesLa yout === u ndefined)  {
  18613                throw "A ctive seri es layout  should not  be null/u ndefined";
  18614           }
  18615           ac tiveSeries Layout = s eriesLayou t;
  18616       }
  18617  
  18618       functi on getActi veSeriesLa yout() {
  18619           re turn activ eSeriesLay out;
  18620       }
  18621  
  18622       functi on keyToMo veNextOrPr eviousImag e(event) {
  18623           if  (event.ke yCode ===  40) //down  key
  18624           {
  18625                setTimeo ut(functio n() {
  18626                    move ToNextOrPr eviousImag e(true);
  18627                }, 0);
  18628           }  else if (e vent.keyCo de === 38)  //Up Key
  18629           {
  18630                setTimeo ut(functio n() {
  18631                    move ToNextOrPr eviousImag e(false);
  18632                }, 0);
  18633           }
  18634       }
  18635  
  18636       /**
  18637        * che ck whether  the image  has the m ultiframe  or not
  18638        * @pa ram {Type}  image - i t specifie s the imag e properti es
  18639        */ 
  18640       functi on canMove Series(ima ge){
  18641           if (!dicomVie wer.thumbn ail.canRun Cine(image )) {
  18642                return(i mage.modal ity == "US ") ? true  : false;
  18643           }  else {
  18644                return t rue;
  18645           }
  18646       }
  18647  
  18648       /**
  18649        * If  the measur ement is n ot complet ed then it  will comp lete that  measuremen t
  18650        * @pa ram {Type}  evt - scr oll event
  18651        */ 
  18652       functi on complet eMeasureme nt(evt) {
  18653           va r toolName  = dicomVi ewer.mouse Tools.getT oolName();
  18654           if (toolName  === "point Measuremen t" || tool Name === " lineMeasur ement" ||  toolName = == "angleM easurement " || 
  18655               toolName  === 'trace Measuremen t' || tool Name === ' volumeMeas urement' | | toolName  === 'elli pseMeasure ment'|| 
  18656               toolName  === 'recta ngleMeasur ement' ||  toolName = == 'mitral MeanGradie ntMeasurem ent') {
  18657                tool = d icomViewer .mouseTool s.getActiv eTool();
  18658                tool.han leMouseOut (evt);
  18659           }
  18660       }
  18661  
  18662       functi on scroll( event) {
  18663           ev ent.preven tDefault() ;
  18664           va r serieLay out = dico mViewer.ge tActiveSer iesLayout( );
  18665           va r studyUid ;
  18666           if (serieLayo ut !== und efined &&  serieLayou t !== null ) {
  18667                studyUid  = serieLa yout.getSt udyUid();
  18668                if((isTo PlayStudy( serieLayou t.getSerie sLayoutId( )) && (isC ineRunning (serieLayo ut.getSeri esLayoutId ())))) {
  18669                    retu rn;
  18670                }
  18671           }
  18672  
  18673           co mpleteMeas urement(ev ent);
  18674  
  18675           va r render =  undefined ;
  18676           if  (serieLay out.imageT ype === IM AGETYPE_RA DSR || ser ieLayout.i mageType = == IMAGETY PE_CDA) {
  18677                render =  serieLayo ut.imageRe nders["srR eport"];
  18678           }  else {
  18679                render =  serieLayo ut.imageRe nders[seri eLayout.se riesLayout Id +"Image Level0x0"] ;
  18680           }
  18681           va r scrollDo wn = event .originalE vent.wheel Delta < 0  || event.o riginalEve nt.detail  > 0;
  18682           va r playerBu ttomImage  = document .getElemen tById("pla yButton_wr apper").ge tElementsB yTagName(' img')[0].s rc;
  18683           if (serieLayo ut.imageTy pe === IMA GETYPE_TIF F || serie Layout.ima geType ===  IMAGETYPE _PDF ||ser ieLayout.i mageType = == IMAGETY PE_RADPDF  || 
  18684               serieLayo ut.imageTy pe === IMA GETYPE_RAD SR || seri eLayout.im ageType == = IMAGETYP E_CDA  ||
  18685               serieLayo ut.imageTy pe === IMA GETYPE_RAD ECG||serie Layout.ima geType ===  IMAGETYPE _RADPDF ||
  18686                serieLay out.series Index ===  undefined  || render. imageIndex  === undef ined )
  18687           {
  18688                return;
  18689           }
  18690           va r image =  dicomViewe r.Series.I mage.getIm age(studyU id, serieL ayout.seri esIndex, r ender.imag eIndex);         
  18691           
  18692          /*  if (dicomV iewer.mous eTools.get ToolName()  === 'Zoom ') {
  18693                return;
  18694                 //When  zoom funct ion in act ive disabl ing scroll  image fea ture Zoom  feature is  based on  mouse whee l event
  18695           }* /
  18696           va r scrollDo wn = event .originalE vent.wheel Delta < 0  || event.o riginalEve nt.detail  > 0;
  18697           va r playerBu ttomImage  = document .getElemen tById("pla yButton_wr apper").ge tElementsB yTagName(' img')[0].s rc;
  18698           va r isImageT humbnails  = dicomVie wer.thumbn ail.isImag eThumbnail (image,fal se);         
  18699           if ((canMoveS eries(imag e)) && ((i sImageThum bnails &&  (isCineRun ning(serie Layout.ser iesLayoutI d) || (ima ge.numberO fFrames == = 1) )) ||  (dicomVie wer.thumbn ail.isSeri esContains Multiframe (studyUid, serieLayou t.seriesIn dex) && im age.number OfFrames = == 1)))
  18700           {
  18701                dicomVie wer.tools. moveSeries (scrollDow n);
  18702           }
  18703           el se
  18704           {
  18705                moveToNe xtOrPrevio usImage(sc rollDown);
  18706           }
  18707                    
  18708           va r firstIma geFrame =  $("#"+seri eLayout.ge tSeriesLay outId()+"  div:first" ).attr("id ");
  18709           va r imageRen der = seri eLayout.ge tImageRend er(firstIm ageFrame);
  18710           va r currentI mageIndex  = null;
  18711           va r currentF rameIndex  = null;
  18712           if (imageRend er != unde fined)
  18713           {
  18714                var anUI Ds = image Render.anU IDs;
  18715                var resu ltArray =  anUIDs.spl it("*");
  18716                currentF rameIndex  = parseInt (resultArr ay[1]);
  18717                currentI mageIndex  = imageRen der.imageI ndex;
  18718           }
  18719           se rieLayout. setImageIn dex(curren tImageInde x);
  18720           se rieLayout. setFrameIn dex(curren tFrameInde x);
  18721           En ableDisabl eNextSerie sImage(ser ieLayout);
  18722       }
  18723  
  18724       functi on getCurr entImageAn dFrameInde x(moveToNe xt, series Layout)
  18725       {
  18726           //  Frame Ind ex must be  calculate  using the  visibilit y of the I mageLevel  viewports.
  18727           va r lastImag eFrame;
  18728           if  (moveToNe xt) {
  18729                lastImag eFrame = $ ("#"+serie sLayout.ge tSeriesLay outId()+"  div:last") .attr("id" );
  18730           }  else {
  18731                lastImag eFrame = $ ("#"+serie sLayout.ge tSeriesLay outId()+"  div:first" ).attr("id ");
  18732           }
  18733  
  18734           va r imageRen der = seri esLayout.g etImageRen der(lastIm ageFrame);
  18735           
  18736           va r imageInd ex = null;
  18737           if (imageRend er != unde fined)
  18738           {
  18739                var anUI Ds = image Render.anU IDs;
  18740                var resu ltArray =  anUIDs.spl it("*");
  18741                var fram eIndex = p arseInt(re sultArray[ 1]);
  18742  
  18743                //imageI ndex = ser iesLayout. getImageIn dex();
  18744                imageInd ex = image Render.ima geIndex;
  18745           }
  18746           if  (imageInd ex === nul l || image Index ===  undefined  || imageIn dex === -1 )
  18747           {
  18748                imageInd ex = serie sLayout.ge tImageInde x();
  18749           }
  18750           re turn [imag eIndex, fr ameIndex];
  18751       }
  18752  
  18753       /**
  18754        * - M ove the Ne xt or Prev ious Image . Boolean  argument w ill decide  whether i t is move  Next or Pr evious ima ge. 
  18755        */
  18756       functi on moveToN extOrPrevi ousImage(m oveToNext,  linkedSer iesLayout,  navigateP os, useSta rtPosition ) {
  18757           en dMeasureme nt();
  18758           va r seriesLa yout = und efined;
  18759           if (linkedSer iesLayout  !== undefi ned) {
  18760                seriesLa yout = lin kedSeriesL ayout;
  18761           }  else {
  18762                seriesLa yout = get ActiveSeri esLayout() ;
  18763           }
  18764  
  18765           va r studyUid  = seriesL ayout.stud yUid;
  18766           va r seriesIn dex = seri esLayout.g etSeriesIn dex();
  18767           va r imageLay outCount =  seriesLay out.getIma geLayoutCo unt();
  18768           va r numberOf Images = d icomViewer .Series.ge tImageCoun t(studyUid , seriesIn dex);
  18769  
  18770           va r imageAnd FrameIndex  = getCurr entImageAn dFrameInde x(moveToNe xt, series Layout);
  18771           va r imageInd ex = image AndFrameIn dex[0];
  18772           va r frameInd ex = image AndFrameIn dex[1];
  18773           
  18774           va r frameCou nt = dicom Viewer.Ser ies.Image. getImageFr ameCount(d icomViewer .Series.Im age.getIma ge(studyUi d, seriesI ndex, imag eIndex));
  18775           if  (frameCou nt === und efined) {
  18776                return;
  18777           }
  18778  
  18779           va r isSeries HasMultifr ame = dico mViewer.th umbnail.is SeriesCont ainsMultif rame(study Uid, serie sIndex);
  18780  
  18781           va r imagePos  = 0;
  18782           if  (navigate Pos === un defined) {
  18783                imagePos  = 1;
  18784           }  else {
  18785                if (navi gatePos.xD iff !== un defined) {
  18786                    var  perImageWi dth = Math .round($(" #" + serie sLayout.ge tSeriesLay outId()).w idth() / ( isSeriesHa sMultifram e ? frameC ount : num berOfImage s));
  18787                    if ( navigatePo s.xDiff >=  perImageW idth) {
  18788                         imagePos =  Math.roun d(navigate Pos.xDiff  / perImage Width);
  18789                    }
  18790                } else i f (navigat ePos.yDiff  !== undef ined) {
  18791                    var  perImageHe ight = Mat h.round($( "#" + seri esLayout.g etSeriesLa youtId()). height() /  (isSeries HasMultifr ame ? fram eCount : n umberOfIma ges));
  18792                    if ( navigatePo s.yDiff >=  perImageH eight) {
  18793                         imagePos =  Math.roun d(navigate Pos.yDiff  / perImage Height);
  18794                    }
  18795                }
  18796           }
  18797  
  18798           va r lastDivI d = $("#"+ seriesLayo ut.getSeri esLayoutId ()+" div:l ast").attr ("id");
  18799           va r firstDiv Id = $("#" +seriesLay out.getSer iesLayoutI d()+" div: first").at tr("id");
  18800           if  (moveToNe xt) {
  18801                if(isSer iesHasMult iframe)
  18802                {
  18803                    var  imageRende rs = serie sLayout.im ageRenders ;
  18804                    var  firstFrame Index = -1 ;
  18805                    var  lastFrameI ndex = 0;
  18806                    if(i mageRender s !== unde fined)
  18807                    {
  18808                         var imageR ender = im ageRenders [firstDivI d];
  18809                         if(imageRe nder !== u ndefined)
  18810                             firstF rameIndex  = parseInt (imageRend er.anUIDs. split("*") [1]);
  18811                         imageRende r = imageR enders[las tDivId]; 
  18812                         if(imageRe nder !== u ndefined)
  18813                             lastFr ameIndex =  parseInt( imageRende r.anUIDs.s plit("*")[ 1]);
  18814                         if(frameCo unt === la stFrameInd ex+1){
  18815                             return ;
  18816                         }else
  18817                         {
  18818                             if (us eStartPosi tion) {
  18819                                 fi rstFrameIn dex = navi gatePos.fr ameIndex;
  18820                             }
  18821                             frameI ndex = fir stFrameInd ex+imagePo s;
  18822                         }
  18823                    }
  18824                }else
  18825                {
  18826                    var  imageRende rs = serie sLayout.im ageRenders ;
  18827                    var  lastImageI ndex = 0;
  18828                    if(i mageRender s !== unde fined)
  18829                    {
  18830                         var imageR ender = im ageRenders [firstDivI d];
  18831                         if(imageRe nder === u ndefined)
  18832                             imageI ndex = -1;
  18833                         else
  18834                             imageI ndex = ima geRender.i mageIndex;
  18835                         imageRende r = imageR enders[las tDivId];
  18836                         if(imageRe nder === u ndefined)
  18837                             lastIm ageIndex =  -1;
  18838                         else 
  18839                             lastIm ageIndex =  imageRend er.imageIn dex;
  18840  
  18841                         if(numberO fImages == = lastImag eIndex+1)
  18842                         {
  18843                             return ;
  18844                         }else
  18845                         {
  18846                             if (us eStartPosi tion) {
  18847                                 im ageIndex =  navigateP os.imageIn dex;
  18848                             }
  18849                             imageI ndex = ima geIndex+im agePos;
  18850                         }
  18851                    }
  18852                }
  18853                
  18854           }  else
  18855           {
  18856                if(isSer iesHasMult iframe)
  18857                {
  18858                    var  imageRende rs = serie sLayout.im ageRenders ;
  18859                    if(i mageRender s !== unde fined)
  18860                    {
  18861                         var firstF rameIndex  = 1;
  18862                         var imageR ender = im ageRenders [firstDivI d];
  18863                         if(imageRe nder !== u ndefined)
  18864                             firstF rameIndex  = parseInt (imageRend er.anUIDs. split("*") [1]);
  18865                         if(firstFr ameIndex < = 0)
  18866                         {
  18867                             return ;
  18868                         }else
  18869                         {
  18870                             if (us eStartPosi tion) {
  18871                                 fi rstFrameIn dex = navi gatePos.fr ameIndex;
  18872                             }
  18873                             frameI ndex = fir stFrameInd ex-imagePo s;
  18874                         }
  18875                    }
  18876                 }else
  18877                 {
  18878                    var  imageRende rs = serie sLayout.im ageRenders ;
  18879                    if(i mageRender s !== unde fined)
  18880                    {
  18881                         var imageR ender = im ageRenders [firstDivI d];
  18882                         if(imageRe nder !== u ndefined)
  18883                             imageI ndex = ima geRender.i mageIndex;
  18884                         if(imageIn dex <= 0)
  18885                         {
  18886                             return ;
  18887                         }else{
  18888                             if (us eStartPosi tion) {
  18889                                 im ageIndex =  navigateP os.imageIn dex;
  18890                             }
  18891                             imageI ndex = ima geIndex-im agePos;
  18892                         }
  18893                    }
  18894  
  18895                 }
  18896           }
  18897  
  18898           lo adimages(s eriesLayou t, seriesI ndex, imag eIndex, fr ameIndex,  undefined,  isSeriesH asMultifra me);
  18899  
  18900           //  Perform t he link op eration
  18901           if (linkedSer iesLayout  === undefi ned) {
  18902                dicomVie wer.link.d oLink(seri esLayout,  moveToNext );
  18903           }
  18904           
  18905           // Move to ne xt frame/i mage
  18906           se riesLayout .setImageI ndex(image Index);
  18907           se riesLayout .setFrameI ndex(frame Index);
  18908           
  18909           // Enable or  disable th e Next/Pre vious seri es, and Ne xt/Previou s image an d repeat s eries
  18910           En ableDisabl eNextSerie sImage(ser iesLayout) ;
  18911  
  18912       }
  18913  
  18914       functi on pauseCi nePlay(run Status, is AllLayout)  {
  18915           if (isAllLayo ut === tru e)
  18916           {
  18917                for(var  key in cin eManager)
  18918                {
  18919                    if ( cineManage r[key] !==  undefined )
  18920                         cineManage r[key].sta tus = runS tatus;
  18921                }
  18922           }e lse
  18923           {
  18924                cineMana ger[getAct iveSeriesL ayout().se riesLayout Id].status  = runStat us; 
  18925           }
  18926           va r layoutId  = getActi veSeriesLa yout().ser iesLayoutI d;
  18927           if (cineManag er[layoutI d] !== und efined &&  cineManage r[layoutId ].status = == CINEPAU SE)
  18928                showCine Rate(0);
  18929           if (isCineRun ning(layou tId))
  18930           {
  18931               if(runSta tus === CI NEPAUSE)
  18932                   updat ePlayIcon( "stop.png" ,"play.png ");
  18933                else
  18934                    upda tePlayIcon ("play.png ","stop.pn g");
  18935           }
  18936       }
  18937       
  18938       functi on stopCin eImage(dir ection, li nkedSeries Layout) {
  18939           va r activeSe riesLayout  = undefin ed;
  18940           if (linkedSer iesLayout  !== undefi ned) {
  18941                activeSe riesLayout  = linkedS eriesLayou t;
  18942           }  else {
  18943                activeSe riesLayout  = getActi veSeriesLa yout();
  18944           }
  18945  
  18946           //  Perform t he link op eration
  18947           if (linkedSer iesLayout  === undefi ned) {
  18948                dicomVie wer.link.d oLink(acti veSeriesLa yout, fals e, directi on, false) ;
  18949           }
  18950  
  18951           va r layoutId  = activeS eriesLayou t.seriesLa youtId;
  18952           va r studyUid  = activeS eriesLayou t.getStudy Uid();
  18953           va r modality  = dicomVi ewer.Serie s.getModal ity(studyU id,activeS eriesLayou t.seriesIn dex);  
  18954           if  (cineMana ger[active SeriesLayo ut.seriesL ayoutId] ! == undefin ed) {
  18955                clearInt erval(cine Manager[ac tiveSeries Layout.ser iesLayoutI d].timer);
  18956                cineMana ger[active SeriesLayo ut.seriesL ayoutId].t imer = nul l;
  18957                showOrHi deInCineRu nning(moda lity, fals e);
  18958                
  18959                //Disabl ing the to ol bar but tons again  as per th e modality  because t he previou s method m aking the  tool bar e nable agai n as cine  is in stop  mode
  18960                enableOr DisableToo ls(modalit y, activeS eriesLayou t);
  18961           }
  18962           sh owCineRate (0);
  18963           my DropDown.w rapper.hid e();
  18964           $( "#" + layo utId).focu s();
  18965  
  18966           va r firstIma geFrame =  $("#"+acti veSeriesLa yout.getSe riesLayout Id()+" div :first").a ttr("id");
  18967           va r imageRen der = acti veSeriesLa yout.getIm ageRender( firstImage Frame);
  18968           va r currentI mageIndex  = null;
  18969           va r currentF rameIndex  = null;
  18970           if (imageRend er != unde fined)
  18971           {
  18972                var anUI Ds = image Render.anU IDs;
  18973                var resu ltArray =  anUIDs.spl it("*");
  18974                currentF rameIndex  = parseInt (resultArr ay[1]);
  18975                currentI mageIndex  = imageRen der.imageI ndex;
  18976           }  else {
  18977                currentI mageIndex  = activeSe riesLayout .getImageI ndex();
  18978                currentF rameIndex  = activeSe riesLayout .getFrameI ndex();
  18979           }
  18980  
  18981           ac tiveSeries Layout.set ImageIndex (currentIm ageIndex);
  18982           ac tiveSeries Layout.set FrameIndex (currentFr ameIndex);
  18983       }
  18984  
  18985       functi on isCineR unning(ser iesLayoutI d) {
  18986           if  (cineMana ger[series LayoutId]  !== undefi ned) {
  18987                if (cine Manager[se riesLayout Id].timer)  {
  18988                    retu rn true;
  18989                }
  18990           }
  18991           re turn false ;
  18992       }
  18993           
  18994       functi on startCi ne()
  18995       {
  18996           va r activeSe riesLayout  = getActi veSeriesLa yout();
  18997           va r seriesLa youtId = a ctiveSerie sLayout.ge tSeriesLay outId();
  18998           va r studyUid  = activeS eriesLayou t.getStudy Uid();
  18999           va r modality  = dicomVi ewer.Serie s.getModal ity(studyU id,activeS eriesLayou t.seriesIn dex);
  19000            v ar directi on = true;
  19001           if (cineManag er[seriesL ayoutId] ! = undefine d) 
  19002                directio n = cineMa nager[seri esLayoutId ].directio n;  
  19003           if (activeSer iesLayout. imageType  ===IMAGETY PE_RADECHO  || modali ty === "XA ")
  19004           {
  19005              if(!isCine Running(se riesLayout Id)){
  19006                  runCin eImage(dir ection);
  19007               }
  19008           }
  19009           el se{
  19010                runCineI mage(direc tion);
  19011                showOrHi deInCineRu nning(moda lity, true );
  19012           }
  19013           En ableDisabl eNextSerie sImage(act iveSeriesL ayout);
  19014       }
  19015  
  19016       /**
  19017        * Pla y/Stop the  Cine on m ouse wheel  click
  19018        */
  19019       functi on toggleC ineRunning () {
  19020           en dMeasureme nt();
  19021           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  19022           va r seriesLa youtId = s eriesLayou t.getSerie sLayoutId( );
  19023           va r studyUid  = seriesL ayout.getS tudyUid();
  19024           va r seriesIn dex = seri esLayout.g etSeriesIn dex();
  19025           va r imageInd ex = serie sLayout.ge tImageInde x();
  19026           va r image =  dicomViewe r.Series.I mage.getIm age(studyU id, series Index, ima geIndex);
  19027           va r isMultiF rame = dic omViewer.t humbnail.i sSeriesCon tainsMulti frame(stud yUid, seri esIndex);
  19028           if (isMultiFr ame === tr ue) {
  19029                imageCou nt = dicom Viewer.Ser ies.Image. getImageFr ameCount(i mage);
  19030           }  else {
  19031                imageCou nt = dicom Viewer.Ser ies.getIma geCount(st udyUid, se riesIndex) ;
  19032           }
  19033           if ((imageCou nt <= 1 &&  !dicomVie wer.scroll .isToPlayS tudy(serie sLayout.se riesLayout Id)) || im ageCount < = 4) {
  19034                return;
  19035           }
  19036           va r directio n = true;
  19037           if (cineManag er[seriesL ayoutId] ! = undefine d && cineM anager[ser iesLayoutI d].directi on != unde fined) 
  19038                directio n = cineMa nager[seri esLayoutId ].directio n;
  19039           if (isCineRun ning(serie sLayoutId) ) {
  19040                stopCine Image(dire ction);
  19041                updatePl ayIcon("st op.png","p lay.png");
  19042                UpdateIm ageType();
  19043           }  else {
  19044                runCineI mage(direc tion);
  19045                updatePl ayIcon("pl ay.png","s top.png");
  19046           }
  19047           // Toggling t he state o f the Next  and Previ ous Image/ Series But ton on mou se wheel c lick
  19048           En ableDisabl eNextSerie sImage(ser iesLayout) ;
  19049       }
  19050       
  19051       functi on isCineR unningOnAn yViewPort( ) {
  19052           fo r (var key  in cineMa nager)
  19053           {
  19054                if (cine Manager[ke y] !== und efined) {
  19055                    if ( cineManage r[key].tim er) {
  19056                         return tru e;
  19057                    }
  19058                }
  19059           }
  19060           re turn false ;
  19061       }
  19062       
  19063       functi on showCin eRate(cine Rate) {
  19064           va r rate = " 0";
  19065           if  (cineRate  !== undef ined) {
  19066                rate = c ineRate;
  19067           }
  19068           if (isNaN(rat e)) 
  19069                rate = 0 ;
  19070           do cument.get ElementByI d("cineRat eDisplay") .innerHTML  = Math.ro und(rate/1 000) + " F PS";
  19071       }
  19072  
  19073       functi on onCineS peedChange () {
  19074           va r seriesLa yout = get ActiveSeri esLayout() ;
  19075           if (cineManag er[seriesL ayout.seri esLayoutId ] === unde fined)
  19076           {
  19077                cineMana ger[series Layout.ser iesLayoutI d] = {};
  19078           }
  19079           ci neManager[ seriesLayo ut.seriesL ayoutId].s peed = $(" #cineSpeed Button").v al();
  19080       };
  19081       
  19082       /**
  19083        * To  check whet her any di alog windo w is open  or not
  19084       */
  19085       functi on isDialo gOpen() {
  19086           va r visible  = false;
  19087           if ($('#dicom Header').i s(':visibl e')) { 
  19088                visible  = true;
  19089           }  else if($( '#imagingD ata').is(' :visible') ) { 
  19090                visible  = true;
  19091           }  else if($( '#viewerVe rsionInfoM odal').is( ':visible' )) { 
  19092                visible  = true;
  19093           }
  19094           if (visible)  {
  19095                updatePl ayIcon("st op.png", " play.png") ;
  19096           }
  19097           re turn visib le;
  19098       }
  19099       
  19100       functi on runCine Image(dire ction, lin kedSeriesL ayout) {
  19101           va r seriesLa yout = und efined;
  19102           if (linkedSer iesLayout  !== undefi ned) {
  19103                seriesLa yout = lin kedSeriesL ayout;
  19104           }  else {
  19105                seriesLa yout = get ActiveSeri esLayout() ;
  19106           }
  19107  
  19108           if (seriesLay out && ser iesLayout. imageType  == IMAGETY PE_JPEG) {
  19109                return;
  19110           }
  19111  
  19112           va r pervious MilliSec;
  19113           va r frameRat ePerSec;
  19114           va r tempmill iSec;
  19115           va r tempdiff  = 0;
  19116           va r frameCou ntForFPS =  0;
  19117           va r imageLay outCount =  seriesLay out.getIma geLayoutCo unt();
  19118           va r seriesIn dex = seri esLayout.g etSeriesIn dex();
  19119           va r imageInd ex = serie sLayout.ge tImageInde x();//imag eAndFrameI ndex[0];
  19120           va r frameInd ex = serie sLayout.ge tFrameInde x();//imag eAndFrameI ndex[1];
  19121           va r studyUid  = seriesL ayout.stud yUid;
  19122           va r modality  = dicomVi ewer.Serie s.getModal ity(studyU id,seriesL ayout.seri esIndex);
  19123           va r image =  dicomViewe r.Series.I mage.getIm age(studyU id, series Index, ima geIndex);
  19124           va r frameCou nt = dicom Viewer.Ser ies.Image. getImageFr ameCount(i mage);
  19125           va r imageCou nt = dicom Viewer.Ser ies.getIma geCount(st udyUid, se riesIndex) ;
  19126           va r seriesCo unt = dico mViewer.St udy.getSer iesCount(s tudyUid);
  19127           va r isMultiF rame = dic omViewer.t humbnail.i sImageThum bnail(imag e);
  19128           if  (cineMana ger[series Layout.ser iesLayoutI d] === und efined) {
  19129                cineMana ger[series Layout.ser iesLayoutI d] = {};
  19130           }
  19131           ci neManager[ seriesLayo ut.seriesL ayoutId].d irection =  direction ;
  19132           ci neManager[ seriesLayo ut.seriesL ayoutId].s tatus = CI NERUN;
  19133           cl earInterva l(cineMana ger[series Layout.ser iesLayoutI d].timer);  // clear  interval
  19134  
  19135           va r imageUid  = dicomVi ewer.Serie s.Image.ge tImageUid( image);
  19136           va r dicomHea der = dico mViewer.he ader.getDi comHeader( imageUid);
  19137           va r cineRate  = $("#cin eSpeedButt on").val() ;
  19138           va r cineRepe atForImage  = 1;
  19139           va r expected CineRate;
  19140           va r isMultiF rame =  di comViewer. thumbnail. isSeriesCo ntainsMult iframe(stu dyUid,seri esIndex);
  19141           if  (dicomHea der !== un defined) {
  19142                cineRate  = dicomHe ader.image Info.cineR ate;
  19143                if (cine Rate === 0  && ((dico mHeader.im ageInfo.nu mberOfFram es > 1 &&  isMultiFra me) || 
  19144                                         !isMu ltiFrame & & imageCou nt > 1)) {
  19145                    cine Rate = $(" #cineSpeed Button").v al();
  19146                    if(m yDropDown  !== null)  {
  19147                         if(cineMan ager[serie sLayout.se riesLayout Id] !== un defined &&  cineManag er[seriesL ayout.seri esLayoutId ].speed != = undefine d) {
  19148                             myDrop Down.value (cineManag er[seriesL ayout.seri esLayoutId ].speed);
  19149                         }
  19150                    }
  19151                } else {
  19152                    if(m yDropDown  !== null)  {
  19153                         myDropDown .wrapper.h ide();
  19154                    }
  19155                }
  19156           }  else {
  19157                if(cineM anager[ser iesLayout. seriesLayo utId].spee d === unde fined) {
  19158                    cine Rate = $(" #cineSpeed Button").v al();
  19159                }
  19160                else {
  19161                    cine Rate = cin eManager[s eriesLayou t.seriesLa youtId].sp eed;
  19162                }
  19163           }
  19164  
  19165           ex pectedCine Rate = cin eRate;
  19166           ci neRate = 1 000 / cine Rate;
  19167           ci neManager[ seriesLayo ut.seriesL ayoutId].c ineRate =  cineRate;
  19168           ci neManager[ seriesLayo ut.seriesL ayoutId].n extImageSt art = true ;
  19169           se riesLayout .setSeries Index(seri esIndex);
  19170           se riesLayout .setImageI ndex(image Index);
  19171           se riesLayout .setStudyU id(studyUi d);
  19172           sh owOrHideIn CineRunnin g(modality , true);
  19173  
  19174           //  Perform t he link op eration
  19175           if (linkedSer iesLayout  === undefi ned) {
  19176                dicomVie wer.link.d oLink(seri esLayout,  false, dir ection, tr ue);
  19177           }
  19178  
  19179           va r moveSeri es = false ;
  19180           va r cineFunc  = functio n(seriesLa yout) {
  19181                if (isDi alogOpen() ) { 
  19182                    retu rn;
  19183                }
  19184                var star tTime = ne w Date().g etTime();
  19185                if(cineM anager[ser iesLayout. seriesLayo utId].time r !== null  && cineMa nager[seri esLayout.s eriesLayou tId].nextI mageStart  == true &&  cineManag er[seriesL ayout.seri esLayoutId ].status = == CINERUN ) {
  19186                    cine Manager[se riesLayout .seriesLay outId].nex tImageStar t = false;
  19187                    var  isToPlaySt udyEnabled  = isToPla yStudy(ser iesLayout. seriesLayo utId);
  19188                    if ( frameCount  === undef ined) {
  19189                         return;
  19190                    } el se {
  19191                         image = di comViewer. Series.Ima ge.getImag e(studyUid , seriesIn dex, image Index);
  19192                         if(seriesI ndex != se riesLayout .seriesInd ex) {
  19193                             imageC ount = dic omViewer.S eries.getI mageCount( studyUid,  seriesInde x);
  19194                             isMult iFrame = d icomViewer .thumbnail .isSeriesC ontainsMul tiframe(se riesLayout .studyUid,  seriesLay out.series Index);
  19195                             frameC ount = dic omViewer.S eries.Imag e.getImage FrameCount (image);
  19196                         }
  19197  
  19198                         var isLoad ed = loadi mages(seri esLayout,  seriesInde x, imageIn dex, frame Index,isTo PlayStudyE nabled, is MultiFrame );
  19199                         if(isToPla yStudyEnab led) {
  19200                             if(rep eatSeriesI ndex !== s eriesIndex  || (isMul tiFrame &&  repeatIma geIndex != = imageInd ex)) {
  19201                                 va r currentS eriesLayou t = series Layout.ima geLayoutDi mension.sp lit("x");
  19202                                 re peatSeries Index = se riesIndex;
  19203                                 re peatImageI ndex = ima geIndex;
  19204                                 se tImageLeve lLayout(st udyUid, cu rrentSerie sLayout[0] , currentS eriesLayou t[1], seri esLayout.s eriesLayou tId, serie sLayout, s eriesIndex , imageInd ex, frameI ndex, true );
  19205                                 va r imagecnt  = isMulti Frame ? fr ameCount :  imageCoun t;
  19206                                 va r studyDiv  = getStud yLayoutId( seriesLayo ut.seriesL ayoutId);
  19207  
  19208                                 if (imagecnt  == 1) {
  19209                                      $('#imag eDisplay'  + studyDiv ).hide();
  19210                                 }  else {
  19211                                      $('#imag eDisplay'  + studyDiv ).show();
  19212                                 }
  19213  
  19214                                 sh owOrHideIn CineRunnin g(modality , true);
  19215                                 if (seriesLay out.getSer iesLayoutI d() === di comViewer. getActiveS eriesLayou t().getSer iesLayoutI d()) {
  19216                                      seriesLa yout.setSe riesIndex( seriesInde x);
  19217                                      seriesLa yout.setIm ageIndex(i mageIndex) ;
  19218                                      seriesLa yout.setSt udyUid(stu dyUid);
  19219                                      if(!isNo nDicomStud y(image.mo dality)) {
  19220                                          upda teThumbnai lSelection (image, se riesIndex,  imageInde x, studyUi d, moveSer ies);
  19221                                      }
  19222                                      moveSeri es = false ;
  19223                                 }
  19224                             }
  19225                         }
  19226                         if(!isLoad ed)
  19227                         {
  19228                             cineMa nager[seri esLayout.s eriesLayou tId].nextI mageStart  = true;
  19229                             return ;
  19230                         }
  19231                         dicomHeade r = dicomV iewer.head er.getDico mHeader(im ageUid);
  19232                         cineRate =  $("#cineS peedButton ").val();
  19233                         if (dicomH eader !==  undefined)  {
  19234                             cineRa te = dicom Header.ima geInfo.cin eRate;
  19235                             if (ci neRate ===  0) {
  19236                                 if (cineManag er[seriesL ayout.seri esLayoutId ].speed == = undefine d) {
  19237                                      cineRate  = $("#cin eSpeedButt on").val() ;
  19238                                 }  else {
  19239                                      cineRate  = cineMan ager[serie sLayout.se riesLayout Id].speed;
  19240                                 }
  19241                             }
  19242                         } else {
  19243                             if(cin eManager[s eriesLayou t.seriesLa youtId].sp eed === un defined) {
  19244                                 ci neRate = $ ("#cineSpe edButton") .val();
  19245                             } else  {
  19246                                 ci neRate = c ineManager [seriesLay out.series LayoutId]. speed;
  19247                             }
  19248                         }
  19249                         expectedCi neRate = c ineRate;
  19250                         cineRate =  1000 / ci neRate;
  19251                         cineManage r[seriesLa yout.serie sLayoutId] .cineRate  = cineRate ;
  19252                    }
  19253  
  19254                    if(i sMultiFram e && frame Count ===  1 || !isMu ltiFrame & & imageCou nt === 1)  {
  19255                         if(isToPla yStudyEnab led)
  19256                         {
  19257                             cineRa te = (dico mViewer.co nfiguratio n.cine.get IdleTime() ) * 1000;
  19258                             cineMa nager[seri esLayout.s eriesLayou tId].cineR ate = cine Rate;
  19259                         }
  19260                         else
  19261                         {
  19262                             return ;
  19263                         }
  19264                    }
  19265                    if ( direction)  {
  19266                         if ((isMul tiFrame &&  frameInde x < (frame Count - 1) ) || (!isM ultiFrame  && imageIn dex < (ima geCount -  1))) {
  19267                             if(isM ultiFrame)  {
  19268                                 fr ameIndex++ ;
  19269                             } else  {
  19270                                 im ageIndex++ ;
  19271                             }
  19272                         } else {
  19273                             var im ageOrFrame Count = is MultiFrame  ? frameCo unt : imag eCount;
  19274                             if (im ageOrFrame Count <= 1  || (image OrFrameCou nt > 1 &&  isToPlaySt udyEnabled )) {
  19275                                 if (cineRepea tForImage  < dicomVie wer.config uration.ci ne.getTime sToRepeat( ) &&
  19276                                     imageOrFr ameCount < = dicomVie wer.config uration.ci ne.getFram esToRepeat () && imag eOrFrameCo unt > 1)
  19277                                 {
  19278                                      cineRepe atForImage  ++;
  19279                                 }
  19280                                 el se
  19281                                 {
  19282                                      cineRepe atForImage  = 1;
  19283                                      imageInd ex++;
  19284                                      if(isMul tiFrame) {
  19285                                          move Series = t rue;
  19286                                      }
  19287                                      image =  dicomViewe r.Series.I mage.getIm age(studyU id, series Index, ima geIndex);
  19288                                 }
  19289                             }
  19290                             var im agelayout  = seriesLa yout.image LayoutDime nsion.spli t("x");
  19291                             if(ima gelayout.l ength == 2 ) {
  19292                                 if (imagelayo ut[0] == " 2" && imag elayout[1]  == "2") {
  19293                                      if (imag eIndex ==  frameIndex  - 3) {
  19294                                          imag eIndex = i mageCount;
  19295                                      }
  19296                                 }  else if(im agelayout[ 0] != "1"  || imagela yout[1] !=  "1") {
  19297                                      if (imag eIndex ==  frameIndex  - 1) {
  19298                                          imag eIndex = i mageCount;
  19299                                      }
  19300                                 }
  19301                             }
  19302                             if(!is MultiFrame  && imageI ndex == (i mageCount  - 1) && im ageOrFrame Count > 1) {
  19303                                 im ageIndex =  0;
  19304                             }
  19305                             if (im ageIndex > = imageCou nt) {
  19306                                 im ageIndex =  0;
  19307                                 if  (isToPlay StudyEnabl ed) {
  19308                                      seriesIn dex++;
  19309                                      moveSeri es = true;
  19310                                      if (seri esIndex >=  seriesCou nt) series Index = 0;
  19311                                      imageCou nt = dicom Viewer.Ser ies.getIma geCount(st udyUid, se riesIndex) ;
  19312                                      image =  dicomViewe r.Series.I mage.getIm age(studyU id, series Index, ima geIndex);
  19313                                      imageUid  = dicomVi ewer.Serie s.Image.ge tImageUid( image);
  19314                                      isMultiF rame =  di comViewer. thumbnail. isSeriesCo ntainsMult iframe(stu dyUid,seri esIndex);
  19315                                 }
  19316                             }
  19317                             frameI ndex = 0;
  19318                             frameC ount = dic omViewer.S eries.Imag e.getImage FrameCount (dicomView er.Series. Image.getI mage(study Uid, serie sIndex, im ageIndex)) ;
  19319                         }
  19320                    } el se {
  19321                         if ((isMul tiFrame &&  frameInde x > 0) ||   (!isMulti Frame && i mageIndex  > 0))  {
  19322                             if(isM ultiFrame)  {
  19323                                 fr ameIndex-- ;
  19324                                 se riesLayout .getProgre ssbar().up dateImageP osition(fr ameCount,  frameIndex );
  19325                             } else  {
  19326                                 im ageIndex-- ;
  19327                             }
  19328                         } else {
  19329                             var im ageOrFrame Count = is MultiFrame  ? frameCo unt : imag eCount;
  19330                             if (im ageOrFrame Count <= 1  || (image OrFrameCou nt > 1 &&  isToPlaySt udyEnabled )) {
  19331                                 if (cineRepea tForImage  < dicomVie wer.config uration.ci ne.getTime sToRepeat( ) && 
  19332                                     imageOrFr ameCount < = dicomVie wer.config uration.ci ne.getFram esToRepeat () && imag eOrFrameCo unt > 1) {
  19333                                      cineRepe atForImage  ++;
  19334                                 }  else {
  19335                                      cineRepe atForImage  = 1;
  19336                                      imageInd ex--;
  19337                                      if(isMul tiFrame) {
  19338                                          move Series = t rue;
  19339                                      }
  19340                                      image =  dicomViewe r.Series.I mage.getIm age(studyU id, series Index, ima geIndex);
  19341                                 }
  19342                             }
  19343                             if(!is MultiFrame  && imageI ndex == 0  && imageOr FrameCount  > 1){
  19344                                 im ageIndex =  imageCoun t - 1;
  19345                             }
  19346                             if (im ageIndex <  0) {
  19347                                 if  (isToPlay StudyEnabl ed) {
  19348                                      seriesIn dex--;
  19349                                      moveSeri es = true;
  19350                                      if (seri esIndex <  0) seriesI ndex = ser iesCount -  1;
  19351                                      imageCou nt = dicom Viewer.Ser ies.getIma geCount(st udyUid, se riesIndex) ;
  19352                                      imageInd ex = image Count - 1;
  19353                                      image =  dicomViewe r.Series.I mage.getIm age(studyU id, series Index, ima geIndex);
  19354                                      imageUid  = dicomVi ewer.Serie s.Image.ge tImageUid( image);
  19355                                 }
  19356                                 //  Image cou nt should  calculate  for new Se ries Index  images.
  19357                                 im ageIndex =  imageCoun t - 1;
  19358                             }
  19359                             frameC ount = dic omViewer.S eries.Imag e.getImage FrameCount (dicomView er.Series. Image.getI mage(study Uid, serie sIndex, im ageIndex)) ;
  19360                             frameI ndex = fra meCount -  1;
  19361                         }
  19362                    }
  19363                    //Di splaying C ine Rate f or multifr ame images
  19364                    if(s eriesLayou t.seriesLa youtId ==  getActiveS eriesLayou t().series LayoutId)
  19365                    {
  19366                         var index  = isMultiF rame ? fra meIndex :  imageIndex ;
  19367                         if (index  == 1) {
  19368                             tempdi ff = 0;
  19369                             frameC ountForFPS  = 0;
  19370                             if (pe rviousMill iSec == un defined) {
  19371                                 pe rviousMill iSec = new  Date().ge tTime();
  19372                             }
  19373                         } else {
  19374                             //Stop  the cine  and play a gain will  go inside  if 
  19375                             if (pe rviousMill iSec == un defined) {
  19376                                 pe rviousMill iSec = new  Date().ge tTime();
  19377                                 fr ameCountFo rFPS = 0;
  19378                             } else  {
  19379                                 fr ameCountFo rFPS ++;
  19380                                 va r currentT ime = new  Date().get Time();
  19381                                 te mpmilliSec  = current Time - per viousMilli Sec;
  19382                                 te mpdiff = t empdiff +  tempmilliS ec;
  19383                             }
  19384                         }
  19385  
  19386                         if (index  != 0) {
  19387                             frameR atePerSec  = Math.rou nd((frameC ountForFPS  * 1000) /  tempdiff) ;
  19388                         }
  19389                         else {
  19390                             frameR atePerSec  = 1;
  19391                         }
  19392  
  19393                         if(frameRa tePerSec ! = undefine d) {
  19394                             if(isN aN(frameRa tePerSec))  {
  19395                                 fr ameRatePer Sec = 0;
  19396                             }
  19397                             docume nt.getElem entById("c ineRateDis play").inn erText = M ath.round( frameRateP erSec) + " / "+Math.r ound(expec tedCineRat e) +" FPS" ;
  19398                         }
  19399                         perviousMi lliSec = n ew Date(). getTime();
  19400                    }
  19401  
  19402                    if ( seriesLayo ut.getProg ressbar(). seriesInde x != serie sIndex ||  seriesLayo ut.getProg ressbar(). imageIndex  != imageI ndex) {
  19403                         seriesLayo ut.getProg ressbar(). setSeriesI nfo(studyU id, series Index, ima geIndex, 0 );
  19404                    }
  19405  
  19406                    if(c ineManager [seriesLay out.series LayoutId]. timer != n ull || cin eManager[s eriesLayou t.seriesLa youtId].ti mer != und efined) {
  19407                         clearInter val(cineMa nager[seri esLayout.s eriesLayou tId].timer ); // clea r interval  
  19408                         var timeDi ff = new D ate().getT ime() - st artTime;
  19409                         cineRate =  Math.abs( cineRate -  timeDiff) ;
  19410  
  19411                         if(cineRat e <= 0 ||  (image &&  isNonDicom Study(imag e.modality )) ) {
  19412                             cineRa te = 1;
  19413                         }
  19414                         cineManage r[seriesLa yout.serie sLayoutId] .timer = s etInterval (cineFunc,  cineRate,  seriesLay out);
  19415                    }
  19416                }
  19417           }
  19418  
  19419           ci neManager[ seriesLayo ut.seriesL ayoutId].t imer = set Interval(c ineFunc, c ineRate,se riesLayout );
  19420       }
  19421  
  19422       functi on getImag eIndex(ser iesIndex,  imageIndex , frameInd ex) {
  19423           wh ile (frame Index > 0)  {
  19424                var coun t = dicomV iewer.Seri es.Image.g etImageFra meCount(di comViewer. Series.Ima ge.getImag e(seriesIn dex, image Index++));
  19425                if (coun t === unde fined) {
  19426                    retu rn count;
  19427                }
  19428                frameInd ex -= coun t;
  19429           }
  19430           re turn image Index - 1;
  19431       }
  19432  
  19433       functi on getImag eIndexOfFr ame(studyU id, series Index, ima geIndex, n extFramesC ount) {
  19434           wh ile (nextF ramesCount  > 0) {
  19435                nextFram esCount -=  dicomView er.Series. Image.getI mageFrameC ount(dicom Viewer.Ser ies.Image. getImage(s tudyUid, s eriesIndex , --imageI ndex));
  19436           }
  19437           re turn image Index; //A dding one  for extra  deduce in  while loop
  19438       }
  19439  
  19440       functi on getNext DownScroll Count(seri esIndex, i mageIndex,  frameInde x) {
  19441           wh ile (frame Index < 0)  {
  19442                frameInd ex += dico mViewer.Se ries.Image .getImageF rameCount( dicomViewe r.Series.I mage.getIm age(series Index, --i mageIndex) );
  19443           }
  19444           re turn image Index;
  19445       }
  19446  
  19447       functi on getScro llDownFram eCount(stu dyUid, ser iesIndex,  imageIndex ) {
  19448           va r count =  0;
  19449           fo r (var i =  --imageIn dex; i >=  0; i--) {
  19450                count +=  dicomView er.Series. Image.getI mageFrameC ount(dicom Viewer.Ser ies.Image. getImage(s tudyUid, s eriesIndex , i));
  19451           }
  19452           re turn count ;
  19453       }
  19454  
  19455       functi on getNext UpScrollCo unt(studyU id, series Index, ima geIndex) {
  19456           va r count =  0;
  19457           fo r (var i =  imageInde x; i < dic omViewer.S eries.getI mageCount( studyUid,  seriesInde x); i++) {
  19458                var fram ecount = d icomViewer .Series.Im age.getIma geFrameCou nt(dicomVi ewer.Serie s.Image.ge tImage(stu dyUid, ser iesIndex,  i));
  19459                if (fram ecount ===  undefined ) {
  19460                    retu rn count;
  19461                }
  19462                count +=  framecoun t;
  19463           }
  19464           re turn count ;
  19465       }
  19466  
  19467       functi on loadIma gesInViewp ort(series Layout, se riesIndex,  imageInde x, frameIn dex,isToPl ayStudyEna bled,image LevelLayou tIndex){
  19468           va r studyUid  = seriesL ayout.getS tudyUid();
  19469           va r image =  dicomViewe r.Series.I mage.getIm age(studyU id, series Index, ima geIndex);
  19470           if (image ===  undefined )
  19471                return;
  19472           va r frameCou nt = dicom Viewer.Ser ies.Image. getImageFr ameCount(i mage);
  19473  
  19474           if  (frameInd ex >= fram eCount) {
  19475                dumpCons oleLogs(LL _DEBUG, un defined, " loadImages InViewport ", "FrameI ndex > Fra meCount, c onsidering  it as Non -Multifram e image.") ;
  19476                if(frame Count <= 1  || isToPl ayStudyEna bled === u ndefined | | isToPlay StudyEnabl ed)
  19477                {
  19478                    imag eIndex++;
  19479                    var  imageCount  = dicomVi ewer.Serie s.getImage Count(stud yUid, seri esIndex);
  19480                    if(i mageIndex  >= imageCo unt) image Index = 0;
  19481                }
  19482                frameInd ex = 0;
  19483  
  19484                if (fram eCount > 1 ) {
  19485                    seri esLayout.g etProgress bar().setS eriesInfo( studyUid,  seriesInde x, imageIn dex, 0);
  19486                }
  19487           }
  19488  
  19489           va r imageLev elId = $(" #" + serie sLayout.ge tSeriesLay outId() +  " div")[im ageLevelLa youtIndex] .id;
  19490           va r imageRen der = seri esLayout.g etImageRen der(imageL evelId);
  19491           im ageIndex =  Math.min( imageIndex , dicomVie wer.Series .getImageC ount(study Uid,series Index)-1);
  19492           im ageIndex =  Math.max( 0, imageIn dex);
  19493           va r image =  dicomViewe r.Series.I mage.getIm age(studyU id, series Index, ima geIndex);
  19494           if  (image !=  undefined  && imageR ender !==  undefined)  {
  19495                var imag eUid = dic omViewer.S eries.Imag e.getImage Uid(image) ;
  19496                var isMu ltiFrame =  dicomView er.thumbna il.isSerie sContainsM ultiframe( studyUid,  seriesInde x);
  19497  
  19498                var load ImageDefer red;
  19499                if (isMu ltiFrame)  {
  19500                    load ImageDefer red = dico mViewer.ge tImage(stu dyUid, ima geUid, fra meIndex, i mageIndex,  image.ima geType, se riesIndex) ;
  19501                } else {
  19502                    load ImageDefer red = dico mViewer.ge tImage(stu dyUid, ima geUid, fra meIndex, s eriesIndex , image.im ageType);
  19503                }
  19504  
  19505                loadImag eDeferred. done(funct ion(imageC anvas) {
  19506                    var  deferred =  $.Deferre d();
  19507                    defe rred.resol ve(imageCa nvas);
  19508                    var  anUIDs =   imageCanva s.imageUid + "*" + im ageCanvas. frameNumbe r;
  19509                    var  newImageIn dex =  par seInt( dic omViewer.S eries.Imag e.getImage Index(stud yUid,serie sIndex, im ageCanvas. imageUid)) ;
  19510                    imag eRender.re fresh(defe rred,anUID s, false,  newImageIn dex, serie sIndex, is ToPlayStud yEnabled);
  19511                    upda teActivePr ogressbar( seriesLayo ut, newIma geIndex, i mageCanvas .frameNumb er);
  19512                    imag eLevelLayo utIndex++;
  19513                     if( $("#" + se riesLayout .getSeries LayoutId()  + " div") .length == = imageLev elLayoutIn dex)
  19514                     {
  19515                          seriesLay out.setSer iesIndex(s eriesIndex );
  19516                         if(cineMan ager[serie sLayout.se riesLayout Id] != und efined) 
  19517                             cineMa nager[seri esLayout.s eriesLayou tId].nextI mageStart  = true;
  19518                     }
  19519                    // N eed to inc rease the  frameIndex  or imageI ndex based  on modali ty type.
  19520                    if($ ("#" + ser iesLayout. getSeriesL ayoutId()  + " div"). length > 0 )
  19521                    {
  19522                         if (dicomV iewer.thum bnail.isIm ageThumbna il(image))
  19523                         {
  19524                             frameI ndex++;
  19525                             dumpCo nsoleLogs( LL_DEBUG,  undefined,  "loadImag esInViewpo rt", "Incr eased the  FrameIndex  to: " + f rameIndex) ;
  19526                         }
  19527                         else if (( dicomViewe r.Series.g etImageCou nt(studyUi d, seriesI ndex) - 1)  != imageI ndex)
  19528                         {
  19529                             imageI ndex++;
  19530                             dumpCo nsoleLogs( LL_DEBUG,  undefined,  undefined , "Increas ed the Ima geIndex to : " + imag eIndex);
  19531                         }
  19532                    }
  19533                     if( $("#" + se riesLayout .getSeries LayoutId()  + " div") .length >  imageLevel LayoutInde x) {
  19534                          loadImage sInViewpor t(seriesLa yout, seri esIndex, i mageIndex,  frameInde x,isToPlay StudyEnabl ed,imageLe velLayoutI ndex);
  19535                     }
  19536                });
  19537  
  19538                loadImag eDeferred. fail(funct ion(){
  19539                    dump ConsoleLog s(LL_WARN,  undefined , "loadIma gesInViewp ort", "Ima ge loading  failed fo r " + imag eIndex);
  19540                    imag eLevelLayo utIndex++;
  19541                    if($ ("#" + ser iesLayout. getSeriesL ayoutId()  + " div"). length > i mageLevelL ayoutIndex )
  19542                         loadImages InViewport (seriesLay out, serie sIndex, im ageIndex,  frameIndex ,isToPlayS tudyEnable d,imageLev elLayoutIn dex);
  19543                    if($ ("#" + ser iesLayout. getSeriesL ayoutId()  + " div"). length ===  imageLeve lLayoutInd ex)
  19544                     {
  19545                         seriesLayo ut.setSeri esIndex(se riesIndex) ;
  19546                         seriesLayo ut.setImag eIndex(new ImageIndex );
  19547                         seriesLayo ut.setFram eIndex(ima geCanvas.f rameNumber );
  19548                         if(cineMan ager[serie sLayout.se riesLayout Id] != und efined) 
  19549                             cineMa nager[seri esLayout.s eriesLayou tId].nextI mageStart  = true;   
  19550                     }
  19551                });
  19552           }
  19553       }
  19554  
  19555       /**
  19556        * Loa d images i s used to  load the i mage using  imageInde x and Fram eIndex.
  19557        * Thi s method w ill loop t he Series  Layout id  and load t he images.
  19558        */
  19559       functi on loadima ges(series Layout, se riesIndex,  imageInde x, frameIn dex,isToPl ayStudyEna bled, isMu ltiFrame)  {
  19560           va r isToPlay StudyEnabl ed = isToP layStudy(s eriesLayou t.seriesLa youtId);
  19561           va r imageLay out = $("# " + series Layout.get SeriesLayo utId() + "  div")[0];
  19562           if (imageLayo ut === und efined) {
  19563                return f alse;
  19564           }
  19565  
  19566           va r imageLev elId = ima geLayout.i d;
  19567           if (imageLeve lId === "" ) return f alse;
  19568           
  19569           va r viewport Count = $( "#" + seri esLayout.g etSeriesLa youtId() +  " div").l ength;
  19570           if (viewportC ount > 0)  {
  19571                if(!isMu ltiFrame)  {
  19572                    var  imageCount  = dicomVi ewer.Serie s.getImage Count(seri esLayout.s tudyUid, s eriesIndex );
  19573                    if(( (imageInde x + viewpo rtCount) > = imageCou nt) && ima geCount >  viewportCo unt) {
  19574                         //Updating  the image  index so  that the l ast image  will not c opy to oth er previou s viewport s in image  level lay out
  19575                         imageIndex  = imageCo unt - view portCount;
  19576                    }
  19577                }
  19578                loadImag esInViewpo rt(seriesL ayout, ser iesIndex,  imageIndex , frameInd ex,isToPla yStudyEnab led,0);
  19579           }
  19580           re turn true;
  19581       }
  19582  
  19583       /**
  19584        * Upd ate the th umbnail se lection.
  19585        */
  19586       functi on updateT humbnailSe lection(im age, activ eSeriesInd ex, active ImageIndex , studyUid , moveSeri es)
  19587       {
  19588           va r selectTh umbnailId  = false;
  19589           if (image ==  undefined  || moveSer ies) {
  19590                selectTh umbnailId  = true;
  19591           }
  19592  
  19593           if  (activeSe riesIndex  === undefi ned || act iveSeriesI ndex === n ull)
  19594           {
  19595                dumpCons oleLogs(LL _WARN, und efined, "u pdateThumb nailSelect ion", "act iveSeriesI ndex is nu ll");
  19596                return;
  19597           }
  19598  
  19599           if  (activeIm ageIndex = == undefin ed || acti veImageInd ex === nul l)
  19600           {
  19601                dumpCons oleLogs(LL _WARN, und efined, "u pdateThumb nailSelect ion", "act iveImageIn dex is nul l");
  19602                return;
  19603           }
  19604           
  19605           if  (image == = undefine d || image  === null)
  19606           {
  19607                image =  dicomViewe r.Series.I mage.getIm age(studyU id, active SeriesInde x, activeI mageIndex) ;
  19608           }
  19609           va r frameCou nt = 0;
  19610           if (image !=  undefined)
  19611           {
  19612                    fram eCount = d icomViewer .Series.Im age.getIma geFrameCou nt(image);
  19613           }
  19614           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  19615            i f (frameCo unt > 1)
  19616            {
  19617                if(serie sLayout.ge tSeriesInd ex() !== a ctiveSerie sIndex ||  seriesLayo ut.getImag eIndex() ! == activeI mageIndex)
  19618                {
  19619                    dump ConsoleLog s(LL_WARN,  undefined , "updateT humbnailSe lection",  "activeSer iesIndex/a ctiveImage Index is m ismatched" );
  19620                    retu rn;
  19621                }
  19622            } else
  19623            {
  19624                 if(seri esLayout.g etSeriesIn dex() !==  activeSeri esIndex)
  19625                {
  19626                    dump ConsoleLog s(LL_WARN,  undefined , "updateT humbnailSe lection",  "activeSer iesIndex i s mismatch ed");
  19627                    retu rn;
  19628                }
  19629            }
  19630           va r thumbnai lId;
  19631           if  (frameCou nt > 1 /*| | (seriesI ndex == te mpseriesIn dex && tem pseriesInd ex != 0)*/  ) {
  19632                thumbnai lId = "ima geviewer_" +dicomView er.replace DotValue(s tudyUid)+" _"+ (activ eSeriesInd ex) + "_th umb" + (ac tiveImageI ndex);
  19633           }  else {
  19634                thumbnai lId = "ima geviewer_" +dicomView er.replace DotValue(s tudyUid)+" _"+ (activ eSeriesInd ex) + "_th umb";
  19635                var elem ent = docu ment.getEl ementById( thumbnailI d);
  19636                if (elem ent == nul l || eleme nt == unde fined) {
  19637                    thum bnailId =  "imageview er_"+dicom Viewer.rep laceDotVal ue(studyUi d)+"_" + ( activeSeri esIndex) +  "_thumb"  + (activeI mageIndex) ;
  19638                }
  19639           }
  19640           
  19641           va r series =  dicomView er.Series. getSeries( studyUid,  activeSeri esIndex, 0 );
  19642           va r appendTh umb = "_th umb";
  19643           if  (series.i skeyImageS eries) {
  19644                activeSe riesIndex  = series.s eriesIndex ;
  19645                appendTh umb = "_ke ythumb";
  19646            }
  19647    
  19648            v ar thumbna ilId;
  19649            i f (frameCo unt > 1 /* || (series Index == t empseriesI ndex && te mpseriesIn dex != 0)* / ) {
  19650                thumbnai lId = "ima geviewer_"  + dicomVi ewer.repla ceDotValue (studyUid)  + "_" + ( activeSeri esIndex) +  appendThu mb + (acti veImageInd ex);
  19651            }  else {
  19652                thumbnai lId = "ima geviewer_"  + dicomVi ewer.repla ceDotValue (studyUid)  + "_" + ( activeSeri esIndex) +  appendThu mb;
  19653                 var ele ment = doc ument.getE lementById (thumbnail Id);
  19654                 if (ele ment == nu ll || elem ent == und efined) {
  19655                    thum bnailId =  "imageview er_" + dic omViewer.r eplaceDotV alue(study Uid) + "_"  + (active SeriesInde x) + appen dThumb + ( activeImag eIndex);
  19656                 }
  19657            }
  19658  
  19659           if  (!$("#" +  thumbnail Id).hasCla ss('select ed-thumbna il-view'))  {
  19660                $('.sele cted-thumb nail-view' ).removeCl ass('selec ted-thumbn ail-view') .addClass( 'default-t humbnail-v iew');
  19661                $("#" +  thumbnailI d).removeC lass("defa ult-thumbn ail-view") .addClass( 'selected- thumbnail- view');
  19662                dumpCons oleLogs(LL _DEBUG, un defined, " updateThum bnailSelec tion", "Hi ghlighting  selected  thumbnail  id : " + t humbnailId );
  19663           }
  19664  
  19665           if (selectThu mbnailId & & thumbnai lId !== un defined) {
  19666                dicomVie wer.thumbn ail.makeTh umbnailVis ible(thumb nailId);
  19667           }
  19668       }
  19669  
  19670       /**
  19671        * Upd ate the pr ogress bar  for the a ctive imag e. The upd ateImagePo sition met hod will b e called t he the upd ateImagePo sition and  updateCac hePosition .
  19672        */
  19673       functi on updateA ctiveProgr essbar(ser iesLayout,  imageInde x, frameIn dex)
  19674       {
  19675           va r seriesIn dex = seri esLayout.g etSeriesIn dex();
  19676                    var  studyUid =  seriesLay out.getStu dyUid();
  19677           va r image =  dicomViewe r.Series.I mage.getIm age(studyU id, series Index, ima geIndex);
  19678            i f (image = == undefin ed) {
  19679                return;
  19680           }
  19681           va r frameCou nt = dicom Viewer.Ser ies.Image. getImageFr ameCount(i mage);
  19682           if  (frameCou nt === und efined) {
  19683                return;
  19684           }
  19685           if  (frameCou nt > 1) {
  19686                seriesLa yout.getPr ogressbar( ).updateIm agePositio n(frameCou nt, frameI ndex);
  19687           }  else {
  19688                seriesLa yout.getPr ogressbar( ).updateIm agePositio n(dicomVie wer.Series .getImageC ount(study Uid, serie sIndex), i mageIndex) ;
  19689           }
  19690       }
  19691  
  19692       /**
  19693        * Set ting the C ine play m ode as wel l as the d irection o f the cine  play
  19694        * @pa ram {Type}  studyPlay By - Cine  play mode  type (Stac k/Study)
  19695        */
  19696       functi on setCine PlayBy(stu dyPlayBy)  {
  19697           va r seriesLa yout = get ActiveSeri esLayout() ;
  19698           if  (cineMana ger[series Layout.ser iesLayoutI d] === und efined) {
  19699                cineMana ger[series Layout.ser iesLayoutI d] = {};
  19700           }
  19701           
  19702           va r linkStud yPlay = fa lse;
  19703           va r directio n = getPla yerDirecti on();
  19704           se tCineDirec tion(direc tion);
  19705  
  19706           if (studyPlay By === "St udy") {
  19707                cineMana ger[series Layout.ser iesLayoutI d].playStu dy = true;
  19708                dicomVie wer.config uration.ci ne.setCine PlayBy("St udy");
  19709                linkStud yPlay = tr ue;
  19710           }  else {
  19711                cineMana ger[series Layout.ser iesLayoutI d].playStu dy = false ;
  19712                dicomVie wer.config uration.ci ne.setCine PlayBy("St ack");
  19713                linkStud yPlay = fa lse;
  19714           }
  19715           
  19716           //  if any se ries is li nked then  getting th at linked  viewport i d
  19717           va r linkSeri esId = dic omViewer.l ink.getTar getViewpor t(seriesLa yout);
  19718           if (linkSerie sId !== un defined) {
  19719                if (cine Manager[li nkSeriesId ] === unde fined) {
  19720                    cine Manager[li nkSeriesId ] = {};
  19721                    cine Manager[li nkSeriesId ].directio n = direct ion;
  19722                }
  19723  
  19724                cineMana ger[linkSe riesId].pl ayStudy =  linkStudyP lay;
  19725           }
  19726       }
  19727       
  19728       functi on isToPla yStudy(lay outId) {
  19729           if  (cineMana ger[layout Id] === un defined ||  cineManag er[layoutI d].playStu dy === und efined) {
  19730                return f alse;
  19731           }
  19732           re turn cineM anager[lay outId].pla yStudy;
  19733       }
  19734  
  19735       functi on setCine Direction( direction)  {
  19736           va r seriesLa yout = get ActiveSeri esLayout() ;
  19737           if  (cineMana ger[series Layout.ser iesLayoutI d] === und efined) {
  19738                cineMana ger[series Layout.ser iesLayoutI d] = {};
  19739           }
  19740           ci neManager[ seriesLayo ut.seriesL ayoutId].d irection =  direction ;
  19741       }
  19742  
  19743       functi on removeC ineManager (serieslay outId) {
  19744           if  (cineMana ger[series layoutId]  !== undefi ned) {
  19745                clearInt erval(cine Manager[se rieslayout Id].timer) ;
  19746                delete c ineManager [serieslay outId];
  19747           }
  19748       }
  19749       
  19750       functi on getimag eCanvasOfV iewPort(se riesLayout ) {
  19751           re turn image CanvasOfVi ewPorts[se riesLayout ];
  19752       }
  19753  
  19754       functi on removei mageCanvas OfViewPort (seriesLay out) {
  19755           im ageCanvasO fViewPorts [seriesLay out] = und efined;
  19756       }
  19757       
  19758       functi on removei mageCanvas OfAllViewP orts(study LayoutId)  {
  19759           fo r(var key  in imageCa nvasOfView Ports){
  19760                             var in dex =  key .indexOf(s tudyLayout Id);
  19761                             if(ind ex >= 0){
  19762                             
  19763                                      delete i mageCanvas OfViewPort s[key];
  19764                                      }
  19765                             }
  19766       }
  19767       
  19768       functi on removei mageCanvas OfAllBacku pViewPorts (studyLayo utId) {
  19769           fo r(var key  in imageCa nvasOfBack upViewPort s){
  19770                             var in dex =  key .indexOf(s tudyLayout Id);
  19771                             if(ind ex >= 0){
  19772                             
  19773                                      delete i mageCanvas OfBackupVi ewPorts[ke y];
  19774                                      }
  19775                             }
  19776       }
  19777       
  19778       functi on setimag eCanvasOfV iewPort(la youtId, im ageCanvas)  {
  19779           if (imageCanv as === und efined) de lete image CanvasOfVi ewPorts[la youtId];
  19780           el se imageCa nvasOfView Ports[layo utId] = im ageCanvas;
  19781       }
  19782  
  19783       functi on removei mageCanvas OfViewPort (layoutId)  {
  19784           de lete image CanvasOfVi ewPorts[la youtId];
  19785       }
  19786       
  19787       functi on getimag eCanvasOfB ackupViewP ort(series Layout) {
  19788           re turn image CanvasOfBa ckupViewPo rts[series Layout];
  19789       }
  19790  
  19791       functi on setimag eCanvasOfB ackupViewP ort(layout Id, imageC anvas) {
  19792           im ageCanvasO fBackupVie wPorts[lay outId] = i mageCanvas ;
  19793       }
  19794       
  19795       functi on removei mageCanvas OfBackupVi ewPort(lay outId) {
  19796           de lete image CanvasOfBa ckupViewPo rts[layout Id];
  19797       }
  19798       
  19799       functi on getCurr entSeriesL ayoutIds()  {
  19800           re turn curre ntSeriesLa youtIds;
  19801       }
  19802  
  19803       functi on convert DicomDateT oDisplayFo rmat(value ) {
  19804           va r dicomDat e = dicomV iewer.chan geNullToEm pty(value) ;
  19805           va r displayD ate = "";
  19806           if  (dicomDat e !== "" & & dicomDat e.length = == 8) {
  19807                displayD ate = dico mDate.subs tring(0,4)  + "-" + d icomDate.s ubstring(4 , 6) + "-"  + dicomDa te.substri ng(6,8);
  19808           }
  19809  
  19810           re turn displ ayDate;
  19811       }
  19812           fu nction cha ngeSelecti on(layoutI d)
  19813           {
  19814                    var  obj={curre ntTarget:{ id:layoutI d}}
  19815                    sele ctViewport (obj);
  19816           }
  19817  
  19818       /**
  19819       * Appl y the pref erence inf o zoom lev el setting  from disp lay settin gs.
  19820       * @par am {Type}  studyUid -  Study Uid
  19821       * @par am {Type}  preference Info - Pre ference In fo object
  19822       * @par am {Type}  seriesInde x - series  Index
  19823       */
  19824       functi on ApplyDi splaySetti ngs(studyU id, prefer enceInfo,  seriesInde x) {
  19825           tr y
  19826           {
  19827                // Apply  the displ ay setting s
  19828                var disp laySetting s = undefi ned;
  19829                var seri es = dicom Viewer.Ser ies.getSer ies(studyU id, series Index);
  19830                if(serie s !== unde fined && s eries.disp laySetting s !== unde fined) {
  19831                    disp laySetting s = series .displaySe ttings;
  19832                }
  19833  
  19834                //Apply  the zoom l evel setti ngs
  19835                preferen ceInfo.zoo mLevelSett ing = (dis playSettin gs === und efined ? p referenceI nfo.zoomLe velSetting  : display Settings.Z oomMode);
  19836           }
  19837           ca tch(e)
  19838           {  }
  19839       }
  19840  
  19841       /**
  19842        * Set  the rearr anged seri es positio ns while c hanging th e series l ayout
  19843        * @pa ram {Type}  positions  
  19844        */ 
  19845       functi on setReAr rangedSeri esPosition s(position s) {
  19846           tr y
  19847           {
  19848                multiFra meImageInd ex = 0;
  19849                actualSe riesIndex  = 0;
  19850                selectTh umbnailIma geIndex =  undefined;
  19851                isViewPo rtDoubleCl icked = fa lse;
  19852                if(posit ions !== u ndefined)  {
  19853                    mult iFrameImag eIndex = p ositions.m ultiFrameI mageIndex;
  19854                    actu alSeriesIn dex = posi tions.actu alSeriesIn dex;
  19855                    sele ctThumbnai lImageInde x = positi ons.select ThumbnailI mageIndex;
  19856                    isVi ewPortDoub leClicked  = position s.isViewPo rtDoubleCl icked;
  19857                    page View = pos itions.pag eView;
  19858                }
  19859           }
  19860           ca tch(e)
  19861           {  }
  19862       }
  19863       
  19864       /**
  19865        * Rem ove the st udy from s tudy level  layout ma p
  19866        * @pa ram {Type}  studyUid
  19867        */ 
  19868       functi on RemoveS tudyLevelL ayout(stud yUid){
  19869           if (studyUid  != undefin ed){
  19870                if(serie sLayoutMap .has(study Uid)){
  19871                    seri esLayoutMa p.set(stud yUid, unde fined);
  19872                }
  19873           }
  19874       }
  19875       
  19876       /**
  19877        * Pla y the repe at cine ma nager
  19878        */ 
  19879       functi on playRep eatCineMan ager(){
  19880           va r allViewp orts =  di comViewer. viewports. getAllView ports();
  19881           if (allViewpo rts === nu ll || allV iewports = == undefin ed) {
  19882                return;
  19883           }
  19884  
  19885           $. each(allVi ewports, f unction(ke y, value)  {
  19886                if(value .studyUid  != undefin ed && valu e.seriesIn dex != und efined ) {
  19887                    for  (var x in  repeatCine Manager) {
  19888                         if(x == va lue.series LayoutId)  {
  19889                             var ob j ={};
  19890                             obj.id  = "playBu tton";
  19891                             dicomV iewer.setA ctiveSerie sLayout(va lue);
  19892                             update PlayIcon(" stop.png", "play.png" );
  19893                             if(rep eatCineMan ager[x].pl ayStudy &&  repeatCin eManager[x ].timer !=  null){
  19894                                 pl ayCineImag e(obj,unde fined);
  19895                                 se tCinePlayB y("Study") ;
  19896                             } else  if(repeat CineManage r[x].playS tudy && re peatCineMa nager[x].t imer == nu ll){
  19897                                 se tCinePlayB y("Study") ;
  19898                             } else  if(!repea tCineManag er[x].play Study && r epeatCineM anager[x]. timer != n ull){
  19899                                 pl ayCineImag e(obj,unde fined);
  19900                                 se tCinePlayB y("Stack") ;
  19901                             } else  if(!repea tCineManag er[x].play Study && r epeatCineM anager[x]. timer == n ull){
  19902                                 se tCinePlayB y("Stack") ;
  19903                             }
  19904                         }
  19905                    }
  19906                }
  19907           }) ;
  19908  
  19909           fo r (var x i n repeatCi neManager)  {
  19910                delete r epeatCineM anager[x];
  19911           }
  19912       }
  19913  
  19914       /**
  19915        * sav e the pres entation
  19916        * @pa ram {Type}  e - click  event pro perties
  19917        * @pa ram {Type}  viewportI d - specif ies the vi ewport Id
  19918        */ 
  19919       functi on savePSt ate(e, vie wportId) {
  19920           Co nfirmDialo g('Do you  want to sa ve this pr esentation ', "save",  e, viewpo rtId);
  19921       }
  19922  
  19923       /**
  19924        * loa d the pren sentaion
  19925        * @pa ram {Type}  e - click  event pro perties
  19926        */ 
  19927       functi on loadPSt ate(e) {
  19928           lo adPStateCo nfirm(e);
  19929       }
  19930  
  19931       /**
  19932        * Cre ate the pr esentation  current U ser PState  Menu
  19933        * @pa ram {Type}  studyUid  - Specifie s the stud y Uid
  19934        * @pa ram {Type}  studyLayo utId - Spe cifies the  study lay out Id
  19935        */ 
  19936       functi on getUser PStateMenu (studyUid,  studyLayo utId) {
  19937           tr y
  19938           {
  19939                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  19940                if(study Details == = undefine d || study Details == = null ||
  19941                   study Details.PS tates ===  undefined  || studyDe tails.PSta tes === nu ll) {
  19942                    retu rn "";
  19943                }
  19944  
  19945                if(study Details.PS tates.All. length ==  0) {
  19946                    retu rn "";
  19947                }
  19948  
  19949                var menu Incremente r = 0;
  19950                var curr entUserPSt ateSeperat orId = stu dyUid+"_CU PState";
  19951                var cont ent = '<li  class="k- separator"  id="'+cur rentUserPS tateSepera torId+'">< /li>';
  19952                studyDet ails.PStat es.All.for Each(funct ion(pState ) {
  19953                    if(! pState.isO therUser)  {
  19954                         pState.men uId = menu Incremente r;
  19955                         var input  = "loadPSS ubmenu_"+s tudyLayout Id+"_"+pSt ate.id+"_" +studyUid;
  19956                         var id ="l oadPSSubme nu_"+study LayoutId+" _"+(menuIn crementer+ +);
  19957                         content +=  '<li id=" '+id+'"><a  href="#"  onclick=di comViewer. loadPState ("'+input+ '")>'+pSta te.name+'< /a></li>'
  19958                    }
  19959                });
  19960  
  19961                var isOt herUserFou nd = study Details.PS tates.All. filter(fun ction(o) {  return o. isOtherUse r === true ; })[0];
  19962                if(!isOt herUserFou nd) {
  19963                    retu rn content ;
  19964                }
  19965  
  19966                var isLo ginUserFou nd = study Details.PS tates.All. filter(fun ction(o) {  return !o .isOtherUs er === tru e; })[0];
  19967                var othe rUserPStat eSeperator Id = study Uid+"_OUPS tate";
  19968  
  19969                if(isLog inUserFoun d) {
  19970                    cont ent += '<l i class="k -separator " id="'+ot herUserPSt ateSeperat orId+'">';
  19971                }
  19972  
  19973                content  += '<li>Ot her User<u l>';
  19974                studyDet ails.PStat es.All.for Each(funct ion(pState ) {
  19975                    if(p State.isOt herUser) {
  19976                         pState.men uId = menu Incremente r;
  19977                         var input  = "loadPSS ubmenu_"+s tudyLayout Id+"_"+pSt ate.id+"_" +studyUid;
  19978                         var id ="l oadPSSubme nu_"+study LayoutId+" _"+(menuIn crementer+ +);
  19979                         content +=  '<li id=" '+id+'"><a  href="#"  onclick=di comViewer. loadPState ("'+input+ '")>'+pSta te.name+'< /a></li>'
  19980                    }
  19981                });
  19982                content  +='</ul></ li>'
  19983  
  19984                return c ontent;
  19985           }
  19986           ca tch(e)
  19987           {  }
  19988  
  19989           re turn "";
  19990       }
  19991  
  19992       /**
  19993        * upd ate the lo ad button  when save  the presen taion
  19994        * @pa ram {Type}  studyUid  - It speci fies the s elected vi ewport stu dy id
  19995        */ 
  19996       functi on updateP State(stud yUid) {
  19997           tr y
  19998           {
  19999                var view portToolba rId = (dic omViewer.g etActiveSe riesLayout ().seriesL ayoutId).s plit("_")[ 1];
  20000                var view portToolba r = "saveA ndLoad_"+v iewportToo lbarId;
  20001                createSa veAndLoadP StateGUI(v iewportToo lbar,study Uid,viewpo rtToolbarI d);
  20002           }
  20003           ca tch(e)
  20004           {  }
  20005       }
  20006  
  20007       /**
  20008        * Cre ate the ke ndo save a nd load bu tton GUI
  20009        * @pa ram {Type}  viewportT oolbarId -  It specif ies the vi ewport id
  20010        * @pa ram {Type}  studyUid  - It speci fies the s elected vi ewport stu dy id
  20011        * @pa ram {Type}  studyLayo utId - It  specifies  the viewpo rt layout  id 
  20012        */ 
  20013       functi on createS aveAndLoad PStateGUI( viewportTo olbarId, s tudyUid, s tudyLayout Id) {
  20014           tr y
  20015           {
  20016                document .getElemen tById(view portToolba rId).inner HTML = "";
  20017                var user PStateMenu Content =  getUserPSt ateMenu(st udyUid, st udyLayoutI d);
  20018                var save Id = "save PState_"+s tudyUid;
  20019                var edit Id = "edit PState_"+s tudyUid;
  20020                var newI d = "newPS tate_"+stu dyUid;
  20021                var dele teId = "de letePState _"+studyUi d;
  20022                var save AndLoadMen u = "saveA ndLoadPSta teMenu_"+s tudyLayout Id;
  20023  
  20024                var cont ent = '<ht ml><body>< ul id="'+s aveAndLoad Menu+'" st yle="displ ay:block;b ackground:  transpare nt">'
  20025                +'<li><i mg src =im ages/loadP State.png  ><ul>'
  20026                +'<li id ="'+dicomV iewer.repl aceDotValu e(saveId)+ '"><a href ="#" oncli ck=dicomVi ewer.saveP State("'+s aveId+'"," '+studyLay outId+'")> Save</a></ li>'
  20027                +'<li st yle="displ ay:none" i d="'+dicom Viewer.rep laceDotVal ue(editId) +'"><a hre f="#" oncl ick=dicomV iewer.edit PState("'+ editId+'") >Edit</a>< /li>'
  20028                +'<li id  ="'+dicom Viewer.rep laceDotVal ue(newId)+ '"><a href ="#" oncli ck=dicomVi ewer.newPS tate("'+ne wId+'")>Ne w</a>'
  20029                +'<li id ="'+dicomV iewer.repl aceDotValu e(deleteId )+'"><a hr ef="#" onc lick=dicom Viewer.del etePState( "'+deleteI d+'")>Dele te</a></li >'
  20030                +'</li>' +userPStat eMenuConte nt+'</body ></html>'
  20031  
  20032                $("#"+vi ewportTool barId).htm l(content) ;
  20033  
  20034                $("#"+sa veAndLoadM enu).kendo Menu({
  20035                    anim ation: { o pen:{ effe cts: "fade In" } }
  20036                });
  20037                selectPS tate(study Uid, study LayoutId);
  20038           }
  20039           ca tch(e)
  20040           {  }
  20041       }
  20042  
  20043       /**
  20044        * Sel ect the PS tate
  20045        * @pa ram {Type}  studyUid  - Specifie s the stud y Uid
  20046        * @pa ram {Type}  studyUid  - Specifie s the stud y layout i d
  20047        */ 
  20048       functi on selectP State(stud yUid, stud yLayoutId)  {
  20049           tr y
  20050           {
  20051                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  20052                if(study Details == = undefine d || study Details == = undefine d) {
  20053                    // I nvalid stu dy details
  20054                    retu rn;
  20055                }
  20056  
  20057                if(study Details.PS tates ===  undefined  || studyDe tails.PSta tes === nu ll) {
  20058                    enab leOrDisabl ePStatesMe nu(studyDe tails, stu dyLayoutId );
  20059                    retu rn;
  20060                }
  20061  
  20062                var sele ctedPState Id = 0;
  20063                var menu Incremente r=0;
  20064                var menu Id = "#loa dPSSubmenu _"+studyLa youtId+"_" ;
  20065                studyDet ails.PStat es.All.for Each(funct ion(pState ) {
  20066                    if(p State.id = == studyDe tails.PSta tes.Active .id) {
  20067                         selectedPS tateId = p State.menu Id;
  20068                    }
  20069                    upda teToolTip( $(menuId+p State.menu Id), pStat e.tooltip,  "top");
  20070                    $(me nuId+menuI ncrementer ++).css("b ackground- color", "# 363636");
  20071                });
  20072  
  20073                if(study Details.PS tates.Acti ve.isEmpty  !== true)  {
  20074                    $(me nuId + sel ectedPStat eId).css(" background ","#868696 ");
  20075                }
  20076  
  20077                var acti vePStateNa me = study Details.PS tates.Acti ve.name;
  20078                var isDi rty = stud yDetails.P States.Act ive.isDirt y;
  20079                if(study Details.PS tates.Acti ve.isNew)  {
  20080                    isDi rty = fals e;
  20081                }
  20082  
  20083                var inne rHtml = ($ (menuId +  selectedPS tateId)[0] .innerHTML ).replace( "*","");
  20084                var upda tedText =  isDirty ?  activePSta teName+"<f ont color= 'red' size =4>*</font >" : "<fon t color='w hite'>"+ac tivePState Name+"</fo nt>";
  20085                innerHtm l = innerH tml.replac e(studyDet ails.PStat es.Active. name,updat edText);
  20086                $(menuId  + selecte dPStateId) [0].innerH TML = inne rHtml;
  20087  
  20088                // Enabl e/ Disable  the PStat e menu ite ms
  20089                enableOr DisablePSt atesMenu(s tudyDetail s, studyLa youtId);
  20090           }
  20091           ca tch(e)
  20092           {  }
  20093       }
  20094  
  20095       /**
  20096        * edi tPState th e PState
  20097        * @pa ram {Type}  studyUid  - Specifie s the stud y Uid
  20098        * @pa ram {Type}  studyUid  - Specifie s the stud y layout i d
  20099        */ 
  20100       functi on editPSt ate(e) {
  20101           tr y
  20102           {
  20103                dicomVie wer.measur ement.edit PState(e);
  20104           }
  20105           ca tch(e)
  20106           {  }
  20107       }
  20108  
  20109       /**
  20110        * new PState the  PState
  20111        * @pa ram {Type}  e - click  event pro perties
  20112        */ 
  20113       functi on newPSta te(e) {
  20114           di comViewer. measuremen t.newPStat e(e);
  20115       }
  20116  
  20117       /**
  20118        * del etePState  the PState
  20119        * @pa ram {Type}  e - click  event pro perties
  20120        */ 
  20121       functi on deleteP State(e) {
  20122           de letePState Confirm(e) ;
  20123       }
  20124  
  20125       /**
  20126        * Ena ble or dis able the P State menu  and its c lick event s
  20127        * @pa ram {Type}  studyDeta ils - Spec ifies the  study deta ils
  20128        * @pa ram {Type}  studyLayo utId - Spe cifies the  study lay out id
  20129        */ 
  20130       functi on enableO rDisablePS tatesMenu( studyDetai ls, studyL ayoutId) {
  20131           tr y
  20132           {
  20133                if(study Details ==  undefined  || studyD etails ==  null) {
  20134                    retu rn;
  20135                }
  20136  
  20137                var stud yUid = stu dyDetails. studyUid;
  20138                var disa bleAllExce ptSave = u ndefined;
  20139                var disa bleEditNew  = undefin ed;
  20140                var isEd itable = u ndefined;
  20141                var enab leAllExcep tSave = un defined;
  20142                var disa bleAll = u ndefined;
  20143                var isEm ptyActiveP State = un defined;
  20144  
  20145                if(study Details.PS tates == u ndefined | | studyDet ails.PStat es == null ) {
  20146                    disa bleAll = t rue;
  20147                } else i f(studyDet ails.PStat es.Active. isEditable  == false)  {
  20148                    disa bleAllExce ptSave = f alse;
  20149                    disa bleEditNew  = false;
  20150                    isEd itable = f alse;
  20151                } else i f(studyDet ails.PStat es.Active. isNew == t rue) {
  20152                    disa bleAllExce ptSave = f alse;
  20153                    disa bleEditNew  = true;
  20154                } else i f(studyDet ails.PStat es.Active. isDirty ==  false) {
  20155                    enab leAllExcep tSave = tr ue;
  20156                } else i f(studyDet ails.PStat es.Active. isEmpty ==  true) {
  20157                    isEm ptyActiveP State = tr ue;
  20158                }
  20159  
  20160                document .getElemen tById("sav eAndLoadPS tateMenu_"  + studyLa youtId).st yle.displa y = disabl eAll ? "no ne" : "blo ck";
  20161                var save Id = "#sav ePState_"+ dicomViewe r.replaceD otValue(st udyUid);
  20162                var edit Id = "#edi tPState_"+ dicomViewe r.replaceD otValue(st udyUid);
  20163                var newI d = "#newP State_"+di comViewer. replaceDot Value(stud yUid);
  20164                var dele teId = "#d eletePStat e_"+dicomV iewer.repl aceDotValu e(studyUid );
  20165  
  20166                $(saveId ).removeCl ass("k-sta te-disable d");
  20167                $(editId ).removeCl ass("k-sta te-disable d");
  20168                $(newId) .removeCla ss("k-stat e-disabled ");
  20169                $(delete Id).remove Class("k-s tate-disab led");
  20170  
  20171                $(saveId )[0].style .pointerEv ents = 'au to';
  20172                $(newId) [0].style. pointerEve nts = 'aut o';
  20173                $(editId )[0].style .pointerEv ents = 'au to';
  20174                $(delete Id)[0].sty le.pointer Events = ' auto';
  20175  
  20176                if(disab leAllExcep tSave == t rue) {
  20177                    $(ne wId).addCl ass("k-sta te-disable d");
  20178                    $(ed itId).addC lass("k-st ate-disabl ed");
  20179                    $(de leteId).ad dClass("k- state-disa bled");
  20180  
  20181                    $(ne wId)[0].st yle.pointe rEvents =  'none';
  20182                    $(ed itId)[0].s tyle.point erEvents =  'none';
  20183                    $(de leteId)[0] .style.poi nterEvents  = 'none';
  20184                } else i f(disableE ditNew ==  true) {
  20185                    $(ne wId).addCl ass("k-sta te-disable d");
  20186                    $(ed itId).addC lass("k-st ate-disabl ed");
  20187  
  20188                    $(ne wId)[0].st yle.pointe rEvents =  'none';
  20189                    $(ed itId)[0].s tyle.point erEvents =  'none'
  20190  
  20191                    if(s tudyDetail s.PStates. Active.isD irty !== t rue) {
  20192                         $(saveId). addClass(" k-state-di sabled");
  20193                         $(saveId)[ 0].style.p ointerEven ts = 'none ';
  20194                    }
  20195                } else i f(isEditab le == fals e) {
  20196                    $(ed itId).addC lass("k-st ate-disabl ed");
  20197                    $(sa veId).addC lass("k-st ate-disabl ed");
  20198                    $(de leteId).ad dClass("k- state-disa bled");
  20199  
  20200                    $(ed itId)[0].s tyle.point erEvents =  'none';
  20201                    $(sa veId)[0].s tyle.point erEvents =  'none';
  20202                    $(de leteId)[0] .style.poi nterEvents  = 'none';
  20203                } else i f(enableAl lExceptSav e == true)  {
  20204                    $(sa veId).addC lass("k-st ate-disabl ed");
  20205                    $(sa veId)[0].s tyle.point erEvents =  'none';
  20206                } else i f(disableA ll === tru e || isEmp tyActivePS tate === t rue) {
  20207                    $(ne wId).addCl ass("k-sta te-disable d");
  20208                    $(ed itId).addC lass("k-st ate-disabl ed");
  20209                    $(de leteId).ad dClass("k- state-disa bled");
  20210                    $(sa veId).addC lass("k-st ate-disabl ed");
  20211  
  20212                    $(ne wId)[0].st yle.pointe rEvents =  'none';
  20213                    $(ed itId)[0].s tyle.point erEvents =  'none';
  20214                    $(de leteId)[0] .style.poi nterEvents  = 'none';
  20215                    $(sa veId)[0].s tyle.point erEvents =  'none';
  20216                }
  20217  
  20218                var tool TipText =  (disableAl l == true  ? "" : "Sa ve/Load pr esentation  state");
  20219                updateTo olTip($("# saveAndLoa d_"+studyL ayoutId),  toolTipTex t, "top");
  20220           }
  20221           ca tch(e)
  20222           {  }
  20223       }
  20224       
  20225       /**
  20226        * Con firmation  dialog for  presentat ion state
  20227        * @pa ram {Type}  message -  Specifies  the confi rmation me ssage
  20228        * @pa ram {Type}  state - S pecifies t he present ation stat e
  20229        * @pa ram {Type}  e - Speci fies the e vent argum ents
  20230        * @pa ram {Type}  viewportI d - Specif ies the vi ewport Id
  20231        * @pa ram {Type}  studyDeta ils - Spec ifies the  study deta ils
  20232        */ 
  20233       functi on Confirm Dialog(mes sage, stat e, e, view portId, st udyDetails ) {
  20234           tr y
  20235           {
  20236                $('<div> </div>').a ppendTo('b ody')
  20237                .html('< div><h6>'+ message+'? </h6></div >')
  20238                .dialog( {
  20239                    moda l: true, t itle: 'HTM L5 Viewer' , zIndex:  10000, aut oOpen: tru e,
  20240                    widt h: 'auto',  resizable : false,
  20241                    butt ons: {
  20242                         "Yes": fun ction() {
  20243                             $(this ).dialog(' close');
  20244                             select Presentati onState(st ate, e, vi ewportId,  studyDetai ls);
  20245                         },
  20246                         "No":  fun ction() {
  20247                             $(this ).dialog(' close');
  20248                             if(sta te == "sav e&load"){
  20249                                 se lectPresen tationStat e("load",  e);
  20250                             }
  20251                         },
  20252                    },
  20253                    clos e: functio n (event,  ui) {
  20254                         $(this).re move();
  20255                    }
  20256                });
  20257           }
  20258           ca tch(e)
  20259           {  }
  20260       };
  20261       
  20262       /**
  20263        * Sel ect the pr esentation  state
  20264        * @pa ram {Type}  state - S pecifies t he present ation stat e
  20265        * @pa ram {Type}  e - Speci fies the e vent argum ents
  20266        * @pa ram {Type}  viewportI d - Specif ies the vi ewport Id
  20267        * @pa ram {Type}  studyDeta ils - Spec ifies the  study deta ils
  20268        */ 
  20269       functi on selectP resentatio nState(sta te, e, vie wportId, s tudyDetail s){
  20270           tr y
  20271           {
  20272                switch(s tate){
  20273                    case  "save":
  20274                         dicomViewe r.measurem ent.savePS tate(
  20275                         {
  20276                             studyU id: e.spli t("_")[1],
  20277                             isPriv ate: false ,
  20278                             isEdit able: true ,
  20279                             isNew:  false,
  20280                             viewpo rtId: view portId
  20281                         });
  20282                         break;
  20283                    case  "load":
  20284                         dicomViewe r.measurem ent.loadPS tate(e.spl it("_")[3] , e);
  20285                         break;
  20286                    case  "delete":
  20287                         dicomViewe r.measurem ent.delete PState(e);
  20288                         break;
  20289                    case  "untitled Delete":
  20290                         dicomViewe r.measurem ent.saveOr DeleteUnSa vedPState( studyDetai ls, false) ;
  20291                         break;
  20292                    case  "save&loa d":
  20293                          dicomView er.measure ment.saveP State(
  20294                         {
  20295                             studyU id: e.spli t("_")[3],
  20296                             isPriv ate: false ,
  20297                             isEdit able: true ,
  20298                             isNew:  false,
  20299                             viewpo rtId: view portId
  20300                         });
  20301                         dicomViewe r.measurem ent.loadPS tate(e.spl it("_")[3] , e);
  20302                         break;
  20303                }
  20304           }
  20305           ca tch(e)
  20306           {  }
  20307       }
  20308  
  20309        /**
  20310        * del ete the PS tate based  on the pr esentation
  20311        * @pa ram {Type}  e - Speci fies the e vent argum ents
  20312        */ 
  20313       functi on deleteP StateConfi rm(e){
  20314           tr y
  20315           {
  20316                var stud yUid = e.s plit("_")[ 1];
  20317                if(study Uid === un defined ||  studyUid  === null)  {
  20318                    // I nvalid par ameters
  20319                    retu rn;
  20320                }
  20321  
  20322                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  20323                if(study Details == = undefine d || study Details == = undefine d) {
  20324                    // I nvalid stu dy details
  20325                    retu rn;
  20326                }
  20327  
  20328                if(study Details.PS tates == u ndefined | | studyDet ails.PStat es == null ) {
  20329                    // I nvalid pre sentation  state 
  20330                    retu rn;
  20331                }
  20332  
  20333                if(study Details.PS tates.Acti ve.isNew = = true) {
  20334                    Conf irmDialog( "Do you wa nt to disc ard the un titled pre sentation  state", "u ntitledDel ete", e, u ndefined,  studyDetai ls);
  20335                    retu rn;
  20336                }
  20337  
  20338                ConfirmD ialog("Do  you want t o delete t he current  presentat ion state" , "delete" , e);
  20339           }
  20340           ca tch(e)
  20341           {  }
  20342       }
  20343  
  20344       /**
  20345        * loa d the PSta te based o n the pres entation s tate
  20346        * @pa ram {Type}  e - Speci fies the e vent argum ents
  20347        */ 
  20348       var di sabePState ConfirmMes sage = tru e;
  20349       functi on loadPSt ateConfirm (e){
  20350           tr y
  20351           {
  20352                var stud yUid = e.s plit("_")[ 3];
  20353                if(study Uid === un defined ||  studyUid  === null)  {
  20354                    // I nvalid par ameters
  20355                    retu rn;
  20356                }
  20357  
  20358                var stud yDetails =  dicomView er.getStud yDetails(s tudyUid);
  20359                if(study Details == = undefine d || study Details == = undefine d) {
  20360                    // I nvalid stu dy details
  20361                    retu rn;
  20362                }
  20363  
  20364                if(study Details.PS tates == u ndefined | | studyDet ails.PStat es == null ) {
  20365                    // I nvalid pre sentation  state 
  20366                    retu rn;
  20367                }
  20368  
  20369                if(study Details.PS tates.Acti ve.isDirty  == true)  {
  20370                    Conf irmDialog( "Current p resentatio n is edite d.<br>Do y ou want to  save the  current pr esentation  and load  the select ed one", " save&load" , e, e.spl it("_")[1] );
  20371                    retu rn;
  20372                } else {
  20373                    if(d isabePStat eConfirmMe ssage) {
  20374                         dicomViewe r.measurem ent.loadPS tate(e.spl it("_")[3] , e, undef ined, fals e);
  20375                    } el se {
  20376                         ConfirmDia log('Do yo u want to  load this  presentati on', "load ", e);
  20377                    }
  20378                }
  20379           }
  20380           ca tch(e)
  20381           {  }
  20382       }
  20383  
  20384       /**
  20385        * end  the unfin ished meas urement
  20386        */ 
  20387       functi on endMeas urement ()  {
  20388           tr y
  20389           {
  20390                if(dicom Viewer.mea surement.i sEditMeasu rement())  {
  20391                    var  tool = dic omViewer.m ouseTools. getActiveT ool();
  20392                    var  event = {} ;
  20393                    even t.type = " dblclick"  ;
  20394                    even t.which =  1;
  20395                    tool .hanleDoub leClick(ev ent);
  20396                }
  20397           }
  20398           ca tch(e)
  20399           {  }
  20400       }
  20401  
  20402       /**
  20403        * che ck the stu dy is dico m or non d icom
  20404        */ 
  20405       functi on isNonDi comStudy ( modality)  {
  20406           tr y
  20407           {
  20408                if(modal ity == ""  || modalit y == undef ined ||
  20409                   modal ity == nul l || modal ity == "EC G" || 
  20410                   modal ity == "SR " || modal ity == "CD A" || 
  20411                   modal ity == "Ge neral") {
  20412                    retu rn true;
  20413                }
  20414                return f alse;
  20415           }
  20416           ca tch(e)
  20417           {  }
  20418       }
  20419  
  20420       /**
  20421        * Aut o play the  cine whil e changing  the serie s layout
  20422        * @pa ram {Type}   
  20423        */ 
  20424       functi on autoCin ePlay() {
  20425           tr y
  20426           {
  20427                var allV iewports =   dicomVie wer.viewpo rts.getAll Viewports( );
  20428                if(allVi ewports == = null ||  allViewpor ts === und efined) {
  20429                    retu rn;
  20430                }
  20431  
  20432                var seri esLayout =  dicomView er.getActi veSeriesLa yout();
  20433                $.each(a llViewport s, functio n(key, val ue) {
  20434                    if(v alue.study Uid != und efined &&  value.seri esIndex !=  undefined  && canPla yCine(valu e.imageTyp e)) {
  20435                         var image  = dicomVie wer.Series .Image.get Image(valu e.studyUid , value.se riesIndex,  value.get ImageIndex ());
  20436                         if(dicomVi ewer.Serie s.Image.ge tImageFram eCount(ima ge) > 1) {
  20437                              if(!i sFullScree nEnabled)  {
  20438                                 di comViewer. setActiveS eriesLayou t(value);
  20439                                 di comViewer. startCine( );
  20440                                 up datePlayIc on("play.p ng", "stop .png");
  20441                              } 
  20442                         }
  20443                    }
  20444                });
  20445  
  20446                if(serie sLayout !=  null && s eriesLayou t != undef ined) {
  20447                    dico mViewer.se tActiveSer iesLayout( seriesLayo ut);
  20448                    if(s eriesLayou t.imageTyp e && canPl ayCine(ser iesLayout. imageType) ) {
  20449                         var image  = dicomVie wer.Series .Image.get Image(seri esLayout.s tudyUid, s eriesLayou t.seriesIn dex, serie sLayout.ge tImageInde x());
  20450                         if(dicomVi ewer.Serie s.Image.ge tImageFram eCount(ima ge) == 1)  {
  20451                             dicomV iewer.tool s.stopCine Image();
  20452                             update PlayIcon(" stop.png",  "play.png ");
  20453                             Enable DisableNex tSeriesIma ge(seriesL ayout);
  20454                         }
  20455                    }
  20456                }
  20457           }
  20458           ca tch(e)
  20459           {  }
  20460       }
  20461  
  20462       dicomV iewer.conv ertDicomDa teToDispla yFormat =  convertDic omDateToDi splayForma t;
  20463       dicomV iewer.getC urrentSeri esLayoutId s = getCur rentSeries LayoutIds;
  20464       dicomV iewer.setI mageLevelL ayout = se tImageLeve lLayout;
  20465       dicomV iewer.setS eriesLayou t = setSer iesLayout;
  20466           di comViewer. setStudyLa yout = set StudyLayou t;
  20467       dicomV iewer.refr eshStudyLa yout = ref reshStudyL ayout;
  20468           di comViewer. createStud yViewport  = createSt udyViewpor t;
  20469           di comViewer. loadStudyI nNextViewp ort = load StudyInNex tViewport;
  20470       dicomV iewer.getA ctiveSerie sLayout =  getActiveS eriesLayou t;
  20471       dicomV iewer.setA ctiveSerie sLayout =  setActiveS eriesLayou t;
  20472       dicomV iewer.show CineRate =  showCineR ate;
  20473       dicomV iewer.paus eCinePlay  = pauseCin ePlay;
  20474           di comViewer. setStudyTo olBarTools  = setStud yToolBarTo ols;
  20475       dicomV iewer.scro ll = {
  20476           mo veToNextOr PreviousIm age : move ToNextOrPr eviousImag e,
  20477           ge tCurrentIm ageAndFram eIndex : g etCurrentI mageAndFra meIndex,
  20478           ru nCineImage  : runCine Image,
  20479           st opCineImag e : stopCi neImage,
  20480           se tCineDirec tion : set CineDirect ion,
  20481           lo adimages :  loadimage s,
  20482           is CineRunnin g : isCine Running,
  20483                    togg leCineRunn ing : togg leCineRunn ing,
  20484           is ToPlayStud y : isToPl ayStudy,
  20485           se tCinePlayB y : setCin ePlayBy
  20486       };
  20487       dicomV iewer.geti mageCanvas OfViewPort  = getimag eCanvasOfV iewPort;
  20488       dicomV iewer.geti mageCanvas OfBackupVi ewPort = g etimageCan vasOfBacku pViewPort;
  20489       dicomV iewer.seti mageCanvas OfBackupVi ewPort = s etimageCan vasOfBacku pViewPort;
  20490       dicomV iewer.remo veimageCan vasOfAllVi ewPorts =  removeimag eCanvasOfA llViewPort s;
  20491       dicomV iewer.seti mageCanvas OfViewPort  = setimag eCanvasOfV iewPort;
  20492       dicomV iewer.remo veimageCan vasOfViewP ort = remo veimageCan vasOfViewP ort;
  20493       dicomV iewer.remo veimageCan vasOfBacku pViewPort  = removeim ageCanvasO fBackupVie wPort;
  20494       dicomV iewer.load ImageFromT humbnail =  loadImage FromThumbn ail;
  20495       dicomV iewer.getI mageIndexF orImageUid  = getImag eIndexForI mageUid;
  20496           di comViewer. startCine  = startCin e;
  20497       dicomV iewer.onCi neSpeedCha nge = onCi neSpeedCha nge;
  20498           di comViewer. changeSele ction = ch angeSelect ion;
  20499       dicomV iewer.remo veCineMana ger = remo veCineMana ger;
  20500       dicomV iewer.remo veimageCan vasOfAllBa ckupViewPo rts = remo veimageCan vasOfAllBa ckupViewPo rts;
  20501       dicomV iewer.IsFu llScreenMo de = IsFul lScreenMod e;
  20502       dicomV iewer.setR eArrangedS eriesPosit ions = set ReArranged SeriesPosi tions;
  20503       dicomV iewer.setD efaultCurs orType = s etDefaultC ursorType;
  20504       dicomV iewer.Remo veStudyLev elLayout =  RemoveStu dyLevelLay out;
  20505       dicomV iewer.play RepeatCine Manager =  playRepeat CineManage r;
  20506       dicomV iewer.save PState = s avePState;
  20507       dicomV iewer.load PState = l oadPState;
  20508       dicomV iewer.upda tePState =  updatePSt ate;
  20509       dicomV iewer.dele tePState =  deletePSt ate;
  20510       dicomV iewer.edit PState = e ditPState;
  20511       dicomV iewer.newP State = ne wPState;
  20512       dicomV iewer.crea teSaveAndL oadPStateG UI = creat eSaveAndLo adPStateGU I;
  20513       dicomV iewer.enab leOrDisabl ePStatesMe nu = enabl eOrDisable PStatesMen u;
  20514       dicomV iewer.Enab leDisableR eferenceLi neMenu = E nableDisab leReferenc eLineMenu;
  20515       dicomV iewer.upda tePreset =  updatePre set;
  20516       dicomV iewer.load images = l oadimages;
  20517       dicomV iewer.getO rUpdateSer iesLayout  = getOrUpd ateSeriesL ayout;
  20518       dicomV iewer.enab leOrDisabl eTools = e nableOrDis ableTools;
  20519       return  dicomView er;
  20520   }(dicomVie wer));/**
  20521    * New nod e file
  20522    */
  20523   var dicomV iewer = (f unction (d icomViewer ) {
  20524  
  20525       "use s trict";
  20526  
  20527       if(dic omViewer = == undefin ed) {
  20528           di comViewer  = {};
  20529       }
  20530       
  20531       var vi ewports={} ;
  20532           
  20533           va r viewport Ids = [];
  20534  
  20535       var se riesLayout MaxId = {} ;
  20536       
  20537       var ba ckupviewpo rts={};
  20538       
  20539       var ba ckupViewpo rtsBySerie sIndex={};
  20540  
  20541       var du plicateVie wportsBySe riesIndex  = {};
  20542  
  20543       var vi ewportImag eLayouts =  [];
  20544  
  20545       var cu rrentPageI mageLayout s = {};
  20546  
  20547       functi on addBack upViewport (viewportI d,viewport ) {
  20548           ba ckupviewpo rts[viewpo rtId] = vi ewport;          
  20549       }
  20550       functi on removeB ackupViewp ort(viewpo rtId) {         
  20551           de lete backu pviewports [viewportI d];                       
  20552       }    
  20553       functi on getBack upViewport ( viewport Id )
  20554       {            
  20555           re turn backu pviewports [viewportI d];
  20556       }   
  20557       
  20558       functi on addBack upViewport BySeriesIn dex(viewpo rtId,viewp ort) {
  20559           ba ckupViewpo rtsBySerie sIndex[vie wportId] =  viewport;              
  20560       }
  20561       functi on removeB ackupViewp ortBySerie sIndex(vie wportId) {         
  20562           de lete backu pViewports BySeriesIn dex[viewpo rtId];                          
  20563       }
  20564       functi on removeA llBackupVi ewportBySe riesIndex( studyLayou tId) {
  20565           fo r(var key  in backupV iewportsBy SeriesInde x){
  20566                var seri eslayout =  backupVie wportsBySe riesIndex[ key];
  20567                var inde x =  serie slayout.se riesLayout Id.indexOf (studyLayo utId);
  20568                             if(ind ex >= 0)
  20569                {
  20570                    dele te backupV iewportsBy SeriesInde x[key];  
  20571                }
  20572           }                                  
  20573       }
  20574       functi on getBack upViewport BySeriesIn dex( viewp ortId )
  20575       {            
  20576           re turn backu pViewports BySeriesIn dex[viewpo rtId];
  20577       }
  20578       
  20579  
  20580       functi on getView port( view portId )
  20581       {
  20582           if (viewportI d === unde fined)
  20583           {
  20584                    thro w "viewpor tId should  not be nu ll or unde fined";
  20585           }
  20586           re turn viewp orts[viewp ortId];
  20587       }
  20588       
  20589       functi on removeV iewport( v iewportId  )
  20590       {
  20591           if (viewportI d === unde fined)
  20592           {
  20593                    thro w "viewpor tId should  not be nu ll or unde fined";
  20594           }
  20595           de lete viewp orts[viewp ortId];
  20596       }
  20597       
  20598       functi on addView port(viewp ortId,view port)
  20599       {
  20600           if (viewportI d === unde fined )
  20601           {
  20602                    thro w "viewpor tId Or vie wportInfo  should not  be null O r undefine d";
  20603           }
  20604           if (viewport  === undefi ned)
  20605           {
  20606                delete v iewports[v iewportId] ;
  20607                return ;
  20608           }
  20609           de lete viewp orts[viewp ortId];
  20610           vi ewports[vi ewportId]  = viewport ;
  20611                    view portIds.pu sh(viewpor tId);
  20612       }
  20613  
  20614       functi on getAllV iewportsId () {
  20615           re turn viewp ortIds;
  20616       }
  20617           
  20618           fu nction rem oveAllView ports()
  20619       {
  20620          vie wports={};     
  20621               viewportI ds = [];
  20622       }
  20623  
  20624           fu nction get ViewportId s()
  20625           {
  20626                    var  unique=vie wportIds.f ilter(func tion(itm,i ,viewportI ds){
  20627                             return  i==viewpo rtIds.inde xOf(itm);
  20628                    });
  20629                    
  20630                    retu rn unique;
  20631           }
  20632       
  20633       functi on getAllV iewports()
  20634       {
  20635           re turn viewp orts;
  20636       }
  20637       
  20638       functi on refresh Viewports(  source)
  20639       {
  20640           if (source == = undefine d)
  20641           {
  20642                return
  20643           }
  20644                    var  parentDiv  = source.s eriesLayou tId;
  20645                    if(p arentDiv = == undefin ed)
  20646                    {
  20647                             parent Div = sour ce.parentE lement;
  20648                    }
  20649                    var  studyDiv =  getStudyL ayoutId(pa rentDiv);
  20650          for  (var key  in viewpor ts)
  20651          {
  20652                       v ar indexOf StudyDiv =  key.index Of(studyDi v);
  20653                       i f(indexOfS tudyDiv >  -1)
  20654                       {
  20655                                var  obj = vie wports[key ];
  20656                   //if( source.ser iesLayoutI d != obj.s eriesLayou tId){
  20657                       o bj.refresh Viewports( source);
  20658                   //}
  20659                       }
  20660          }
  20661       }
  20662  
  20663       functi on addSeri esLayoutMa xId(series LayoutId,  viewportId ) {
  20664           se riesLayout MaxId[view portId] =  seriesLayo utId;
  20665       }
  20666  
  20667       functi on getSeri esLayoutMa xId(viewpo rtId) {
  20668           vi ewportId =  (viewport Id === und efined ||  viewportId  === null)  ? "studyV iewer1x1"  : viewport Id;
  20669           re turn serie sLayoutMax Id[viewpor tId];
  20670       }
  20671           fu nction rem oveViewpor tsByStudyL ayout(stud yLayoutId) {
  20672                    
  20673                    for( var key in  viewports ){
  20674                             var in dex =  key .indexOf(s tudyLayout Id);
  20675                             if(ind ex >= 0){
  20676                             
  20677                                      delete v iewports[k ey];
  20678                                      }
  20679                             }
  20680           }
  20681       functi on backupV iewableVie wportsBySe riesIndex( studyLayou tId){
  20682                    
  20683                    for( var key in  viewports )
  20684           {
  20685                var inde x =  key.i ndexOf(stu dyLayoutId );
  20686                             if(ind ex >= 0)
  20687                {
  20688                    var  viewport =  viewports [key];
  20689                    if(v iewport.ge tSeriesInd ex() !== u ndefined)
  20690                    {
  20691                         var imageV alue = dic omViewer.S eries.Imag e.getImage (viewport. getStudyUi d(),viewpo rt.getSeri esIndex(), viewport.g etImageInd ex()); 
  20692                         if(imageVa lue !== un defined)
  20693                         {
  20694                             if(dic omViewer.t humbnail.i sImageThum bnail(imag eValue))
  20695                                 ad dBackupVie wportBySer iesIndex(v iewport.ge tStudyUid( )+"_"+view port.getIm ageIndex() ,viewport) ;
  20696                             else
  20697                                 ad dBackupVie wportBySer iesIndex(v iewport.ge tStudyUid( )+"_"+view port.getSe riesIndex( ),viewport );
  20698                         }
  20699                    }
  20700                }
  20701                    }
  20702           }
  20703       
  20704       functi on deleteA ndCreateNe wViewport( studyLayou tId){
  20705           fo r(var key  in viewpor ts)
  20706           {
  20707                             var in dex =  key .indexOf(s tudyLayout Id);
  20708                             if(ind ex >= 0)
  20709                {
  20710                    var  newLayout  = new Seri esLevelLay out(key);
  20711                    newL ayout.imag eLayoutDim ension = " 1x1";
  20712                    var  preference Info = new  Preferenc eInfo();
  20713                    pref erenceInfo .init();
  20714                    newL ayout.setP referenceI nfo(prefer enceInfo);
  20715                    view ports[key]  = newLayo ut;
  20716                    dico mViewer.se timageCanv asOfViewPo rt(key,und efined);
  20717                    dico mViewer.re moveCineMa nager(key) ;
  20718                    newL ayout.remo veAllImage Renders();
  20719                    newL ayout.setS eriesIndex (undefined );
  20720                    newL ayout.setI mageIndex( undefined) ;
  20721                    newL ayout.setF rameIndex( undefined) ;
  20722                    dico mViewer.ch angeSelect ion(key);
  20723                }
  20724           }
  20725       }
  20726  
  20727       functi on deleteV iewportsBy Thumbnail( studyUid){
  20728           va r tempStud yLayoutId  = "";
  20729           fo r(var key  in viewpor ts){
  20730                         var viewpo rt = viewp orts[key];
  20731                var view portStudyU id = viewp ort.getStu dyUid();
  20732                if(viewp ortStudyUi d != undef ined)
  20733                viewport StudyUid =  dicomView er.replace DotValue(v iewportStu dyUid);
  20734                if(study Uid === vi ewportStud yUid){
  20735                     var  newLayout  = new Ser iesLevelLa yout(key);
  20736                    newL ayout.imag eLayoutDim ension = " 1x1";
  20737                    var  preference Info = new  Preferenc eInfo();
  20738                    pref erenceInfo .init();
  20739                    newL ayout.setP referenceI nfo(prefer enceInfo);
  20740                    view ports[key]  = newLayo ut;
  20741                    dico mViewer.se timageCanv asOfViewPo rt(key,und efined);
  20742                                      
  20743                    var  studyLayou tDivId = g etStudyLay outId(key) ;
  20744                    if(s tudyLayout DivId != t empStudyLa youtId)
  20745                    {
  20746                         tempStudyL ayoutId =  studyLayou tDivId;
  20747                         dicomViewe r.setSerie sLayout(un defined, 1 , 1, 0, nu ll, tempSt udyLayoutI d);    
  20748                    }
  20749                    
  20750                }
  20751                  //  di comViewer. setimageCa nvasOfView Port(key,u ndefined);
  20752                                      }
  20753                             //}
  20754       }
  20755       /**
  20756       *retur n true if  the image  is availab le in any  of the vie wport else  false
  20757       **/
  20758       functi on isImage Visible(se riesIndex,  imageInde x) {
  20759           fo r (var vie wportId in  viewports ) {
  20760                var view portObj =  getViewpor t(viewport Id);
  20761                var view portSeries Index = vi ewportObj. seriesInde x;
  20762                var view portImageI ndex = vie wportObj.s crollData. imageIndex ;
  20763                if(image Index ===  undefined)
  20764                {
  20765                    if ( seriesInde x === view portSeries Index) {
  20766                         return tru e;
  20767                    }
  20768                }
  20769                else
  20770                {
  20771                    if ( seriesInde x === view portSeries Index && i mageIndex  === viewpo rtImageInd ex) {
  20772                         return tru e;
  20773                    }
  20774                }
  20775           }
  20776           re turn false ;
  20777       }
  20778           
  20779       /**
  20780       *retur n viewport  if the im age is in  view 
  20781       **/
  20782       functi on getView portByImag eIndex(stu dyUid,seri esIndex,im ageIndex){
  20783           fo r(var key  in viewpor ts)
  20784           {
  20785                if(viewp orts[key]. getStudyUi d() === st udyUid &&  viewports[ key].getSe riesIndex( ) === seri esIndex &&  viewports [key].getI mageIndex( ) === imag eIndex)
  20786                {
  20787                    if(i sImageVisi ble(viewpo rts[key].g etSeriesIn dex(), vie wports[key ].getImage Index()))
  20788                    {
  20789                         return vie wports[key ];
  20790                    }
  20791                }
  20792           }
  20793           re turn undef ined;
  20794       }
  20795       
  20796       /**
  20797       *retur n true if  the image  is availab le in any  of the vie wport else  false
  20798       **/
  20799       functi on checkVe wportAvail able(serie sLayoutID,  studyUid) {
  20800           va r currentV iewportIDS  = [];
  20801           va r check =  false;
  20802           va r currentS tudyUid =  studyUid;
  20803           va r currentS tudyLayout Id = getSt udyLayoutI d(seriesLa youtID);
  20804           va r allviewp ortIDs = d icomViewer .viewports .getViewpo rtIds();
  20805           va r viewPort Count = 0;
  20806           va r allstudy Vewport =  dicomViewe r.viewport s.getAllVi ewports();
  20807           va r indexCou nt =0;
  20808           fo r(var inde xl = 0; in dexl < all viewportID s.length;  indexl++){
  20809               var vewpo rt = dicom Viewer.vie wports.get Viewport(a llviewport IDs[indexl ]);
  20810                if(vewpo rt !== und efined){    
  20811                    curr entViewpor tIDS[index Count] = a llviewport IDs[indexl ];
  20812                    inde xCount++;
  20813                }
  20814           }
  20815           fo r(var inde x =0; inde x < curren tViewportI DS.length;  index++){
  20816           va r sVewport  = dicomVi ewer.viewp orts.getVi ewport(cur rentViewpo rtIDS[inde x])
  20817           va r viewport StudyUid =  sVewport. studyUid;
  20818           va r vewportI d = getStu dyLayoutId (currentVi ewportIDS[ index]);
  20819                if(vewpo rtId == cu rrentStudy LayoutId & & currentS tudyUid ==  viewportS tudyUid){
  20820                    chec k = true;
  20821                }
  20822                if(viewp ortStudyUi d == undef ined || vi ewportStud yUid != cu rrentStudy Uid){
  20823                    view PortCount+ +; 
  20824                }
  20825                if(viewP ortCount = == current ViewportID S.length){
  20826                    chec k = true;
  20827                }
  20828           }
  20829           re turn check ;
  20830       }
  20831  
  20832       /**
  20833        * Get  the view  port by in dex
  20834        * @pa ram {Type}  index - s pecifies t he index v alue 
  20835        * @pa ram {Type}  studyId -  specifies  the study  Layout Id
  20836        */ 
  20837       functi on getDupl icateViewp ortByIndex (viewportI ndex, stud yLayoutId)  {
  20838           tr y
  20839           {
  20840                if(dupli cateViewpo rtsBySerie sIndex !=  undefined  && duplica teViewport sBySeriesI ndex != nu ll) {
  20841                    var  index = Ob ject.keys( duplicateV iewportsBy SeriesInde x)[viewpor tIndex];
  20842                    if(i ndex.split ("_")[1] = = studyLay outId) {
  20843                         return dup licateView portsBySer iesIndex[i ndex];
  20844                    }
  20845                }
  20846  
  20847                return u ndefined;
  20848           }
  20849           ca tch(e)
  20850           {  }
  20851  
  20852           re turn undef ined;
  20853       }
  20854  
  20855       /**
  20856        * Add  the dupli cate view  ports base d on the v iewport Id
  20857        * @pa ram {Type}  viewportI d - Specif ies the vi ewport Id
  20858        * @pa ram {Type}  viewport  - Specifie s the view port objec t
  20859        */ 
  20860       functi on addDupl icateViewp ortsBySeri esIndex(vi ewportId,  viewport)  {
  20861           tr y
  20862           {
  20863                for(var  index = 0;  index <=  Object.key s(duplicat eViewports BySeriesIn dex).lengt h; index++ ) {
  20864                    if(d uplicateVi ewportsByS eriesIndex [viewportI d + "_" +  index] ==  undefined)  {
  20865                         duplicateV iewportsBy SeriesInde x[viewport Id + "_" +  index] =  viewport;
  20866                         break;
  20867                    }
  20868                }
  20869           }
  20870           ca tch(e)
  20871           {  }
  20872       }
  20873  
  20874       /**
  20875        * Rem ove the vi ew port ob ject based  on the vi ewport Id
  20876        * @pa ram {Type}  viewportI d - Specif ies the vi ewport Id
  20877        */ 
  20878       functi on removeD uplicateVi ewportsByS eriesIndex (viewportI d) {
  20879           tr y
  20880           {
  20881                for(var  index = Ob ject.keys( duplicateV iewportsBy SeriesInde x).length;  index >=  0; index-- ) {
  20882                    if(d uplicateVi ewportsByS eriesIndex [viewportI d + "_" +  index] !=  undefined)  {
  20883                         delete dup licateView portsBySer iesIndex[v iewportId  + "_" + in dex];
  20884                         break;
  20885                    }
  20886                }
  20887           }
  20888           ca tch(e)
  20889           {  }
  20890       }
  20891  
  20892       /**
  20893        * Rem ove the du plicate vi ew ports b ased on th e study la yout
  20894        * @pa ram {Type}  studyLayo utId - spe cifies the  study lay out value
  20895        */ 
  20896       functi on removeD uplicateVi ewportsByS tudyLayout (studyLayo utId) {
  20897           tr y
  20898           {
  20899                for(var  key in dup licateView portsBySer iesIndex){
  20900                    var  index =  k ey.indexOf (studyLayo utId);
  20901                    if(i ndex >= 0) {
  20902                         delete dup licateView portsBySer iesIndex[k ey];
  20903                    }
  20904                }
  20905           }
  20906           ca tch(e)
  20907           {  }
  20908       }
  20909  
  20910       /**
  20911        * Che ck whether  the view  port is al ready avia lable or n ot
  20912        * @pa ram {Type}  isMultiFr ame - spec ifies the  muliframe  flag
  20913        * @pa ram {Type}  index - s pecifies t he series/ image inde x
  20914        */ 
  20915       functi on isDupli cateViewpo rt(isMulti Frame, ind ex) {
  20916           tr y
  20917           {
  20918                var coun t = 0;
  20919                for(var  key in vie wports) {
  20920                    var  viewport =  viewports [key];
  20921                    if(i sMultiFram e) {
  20922                         if(viewpor t.scrollDa ta.imageIn dex == ind ex) {
  20923                             count  ++;
  20924                         }
  20925                    } el se {
  20926                         if(viewpor t.seriesIn dex == ind ex) {
  20927                             count  ++;
  20928                         }
  20929                    }
  20930                }
  20931  
  20932                if(count  > 1) {
  20933                    retu rn true;
  20934                }
  20935  
  20936                return f alse;
  20937           }
  20938           ca tch(e)
  20939           {  }
  20940  
  20941           re turn false ;
  20942       }
  20943  
  20944       /**
  20945        * Get  the selec ted view p ort based  on the lay out Id
  20946        * @pa ram {Type}  studyDiv  - specifie s the stud y DivId
  20947        * @pa ram {Type}  rowMax -  specifies  the row ma x value
  20948        * @pa ram {Type}  columnMax  - specifi es the col umn max va lue
  20949        * @pa ram {Type}  layoutNum ber - spec ifies the  layout num ber
  20950        */ 
  20951       functi on getSele ctedViewpo rt(studyDi v, rowMax,  columnMax , layoutNu mber) {
  20952           tr y
  20953           {
  20954                var view portNumber  = 1;
  20955                for(var  row = 1; r ow <= rowM ax; row++)  {
  20956                    for( var column  = 1; colu mn <= colu mnMax; col umn++) {
  20957                         var viewpo rt = viewp orts["imag eviewer_"  + studyDiv  + "_" + r ow + "x" +  column];
  20958                         if(viewpor t != undef ined && vi ewport !=  null) {
  20959                             if(vie wportNumbe r == layou tNumber) {
  20960                                 re turn viewp ort;
  20961                             }
  20962                         }
  20963                         viewportNu mber++;
  20964                    }
  20965                }
  20966                
  20967                return u ndefined;
  20968           }
  20969           ca tch(e)
  20970           {  }
  20971           
  20972           re turn undef ined;
  20973       }
  20974  
  20975       /**
  20976        * Get  the view  port order  number ba sed on the  view port  list
  20977        * @pa ram {Type}  rowMax  -  specifies  the row v alue
  20978        * @pa ram {Type}  columnMax  - specifi es the col umn value
  20979        * @pa ram {Type}  layoutId  - specifie s the layo ut Id
  20980        */ 
  20981       functi on getView portNumber (rowMax, c olumnMax,  layoutId)  {
  20982           tr y
  20983           {
  20984              var viewpo rtNumber =  1;
  20985              for(var ro w = 1; row  <= rowMax ; row++) {
  20986                  for(va r column =  1; column  <= column Max; colum n++) {
  20987                      if ((row + "x " + column ) == layou tId) {
  20988                           return v iewportNum ber;
  20989                      }
  20990                      vi ewportNumb er ++;
  20991                  }
  20992              }
  20993                
  20994              return 0;
  20995           }
  20996           ca tch(e)
  20997           {  }
  20998       }
  20999  
  21000       /**
  21001        * Get  the backu p for imag e layout d imension w hile navig ating the  page 
  21002        * @pa ram {Type}  studyUid  - specifie s the stud yUid
  21003        * @pa ram {Type}  rowMax -  specifies  the series  layout ro w value
  21004        * @pa ram {Type}  columnMax  - specifi es the ser ies layout  column va lue
  21005        */ 
  21006       functi on getBack upImageLay outs(study Uid, rowMa x, columnM ax) {
  21007           tr y
  21008           {
  21009                if(viewp orts != nu ll && view ports != u ndefined)  {
  21010                    for( var row =  1; row <=  rowMax; ro w++) {
  21011                         for(var co lumn = 1;  column <=  columnMax;  column++)  {
  21012                             var vi ewport = v iewports[" imageviewe r_" + stud yUid + "_"  + row + " x" + colum n];
  21013                             if(vie wport != n ull && vie wport != u ndefined)  {
  21014                                 vi ewportImag eLayouts.p ush(viewpo rt.getImag eLayoutDim ension());
  21015                                 cu rrentPageI mageLayout s[viewport .seriesInd ex] = view port.getIm ageLayoutD imension() ;
  21016                             }
  21017                         }
  21018                    }
  21019                }
  21020           }
  21021           ca tch(e)
  21022           {  }
  21023       }
  21024  
  21025       /**
  21026        * Get  the viewp ort image  layout bas ed on the  page serie s index 
  21027        * @pa ram {Type}  seriesInd ex - Speci fies the s eries inde x
  21028        * @pa ram {Type}  viewportI ndex - Spe cifies the  viewport  index
  21029        */ 
  21030       functi on getView portImageL ayout(seri esIndex, v iewportInd ex) {
  21031           tr y
  21032           {
  21033                for(var  key in cur rentPageIm ageLayouts ) {
  21034                    if(p arseInt(ke y) === ser iesIndex)  {
  21035                         return cur rentPageIm ageLayouts [key];
  21036                    }
  21037                }
  21038  
  21039                return v iewportIma geLayouts[ viewportIn dex];  
  21040           }
  21041           ca tch(e)
  21042           {  }
  21043       }
  21044  
  21045       /**
  21046        * del ete the vi ewport ima ge layouts
  21047        */ 
  21048       functi on deleteV iewportIma geLayouts( ) {
  21049           tr y
  21050           {
  21051                viewport ImageLayou ts = [];
  21052                for(var  key in cur rentPageIm ageLayouts ) {
  21053                    dele te current PageImageL ayouts[key ];
  21054                }
  21055           }
  21056           ca tch(e)
  21057           {  }
  21058       }
  21059  
  21060       dicomV iewer.view ports={
  21061           ge tAllViewpo rtsId : ge tAllViewpo rtsId,         
  21062           ad dBackupVie wport : ad dBackupVie wport,
  21063           ge tViewport  : getViewp ort,
  21064           ad dViewport  : addViewp ort,
  21065           re moveViewpo rt : remov eViewport,
  21066           ge tViewportI ds : getVi ewportIds,
  21067           ge tAllViewpo rts : getA llViewport s,
  21068           re freshViewp orts : ref reshViewpo rts,
  21069           ad dSeriesLay outMaxId :  addSeries LayoutMaxI d,
  21070           ge tSeriesLay outMaxId :  getSeries LayoutMaxI d,
  21071                    remo veAllViewp orts : rem oveAllView ports,
  21072                    remo veViewport sByStudyLa yout:remov eViewports ByStudyLay out,
  21073           de leteAndCre ateNewView port:delet eAndCreate NewViewpor t,
  21074           de leteViewpo rtsByThumb nail:delet eViewports ByThumbnai l,
  21075           is ImageVisib le: isImag eVisible,
  21076           ch eckVewport Available  : checkVew portAvaila ble,
  21077           ge tViewportB yImageInde x : getVie wportByIma geIndex,         
  21078           ge tBackupVie wport : ge tBackupVie wport,
  21079           re moveBackup Viewport :  removeBac kupViewpor t,
  21080           ad dBackupVie wportBySer iesIndex :  addBackup ViewportBy SeriesInde x,
  21081           re moveBackup ViewportBy SeriesInde x : remove BackupView portBySeri esIndex,
  21082           re moveAllBac kupViewpor tBySeriesI ndex : rem oveAllBack upViewport BySeriesIn dex,
  21083           ge tBackupVie wportBySer iesIndex :  getBackup ViewportBy SeriesInde x,
  21084           ba ckupViewab leViewport sBySeriesI ndex : bac kupViewabl eViewports BySeriesIn dex,
  21085           ge tDuplicate ViewportBy Index : ge tDuplicate ViewportBy Index,
  21086           ad dDuplicate ViewportsB ySeriesInd ex : addDu plicateVie wportsBySe riesIndex,
  21087           re moveDuplic ateViewpor tsBySeries Index : re moveDuplic ateViewpor tsBySeries Index,
  21088           re moveDuplic ateViewpor tsByStudyL ayout : re moveDuplic ateViewpor tsByStudyL ayout,
  21089           is DuplicateV iewport :  isDuplicat eViewport,
  21090           ge tSelectedV iewport :  getSelecte dViewport,
  21091           ge tViewportN umber : ge tViewportN umber,
  21092           ge tBackupIma geLayouts  : getBacku pImageLayo uts,
  21093           ge tViewportI mageLayout  : getView portImageL ayout,
  21094           de leteViewpo rtImageLay outs : del eteViewpor tImageLayo uts
  21095       };
  21096       
  21097       
  21098       return  dicomView er;
  21099   }(dicomVie wer));var  dicomViewe r = (funct ion(dicomV iewer) {
  21100  
  21101       "use s trict";
  21102  
  21103       if (di comViewer  === undefi ned) {
  21104           di comViewer  = {};
  21105       }
  21106  
  21107       var ca cheIndicat ors = {};
  21108       /**
  21109        *@par am indicat or
  21110        *get  the indict or object  from the a rgument an d save ind icator ins ide the
  21111        *cach eIndicator s object
  21112        *cach eIndicator s object c ontains ke y as viewp ort Id and  value as  indicator
  21113        */
  21114       functi on addCach eIndicator (indicator ) {
  21115           if  (indicato r === unde fined) {
  21116                throw "a ddCacheInd icator : i ndicator i s undefine d";
  21117           }
  21118           ca cheIndicat ors[indica tor.parent ElementId]  = indicat or
  21119       }
  21120  
  21121       /**
  21122        *@par am seriesI ndex
  21123        *Iter ate the ca cheIndicat ors object  based on  the argume nt(seriesI ndex)
  21124        *and  the series  index pre sent in th e indicato r return t he indicat or object
  21125        */
  21126       functi on getCach eIndicator (seriesInd ex, imageI ndex) {
  21127                var key;
  21128                var prog ressbar;
  21129                //Key is  viewport  div id
  21130                for (key  in cacheI ndicators)  {
  21131                    if ( cacheIndic ators.hasO wnProperty (key)) {
  21132                         var indica tor = cach eIndicator s[key];
  21133                         if ((indic ator.serie sIndex ==  seriesInde x && !indi cator.isMu ltiframe)  || 
  21134                             (indic ator.image Index == s eriesIndex  && indica tor.isMult iframe)) {
  21135                             return  indicator ;
  21136                         } else {
  21137                             if (in dicator.se riesIndex  == seriesI ndex ) {
  21138                                 pr ogressbar  = indicato r;
  21139                             }
  21140                         }
  21141                    }
  21142                }
  21143                return p rogressbar ;
  21144           }
  21145           /* *
  21146            * This trigg er is used  to update  the progr ess bar ba sed on the  caching
  21147            * using the  current ca ching inde x and tota l count we  are calcu lating
  21148            * the percen tage and u pdating in  the progr ess bar us ing progre ss.drawIma geCacheInd icator()
  21149            * /
  21150       $(docu ment).on(" update", f unction(e,  totalCoun t, current Index, pro gress) {
  21151           va r percenta geVal = (c urrentInde x / totalC ount) * 10 0;
  21152           pr ogress.cac hedPercent age = perc entageVal;
  21153           va r position  = progres s.imageInd icator.wid th * (perc entageVal  / 100);
  21154           pr ogress.cac hedIndicat ionPoint =  position;
  21155           pr ogress.dra wImageCach eIndicator ();
  21156       });
  21157  
  21158       dicomV iewer.cach eIndicator  = {
  21159           ad dCacheIndi cator: add CacheIndic ator,
  21160           ge tCacheIndi cator: get CacheIndic ator,
  21161       };
  21162  
  21163       return  dicomView er;
  21164   }(dicomVie wer));var  dicomViewe r = (funct ion (dicom Viewer) {
  21165  
  21166       "use s trict";
  21167  
  21168       if(dic omViewer = == undefin ed) {
  21169           di comViewer  = {};
  21170       }
  21171           
  21172       var  i sRefLineEn abled = tr ue;
  21173       
  21174       functi on updateX RefLine(im ageRendere r,actualDC , presenta tion)
  21175       {
  21176           // Gets the a ctive view port
  21177           va r layout =  dicomView er.getActi veSeriesLa yout();
  21178           va r isScoutL ineVisible  = dicomVi ewer.tools .isScoutLi neVisible( );
  21179           // Get all im age render er 
  21180           va r imageRen ders = lay out.getAll ImageRende rs();
  21181            v ar sourceI mageUid =  undefined;
  21182            f or (var iK ey in imag eRenders)
  21183            {
  21184                var acti veLayoutId  = layout. getSeriesL ayoutId();
  21185                if (imag eRenders[i Key].paren tElement.i ndexOf(act iveLayoutI d) != -1)  {
  21186                    sour ceImageUid  =  imageR enders[iKe y].getImag eUid();
  21187                    brea k;
  21188                }
  21189            }
  21190           va r targetIm ageUid = i mageRender er.getImag eUid();
  21191           va r refLine  = dicomVie wer.xRefLi ne.getRefL ine(source ImageUid,t argetImage Uid);
  21192           if (refLine = == undefin ed)
  21193           {
  21194                return;
  21195           }
  21196           el se if (isS coutLineVi sible)
  21197           {
  21198                var star t =  dicom Viewer.mea surement.d raw.getCan vasCoordin atesForIma geCoordina tes({x:ref Line.x1,y: refLine.y1 },imageRen derer);
  21199                var end  = dicomVie wer.measur ement.draw .getCanvas Coordinate sForImageC oordinates ({x:refLin e.x2,y:ref Line.y2},i mageRender er);
  21200                var scal e = presen tation.get Zoom();
  21201  
  21202                var scou tLineStyle  = dicomVi ewer.measu rement.dra w.getScout LineStyle( );
  21203                actualDC .strokeSty le = scout LineStyle. lineColor;  // line c olor
  21204                var font Style = "n ormal";
  21205                if (scou tLineStyle .isItalic  && scoutLi neStyle.is Bold) {
  21206                    font Style = "i talic bold ";
  21207                } else i f (scoutLi neStyle.is Italic) {
  21208                    font Style = "i talic";
  21209                } if (sc outLineSty le.isBold)  {
  21210                    font Style = "b old";
  21211                }
  21212                actualDC .font = fo ntStyle +   " " + (sc outLineSty le.fontSiz e / imageR enderer.sc aleValue)  + "px" + "  " + scout LineStyle. fontName;
  21213                actualDC .lineWidth  = scoutLi neStyle.li neWidth /  imageRende rer.scaleV alue;
  21214                actualDC .beginPath ();
  21215                actualDC .moveTo(st art.x,star t.y) ;
  21216                actualDC .lineTo(en d.x, end.y );
  21217                actualDC .setLineDa sh([]);
  21218                actualDC .closePath ();
  21219                actualDC .stroke();
  21220           }
  21221       }
  21222      
  21223           di comViewer. refLine =  {
  21224           up dateXRefLi ne: update XRefLine
  21225           };
  21226           
  21227             
  21228       return  dicomView er;
  21229   }(dicomVie wer));var  dicomViewe r = (funct ion (dicom Viewer) {
  21230  
  21231       "use s trict";
  21232  
  21233       if(dic omViewer = == undefin ed) {
  21234           di comViewer  = {};
  21235       }
  21236  
  21237       var xR efLineStor e = {};
  21238           va r refLineW orker;
  21239           va r useWorke rQueue = t rue;
  21240  
  21241       //Enab le/disable  the xref  jason call  
  21242       var is XrefJasonC allRequire d = false;
  21243           fu nction ini tRefLines( )
  21244           {
  21245           se tTimeout(f unction(){ initRefLin esByRecurs ive(0)}, 1 000);
  21246       }
  21247       
  21248       /**
  21249        *@par am studyDa ta
  21250        *set  the study  details to  parse the  xref line
  21251        */
  21252       functi on renderX RefLines(s tudyData)
  21253       {
  21254           // Check whet her the ja son call i s required  
  21255           if (isXrefJas onCallRequ ired === t rue)
  21256           {
  21257                initRefL ines();
  21258           }  else if(us eWorkerQue ue) {
  21259                createXR efWorkerQu eue(studyD ata);
  21260           }  else {
  21261                calculat eXRefLines (studyData );
  21262           }
  21263       }
  21264  
  21265       functi on calcula teXRefLine s(nStudyDa ta) {
  21266           va r imagesAr ray = [];
  21267           va r count =  nStudyData .seriesCou nt;
  21268           va r currentT ime = new  Date().get Time();
  21269           fo r (var ind ex = 0; in dex < coun t; index++ ) {
  21270                var sour ceImage =  dicomViewe r.Series.g etAllImage s(nStudyDa ta.studyUi d, index);
  21271                imagesAr ray = imag esArray.co ncat(sourc eImage);
  21272           }
  21273                    
  21274                    var  workerData  = {
  21275                             reques t: "RefLin e",
  21276                             images Array: ima gesArray
  21277                    };
  21278                    if ( typeof(Wor ker) !== " undefined" ) {
  21279  
  21280                                               if (typeof (refLineWo rker) == " undefined" ) {
  21281                                                       re fLineWorke r = new Wo rker("js/d icom/image CacheWorke r.js?v=201 8092411521 2");
  21282                                               }
  21283                                               numberOfWe bWorkers =  numberOfW ebWorkers+ 1;
  21284                                               refLineWor ker.postMe ssage(work erData);
  21285                                               refLineWor ker.onmess age = func tion(event ) {
  21286                                                       va r text = e vent.data;    
  21287                                                       ad dRefLinesV iewerCode( text.sourc eImageUid,  text.targ etImageUid , text.val ue);
  21288                             refLin eWorker.te rminate();
  21289                             refLin eWorker =  undefined;
  21290                                               };
  21291                             }
  21292                             else
  21293                             {
  21294                                      for (var  sourceIma geIndex =  0; sourceI mageIndex  < imagesAr ray.length ; sourceIm ageIndex++ ) {
  21295                                               var source Image = im agesArray[ sourceImag eIndex];
  21296  
  21297                                               for (var t argetImage Index = 0;  targetIma geIndex <  imagesArra y.length;  targetImag eIndex++)  {
  21298                                                       va r targetIm age = imag esArray[ta rgetImageI ndex];
  21299                                                       if  (sourceIm age.imageU id === tar getImage.i mageUid) {
  21300                                                                cont inue;
  21301                                                       }
  21302  
  21303                                                       va r value =  dicomViewe r.xRefLine Viewer.cal culateProj ectSlice(s ourceImage .imagePlan e, targetI mage.image Plane);
  21304                                                       ad dRefLinesV iewerCode( sourceImag e.imageUid , targetIm age.imageU id, value) ;
  21305                                               }
  21306                                      }
  21307                             }
  21308       }
  21309  
  21310       functi on initRef LinesByRec ursive(rec ursionNumb er)
  21311       {
  21312           tr y {
  21313                var t0 =  Date.now( );
  21314                dumpCons oleLogs(LL _INFO, und efined, "i nitRefLine sByRecursi ve ", "Sta rt", undef ined, true );
  21315  
  21316                var curr entTime =  new Date() .getTime() ;
  21317                var urlP arameters  = {
  21318                    Stud yUid : dic omViewer.S tudy.getSt udyUidd()  ,
  21319                    Secu rityToken  : dicomVie wer.securi ty.getSecu rityToken( ),
  21320                    Requ estId: new  Date().ge tTime()
  21321                };
  21322                var url  = dicomVie wer.url.ge tReference LineURL(ur lParameter s);
  21323                dumpCons oleLogs(LL _INFO, und efined, un defined, " Refernce l ine url :  " + url);
  21324                $.ajax({
  21325                    url  : url, 
  21326                    type : 'GET',
  21327                    data Type: "jso n",
  21328                    asyn c : true,
  21329                    cros sDomain: t rue,
  21330                    succ ess : func tion(data) {
  21331                         for(var i= 0;i<data.l ength;i++)
  21332                         {
  21333                             var xR efSet = da ta[i];
  21334                             var so urceImageU id = xRefS et.src;
  21335                             var ta rgetRefLin es = xRefS et.lines;
  21336                             for(va r j=0;j<ta rgetRefLin es.length; j++)
  21337                             {
  21338                                 ad dRefLines( sourceImag eUid ,targ etRefLines [j]);
  21339                             }
  21340                         }
  21341                    },
  21342                    erro r : functi on(xhr, st atus){
  21343                         if(recursi onNumber <  10)
  21344                         {
  21345                             recurs ionNumber+ +;
  21346  
  21347                             initRe fLinesByRe cursive(re cursionNum ber);
  21348                         }
  21349                    }
  21350                });
  21351                dumpCons oleLogs(LL _INFO, und efined, "i nitRefLine sByRecursi ve ", "End ", (Date.n ow() - t0) , true);
  21352           }
  21353           ca tch(e)
  21354           {
  21355                dumpCons oleLogs(LL _ERROR, un defined, " initRefLin esByRecurs ive", e.me ssage, und efined, tr ue); 
  21356           }
  21357           fi nally {
  21358                
  21359           }
  21360           }
  21361  
  21362           fu nction add RefLines(s ourceImage Uid ,refLi neObject)
  21363           {
  21364           xR efLineStor e[getRefLi neKey(sour ceImageUid  , refLine Object.tgt )] = refLi neObject;
  21365           }
  21366  
  21367           fu nction add RefLinesVi ewerCode(s ourceImage Uid, targe tImageUid,  value)
  21368           {
  21369           xR efLineStor e[getRefLi neKey(sour ceImageUid  , targetI mageUid)]  = value;
  21370           }
  21371  
  21372       functi on getRefL ine(source ImageUid ,  targetIma geUid)
  21373       {
  21374            r eturn xRef LineStore[ getRefLine Key(source ImageUid ,  targetIma geUid)];
  21375       }
  21376  
  21377       functi on getRefL ineKey(sou rceImageUi d , target ImageUid)
  21378           {
  21379                    retu rn sourceI mageUid +  "x" + targ etImageUid ;
  21380           }
  21381  
  21382       functi on getSour ceImageUid (x , y) {
  21383           va r minDista nce = unde fined;
  21384           va r imageUid s = undefi ned;
  21385           $. each(xRefL ineStore,  function(k ey, value)  {
  21386                if(value  !== undef ined) {
  21387                    var  distance =  Math.sqrt ((x - valu e.x1) * (x  - value.x 1 ) + (y -  value.y1)  * (y - va lue.y1));
  21388                    if(m inDistance  === undef ined) {
  21389                         minDistanc e = distan ce;
  21390                         imageUids  = key;
  21391                    } el se {
  21392                         distance =  Math.min( minDistanc e, distanc e);
  21393                         if(Math.ro und(distan ce) !== Ma th.round(m inDistance )) {
  21394                             minDis tance = di stance;
  21395                             imageU ids = key;
  21396                         }
  21397                    }
  21398                }
  21399           }) ;
  21400  
  21401           re turn image Uids;
  21402       }
  21403  
  21404       /**
  21405        * cre ate xRef w orker queu e
  21406        * @pa ram {Type}  study 
  21407        */ 
  21408       functi on createX RefWorkerQ ueue(study ) {
  21409           tr y
  21410           {
  21411                if(study  === undef ined || st udy === nu ll) {
  21412                    retu rn;
  21413                }
  21414  
  21415                var imag es = [];
  21416                for (var  index = 0 ; index <  study.seri esCount; i ndex++) {
  21417                    imag es = image s.concat(d icomViewer .Series.ge tAllImages (study.stu dyUid, ind ex));
  21418                }
  21419  
  21420                if(study .isXRefLin eFound !==  true) {
  21421                    retu rn;
  21422                }
  21423  
  21424                var xRef WorkerQueu e = new Wo rkerQueue( 2000);
  21425                var jobI dIncrement er = 1;
  21426                images.f orEach(fun ction(imag e) {
  21427                    var  workerJob  =
  21428                    {
  21429                         sourceImag e : image,
  21430                         targetImag es : image s,
  21431                         type : "xR ef",
  21432                         id : jobId Incremente r,
  21433                         workerQueu e : xRefWo rkerQueue,
  21434                         isProcessi ng : false
  21435                    };
  21436  
  21437                    var  xRefWorker Thread = n ew WorkerT hread(work erJob);
  21438                    xRef WorkerQueu e.push(fun ction() {  return xRe fWorkerThr ead.proces sJob() });
  21439                    jobI dIncrement er++;
  21440                });
  21441           }
  21442           ca tch(e)
  21443           {  }
  21444       }
  21445  
  21446           di comViewer. xRefLine =  {
  21447                    init RefLines :  initRefLi nes,
  21448                    getR efLine : g etRefLine,
  21449           re nderXRefLi nes : rend erXRefLine s,
  21450           ge tSourceIma geUid : ge tSourceIma geUid,
  21451           ad dRefLinesV iewerCode  : addRefLi nesViewerC ode
  21452           };
  21453  
  21454       return  dicomView er;
  21455   }(dicomVie wer));/**
  21456   * Use to d raw Vertic al and hor izontal ca liper in E CG images
  21457   **/
  21458   var dicomV iewer = (f unction (d icomViewer ) {
  21459       "use s trict";
  21460  
  21461       if (di comViewer  === undefi ned) {
  21462           di comViewer  = {};
  21463       }
  21464  
  21465       var is Horizontal Caliper =  false;
  21466       var is Horizontal LeftHandle r = false;
  21467       var is Horizontal RightHandl er = false ;
  21468       var is Horizontal Move = tru e;
  21469       var mo usePreviou sPosition  = {x: 0, y : 0};
  21470  
  21471       var is VerticalCa liperStart  = false;
  21472       var is VerticalCa liperEnd =  false;
  21473       var is VerticalMo ve = true;
  21474           va r showCali per = {};
  21475       var sh owCaliperS tatus = {} ;
  21476  
  21477       var is CaliperEna ble = fals e;
  21478           
  21479           // horizontal  caliper m easuremnts  unit
  21480       var ms  = undefin ed;
  21481       var bp m = undefi ned;
  21482           
  21483           // vertical c aliper mea suremnts u nit
  21484       var uv  = undefin ed;
  21485       var mm  = undefin ed;
  21486  
  21487       // Sta tic values  used for  caliper ca lculation
  21488       var mm _Per_Inch  = 25.4;
  21489       var In ch_Per_mm  = 1.0 / mm _Per_Inch;
  21490       var _m m_Per_Grid Line = 5.0 ;
  21491           
  21492           // values sav ed in hori zontal cal iper based  on the im ageid(key)
  21493           va r horizont alCaliperV alues = {} ;
  21494           
  21495           // values sav ed in vert ical calip er based o n the imag eid(key)
  21496           va r vertical CaliperVal ues = {};
  21497  
  21498       /**
  21499       * Get  the Mouse  position
  21500       */
  21501       functi on getMous ePos(canva s, evt) {
  21502           va r rect = c anvas.getB oundingCli entRect();
  21503           va r activeSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  21504           va r imgRende r = active SeriesLayo ut.getImag eRender("e cgData");
  21505           va r scaleVal ue =  imgR ender.temp EcgScale;/ /getScaleV alue();
  21506           re turn {
  21507                x: (evt. clientX -  rect.left)  / scaleVa lue,
  21508                y: (evt. clientY -  rect.top)  / scaleVal ue
  21509           };
  21510       }
  21511  
  21512       /**
  21513       * Draw  the calip er on firs t click on  the ECG i mage.
  21514       */
  21515       functi on initEcg Caliper()  {
  21516           va r activeSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  21517                    var  imageId =  getImageId FromSeries Layout(act iveSeriesL ayout);
  21518                    var  horizontal Values = g etHorizont alCaliper( imageId);
  21519                    //ch eck if the  caliper v alue is al ready avia ble for th e particul ar image o r not
  21520                    //If  the value  is not av ilble hori zontalValu es is unde fined
  21521                     if  (horizonta lValues == = undefine d) {
  21522                var canv as = docum ent.getEle mentById(' imageEcgCa nvas' + ac tiveSeries Layout.get SeriesLayo utId());
  21523                var cont ext = canv as.getCont ext('2d');
  21524  
  21525                canvas.a ddEventLis tener('mou sedown', f unction (e vt) {
  21526                                      horizont alValues =  getHorizo ntalCalipe r(imageId) ;
  21527                                      if (hori zontalValu es === und efined) {
  21528                         drawVertic alCanvas(e vt);
  21529                         drawHorizo ntalCanvas (evt);
  21530                    }
  21531                }, false );
  21532  
  21533                canvas.a ddEventLis tener('mou seup', fun ction (evt ) {
  21534                    if ( activeSeri esLayout.i sCaliperEn able) {
  21535                         activeSeri esLayout.s etCaliperE nable(fals e);
  21536  
  21537                         // Save th e preferen ce 
  21538                         var imageR ender = ac tiveSeries Layout.get ImageRende r("ecgData ");
  21539                         if(imageRe nder !== u ndefined)  {
  21540                             imageR ender.appl yOrRevertD isplaySett ings(undef ined, unde fined, und efined, tr ue);
  21541                         }
  21542                    }
  21543                }, false );
  21544  
  21545                $("#imag eEcgCanvas " + active SeriesLayo ut.getSeri esLayoutId ()).mousem ove(clickA ndMove);
  21546                             //disp lay calipe
  21547                             setSho wCaliper(i mageId, tr ue);
  21548                setCalip erStatus(a ctiveSerie sLayout.ge tSeriesLay outId(), " visible");  
  21549           }
  21550       }
  21551  
  21552       var cl ickAndMove  = functio n (evt) {
  21553           va r activeSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  21554                    var  imageId =  getImageId FromSeries Layout(act iveSeriesL ayout);
  21555                    if(! isShowcali per(imageI d)){
  21556                             return ;
  21557                    }
  21558           va r horizont alCaliper  = getHoriz ontalCalip er(imageId );
  21559           va r vertical Caliper =  getVertica lCaliper(i mageId);
  21560                    var  canvas = d ocument.ge tElementBy Id('imageE cgCanvas'  + activeSe riesLayout .getSeries LayoutId() );
  21561           va r context  = canvas.g etContext( '2d');
  21562           va r imageDat a = active SeriesLayo ut.getEcgC anvas();
  21563           va r mousePos ition = ge tMousePos( canvas, ev t);
  21564  
  21565           if  (horizont alCaliper  === undefi ned || ver ticalCalip er === und efined) {
  21566                return;
  21567           }
  21568                    if ( activeSeri esLayout.i sCaliperEn able) {
  21569                             return ;
  21570            }
  21571           
  21572           if  (evt.whic h == 1 &&  evt.button s == 1) {
  21573                if (isHo rizontalCa liper) {
  21574                    if ( isHorizont alLeftHand ler) {
  21575                         horizontal Caliper["c enterLineS tartX"] =  mousePosit ion.x;
  21576                         horizontal Caliper["c enterLineE ndX"] = ho rizontalCa liper["las tLineStart X"];
  21577  
  21578                         horizontal Caliper["f irstLineSt artX"] = m ousePositi on.x;
  21579                         horizontal Caliper["f irstLineEn dX"] = mou sePosition .x;
  21580  
  21581                         clearCurre ntImage(co ntext);
  21582                         drawHorizo ntalCalipe r(context,  horizonta lCaliper);
  21583                         drawVertic alCaliper( context, v erticalCal iper);
  21584                    } el se if (isH orizontalR ightHandle r) {
  21585                         horizontal Caliper["c enterLineS tartX"] =  horizontal Caliper["f irstLineSt artX"];
  21586                         horizontal Caliper["c enterLineE ndX"] = mo usePositio n.x;
  21587  
  21588                         horizontal Caliper["l astLineSta rtX"] = mo usePositio n.x;
  21589                         horizontal Caliper["l astLineEnd X"] = mous ePosition. x;
  21590  
  21591                         clearCurre ntImage(co ntext);
  21592                         drawHorizo ntalCalipe r(context,  horizonta lCaliper);
  21593                         drawVertic alCaliper( context, v erticalCal iper);
  21594                    } el se if (isH orizontalM ove) {
  21595                         var deltaP ointX = mo usePositio n.x - mous ePreviousP osition.x;
  21596                         var deltaP ointY = mo usePositio n.y - mous ePreviousP osition.y;
  21597  
  21598                         horizontal Caliper["c enterLineS tartX"] =  horizontal Caliper["c enterLineS tartX"] +  deltaPoint X;
  21599                         horizontal Caliper["c enterLineE ndX"] = ho rizontalCa liper["cen terLineEnd X"] + delt aPointX;
  21600  
  21601                         horizontal Caliper["f irstLineSt artX"] = h orizontalC aliper["fi rstLineSta rtX"] + de ltaPointX;
  21602                         horizontal Caliper["f irstLineEn dX"] = hor izontalCal iper["firs tLineEndX" ] + deltaP ointX;
  21603  
  21604                         horizontal Caliper["l astLineSta rtX"] = ho rizontalCa liper["las tLineStart X"] + delt aPointX;
  21605                         horizontal Caliper["l astLineEnd X"] = hori zontalCali per["lastL ineEndX"]  + deltaPoi ntX;
  21606  
  21607                         horizontal Caliper["c enterLineS tartY"] =  horizontal Caliper["c enterLineS tartY"]  +  deltaPoin tY;
  21608                         horizontal Caliper["c enterLineE ndY"] = ho rizontalCa liper["cen terLineEnd Y"] + delt aPointY;
  21609  
  21610                         horizontal Caliper["f irstLineSt artY"] = h orizontalC aliper["fi rstLineSta rtY"] + de ltaPointY;
  21611                         horizontal Caliper["f irstLineEn dY"] = hor izontalCal iper["firs tLineEndY" ] + deltaP ointY;
  21612  
  21613                         horizontal Caliper["l astLineSta rtY"] = ho rizontalCa liper["las tLineStart Y"] + delt aPointY;
  21614                         horizontal Caliper["l astLineEnd Y"] = hori zontalCali per["lastL ineEndY"]  + deltaPoi ntY;
  21615  
  21616                         clearCurre ntImage(co ntext);
  21617                         drawHorizo ntalCalipe r(context,  horizonta lCaliper);
  21618                         drawVertic alCaliper( context, v erticalCal iper);
  21619                    }
  21620                } else i f (isVerti calCaliper Start) {
  21621                    var  mouseX = m ousePositi on.x;
  21622                    var  mouseY = m ousePositi on.y;
  21623  
  21624                    vert icalCalipe r["firstLi neStartX"]  = vertica lCaliper[" firstLineS tartX"];
  21625                    vert icalCalipe r["firstLi neStartY"]  = mouseY;
  21626                    vert icalCalipe r["firstLi neEndX"] =  verticalC aliper["fi rstLineEnd X"];
  21627                    vert icalCalipe r["firstLi neEndY"] =  mouseY;
  21628  
  21629                    var  secondYVer tical = mo useY;
  21630  
  21631                    vert icalCalipe r["centerL ineStartY" ] = second YVertical;
  21632  
  21633                    clea rCurrentIm age(contex t);
  21634                    draw VerticalCa liper(cont ext, verti calCaliper );
  21635                    draw Horizontal Caliper(co ntext, hor izontalCal iper);
  21636                } else i f (isVerti calCaliper End) {
  21637                    var  mouseX = m ousePositi on.x;
  21638                    var  mouseY = m ousePositi on.y;
  21639  
  21640                    vert icalCalipe r["centerL ineEndY"]  = mouseY;
  21641  
  21642                    vert icalCalipe r["lastLin eStartY"]  = mouseY;
  21643                    vert icalCalipe r["lastLin eEndY"] =  mouseY;
  21644  
  21645                    clea rCurrentIm age(contex t);
  21646                    draw VerticalCa liper(cont ext, verti calCaliper );
  21647                    draw Horizontal Caliper(co ntext, hor izontalCal iper);
  21648                } else i f (isVerti calMove) {
  21649                    var  deltaPoint X = mouseP osition.x  - mousePre viousPosit ion.x;
  21650                    var  deltaPoint Y = mouseP osition.y  - mousePre viousPosit ion.y;
  21651                    vert icalCalipe r["centerL ineStartX" ] = vertic alCaliper[ "centerLin eStartX"]  + deltaPoi ntX;
  21652                    vert icalCalipe r["centerL ineEndX"]  = vertical Caliper["c enterLineE ndX"] + de ltaPointX;
  21653  
  21654                    vert icalCalipe r["firstLi neStartX"]  = vertica lCaliper[" firstLineS tartX"] +  deltaPoint X;
  21655                    vert icalCalipe r["firstLi neEndX"] =  verticalC aliper["fi rstLineEnd X"] + delt aPointX;
  21656  
  21657                    vert icalCalipe r["lastLin eStartX"]  = vertical Caliper["l astLineSta rtX"] + de ltaPointX;
  21658                    vert icalCalipe r["lastLin eEndX"] =  verticalCa liper["las tLineEndX" ] + deltaP ointX;
  21659  
  21660                    vert icalCalipe r["centerL ineStartY" ] = vertic alCaliper[ "centerLin eStartY"]  + deltaPoi ntY;
  21661                    vert icalCalipe r["centerL ineEndY"]  = vertical Caliper["c enterLineE ndY"] + de ltaPointY;
  21662  
  21663                    vert icalCalipe r["firstLi neStartY"]  = vertica lCaliper[" firstLineS tartY"] +  deltaPoint Y;
  21664                    vert icalCalipe r["firstLi neEndY"] =  verticalC aliper["fi rstLineEnd Y"] + delt aPointY;
  21665  
  21666                    vert icalCalipe r["lastLin eStartY"]  = vertical Caliper["l astLineSta rtY"] + de ltaPointY;
  21667                    vert icalCalipe r["lastLin eEndY"] =  verticalCa liper["las tLineEndY" ] + deltaP ointY;
  21668                }
  21669                clearCur rentImage( context);
  21670                drawVert icalCalipe r(context,  verticalC aliper);
  21671                drawHori zontalCali per(contex t, horizon talCaliper );
  21672           }  else {
  21673                isClicka ndMoveHori zontal(evt );
  21674                if (!isH orizontalC aliper) {
  21675                    isCl ickandMove Vertical(e vt);
  21676                } else i f (mouseIn MidLine(ev t) && !isH orizontalC aliper) {
  21677                    $('# viewport_V iew').css( 'cursor',  'move');
  21678                } else i f ((!isHor izontalCal iper)) {
  21679                    $('# viewport_V iew').css( 'cursor',  'default') ;
  21680                }
  21681           }
  21682  
  21683           mo usePreviou sPosition. x = mouseP osition.x;
  21684           mo usePreviou sPosition. y = mouseP osition.y;
  21685       };
  21686  
  21687       functi on mouseIn MidLine(ev t) {
  21688           va r activeSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  21689                    var  imageId =  getImageId FromSeries Layout(act iveSeriesL ayout);
  21690           va r horizont alCaliper  = getHoriz ontalCalip er(imageId );
  21691           va r vertical Caliper =  getVertica lCaliper(i mageId);
  21692  
  21693           va r canvas =  document. getElement ById('imag eEcgCanvas ' + active SeriesLayo ut.getSeri esLayoutId ());
  21694           va r context  = canvas.g etContext( '2d');
  21695           va r mousePos  = getMous ePos(canva s, evt);
  21696           va r mouseX =  mousePos. x;
  21697           va r mouseY =  mousePos. y;
  21698           if  (calulate NearPoint( mouseY, ho rizontalCa liper["cen terLineSta rtY"]) &&  (mouseX >  horizontal Caliper["c enterLineS tartX"]) & & (mouseX  < horizont alCaliper[ "centerLin eEndX"]))  {
  21699                return t rue;
  21700           }  else {
  21701                return f alse;
  21702           }
  21703       }
  21704  
  21705      functio n drawHori zontalCanv as(evt) {
  21706           va r activeSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  21707           va r horizont alCaliper  = {};
  21708           va r canvas =  document. getElement ById('imag eEcgCanvas ' + active SeriesLayo ut.getSeri esLayoutId ());
  21709           va r context  = canvas.g etContext( '2d');
  21710           va r mousePos  = getMous ePos(canva s, evt);
  21711                    
  21712                    mous ePos.x = m ousePos.x- 60;
  21713                    mous ePos.y = m ousePos.y- 30;
  21714                    
  21715           va r scaleVal ue = getSc aleValue() ;
  21716  
  21717           ho rizontalCa liper["cen terLineSta rtX"] = mo usePos.x -  (50/scale Value);
  21718           ho rizontalCa liper["cen terLineSta rtY"] = mo usePos.y;
  21719           ho rizontalCa liper["cen terLineEnd X"] = mous ePos.x + ( 50/scaleVa lue);
  21720           ho rizontalCa liper["cen terLineEnd Y"] = mous ePos.y;
  21721  
  21722           ho rizontalCa liper["fir stLineStar tX"] = mou sePos.x -  (50/scaleV alue);
  21723           ho rizontalCa liper["fir stLineStar tY"] = mou sePos.y -  (12/scaleV alue);
  21724           ho rizontalCa liper["fir stLineEndX "] = mouse Pos.x - (5 0/scaleVal ue);
  21725           ho rizontalCa liper["fir stLineEndY "] = mouse Pos.y + (7 0/scaleVal ue);
  21726  
  21727           ho rizontalCa liper["las tLineStart X"] = mous ePos.x + ( 50/scaleVa lue);
  21728           ho rizontalCa liper["las tLineStart Y"] = mous ePos.y - ( 12/scaleVa lue);
  21729           ho rizontalCa liper["las tLineEndX" ] = mouseP os.x + (50 /scaleValu e);
  21730           ho rizontalCa liper["las tLineEndY" ] = mouseP os.y + (70 /scaleValu e);
  21731  
  21732           dr awHorizont alCaliper( context, h orizontalC aliper);
  21733       }
  21734  
  21735       functi on drawVer ticalCanva s(evt) {
  21736           va r activeSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  21737           va r vertical Caliper =  {};
  21738  
  21739           va r canvas =  document. getElement ById('imag eEcgCanvas ' + active SeriesLayo ut.getSeri esLayoutId ());
  21740           va r context  = canvas.g etContext( '2d');
  21741           va r mousePos  = getMous ePos(canva s, evt);
  21742  
  21743           va r scaleVal ue = getSc aleValue() ;
  21744           ve rticalCali per["first LineStartX "] = mouse Pos.x + (9 /scaleValu e);
  21745           ve rticalCali per["first LineStartY "] = mouse Pos.y - (4 0/scaleVal ue);
  21746           ve rticalCali per["first LineEndX"]  = mousePo s.x + (90/ scaleValue );
  21747           ve rticalCali per["first LineEndY"]  = mousePo s.y - (40/ scaleValue );
  21748  
  21749           ve rticalCali per["cente rLineStart X"] = mous ePos.x + ( 80/scaleVa lue);
  21750           ve rticalCali per["cente rLineStart Y"] = mous ePos.y - ( 40/scaleVa lue);
  21751           ve rticalCali per["cente rLineEndX" ] = mouseP os.x + (80 /scaleValu e);
  21752           ve rticalCali per["cente rLineEndY" ] = mouseP os.y + (40 /scaleValu e);
  21753  
  21754           ve rticalCali per["lastL ineStartX" ] = mouseP os.x + (9/ scaleValue );
  21755           ve rticalCali per["lastL ineStartY" ] = mouseP os.y + (40 /scaleValu e);
  21756           ve rticalCali per["lastL ineEndX"]  = mousePos .x + (90/s caleValue) ;
  21757           ve rticalCali per["lastL ineEndY"]  = mousePos .y + (40/s caleValue) ;
  21758  
  21759           dr awVertical Caliper(co ntext, ver ticalCalip er);
  21760       }
  21761           
  21762       functi on isClick andMoveHor izontal(ev t) {
  21763           is Horizontal Caliper =  false;
  21764           is Horizontal LeftHandle r = false;
  21765           is Horizontal RightHandl er = false ;
  21766           is Horizontal Move = fal se;
  21767           va r activeSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  21768                    var  imageId =  getImageId FromSeries Layout(act iveSeriesL ayout)
  21769           va r horizont alCaliper  = getHoriz ontalCalip er(imageId );
  21770           va r vertical Caliper =  getVertica lCaliper(i mageId);
  21771  
  21772           va r canvas =  document. getElement ById('imag eEcgCanvas ' + active SeriesLayo ut.getSeri esLayoutId ());
  21773           va r context  = canvas.g etContext( '2d');
  21774           va r mousePos  = getMous ePos(canva s, evt);
  21775           va r mouseX =  mousePos. x;
  21776           va r mouseY =  mousePos. y;
  21777           if  (calulate NearPoint( horizontal Caliper["f irstLineSt artX"], mo useX) && ( horizontal Caliper["f irstLineSt artY"] <=  mouseY &&  horizontal Caliper["f irstLineEn dY"] >= mo useY)) {
  21778                $('#view port_View' ).css('cur sor', 'e-r esize');
  21779                isHorizo ntalCalipe r = true;
  21780                isHorizo ntalLeftHa ndler = tr ue;
  21781           }  else if (c alulateNea rPoint(hor izontalCal iper["last LineStartX "], mouseX ) && (hori zontalCali per["lastL ineStartY" ] <= mouse Y && horiz ontalCalip er["lastLi neEndY"] > = mouseY))  {
  21782                $('#view port_View' ).css('cur sor', 'e-r esize');
  21783                isHorizo ntalCalipe r = true;
  21784                isHorizo ntalRightH andler = t rue;
  21785           }  else if (c alulateNea rPoint(mou seY, horiz ontalCalip er["center LineStartY "]) && ((m ouseX >= h orizontalC aliper["ce nterLineSt artX"]) &&  (mouseX < = horizont alCaliper[ "centerLin eEndX"]) | | (mouseX  <= horizon talCaliper ["centerLi neStartX"] ) && (mous eX >= hori zontalCali per["cente rLineEndX" ]))){ 
  21786                $('#view port_View' ).css('cur sor', 'mov e');
  21787                isHorizo ntalMove =  true;
  21788                isHorizo ntalCalipe r = true;
  21789           }
  21790       }
  21791  
  21792       functi on isClick andMoveVer tical(evt)  {
  21793                    var  activeSeri esLayout =  dicomView er.getActi veSeriesLa yout();
  21794                    var  imageId =  getImageId FromSeries Layout(act iveSeriesL ayout);
  21795                    
  21796           va r vertical Caliper =  getVertica lCaliper(i mageId);
  21797  
  21798           va r activeSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  21799           va r canvas =  document. getElement ById('imag eEcgCanvas ' + active SeriesLayo ut.getSeri esLayoutId ());
  21800           va r context  = canvas.g etContext( '2d');
  21801           va r mousePos  = getMous ePos(canva s, evt);
  21802           va r mousePos X = mouseP os.x;
  21803           va r mousePos Y = mouseP os.y;
  21804  
  21805           if  (calulate NearPoint( mousePosY,  verticalC aliper["fi rstLineSta rtY"]) &&  (mousePosX  > vertica lCaliper[" firstLineS tartX"]) & & (mousePo sX < verti calCaliper ["firstLin eEndX"]))  {
  21806                $('#view port_View' ).css('cur sor', 's-r esize');
  21807                isVertic alCaliperS tart = tru e;
  21808                isVertic alCaliperE nd = false ;
  21809                isVertic alMove = f alse;
  21810           }  else if (c alulateNea rPoint(mou sePosY, ve rticalCali per["lastL ineStartY" ]) && (mou sePosX > v erticalCal iper["last LineStartX "]) && (mo usePosX <  verticalCa liper["las tLineEndX" ])) {
  21811                $('#view port_View' ).css('cur sor', 's-r esize');
  21812                isVertic alCaliperS tart = fal se;
  21813                isVertic alCaliperE nd = true;
  21814                isVertic alMove = f alse;
  21815           }  else if (c alulateNea rPoint(mou sePosX, ve rticalCali per["cente rLineStart X"]) && (( mousePosY  > vertical Caliper["c enterLineS tartY"]) & & (mousePo sY < verti calCaliper ["centerLi neEndY"])  || (mouseP osY < vert icalCalipe r["centerL ineStartY" ]) && (mou sePosY > v erticalCal iper["cent erLineEndY "]))) {
  21816                $('#view port_View' ).css('cur sor', 'mov e');
  21817                isVertic alCaliperS tart = fal se;
  21818                isVertic alCaliperE nd = false ;
  21819                isVertic alMove = t rue;
  21820           }  else {
  21821                isVertic alCaliperS tart = fal se;
  21822                isVertic alCaliperE nd = false ;
  21823                isVertic alMove = f alse;
  21824                $('#view port_View' ).css('cur sor', 'def ault');
  21825           }
  21826       }
  21827  
  21828       functi on drawCal iper() {
  21829           in itEcgCalip er();
  21830       }
  21831  
  21832       functi on calulat eNearPoint (firstValu e, secondV alue) {
  21833           va r result;
  21834           if  (firstVal ue >= seco ndValue) {
  21835                result =  firstValu e - second Value;
  21836           }  else if (s econdValue  > firstVa lue) {
  21837                result =  secondVal ue - first Value;
  21838           }
  21839  
  21840           if  (result < = 5) {
  21841                return t rue;
  21842           }
  21843           re turn false ;
  21844       }
  21845  
  21846           /* *
  21847           *@ param vert icalCalipe r
  21848           *r eturn the  length of  the vertic al caliper
  21849           */
  21850       functi on getLeng thOfVertic alCaliper( verticalCa liper) {
  21851           va r dx = Mat h.abs(vert icalCalipe r["centerL ineStartX" ] - vertic alCaliper[ "centerLin eEndX"]);
  21852           va r dy = Mat h.abs(vert icalCalipe r["centerL ineStartY" ] - vertic alCaliper[ "centerLin eEndY"]);
  21853  
  21854           va r lengthIn CM = getDi stance(dx,  dy);
  21855           du mpConsoleL ogs(LL_DEB UG, undefi ned, "getL engthOfVer ticalCalip er", "Leng th : " + l engthInCM  + "cm");
  21856           re turn lengt hInCM;
  21857       }
  21858           
  21859           /* *
  21860           *@ param hori zontalCali per
  21861           *r eturn the  length of  the horizo ntal calip er
  21862           */
  21863       functi on getLeng thOfHorizo ntalCalipe r(horizont alCaliper)  {
  21864           va r dx = Mat h.abs(hori zontalCali per["cente rLineStart X"] - hori zontalCali per["cente rLineEndX" ]);
  21865           va r dy = Mat h.abs(hori zontalCali per["cente rLineStart Y"] - hori zontalCali per["cente rLineEndY" ]);
  21866  
  21867           va r lengthIn CM = getDi stance(dx,  dy);
  21868           du mpConsoleL ogs(LL_DEB UG, undefi ned, "getL engthOfHor izontalCal iper", "Le ngth : " +  lengthInC M + "cm");
  21869           re turn lengt hInCM;
  21870       }
  21871  
  21872       /**
  21873        * Get  the dista nce betwee n two poin ts in pixe l.
  21874        */
  21875       functi on getDist ance(first Point, sec ondPoint)
  21876       {
  21877           va r x1MinusX 2Square =  Math.pow(f irstPoint,  2.0);
  21878           va r y1MinusY 2Square =  Math.pow(s econdPoint , 2.0);
  21879  
  21880           re turn Math. sqrt(x1Min usX2Square  + y1Minus Y2Square);
  21881       }
  21882  
  21883       functi on getGain (gain) {
  21884           sw itch (gain ) {
  21885                case 0:
  21886                    retu rn 5.0;
  21887                case 1:
  21888                    retu rn 10.0;
  21889                case 2:
  21890                    retu rn 20.0;
  21891                case 3:
  21892                    retu rn 40.0;
  21893                default:
  21894                    retu rn 10.0;
  21895           }
  21896       }
  21897  
  21898       functi on overlay Element(le ngthOfLine , isVertic al) {
  21899           va r preferen ceInfo = d icomViewer .getActive SeriesLayo ut().prefe renceInfo;
  21900           va r aScaleFa ctor = 1;
  21901  
  21902           va r aGain =  getGain(pr eferenceIn fo.selecte dEcgFormat .Gain);
  21903           va r aPtsDist ance = len gthOfLine;
  21904           va r aDotsPer InchX = aS caleFactor  * 100;
  21905           va r aDotsPer InchY = aS caleFactor  * 100;
  21906           va r aGridCel lWidth = M ath.round( (aDotsPerI nchX * Inc h_Per_mm)  * _mm_Per_ GridLine);
  21907           va r aGridCel lHeight =  Math.round ((aDotsPer InchY * In ch_Per_mm)  * _mm_Per _GridLine) ;
  21908           va r aTotalMi llimeters  = (aPtsDis tance / aG ridCellWid th) * _mm_ Per_GridLi ne;
  21909           va r grid200P ercentCell Width = 40 ; // Initi alize the  cell grid  size for 2 00%
  21910  
  21911           if  (isVertic al) {
  21912                var aSta ndardGain  = 10.0;
  21913                var aMil limeterPer uV = 100.0 ;
  21914                var aAve rageGain =  (aStandar dGain / aG ain);
  21915                var aMil liMeter =  (aAverageG ain * aTot alMillimet ers);
  21916  
  21917                if (aMil liMeter ==  0) {
  21918                    aMil liMeter =  0.1;
  21919                }
  21920  
  21921                var aTot aluV = (aM illiMeter  * aMillime terPeruV);
  21922                mm = aMi lliMeter;
  21923                uv = Mat h.round(aT otaluV);
  21924                var logM essage = " Millimeter  => " + mm  + "\n \
  21925                                    Total volt s => " + u v;
  21926                dumpCons oleLogs(LL _DEBUG, "V ertical ca liper meas urement un its", "ove rlayElemen t", logMes sage);
  21927           }  else {
  21928                var aTot alMilliSec ond = aTot alMillimet ers * grid 200Percent CellWidth;
  21929                if (aTot alMilliSec ond == 0)  {
  21930                    aTot alMilliSec ond = 1;
  21931                }
  21932                var aBea tsPerMinut e = 60000;
  21933                var aTot alBreatsPe rMinute =  aBeatsPerM inute / aT otalMilliS econd;
  21934  
  21935                bpm = Ma th.round(a TotalBreat sPerMinute );
  21936                ms = Mat h.round(aT otalMilliS econd);
  21937                
  21938                var logM essage = " Beats per  minute =>  " + bpm +  "\n \
  21939                                    Total mill iseconds = > " + ms;
  21940                dumpCons oleLogs(LL _DEBUG, "H orizontal  caliper me asurement  units", "o verlayElem ent", logM essage);
  21941           }
  21942       }
  21943  
  21944       functi on horizon atlMeasure mentText(c ontext) {
  21945           va r activeSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  21946                    var  imageId =  getImageId FromSeries Layout(act iveSeriesL ayout);
  21947           va r horizont alCaliper  = getHoriz ontalCalip er(imageId );
  21948  
  21949           co ntext.font  = '12pt C alibri';
  21950           co ntext.text Align = 'c enter';
  21951           co ntext.text Align = 'c enter';
  21952  
  21953           if  (activeSe riesLayout .preferenc eInfo.pref erenceData .gridColor  === 'grey Grid') {
  21954                context. fillStyle  = 'white';
  21955           }  else {
  21956                context. fillStyle  = 'blue';
  21957           }
  21958  
  21959           /*
  21960           *I dentify th e middle p oint of st right stra ight line
  21961           *  MidPoint =  (x+x1)/2, (y+y1)/2
  21962           */
  21963           va r middlePo intOfXaxis  = (horizo ntalCalipe r["centerL ineStartX" ] + horizo ntalCalipe r["centerL ineEndX"])  / 2;
  21964           va r middlePo intOfYaxis  = (horizo ntalCalipe r["centerL ineStartY" ] + horizo ntalCalipe r["centerL ineEndY"])  / 2;
  21965  
  21966           co ntext.fill Text(ms +  ' ms', mid dlePointOf Xaxis - 5,  middlePoi ntOfYaxis  - 30);
  21967           co ntext.fill Text(bpm +  ' BPM', m iddlePoint OfXaxis -  5, middleP ointOfYaxi s - 10);
  21968       }
  21969  
  21970       functi on vertica lMeasureme ntText(con text) {
  21971           va r activeSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  21972                    var  imageId =  activeSeri esLayout.g etImageRen der("ecgDa ta").getIm ageUid();
  21973           va r vertical Caliper =  getVertica lCaliper(i mageId);/* activeSeri esLayout.v erticalCal iper;*/
  21974  
  21975           co ntext.font  = '12pt C alibri';
  21976           co ntext.text Align = 'l eft';
  21977           
  21978                    if ( activeSeri esLayout.p referenceI nfo.prefer enceData.g ridColor = == 'greyGr id') {
  21979                context. fillStyle  = 'white';
  21980           }  else {
  21981                context. fillStyle  = 'blue';
  21982           }
  21983  
  21984           /*
  21985           *I dentify th e middle p oint of st right stra ight line
  21986           *  MidPoint =  (x+x1)/2, (y+y1)/2
  21987           */
  21988           va r middlePo intOfXaxis  = (vertic alCaliper[ "centerLin eStartX"]  + vertical Caliper["c enterLineE ndX"]) / 2 ;
  21989           va r middlePo intOfYaxis  = (vertic alCaliper[ "centerLin eStartY"]  + vertical Caliper["c enterLineE ndY"]) / 2 ;
  21990                    
  21991                    cont ext.fillTe xt(mm.toFi xed(2) + '  mm', midd lePointOfX axis + 10,  middlePoi ntOfYaxis) ;
  21992           co ntext.fill Text(uv +  ' uv', mid dlePointOf Xaxis + 10 , middlePo intOfYaxis  + 20);
  21993           
  21994       }
  21995  
  21996       functi on drawHor izontalCal iper(conte xt, horizo ntalCalipe r) {
  21997           co ntext.move To(horizon talCaliper ["centerLi neStartX"] , horizont alCaliper[ "centerLin eStartY"]) ;
  21998           co ntext.line To(horizon talCaliper ["centerLi neEndX"],  horizontal Caliper["c enterLineE ndY"]);
  21999  
  22000           co ntext.move To(horizon talCaliper ["firstLin eStartX"],  horizonta lCaliper[" firstLineS tartY"]);
  22001           co ntext.line To(horizon talCaliper ["firstLin eEndX"], h orizontalC aliper["fi rstLineEnd Y"]);
  22002  
  22003           co ntext.move To(horizon talCaliper ["lastLine StartX"],  horizontal Caliper["l astLineSta rtY"]);
  22004           co ntext.line To(horizon talCaliper ["lastLine EndX"], ho rizontalCa liper["las tLineEndY" ]);
  22005  
  22006           if  (dicomVie wer.getAct iveSeriesL ayout().pr eferenceIn fo.prefere nceData.gr idColor == = 'greyGri d') {
  22007                context. strokeStyl e = 'white ';
  22008           }  else {
  22009                context. strokeStyl e = 'blue' ;
  22010           }
  22011  
  22012           co ntext.stro ke();
  22013                    
  22014                    var  imageId =  getImageId FromSeries Layout(dic omViewer.g etActiveSe riesLayout ());
  22015                    setH orizontalC aliper(ima geId,horiz ontalCalip er);
  22016  
  22017           va r length =  getLength OfHorizont alCaliper( horizontal Caliper);
  22018           ov erlayEleme nt(length,  false);
  22019           ho rizonatlMe asurementT ext(contex t);
  22020       }
  22021  
  22022       functi on drawVer ticalCalip er(context , vertical Caliper) {
  22023           co ntext.move To(vertica lCaliper[" firstLineS tartX"], v erticalCal iper["firs tLineStart Y"]);
  22024           co ntext.line To(vertica lCaliper[" firstLineE ndX"], ver ticalCalip er["firstL ineEndY"]) ;
  22025  
  22026           co ntext.move To(vertica lCaliper[" centerLine StartX"],  verticalCa liper["cen terLineSta rtY"]);
  22027           co ntext.line To(vertica lCaliper[" centerLine EndX"], ve rticalCali per["cente rLineEndY" ]);
  22028  
  22029           co ntext.move To(vertica lCaliper[" lastLineSt artX"], ve rticalCali per["lastL ineStartY" ]);
  22030           co ntext.line To(vertica lCaliper[" lastLineEn dX"], vert icalCalipe r["lastLin eEndY"]);
  22031  
  22032           if  (dicomVie wer.getAct iveSeriesL ayout().pr eferenceIn fo.prefere nceData.gr idColor == = 'greyGri d') {
  22033                context. strokeStyl e = 'white ';
  22034           }  else {
  22035                context. strokeStyl e = 'blue' ;
  22036           }
  22037           co ntext.stro ke();
  22038                    
  22039                    var  imageId =  getImageId FromSeries Layout(dic omViewer.g etActiveSe riesLayout ());
  22040                    setV erticalCal iper(image Id,vertica lCaliper);
  22041           
  22042           va r length =  getLength OfVertical Caliper(ve rticalCali per);
  22043           ov erlayEleme nt(length,  true);
  22044           ve rticalMeas urementTex t(context) ;
  22045       }
  22046  
  22047       functi on redrawB othCaliper (activeSer iesLayout)  {
  22048           va r canvas =  document. getElement ById('imag eEcgCanvas ' + active SeriesLayo ut.getSeri esLayoutId ());
  22049           va r context  = canvas.g etContext( '2d');           
  22050                    var  imageId =  getImageId FromSeries Layout(act iveSeriesL ayout);
  22051                    if(d icomViewer .isShowcal iper(image Id)){
  22052                clearCur rentImage( context);
  22053                    draw Horizontal Caliper(co ntext, get Horizontal Caliper(im ageId));
  22054                    draw VerticalCa liper(cont ext, getVe rticalCali per(imageI d));
  22055                setCalip erStatus(a ctiveSerie sLayout.ge tSeriesLay outId(), " visible");
  22056                    }
  22057           $( "#imageEcg Canvas" +  activeSeri esLayout.g etSeriesLa youtId()). mousemove( clickAndMo ve);
  22058       }
  22059  
  22060       functi on clearCu rrentImage (context)  {
  22061           co ntext.clea rRect(0, 0 , context. canvas.wid th, contex t.canvas.h eight);
  22062           va r imageDat a = dicomV iewer.getA ctiveSerie sLayout(). getEcgCanv as();
  22063           co ntext.putI mageData(i mageData,  0, 0);
  22064           co ntext.begi nPath();
  22065       }
  22066           
  22067           /* *
  22068           *@ param seri esLayout
  22069           *  retun the  image id f rom the se ries layou t
  22070           */
  22071           fu nction get ImageIdFro mSeriesLay out(series Layout){
  22072                    if(s eriesLayou t === null  || series Layout ===  undefined ){
  22073                             throw  "seriesLay out cannot  be null o r undefine d"
  22074                    }
  22075                    retu rn seriesL ayout.getI mageRender ("ecgData" ).getImage Uid();
  22076           }
  22077  
  22078       functi on getScal eValue() {
  22079           va r activeSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  22080           va r canvas =  document. getElement ById('imag eEcgCanvas ' + active SeriesLayo ut.getSeri esLayoutId ());
  22081           va r context  = canvas.g etContext( '2d');
  22082           
  22083           va r imageRen derer = ac tiveSeries Layout.get ImageRende r("ecgData ");
  22084  
  22085           va r scaleVal ue = image Renderer.g etZoomLeve l();
  22086           if  (scaleVal ue === und efined ||  scaleValue  === null  || scaleVa lue === In finity) {
  22087                scaleVal ue = 1;
  22088           }
  22089           re turn scale Value;
  22090       }
  22091       
  22092           fu nction hid eCaliper() {
  22093                    var  activeSeri esLayout =  dicomView er.getActi veSeriesLa yout();
  22094           va r imageId  = getImage IdFromSeri esLayout(a ctiveSerie sLayout);
  22095                    //hi de caliper
  22096                    setS howCaliper (imageId,f alse);
  22097                    var  canvas = d ocument.ge tElementBy Id('imageE cgCanvas'  + activeSe riesLayout .getSeries LayoutId() );
  22098           va r context  = canvas.g etContext( '2d');
  22099                    clea rCurrentIm age(contex t);
  22100           se tCaliperSt atus(activ eSeriesLay out.getSer iesLayoutI d(), "invi sible");
  22101           $( '#viewport _View').cs s('cursor' , 'default ');
  22102           }
  22103       
  22104           fu nction dis playCalipe r(){
  22105                    var  activeSeri esLayout =  dicomView er.getActi veSeriesLa yout();
  22106           va r imageId  = getImage IdFromSeri esLayout(a ctiveSerie sLayout);
  22107                    //di splay cali per
  22108                    setS howCaliper (imageId,t rue);
  22109                    var  canvas = d ocument.ge tElementBy Id('imageE cgCanvas'  + activeSe riesLayout .getSeries LayoutId() );
  22110           va r context  = canvas.g etContext( '2d');
  22111                    clea rCurrentIm age(contex t);
  22112                    draw Horizontal Caliper(co ntext, get Horizontal Caliper(im ageId));
  22113           dr awVertical Caliper(co ntext, get VerticalCa liper(imag eId));
  22114           se tCaliperSt atus(activ eSeriesLay out.getSer iesLayoutI d(), "visi ble");
  22115           }
  22116       
  22117           /* *
  22118           *@ param imag eId
  22119           *@ param valu e
  22120           *  save the h orizontal  caliper va lues to dr aw in the  ecg canvas  based on  the image  Id
  22121           */
  22122           fu nction set Horizontal Caliper(im ageId, val ues){          
  22123                    hori zontalCali perValues[ imageId] =  values;
  22124           }
  22125           
  22126           /* *
  22127           *@ param imag eId
  22128           *@ param valu e
  22129           *  save the v ertical ca liper valu es to draw  in the ec g canvas b ased on th e image Id
  22130           */
  22131           fu nction set VerticalCa liper(imag eId, value s){
  22132                    
  22133                    vert icalCalipe rValues[im ageId] = v alues;
  22134           }
  22135           
  22136           /* *
  22137           *@ param imag eId
  22138           *  Retrive th e horizont al caliper  values ba sed on the  imageId
  22139           */
  22140           fu nction get Horizontal Caliper(im ageId){
  22141                    
  22142                    retu rn horizon talCaliper Values[ima geId];
  22143           }
  22144           
  22145           /* *
  22146           *@ param imag eId
  22147           *R etrive the  Vertical  caliper va lues based  on the im ageId
  22148           */
  22149           fu nction get VerticalCa liper(imag eId){
  22150                    
  22151                    retu rn vertica lCaliperVa lues[image Id];
  22152           }
  22153       
  22154           fu nction set ShowCalipe r(imageId,  flag){
  22155                    show Caliper[im ageId] = f lag;
  22156           }
  22157           
  22158           fu nction isS howcaliper (imageId){
  22159                    retu rn showCal iper[image Id];
  22160           }
  22161  
  22162       functi on setCali perStatus( layoutID,  status)
  22163       {
  22164         show CaliperSta tus[layout ID] = stat us;
  22165       }
  22166  
  22167       functi on getCali perStatus( layoutID){
  22168         retu rn showCal iperStatus [layoutID] ;
  22169       }
  22170  
  22171       functi on removeA llCaliperS tatus(){
  22172           fo r(var key  in showCal iperStatus ){
  22173                 delete  showCalipe rStatus[ke y];  
  22174           } 
  22175       }
  22176  
  22177       /**
  22178       * Reve rt the app lied horiz ontal and  vertical c aliper val ues
  22179       */
  22180       functi on RevertC aliper(){
  22181           va r imageId  = getImage IdFromSeri esLayout(d icomViewer .getActive SeriesLayo ut());
  22182           va r activeSe riesLayout  = dicomVi ewer.getAc tiveSeries Layout();
  22183           va r imgRende rer = acti veSeriesLa yout.getIm ageRender( "ecgData") ;
  22184           if (imgRender er !== und efined){
  22185                setHoriz ontalCalip er(imageId , undefine d);
  22186                setVerti calCaliper (imageId,  undefined) ;
  22187                setShowC aliper(ima geId, fals e);
  22188                setCalip erStatus(a ctiveSerie sLayout.se riesLayout Id, undefi ned);
  22189           }
  22190       }
  22191  
  22192       /**
  22193        * Pri nt the hor izontal/ve rtical cal iper
  22194        * @pa ram {Type}  context -  specifies  the print  context
  22195        * @pa ram {Type}  imageUid  - specifie s the imag e Uid
  22196        */ 
  22197       functi on printCa liper(cont ext, image Uid) {
  22198           tr y
  22199           {
  22200                var hori zontalCali per = getH orizontalC aliper(ima geUid);
  22201                var vert icalCalipe r = getVer ticalCalip er(imageUi d);
  22202                if(horiz ontalCalip er && vert icalCalipe r) {
  22203                    draw Horizontal Caliper(co ntext, hor izontalCal iper);
  22204                    draw VerticalCa liper(cont ext, verti calCaliper );
  22205                }
  22206           }
  22207           ca tch(e)
  22208           {  }
  22209       }
  22210  
  22211       dicomV iewer.draw Caliper =  drawCalipe r;
  22212       dicomV iewer.redr awBothCali per = redr awBothCali per;
  22213           di comViewer. getHorizon talCaliper  = getHori zontalCali per;
  22214           di comViewer. isShowcali per = isSh owcaliper;
  22215           di comViewer. hideCalipe r = hideCa liper;
  22216           di comViewer. displayCal iper = dis playCalipe r;
  22217       dicomV iewer.remo veAllCalip erStatus =  removeAll CaliperSta tus;
  22218       dicomV iewer.getC aliperStat us = getCa liperStatu s;
  22219       dicomV iewer.Reve rtCaliper  = RevertCa liper;
  22220       dicomV iewer.prin tCaliper =  printCali per;
  22221       return  dicomView er;
  22222   } (dicomVi ewer));var  dicomView er = (func tion(dicom Viewer)
  22223   {
  22224       if(dic omViewer = == undefin ed) {
  22225           di comViewer  = {};
  22226       }
  22227  
  22228       var ci nePreferen ce = {
  22229  
  22230       };
  22231       
  22232       var ec gPreferenc e = {
  22233  
  22234       };
  22235  
  22236       var di splayPrefe rence = {
  22237  
  22238       };
  22239       
  22240       var co pyAttribut esPreferen ce = {
  22241  
  22242       };
  22243       
  22244       var lo gPreferenc e = {
  22245  
  22246       };
  22247  
  22248       functi on getCine Preference (type, ove rride) {
  22249           if  (cinePref erence[typ e].useDefa ult && ove rride) {
  22250                type = " SYSTEM";
  22251           }
  22252           re turn cineP reference[ type];
  22253       }
  22254  
  22255       functi on setCine Preference (preferenc eData, typ e) {
  22256           ci nePreferen ce[type] =  preferenc eData;
  22257           if (type == " USER") {
  22258                //updati ng the cin e tool bar  repeat st udy/series  according  to the ci ne prefere nces 
  22259                cineplay By(getCine PlayBy());
  22260           }
  22261       }
  22262  
  22263       functi on getCine PlayBy() {
  22264           va r type = " USER";
  22265           if  (cinePref erence[typ e].useDefa ult) {
  22266                type = " SYSTEM";
  22267           }
  22268           re turn cineP reference[ type].paly selection;
  22269       }
  22270  
  22271       functi on setCine PlayBy(pla yBy) {
  22272           ci nePreferen ce["USER"] .palyselec tion = pla yBy;
  22273       }
  22274       
  22275       functi on getFram esToRepeat () {
  22276           va r type = " USER";
  22277           if  (cinePref erence[typ e].useDefa ult) {
  22278                type = " SYSTEM";
  22279           }
  22280           re turn cineP reference[ type].fram esToRepeat ;
  22281       }
  22282  
  22283       functi on getTime sToRepeat( ) {
  22284           va r type = " USER";
  22285           if  (cinePref erence[typ e].useDefa ult) {
  22286                type = " SYSTEM";
  22287           }
  22288           re turn cineP reference[ type].time sToRepeat;
  22289       }
  22290  
  22291       functi on getIdle Time() {
  22292           va r type = " USER";
  22293           if  (cinePref erence[typ e].useDefa ult) {
  22294                type = " SYSTEM";
  22295           }
  22296           re turn cineP reference[ type].idle Time;
  22297       }
  22298  
  22299       functi on getEcgP reference( type, over ride) {
  22300           if  (ecgPrefe rence[type ].useDefau lt && over ride) {
  22301                type = " SYSTEM";
  22302           }
  22303           re turn ecgPr eference[t ype];
  22304       }
  22305  
  22306       functi on setEcgP reference( preference Data, type ) {
  22307           ec gPreferenc e[type] =  preference Data;
  22308       }
  22309  
  22310       functi on getDisp layPrefere nce(type,  override)  {
  22311           if  (displayP reference[ type].useD efault &&  override)  {
  22312                type = " SYSTEM";
  22313           }
  22314           re turn displ ayPreferen ce[type];
  22315       }
  22316  
  22317       functi on setDisp layPrefere nce(prefer enceData,  type) {
  22318           di splayPrefe rence[type ] = prefer enceData;
  22319       }
  22320  
  22321       functi on getCopy AttribPref erence(typ e, overrid e) {
  22322           if  (copyAttr ibutesPref erence[typ e].useDefa ult && ove rride) {
  22323                type = " SYSTEM";
  22324           }
  22325           re turn copyA ttributesP reference[ type];
  22326       }
  22327  
  22328       functi on setCopy AttribPref erence(pre ferenceDat a, type) {
  22329           co pyAttribut esPreferen ce[type] =  preferenc eData;
  22330       }
  22331       
  22332       functi on getLogP reference( type, over ride) {
  22333           if  (logPrefe rence[type ].useDefau lt && over ride) {
  22334                type = " SYSTEM";
  22335           }
  22336           re turn logPr eference[t ype];
  22337       }
  22338       
  22339       functi on setLogP reference( preference Data, type ) {
  22340           lo gPreferenc e[type] =  preference Data;
  22341           di comViewer. logUtility .setLogPre ference();
  22342       }
  22343       
  22344       dicomV iewer.conf iguration  = {
  22345           ci ne : {
  22346                getCineP reference:  getCinePr eference,
  22347                setCineP reference:  setCinePr eference,
  22348                getCineP layBy: get CinePlayBy ,
  22349                setCineP layBy: set CinePlayBy ,
  22350                getFrame sToRepeat:  getFrames ToRepeat,
  22351                getTimes ToRepeat:  getTimesTo Repeat,
  22352                getIdleT ime: getId leTime
  22353           },
  22354           ec g : {
  22355                getEcgPr eference:  getEcgPref erence,
  22356                setEcgPr eference:  setEcgPref erence
  22357           },
  22358           di splay : {
  22359                getDispl ayPreferen ce: getDis playPrefer ence,
  22360                setDispl ayPreferen ce: setDis playPrefer ence
  22361           },
  22362           co pyAttrib :  {
  22363                getCopyA ttribPrefe rence: get CopyAttrib Preference ,
  22364                setCopyA ttribPrefe rence: set CopyAttrib Preference
  22365           },
  22366           lo g : {
  22367                getLogPr eference :  getLogPre ference,
  22368                setLogPr eference :  setLogPre ference
  22369           }
  22370       };
  22371       
  22372   return dic omViewer;
  22373           
  22374   }(dicomVie wer));/**
  22375    * This mo dule deals  with link ing series  within a  study
  22376    */
  22377  
  22378   var dicomV iewer = (f unction(di comViewer)  {
  22379       if (di comViewer  === undefi ned) {
  22380           di comViewer  = {};
  22381       }
  22382  
  22383       var li nkGroup =  [];
  22384       var ac tiveStudyU id = null;
  22385       var ac tiveViewpo rtId = nul l;
  22386       var is LinkToolAc tive = fal se;
  22387  
  22388       functi on linkSer ies() {
  22389           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  22390           va r studyUid  = seriesL ayout.getS tudyUid();
  22391  
  22392           if  (isLinkTo olActive)  {
  22393                if (acti veStudyUid  == studyU id && acti veViewport Id !== ser iesLayout. getSeriesL ayoutId())  {
  22394                    var  seriesGrou p = [];
  22395                    var  isStudyExi sts = fals e;
  22396                    $.ea ch(linkGro up, functi on(key, va lue) {
  22397                         if (value. studyUid = = activeSt udyUid) {
  22398                             series Group = li nkGroup[ke y].linkedS eries;
  22399                             isStud yExists =  true;
  22400                             return  false;
  22401                         }
  22402                    });
  22403                    seri esGroup.pu sh
  22404                    (
  22405                         {
  22406                             source ViewportId : activeVi ewportId,
  22407                             target ViewportId : seriesLa yout.getSe riesLayout Id()
  22408                         }
  22409                    );
  22410  
  22411                    if ( !isStudyEx ists) {
  22412                         linkGroup. push({stud yUid: acti veStudyUid , linkedSe ries: seri esGroup});
  22413                    }
  22414                    
  22415                    isLi nkToolActi ve = false ;
  22416                } else {
  22417                    rese tActiveLin kData();
  22418                }
  22419           }  else {
  22420                setActiv eLinkData( seriesLayo ut);
  22421           }
  22422       }
  22423  
  22424       functi on unLinkS eries(seri esId) {
  22425           va r seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  22426           va r studyUid  = seriesL ayout.getS tudyUid();
  22427  
  22428           va r isLinked  = false;
  22429           va r arrIndex  = null;
  22430  
  22431           $. each(linkG roup, func tion(key,  value) {
  22432                if (valu e.studyUid  == studyU id) {
  22433                    $.ea ch(value.l inkedSerie s, functio n(key, val ue_) {
  22434                         if (value_ .sourceVie wportId == = seriesLa yout.getSe riesLayout Id() || 
  22435                             value_ .targetVie wportId == = seriesLa yout.getSe riesLayout Id()) {
  22436                             isLink ed = true;
  22437                         }
  22438  
  22439                         if (isLink ed) {
  22440                             arrInd ex = key;
  22441                             return  false;
  22442                         }
  22443                    });
  22444  
  22445                    if(i sLinked) {
  22446                         value.link edSeries.s plice(arrI ndex, 1);
  22447                         return tru e;
  22448                    }
  22449                }
  22450           }) ;
  22451       }
  22452  
  22453       functi on isLinkE nabled() {
  22454           tr y
  22455           {
  22456                var seri esLayout =  dicomView er.getActi veSeriesLa yout();
  22457                if(serie sLayout == = undefine d || serie sLayout == = null ||  seriesLayo ut.seriesI ndex === u ndefined)  {
  22458                    retu rn false;
  22459                }
  22460  
  22461                var stud yUid = ser iesLayout. getStudyUi d();
  22462                var stud yDetials =  dicomView er.getStud yDetails(s tudyUid);
  22463                var numb erOfSeries  = dicomVi ewer.Study .getSeries Count(stud yUid);
  22464                var isCh eck = fals e;
  22465  
  22466                // Show  or hide th e link men u
  22467                if(dicom Viewer.Stu dy.getSeri esCount(se riesLayout .getStudyU id()) > 1)  {
  22468                    isCh eck = true ;
  22469                } else {
  22470                    var  numberOfIm ages = dic omViewer.S eries.getI mageCount( seriesLayo ut.getStud yUid(), 0) ;
  22471                    if(n umberOfIma ges > 1 &&  dicomView er.thumbna il.isSerie sContainsM ultiframe( seriesLayo ut.getStud yUid(), 0) ) {
  22472                         isCheck =  true;
  22473                    } el se {
  22474                         isCheck =  false;
  22475                    }
  22476                }
  22477  
  22478                if(isChe ck == true  && dicomV iewer.thum bnail.isSe riesContai nsMultifra me(seriesL ayout.getS tudyUid(),  0)) {
  22479                    var  image = di comViewer. Series.Ima ge.getImag e(studyUid , seriesLa yout.serie sIndex, se riesLayout .scrollDat a.imageInd ex);
  22480                    if(i mage && im age.number OfFrames < = 1 && !is SeriesLink ed()) {
  22481                         isCheck =   false; 
  22482                    }
  22483                }
  22484  
  22485                dicomVie wer.Enable DisableRef erenceLine Menu(serie sLayout);
  22486                if(study Detials != = null &&  studyDetia ls !== und efined) {
  22487                    if(s eriesLayou t.imageTyp e === IMAG ETYPE_RADE CG||series Layout.ima geType ===  IMAGETYPE _RADPDF ||  isCheck = = false) {
  22488                             return  false;
  22489                    }
  22490                    if(s tudyDetial s.isDicom)  {
  22491                         return tru e;
  22492                    }
  22493                }
  22494           }
  22495           ca tch(e)
  22496           {  }
  22497  
  22498           re turn false ;
  22499       }
  22500  
  22501       functi on updateL inkMenu()  {
  22502           va r cursor =  document. getElement ById('view port_View' ).style.cu rsor;
  22503           if  (cursor ! = 'url("im ages/link. cur"), aut o' && curs or != 'url (images/li nk.cur), a uto') {
  22504                resetAct iveLinkDat a();
  22505           }
  22506          
  22507           $( "#linkButt on_overflo w").css("b ackground- color", "# 363636");
  22508  
  22509           if (isLinkEna bled()) {
  22510                $(".link Series").s how();
  22511                $("#link Button").r emoveClass ("k-state- disabled") ;
  22512                $("#link Button_ove rflow").sh ow();
  22513                $(".link Series").t ext(isSeri esLinked()  ? "UnLink  Viewport"  : "Link V iewport");
  22514                $("#cont ext-link") .show();
  22515                $("#cont ext-link-m enu").show ();
  22516           }  else {
  22517                $(".link Series").h ide();
  22518                $("#link Button").a ddClass("k -state-dis abled");
  22519                $("#link Button_ove rflow").hi de();
  22520                $("#cont ext-link") .hide();
  22521                $("#cont ext-link-m enu").hide ();
  22522           }
  22523       }
  22524  
  22525       functi on setActi veLinkData (seriesLay out) {
  22526           ac tiveStudyU id = serie sLayout.ge tStudyUid( );
  22527           ac tiveViewpo rtId = ser iesLayout. getSeriesL ayoutId();
  22528           is LinkToolAc tive = tru e;
  22529       }
  22530  
  22531       functi on getLink ToolActive () {
  22532           re turn isLin kToolActiv e;
  22533       }
  22534  
  22535       functi on isSerie sLinked(so urceViewpo rt) {
  22536           va r seriesLa yout = und efined;
  22537           if (sourceVie wport !==  undefined)  {
  22538                seriesLa yout = sou rceViewpor t;
  22539           }  else {
  22540                seriesLa yout = dic omViewer.g etActiveSe riesLayout ();
  22541           }
  22542  
  22543           va r studyUid  = seriesL ayout.getS tudyUid();
  22544           va r isLinked  = false;
  22545  
  22546           $. each(linkG roup, func tion(key,  value) {
  22547                if (valu e.studyUid  == studyU id) {
  22548                    valu e.linkedSe ries.some( function(s eriesGroup ) {
  22549                         if (series Group.sour ceViewport Id === ser iesLayout. getSeriesL ayoutId()  || 
  22550                            seriesG roup.targe tViewportI d === seri esLayout.g etSeriesLa youtId())  {
  22551                             isLink ed = true;
  22552                         }
  22553  
  22554                         if (isLink ed) {
  22555                             return  true;
  22556                         }
  22557                    });
  22558                }
  22559           }) ;
  22560  
  22561           re turn isLin ked;
  22562       }
  22563  
  22564       functi on resetAc tiveLinkDa ta() {
  22565           ac tiveStudyU id = null;
  22566           ac tiveViewpo rtId = nul l;
  22567           is LinkToolAc tive = fal se;
  22568       }
  22569  
  22570       /**
  22571        * Per form the l ink operat ion
  22572        * @pa ram {Type}  sourceVie wport - Sp ecifies th e source v iew port
  22573        * @pa ram {Type}  moveToNex t - Flag t o navigate  forward o r backward
  22574        */ 
  22575       functi on doLink( sourceView port, move ToNext, di rection, c ineMode) {
  22576           tr y
  22577           {
  22578                if(sourc eViewport  === undefi ned || sou rceViewpor t === null ) {
  22579                    retu rn;
  22580                }
  22581  
  22582                if (isSe riesLinked (sourceVie wport) !==  true) {
  22583                    retu rn;
  22584                }
  22585  
  22586                var targ etViewport Id = getTa rgetViewpo rt(sourceV iewport);
  22587  
  22588                var view port = dic omViewer.v iewports.g etViewport (targetVie wportId);
  22589                if(viewp ort === un defined ||  viewport  === null)  {
  22590                    retu rn;
  22591                }
  22592  
  22593                if (cine Mode != un defined) {
  22594                    if ( cineMode)  {
  22595                         dicomViewe r.scroll.r unCineImag e(directio n, viewpor t);
  22596                    } el se {
  22597                         dicomViewe r.scroll.s topCineIma ge(directi on, viewpo rt);
  22598                    }
  22599                } else {
  22600                    dico mViewer.sc roll.moveT oNextOrPre viousImage (moveToNex t, viewpor t);
  22601                }
  22602           }
  22603           ca tch(e)
  22604           {  }
  22605       }
  22606       
  22607       /**
  22608        * To  get the ta rget viewp ort id, li nked with  the source  viewport
  22609        * @pa ram {Type}  sourceVie wport - Sp ecifies th e source v iewport
  22610        */
  22611       functi on getTarg etViewport (sourceVie wport) {
  22612           va r targetVi ewportId =  undefined ;
  22613                $.each(l inkGroup,  function(k ey, value)  {
  22614                    if ( value.stud yUid === s ourceViewp ort.getStu dyUid()) {
  22615                         value.link edSeries.s ome(functi on(seriesG roup) {
  22616                             if (se riesGroup. sourceView portId ===  sourceVie wport.getS eriesLayou tId()) {
  22617                                 ta rgetViewpo rtId = ser iesGroup.t argetViewp ortId;
  22618                             } else  if(series Group.targ etViewport Id === sou rceViewpor t.getSerie sLayoutId( )) {
  22619                                 ta rgetViewpo rtId = ser iesGroup.s ourceViewp ortId;
  22620                             }
  22621  
  22622                             if (ta rgetViewpo rtId !== u ndefined)  {
  22623                                 re turn true;
  22624                             }
  22625                         });
  22626                    }
  22627                });
  22628           re turn targe tViewportI d;
  22629       }
  22630  
  22631       dicomV iewer.link  = {
  22632           li nkSeries:  linkSeries ,
  22633           un LinkSeries : unLinkSe ries,
  22634           up dateLinkMe nu: update LinkMenu,
  22635           ge tLinkToolA ctive: get LinkToolAc tive,
  22636           is SeriesLink ed: isSeri esLinked,
  22637           re setActiveL inkData: r esetActive LinkData,
  22638           do Link: doLi nk,
  22639           ge tTargetVie wport: get TargetView port
  22640       }
  22641  
  22642       return  dicomView er;
  22643   }(dicomVie wer));
  22644  
  22645