27. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 4/9/2018 3:46:05 PM Eastern 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.

27.1 Files compared

# Location File Last Modified
1 TelehealthMgmtPlat_4.0.zip\Telehealth Management Platform 4.0\CRM-Prod.zip\CRM-Prod\VA.TMP.WebResources\J Script Functions\ServiceActivity mcs_ServiceActivity.js Fri Feb 23 23:11:34 2018 UTC
2 TelehealthMgmtPlat_4.0.zip\Telehealth Management Platform 4.0\CRM-Prod.zip\CRM-Prod\VA.TMP.WebResources\J Script Functions\ServiceActivity mcs_ServiceActivity.js Mon Apr 9 12:59:56 2018 UTC

27.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 3 26626
Changed 2 4
Inserted 0 0
Removed 0 0

27.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

27.4 Active regular expressions

No regular expressions were active.

27.5 Comparison detail

  1   /*!
  2    * jQuery  JavaScript  Library v 1.7.1
  3    * http:// jquery.com /
  4    *
  5    * Copyrig ht 2011, J ohn Resig
  6    * Dual li censed und er the MIT  or GPL Ve rsion 2 li censes.
  7    * http:// jquery.org /license
  8    *
  9    * Include s Sizzle.j s
  10    * http:// sizzlejs.c om/
  11    * Copyrig ht 2011, T he Dojo Fo undation
  12    * Release d under th e MIT, BSD , and GPL  Licenses.
  13    *
  14    * Date: M on Nov 21  21:11:03 2 011 -0500
  15    */
  16   (function(  window, u ndefined )  {
  17  
  18   // Use the  correct d ocument ac cordingly  with windo w argument  (sandbox)
  19   var docume nt = windo w.document ,
  20           na vigator =  window.nav igator,
  21           lo cation = w indow.loca tion;
  22   var jQuery  = (functi on() {
  23  
  24   // Define  a local co py of jQue ry
  25   var jQuery  = functio n( selecto r, context  ) {
  26                    // T he jQuery  object is  actually j ust the in it constru ctor 'enha nced'
  27                    retu rn new jQu ery.fn.ini t( selecto r, context , rootjQue ry );
  28           },
  29  
  30           //  Map over  jQuery in  case of ov erwrite
  31           _j Query = wi ndow.jQuer y,
  32  
  33           //  Map over  the $ in c ase of ove rwrite
  34           _$  = window. $,
  35  
  36           //  A central  reference  to the ro ot jQuery( document)
  37           ro otjQuery,
  38  
  39           //  A simple  way to che ck for HTM L strings  or ID stri ngs
  40           //  Prioritiz e #id over  <tag> to  avoid XSS  via locati on.hash (# 9521)
  41           qu ickExpr =  /^(?:[^#<] *(<[\w\W]+ >)[^>]*$|# ([\w\-]*)$ )/,
  42  
  43           //  Check if  a string h as a non-w hitespace  character  in it
  44           rn otwhite =  /\S/,
  45  
  46           //  Used for  trimming w hitespace
  47           tr imLeft = / ^\s+/,
  48           tr imRight =  /\s+$/,
  49  
  50           //  Match a s tandalone  tag
  51           rs ingleTag =  /^<(\w+)\ s*\/?>(?:< \/\1>)?$/,
  52  
  53           //  JSON RegE xp
  54           rv alidchars  = /^[\],:{ }\s]*$/,
  55           rv alidescape  = /\\(?:[ "\\\/bfnrt ]|u[0-9a-f A-F]{4})/g ,
  56           rv alidtokens  = /"[^"\\ \n\r]*"|tr ue|false|n ull|-?\d+( ?:\.\d*)?( ?:[eE][+\- ]?\d+)?/g,
  57           rv alidbraces  = /(?:^|: |,)(?:\s*\ [)+/g,
  58  
  59           //  Useragent  RegExp
  60           rw ebkit = /( webkit)[ \ /]([\w.]+) /,
  61           ro pera = /(o pera)(?:.* version)?[  \/]([\w.] +)/,
  62           rm sie = /(ms ie) ([\w.] +)/,
  63           rm ozilla = / (mozilla)( ?:.*? rv:( [\w.]+))?/ ,
  64  
  65           //  Matches d ashed stri ng for cam elizing
  66           rd ashAlpha =  /-([a-z]| [0-9])/ig,
  67           rm sPrefix =  /^-ms-/,
  68  
  69           //  Used by j Query.came lCase as c allback to  replace()
  70           fc amelCase =  function(  all, lett er ) {
  71                    retu rn ( lette r + "" ).t oUpperCase ();
  72           },
  73  
  74           //  Keep a Us erAgent st ring for u se with jQ uery.brows er
  75           us erAgent =  navigator. userAgent,
  76  
  77           //  For match ing the en gine and v ersion of  the browse r
  78           br owserMatch ,
  79  
  80           //  The defer red used o n DOM read y
  81           re adyList,
  82  
  83           //  The ready  event han dler
  84           DO MContentLo aded,
  85  
  86           //  Save a re ference to  some core  methods
  87           to String = O bject.prot otype.toSt ring,
  88           ha sOwn = Obj ect.protot ype.hasOwn Property,
  89           pu sh = Array .prototype .push,
  90           sl ice = Arra y.prototyp e.slice,
  91           tr im = Strin g.prototyp e.trim,
  92           in dexOf = Ar ray.protot ype.indexO f,
  93  
  94           //  [[Class]]  -> type p airs
  95           cl ass2type =  {};
  96  
  97   jQuery.fn  = jQuery.p rototype =  {
  98           co nstructor:  jQuery,
  99           in it: functi on( select or, contex t, rootjQu ery ) {
  100                    var  match, ele m, ret, do c;
  101  
  102                    // H andle $("" ), $(null) , or $(und efined)
  103                    if (  !selector  ) {
  104                             return  this;
  105                    }
  106  
  107                    // H andle $(DO MElement)
  108                    if (  selector. nodeType )  {
  109                             this.c ontext = t his[0] = s elector;
  110                             this.l ength = 1;
  111                             return  this;
  112                    }
  113  
  114                    // T he body el ement only  exists on ce, optimi ze finding  it
  115                    if (  selector  === "body"  && !conte xt && docu ment.body  ) {
  116                             this.c ontext = d ocument;
  117                             this[0 ] = docume nt.body;
  118                             this.s elector =  selector;
  119                             this.l ength = 1;
  120                             return  this;
  121                    }
  122  
  123                    // H andle HTML  strings
  124                    if (  typeof se lector ===  "string"  ) {
  125                             // Are  we dealin g with HTM L string o r an ID?
  126                             if ( s elector.ch arAt(0) == = "<" && s elector.ch arAt( sele ctor.lengt h - 1 ) == = ">" && s elector.le ngth >= 3  ) {
  127                                      // Assum e that str ings that  start and  end with < > are HTML  and skip  the regex  check
  128                                      match =  [ null, se lector, nu ll ];
  129  
  130                             } else  {
  131                                      match =  quickExpr. exec( sele ctor );
  132                             }
  133  
  134                             // Ver ify a matc h, and tha t no conte xt was spe cified for  #id
  135                             if ( m atch && (m atch[1] ||  !context)  ) {
  136  
  137                                      // HANDL E: $(html)  -> $(arra y)
  138                                      if ( mat ch[1] ) {
  139                                               context =  context in stanceof j Query ? co ntext[0] :  context;
  140                                               doc = ( co ntext ? co ntext.owne rDocument  || context  : documen t );
  141  
  142                                               // If a si ngle strin g is passe d in and i t's a sing le tag
  143                                               // just do  a createE lement and  skip the  rest
  144                                               ret = rsin gleTag.exe c( selecto r );
  145  
  146                                               if ( ret )  {
  147                                                       if  ( jQuery. isPlainObj ect( conte xt ) ) {
  148                                                                sele ctor = [ d ocument.cr eateElemen t( ret[1]  ) ];
  149                                                                jQue ry.fn.attr .call( sel ector, con text, true  );
  150  
  151                                                       }  else {
  152                                                                sele ctor = [ d oc.createE lement( re t[1] ) ];
  153                                                       }
  154  
  155                                               } else {
  156                                                       re t = jQuery .buildFrag ment( [ ma tch[1] ],  [ doc ] );
  157                                                       se lector = (  ret.cache able ? jQu ery.clone( ret.fragme nt) : ret. fragment ) .childNode s;
  158                                               }
  159  
  160                                               return jQu ery.merge(  this, sel ector );
  161  
  162                                      // HANDL E: $("#id" )
  163                                      } else {
  164                                               elem = doc ument.getE lementById ( match[2]  );
  165  
  166                                               // Check p arentNode  to catch w hen Blackb erry 4.6 r eturns
  167                                               // nodes t hat are no  longer in  the docum ent #6963
  168                                               if ( elem  && elem.pa rentNode )  {
  169                                                       //  Handle th e case whe re IE and  Opera retu rn items
  170                                                       //  by name i nstead of  ID
  171                                                       if  ( elem.id  !== match [2] ) {
  172                                                                retu rn rootjQu ery.find(  selector ) ;
  173                                                       }
  174  
  175                                                       //  Otherwise , we injec t the elem ent direct ly into th e jQuery o bject
  176                                                       th is.length  = 1;
  177                                                       th is[0] = el em;
  178                                               }
  179  
  180                                               this.conte xt = docum ent;
  181                                               this.selec tor = sele ctor;
  182                                               return thi s;
  183                                      }
  184  
  185                             // HAN DLE: $(exp r, $(...))
  186                             } else  if ( !con text || co ntext.jque ry ) {
  187                                      return (  context | | rootjQue ry ).find(  selector  );
  188  
  189                             // HAN DLE: $(exp r, context )
  190                             // (wh ich is jus t equivale nt to: $(c ontext).fi nd(expr)
  191                             } else  {
  192                                      return t his.constr uctor( con text ).fin d( selecto r );
  193                             }
  194  
  195                    // H ANDLE: $(f unction)
  196                    // S hortcut fo r document  ready
  197                    } el se if ( jQ uery.isFun ction( sel ector ) )  {
  198                             return  rootjQuer y.ready( s elector );
  199                    }
  200  
  201                    if (  selector. selector ! == undefin ed ) {
  202                             this.s elector =  selector.s elector;
  203                             this.c ontext = s elector.co ntext;
  204                    }
  205  
  206                    retu rn jQuery. makeArray(  selector,  this );
  207           },
  208  
  209           //  Start wit h an empty  selector
  210           se lector: "" ,
  211  
  212           //  The curre nt version  of jQuery  being use d
  213           jq uery: "1.7 .1",
  214  
  215           //  The defau lt length  of a jQuer y object i s 0
  216           le ngth: 0,
  217  
  218           //  The numbe r of eleme nts contai ned in the  matched e lement set
  219           si ze: functi on() {
  220                    retu rn this.le ngth;
  221           },
  222  
  223           to Array: fun ction() {
  224                    retu rn slice.c all( this,  0 );
  225           },
  226  
  227           //  Get the N th element  in the ma tched elem ent set OR
  228           //  Get the w hole match ed element  set as a  clean arra y
  229           ge t: functio n( num ) {
  230                    retu rn num ==  null ?
  231  
  232                             // Ret urn a 'cle an' array
  233                             this.t oArray() :
  234  
  235                             // Ret urn just t he object
  236                             ( num  < 0 ? this [ this.len gth + num  ] : this[  num ] );
  237           },
  238  
  239           //  Take an a rray of el ements and  push it o nto the st ack
  240           //  (returnin g the new  matched el ement set)
  241           pu shStack: f unction( e lems, name , selector  ) {
  242                    // B uild a new  jQuery ma tched elem ent set
  243                    var  ret = this .construct or();
  244  
  245                    if (  jQuery.is Array( ele ms ) ) {
  246                             push.a pply( ret,  elems );
  247  
  248                    } el se {
  249                             jQuery .merge( re t, elems ) ;
  250                    }
  251  
  252                    // A dd the old  object on to the sta ck (as a r eference)
  253                    ret. prevObject  = this;
  254  
  255                    ret. context =  this.conte xt;
  256  
  257                    if (  name ===  "find" ) {
  258                             ret.se lector = t his.select or + ( thi s.selector  ? " " : " " ) + sele ctor;
  259                    } el se if ( na me ) {
  260                             ret.se lector = t his.select or + "." +  name + "( " + select or + ")";
  261                    }
  262  
  263                    // R eturn the  newly-form ed element  set
  264                    retu rn ret;
  265           },
  266  
  267           //  Execute a  callback  for every  element in  the match ed set.
  268           //  (You can  seed the a rguments w ith an arr ay of args , but this  is
  269           //  only used  internall y.)
  270           ea ch: functi on( callba ck, args )  {
  271                    retu rn jQuery. each( this , callback , args );
  272           },
  273  
  274           re ady: funct ion( fn )  {
  275                    // A ttach the  listeners
  276                    jQue ry.bindRea dy();
  277  
  278                    // A dd the cal lback
  279                    read yList.add(  fn );
  280  
  281                    retu rn this;
  282           },
  283  
  284           eq : function ( i ) {
  285                    i =  +i;
  286                    retu rn i === - 1 ?
  287                             this.s lice( i )  :
  288                             this.s lice( i, i  + 1 );
  289           },
  290  
  291           fi rst: funct ion() {
  292                    retu rn this.eq ( 0 );
  293           },
  294  
  295           la st: functi on() {
  296                    retu rn this.eq ( -1 );
  297           },
  298  
  299           sl ice: funct ion() {
  300                    retu rn this.pu shStack( s lice.apply ( this, ar guments ),
  301                             "slice ", slice.c all(argume nts).join( ",") );
  302           },
  303  
  304           ma p: functio n( callbac k ) {
  305                    retu rn this.pu shStack( j Query.map( this, func tion( elem , i ) {
  306                             return  callback. call( elem , i, elem  );
  307                    }));
  308           },
  309  
  310           en d: functio n() {
  311                    retu rn this.pr evObject | | this.con structor(n ull);
  312           },
  313  
  314           //  For inter nal use on ly.
  315           //  Behaves l ike an Arr ay's metho d, not lik e a jQuery  method.
  316           pu sh: push,
  317           so rt: [].sor t,
  318           sp lice: [].s plice
  319   };
  320  
  321   // Give th e init fun ction the  jQuery pro totype for  later ins tantiation
  322   jQuery.fn. init.proto type = jQu ery.fn;
  323  
  324   jQuery.ext end = jQue ry.fn.exte nd = funct ion() {
  325           va r options,  name, src , copy, co pyIsArray,  clone,
  326                    targ et = argum ents[0] ||  {},
  327                    i =  1,
  328                    leng th = argum ents.lengt h,
  329                    deep  = false;
  330  
  331           //  Handle a  deep copy  situation
  332           if  ( typeof  target ===  "boolean"  ) {
  333                    deep  = target;
  334                    targ et = argum ents[1] ||  {};
  335                    // s kip the bo olean and  the target
  336                    i =  2;
  337           }
  338  
  339           //  Handle ca se when ta rget is a  string or  something  (possible  in deep co py)
  340           if  ( typeof  target !==  "object"  && !jQuery .isFunctio n(target)  ) {
  341                    targ et = {};
  342           }
  343  
  344           //  extend jQ uery itsel f if only  one argume nt is pass ed
  345           if  ( length  === i ) {
  346                    targ et = this;
  347                    --i;
  348           }
  349  
  350           fo r ( ; i <  length; i+ + ) {
  351                    // O nly deal w ith non-nu ll/undefin ed values
  352                    if (  (options  = argument s[ i ]) !=  null ) {
  353                             // Ext end the ba se object
  354                             for (  name in op tions ) {
  355                                      src = ta rget[ name  ];
  356                                      copy = o ptions[ na me ];
  357  
  358                                      // Preve nt never-e nding loop
  359                                      if ( tar get === co py ) {
  360                                               continue;
  361                                      }
  362  
  363                                      // Recur se if we'r e merging  plain obje cts or arr ays
  364                                      if ( dee p && copy  && ( jQuer y.isPlainO bject(copy ) || (copy IsArray =  jQuery.isA rray(copy) ) ) ) {
  365                                               if ( copyI sArray ) {
  366                                                       co pyIsArray  = false;
  367                                                       cl one = src  && jQuery. isArray(sr c) ? src :  [];
  368  
  369                                               } else {
  370                                                       cl one = src  && jQuery. isPlainObj ect(src) ?  src : {};
  371                                               }
  372  
  373                                               // Never m ove origin al objects , clone th em
  374                                               target[ na me ] = jQu ery.extend ( deep, cl one, copy  );
  375  
  376                                      // Don't  bring in  undefined  values
  377                                      } else i f ( copy ! == undefin ed ) {
  378                                               target[ na me ] = cop y;
  379                                      }
  380                             }
  381                    }
  382           }
  383  
  384           //  Return th e modified  object
  385           re turn targe t;
  386   };
  387  
  388   jQuery.ext end({
  389           no Conflict:  function(  deep ) {
  390                    if (  window.$  === jQuery  ) {
  391                             window .$ = _$;
  392                    }
  393  
  394                    if (  deep && w indow.jQue ry === jQu ery ) {
  395                             window .jQuery =  _jQuery;
  396                    }
  397  
  398                    retu rn jQuery;
  399           },
  400  
  401           //  Is the DO M ready to  be used?  Set to tru e once it  occurs.
  402           is Ready: fal se,
  403  
  404           //  A counter  to track  how many i tems to wa it for bef ore
  405           //  the ready  event fir es. See #6 781
  406           re adyWait: 1 ,
  407  
  408           //  Hold (or  release) t he ready e vent
  409           ho ldReady: f unction( h old ) {
  410                    if (  hold ) {
  411                             jQuery .readyWait ++;
  412                    } el se {
  413                             jQuery .ready( tr ue );
  414                    }
  415           },
  416  
  417           //  Handle wh en the DOM  is ready
  418           re ady: funct ion( wait  ) {
  419                    // E ither a re leased hol d or an DO Mready/loa d event an d not yet  ready
  420                    if (  (wait ===  true && ! --jQuery.r eadyWait)  || (wait ! == true &&  !jQuery.i sReady) )  {
  421                             // Mak e sure bod y exists,  at least,  in case IE  gets a li ttle overz ealous (ti cket #5443 ).
  422                             if ( ! document.b ody ) {
  423                                      return s etTimeout(  jQuery.re ady, 1 );
  424                             }
  425  
  426                             // Rem ember that  the DOM i s ready
  427                             jQuery .isReady =  true;
  428  
  429                             // If  a normal D OM Ready e vent fired , decremen t, and wai t if need  be
  430                             if ( w ait !== tr ue && --jQ uery.ready Wait > 0 )  {
  431                                      return;
  432                             }
  433  
  434                             // If  there are  functions  bound, to  execute
  435                             readyL ist.fireWi th( docume nt, [ jQue ry ] );
  436  
  437                             // Tri gger any b ound ready  events
  438                             if ( j Query.fn.t rigger ) {
  439                                      jQuery(  document ) .trigger(  "ready" ). off( "read y" );
  440                             }
  441                    }
  442           },
  443  
  444           bi ndReady: f unction()  {
  445                    if (  readyList  ) {
  446                             return ;
  447                    }
  448  
  449                    read yList = jQ uery.Callb acks( "onc e memory"  );
  450  
  451                    // C atch cases  where $(d ocument).r eady() is  called aft er the
  452                    // b rowser eve nt has alr eady occur red.
  453                    if (  document. readyState  === "comp lete" ) {
  454                             // Han dle it asy nchronousl y to allow  scripts t he opportu nity to de lay ready
  455                             return  setTimeou t( jQuery. ready, 1 ) ;
  456                    }
  457  
  458                    // M ozilla, Op era and we bkit night lies curre ntly suppo rt this ev ent
  459                    if (  document. addEventLi stener ) {
  460                             // Use  the handy  event cal lback
  461                             docume nt.addEven tListener(  "DOMConte ntLoaded",  DOMConten tLoaded, f alse );
  462  
  463                             // A f allback to  window.on load, that  will alwa ys work
  464                             window .addEventL istener( " load", jQu ery.ready,  false );
  465  
  466                    // I f IE event  model is  used
  467                    } el se if ( do cument.att achEvent )  {
  468                             // ens ure firing  before on load,
  469                             // may be late bu t safe als o for ifra mes
  470                             docume nt.attachE vent( "onr eadystatec hange", DO MContentLo aded );
  471  
  472                             // A f allback to  window.on load, that  will alwa ys work
  473                             window .attachEve nt( "onloa d", jQuery .ready );
  474  
  475                             // If  IE and not  a frame
  476                             // con tinually c heck to se e if the d ocument is  ready
  477                             var to plevel = f alse;
  478  
  479                             try {
  480                                      toplevel  = window. frameEleme nt == null ;
  481                             } catc h(e) {}
  482  
  483                             if ( d ocument.do cumentElem ent.doScro ll && topl evel ) {
  484                                      doScroll Check();
  485                             }
  486                    }
  487           },
  488  
  489           //  See test/ unit/core. js for det ails conce rning isFu nction.
  490           //  Since ver sion 1.3,  DOM method s and func tions like  alert
  491           //  aren't su pported. T hey return  false on  IE (#2968) .
  492           is Function:  function(  obj ) {
  493                    retu rn jQuery. type(obj)  === "funct ion";
  494           },
  495  
  496           is Array: Arr ay.isArray  || functi on( obj )  {
  497                    retu rn jQuery. type(obj)  === "array ";
  498           },
  499  
  500           //  A crude w ay of dete rmining if  an object  is a wind ow
  501           is Window: fu nction( ob j ) {
  502                    retu rn obj &&  typeof obj  === "obje ct" && "se tInterval"  in obj;
  503           },
  504  
  505           is Numeric: f unction( o bj ) {
  506                    retu rn !isNaN(  parseFloa t(obj) ) & & isFinite ( obj );
  507           },
  508  
  509           ty pe: functi on( obj )  {
  510                    retu rn obj ==  null ?
  511                             String ( obj ) :
  512                             class2 type[ toSt ring.call( obj) ] ||  "object";
  513           },
  514  
  515           is PlainObjec t: functio n( obj ) {
  516                    // M ust be an  Object.
  517                    // B ecause of  IE, we als o have to  check the  presence o f the cons tructor pr operty.
  518                    // M ake sure t hat DOM no des and wi ndow objec ts don't p ass throug h, as well
  519                    if (  !obj || j Query.type (obj) !==  "object" | | obj.node Type || jQ uery.isWin dow( obj )  ) {
  520                             return  false;
  521                    }
  522  
  523                    try  {
  524                             // Not  own const ructor pro perty must  be Object
  525                             if ( o bj.constru ctor &&
  526                                      !hasOwn. call(obj,  "construct or") &&
  527                                      !hasOwn. call(obj.c onstructor .prototype , "isProto typeOf") )  {
  528                                      return f alse;
  529                             }
  530                    } ca tch ( e )  {
  531                             // IE8 ,9 Will th row except ions on ce rtain host  objects # 9897
  532                             return  false;
  533                    }
  534  
  535                    // O wn propert ies are en umerated f irstly, so  to speed  up,
  536                    // i f last one  is own, t hen all pr operties a re own.
  537  
  538                    var  key;
  539                    for  ( key in o bj ) {}
  540  
  541                    retu rn key ===  undefined  || hasOwn .call( obj , key );
  542           },
  543  
  544           is EmptyObjec t: functio n( obj ) {
  545                    for  ( var name  in obj )  {
  546                             return  false;
  547                    }
  548                    retu rn true;
  549           },
  550  
  551           er ror: funct ion( msg )  {
  552                    thro w new Erro r( msg );
  553           },
  554  
  555           pa rseJSON: f unction( d ata ) {
  556                    if (  typeof da ta !== "st ring" || ! data ) {
  557                             return  null;
  558                    }
  559  
  560                    // M ake sure l eading/tra iling whit espace is  removed (I E can't ha ndle it)
  561                    data  = jQuery. trim( data  );
  562  
  563                    // A ttempt to  parse usin g the nati ve JSON pa rser first
  564                    if (  window.JS ON && wind ow.JSON.pa rse ) {
  565                             return  window.JS ON.parse(  data );
  566                    }
  567  
  568                    // M ake sure t he incomin g data is  actual JSO N
  569                    // L ogic borro wed from h ttp://json .org/json2 .js
  570                    if (  rvalidcha rs.test( d ata.replac e( rvalide scape, "@"  )
  571                             .repla ce( rvalid tokens, "] " )
  572                             .repla ce( rvalid braces, "" )) ) {
  573  
  574                             return  ( new Fun ction( "re turn " + d ata ) )();
  575  
  576                    }
  577                    jQue ry.error(  "Invalid J SON: " + d ata );
  578           },
  579  
  580           //  Cross-bro wser xml p arsing
  581           pa rseXML: fu nction( da ta ) {
  582                    var  xml, tmp;
  583                    try  {
  584                             if ( w indow.DOMP arser ) {  // Standar d
  585                                      tmp = ne w DOMParse r();
  586                                      xml = tm p.parseFro mString( d ata , "tex t/xml" );
  587                             } else  { // IE
  588                                      xml = ne w ActiveXO bject( "Mi crosoft.XM LDOM" );
  589                                      xml.asyn c = "false ";
  590                                      xml.load XML( data  );
  591                             }
  592                    } ca tch( e ) {
  593                             xml =  undefined;
  594                    }
  595                    if (  !xml || ! xml.docume ntElement  || xml.get ElementsBy TagName( " parsererro r" ).lengt h ) {
  596                             jQuery .error( "I nvalid XML : " + data  );
  597                    }
  598                    retu rn xml;
  599           },
  600  
  601           no op: functi on() {},
  602  
  603           //  Evaluates  a script  in a globa l context
  604           //  Workaroun ds based o n findings  by Jim Dr iscoll
  605           //  http://we blogs.java .net/blog/ driscoll/a rchive/200 9/09/08/ev al-javascr ipt-global -context
  606           gl obalEval:  function(  data ) {
  607                    if (  data && r notwhite.t est( data  ) ) {
  608                             // We  use execSc ript on In ternet Exp lorer
  609                             // We  use an ano nymous fun ction so t hat contex t is windo w
  610                             // rat her than j Query in F irefox
  611                             ( wind ow.execScr ipt || fun ction( dat a ) {
  612                                      window[  "eval" ].c all( windo w, data );
  613                             } )( d ata );
  614                    }
  615           },
  616  
  617           //  Convert d ashed to c amelCase;  used by th e css and  data modul es
  618           //  Microsoft  forgot to  hump thei r vendor p refix (#95 72)
  619           ca melCase: f unction( s tring ) {
  620                    retu rn string. replace( r msPrefix,  "ms-" ).re place( rda shAlpha, f camelCase  );
  621           },
  622  
  623           no deName: fu nction( el em, name )  {
  624                    retu rn elem.no deName &&  elem.nodeN ame.toUppe rCase() == = name.toU pperCase() ;
  625           },
  626  
  627           //  args is f or interna l usage on ly
  628           ea ch: functi on( object , callback , args ) {
  629                    var  name, i =  0,
  630                             length  = object. length,
  631                             isObj  = length = == undefin ed || jQue ry.isFunct ion( objec t );
  632  
  633                    if (  args ) {
  634                             if ( i sObj ) {
  635                                      for ( na me in obje ct ) {
  636                                               if ( callb ack.apply(  object[ n ame ], arg s ) === fa lse ) {
  637                                                       br eak;
  638                                               }
  639                                      }
  640                             } else  {
  641                                      for ( ;  i < length ; ) {
  642                                               if ( callb ack.apply(  object[ i ++ ], args  ) === fal se ) {
  643                                                       br eak;
  644                                               }
  645                                      }
  646                             }
  647  
  648                    // A  special,  fast, case  for the m ost common  use of ea ch
  649                    } el se {
  650                             if ( i sObj ) {
  651                                      for ( na me in obje ct ) {
  652                                               if ( callb ack.call(  object[ na me ], name , object[  name ] ) = == false )  {
  653                                                       br eak;
  654                                               }
  655                                      }
  656                             } else  {
  657                                      for ( ;  i < length ; ) {
  658                                               if ( callb ack.call(  object[ i  ], i, obje ct[ i++ ]  ) === fals e ) {
  659                                                       br eak;
  660                                               }
  661                                      }
  662                             }
  663                    }
  664  
  665                    retu rn object;
  666           },
  667  
  668           //  Use nativ e String.t rim functi on whereve r possible
  669           tr im: trim ?
  670                    func tion( text  ) {
  671                             return  text == n ull ?
  672                                      "" :
  673                                      trim.cal l( text );
  674                    } :
  675  
  676                    // O therwise u se our own  trimming  functional ity
  677                    func tion( text  ) {
  678                             return  text == n ull ?
  679                                      "" :
  680                                      text.toS tring().re place( tri mLeft, ""  ).replace(  trimRight , "" );
  681                    },
  682  
  683           //  results i s for inte rnal usage  only
  684           ma keArray: f unction( a rray, resu lts ) {
  685                    var  ret = resu lts || [];
  686  
  687                    if (  array !=  null ) {
  688                             // The  window, s trings (an d function s) also ha ve 'length '
  689                             // Twe aked logic  slightly  to handle  Blackberry  4.7 RegEx p issues # 6930
  690                             var ty pe = jQuer y.type( ar ray );
  691  
  692                             if ( a rray.lengt h == null  || type == = "string"  || type = == "functi on" || typ e === "reg exp" || jQ uery.isWin dow( array  ) ) {
  693                                      push.cal l( ret, ar ray );
  694                             } else  {
  695                                      jQuery.m erge( ret,  array );
  696                             }
  697                    }
  698  
  699                    retu rn ret;
  700           },
  701  
  702           in Array: fun ction( ele m, array,  i ) {
  703                    var  len;
  704  
  705                    if (  array ) {
  706                             if ( i ndexOf ) {
  707                                      return i ndexOf.cal l( array,  elem, i );
  708                             }
  709  
  710                             len =  array.leng th;
  711                             i = i  ? i < 0 ?  Math.max(  0, len + i  ) : i : 0 ;
  712  
  713                             for (  ; i < len;  i++ ) {
  714                                      // Skip  accessing  in sparse  arrays
  715                                      if ( i i n array &&  array[ i  ] === elem  ) {
  716                                               return i;
  717                                      }
  718                             }
  719                    }
  720  
  721                    retu rn -1;
  722           },
  723  
  724           me rge: funct ion( first , second )  {
  725                    var  i = first. length,
  726                             j = 0;
  727  
  728                    if (  typeof se cond.lengt h === "num ber" ) {
  729                             for (  var l = se cond.lengt h; j < l;  j++ ) {
  730                                      first[ i ++ ] = sec ond[ j ];
  731                             }
  732  
  733                    } el se {
  734                             while  ( second[j ] !== unde fined ) {
  735                                      first[ i ++ ] = sec ond[ j++ ] ;
  736                             }
  737                    }
  738  
  739                    firs t.length =  i;
  740  
  741                    retu rn first;
  742           },
  743  
  744           gr ep: functi on( elems,  callback,  inv ) {
  745                    var  ret = [],  retVal;
  746                    inv  = !!inv;
  747  
  748                    // G o through  the array,  only savi ng the ite ms
  749                    // t hat pass t he validat or functio n
  750                    for  ( var i =  0, length  = elems.le ngth; i <  length; i+ + ) {
  751                             retVal  = !!callb ack( elems [ i ], i ) ;
  752                             if ( i nv !== ret Val ) {
  753                                      ret.push ( elems[ i  ] );
  754                             }
  755                    }
  756  
  757                    retu rn ret;
  758           },
  759  
  760           //  arg is fo r internal  usage onl y
  761           ma p: functio n( elems,  callback,  arg ) {
  762                    var  value, key , ret = [] ,
  763                             i = 0,
  764                             length  = elems.l ength,
  765                             // jqu ery object s are trea ted as arr ays
  766                             isArra y = elems  instanceof  jQuery ||  length != = undefine d && typeo f length = == "number " && ( ( l ength > 0  && elems[  0 ] && ele ms[ length  -1 ] ) ||  length == = 0 || jQu ery.isArra y( elems )  ) ;
  767  
  768                    // G o through  the array,  translati ng each of  the items  to their
  769                    if (  isArray )  {
  770                             for (  ; i < leng th; i++ )  {
  771                                      value =  callback(  elems[ i ] , i, arg ) ;
  772  
  773                                      if ( val ue != null  ) {
  774                                               ret[ ret.l ength ] =  value;
  775                                      }
  776                             }
  777  
  778                    // G o through  every key  on the obj ect,
  779                    } el se {
  780                             for (  key in ele ms ) {
  781                                      value =  callback(  elems[ key  ], key, a rg );
  782  
  783                                      if ( val ue != null  ) {
  784                                               ret[ ret.l ength ] =  value;
  785                                      }
  786                             }
  787                    }
  788  
  789                    // F latten any  nested ar rays
  790                    retu rn ret.con cat.apply(  [], ret ) ;
  791           },
  792  
  793           //  A global  GUID count er for obj ects
  794           gu id: 1,
  795  
  796           //  Bind a fu nction to  a context,  optionall y partiall y applying  any
  797           //  arguments .
  798           pr oxy: funct ion( fn, c ontext ) {
  799                    if (  typeof co ntext ===  "string" )  {
  800                             var tm p = fn[ co ntext ];
  801                             contex t = fn;
  802                             fn = t mp;
  803                    }
  804  
  805                    // Q uick check  to determ ine if tar get is cal lable, in  the spec
  806                    // t his throws  a TypeErr or, but we  will just  return un defined.
  807                    if (  !jQuery.i sFunction(  fn ) ) {
  808                             return  undefined ;
  809                    }
  810  
  811                    // S imulated b ind
  812                    var  args = sli ce.call( a rguments,  2 ),
  813                             proxy  = function () {
  814                                      return f n.apply( c ontext, ar gs.concat(  slice.cal l( argumen ts ) ) );
  815                             };
  816  
  817                    // S et the gui d of uniqu e handler  to the sam e of origi nal handle r, so it c an be remo ved
  818                    prox y.guid = f n.guid = f n.guid ||  proxy.guid  || jQuery .guid++;
  819  
  820                    retu rn proxy;
  821           },
  822  
  823           //  Mutifunct ional meth od to get  and set va lues to a  collection
  824           //  The value /s can opt ionally be  executed  if it's a  function
  825           ac cess: func tion( elem s, key, va lue, exec,  fn, pass  ) {
  826                    var  length = e lems.lengt h;
  827  
  828                    // S etting man y attribut es
  829                    if (  typeof ke y === "obj ect" ) {
  830                             for (  var k in k ey ) {
  831                                      jQuery.a ccess( ele ms, k, key [k], exec,  fn, value  );
  832                             }
  833                             return  elems;
  834                    }
  835  
  836                    // S etting one  attribute
  837                    if (  value !==  undefined  ) {
  838                             // Opt ionally, f unction va lues get e xecuted if  exec is t rue
  839                             exec =  !pass &&  exec && jQ uery.isFun ction(valu e);
  840  
  841                             for (  var i = 0;  i < lengt h; i++ ) {
  842                                      fn( elem s[i], key,  exec ? va lue.call(  elems[i],  i, fn( ele ms[i], key  ) ) : val ue, pass ) ;
  843                             }
  844  
  845                             return  elems;
  846                    }
  847  
  848                    // G etting an  attribute
  849                    retu rn length  ? fn( elem s[0], key  ) : undefi ned;
  850           },
  851  
  852           no w: functio n() {
  853                    retu rn ( new D ate() ).ge tTime();
  854           },
  855  
  856           //  Use of jQ uery.brows er is frow ned upon.
  857           //  More deta ils: http: //docs.jqu ery.com/Ut ilities/jQ uery.brows er
  858           ua Match: fun ction( ua  ) {
  859                    ua =  ua.toLowe rCase();
  860  
  861                    var  match = rw ebkit.exec ( ua ) ||
  862                             ropera .exec( ua  ) ||
  863                             rmsie. exec( ua )  ||
  864                             ua.ind exOf("comp atible") <  0 && rmoz illa.exec(  ua ) ||
  865                             [];
  866  
  867                    retu rn { brows er: match[ 1] || "",  version: m atch[2] ||  "0" };
  868           },
  869  
  870           su b: functio n() {
  871                    func tion jQuer ySub( sele ctor, cont ext ) {
  872                             return  new jQuer ySub.fn.in it( select or, contex t );
  873                    }
  874                    jQue ry.extend(  true, jQu erySub, th is );
  875                    jQue rySub.supe rclass = t his;
  876                    jQue rySub.fn =  jQuerySub .prototype  = this();
  877                    jQue rySub.fn.c onstructor  = jQueryS ub;
  878                    jQue rySub.sub  = this.sub ;
  879                    jQue rySub.fn.i nit = func tion init(  selector,  context )  {
  880                             if ( c ontext &&  context in stanceof j Query && ! (context i nstanceof  jQuerySub)  ) {
  881                                      context  = jQuerySu b( context  );
  882                             }
  883  
  884                             return  jQuery.fn .init.call ( this, se lector, co ntext, roo tjQuerySub  );
  885                    };
  886                    jQue rySub.fn.i nit.protot ype = jQue rySub.fn;
  887                    var  rootjQuery Sub = jQue rySub(docu ment);
  888                    retu rn jQueryS ub;
  889           },
  890  
  891           br owser: {}
  892   });
  893  
  894   // Populat e the clas s2type map
  895   jQuery.eac h("Boolean  Number St ring Funct ion Array  Date RegEx p Object". split(" ") , function (i, name)  {
  896           cl ass2type[  "[object "  + name +  "]" ] = na me.toLower Case();
  897   });
  898  
  899   browserMat ch = jQuer y.uaMatch(  userAgent  );
  900   if ( brows erMatch.br owser ) {
  901           jQ uery.brows er[ browse rMatch.bro wser ] = t rue;
  902           jQ uery.brows er.version  = browser Match.vers ion;
  903   }
  904  
  905   // Depreca ted, use j Query.brow ser.webkit  instead
  906   if ( jQuer y.browser. webkit ) {
  907           jQ uery.brows er.safari  = true;
  908   }
  909  
  910   // IE does n't match  non-breaki ng spaces  with \s
  911   if ( rnotw hite.test(  "\xA0" )  ) {
  912           tr imLeft = / ^[\s\xA0]+ /;
  913           tr imRight =  /[\s\xA0]+ $/;
  914   }
  915  
  916   // All jQu ery object s should p oint back  to these
  917   rootjQuery  = jQuery( document);
  918  
  919   // Cleanup  functions  for the d ocument re ady method
  920   if ( docum ent.addEve ntListener  ) {
  921           DO MContentLo aded = fun ction() {
  922                    docu ment.remov eEventList ener( "DOM ContentLoa ded", DOMC ontentLoad ed, false  );
  923                    jQue ry.ready() ;
  924           };
  925  
  926   } else if  ( document .attachEve nt ) {
  927           DO MContentLo aded = fun ction() {
  928                    // M ake sure b ody exists , at least , in case  IE gets a  little ove rzealous ( ticket #54 43).
  929                    if (  document. readyState  === "comp lete" ) {
  930                             docume nt.detachE vent( "onr eadystatec hange", DO MContentLo aded );
  931                             jQuery .ready();
  932                    }
  933           };
  934   }
  935  
  936   // The DOM  ready che ck for Int ernet Expl orer
  937   function d oScrollChe ck() {
  938           if  ( jQuery. isReady )  {
  939                    retu rn;
  940           }
  941  
  942           tr y {
  943                    // I f IE is us ed, use th e trick by  Diego Per ini
  944                    // h ttp://java script.nwb ox.com/IEC ontentLoad ed/
  945                    docu ment.docum entElement .doScroll( "left");
  946           }  catch(e) {
  947                    setT imeout( do ScrollChec k, 1 );
  948                    retu rn;
  949           }
  950  
  951           //  and execu te any wai ting funct ions
  952           jQ uery.ready ();
  953   }
  954  
  955   return jQu ery;
  956  
  957   })();
  958  
  959  
  960   // String  to Object  flags form at cache
  961   var flagsC ache = {};
  962  
  963   // Convert  String-fo rmatted fl ags into O bject-form atted ones  and store  in cache
  964   function c reateFlags ( flags )  {
  965           va r object =  flagsCach e[ flags ]  = {},
  966                    i, l ength;
  967           fl ags = flag s.split( / \s+/ );
  968           fo r ( i = 0,  length =  flags.leng th; i < le ngth; i++  ) {
  969                    obje ct[ flags[ i] ] = tru e;
  970           }
  971           re turn objec t;
  972   }
  973  
  974   /*
  975    * Create  a callback  list usin g the foll owing para meters:
  976    *
  977    *      fl ags:  an o ptional li st of spac e-separate d flags th at will ch ange how
  978    *                        the ca llback lis t behaves
  979    *
  980    * By defa ult a call back list  will act l ike an eve nt callbac k list and  can be
  981    * "fired"  multiple  times.
  982    *
  983    * Possibl e flags:
  984    *
  985    *      on ce:                     will ens ure the ca llback lis t can only  be fired  once (like  a Deferre d)
  986    *
  987    *      me mory:                   will kee p track of  previous  values and  will call  any callb ack added
  988    *                                          after the  list has b een fired  right away  with the  latest "me morized"
  989    *                                          values (li ke a Defer red)
  990    *
  991    *      un ique:                   will ens ure a call back can o nly be add ed once (n o duplicat e in the l ist)
  992    *
  993    *      st opOnFalse:     interr upt callin gs when a  callback r eturns fal se
  994    *
  995    */
  996   jQuery.Cal lbacks = f unction( f lags ) {
  997  
  998           //  Convert f lags from  String-for matted to  Object-for matted
  999           //  (we check  in cache  first)
  1000           fl ags = flag s ? ( flag sCache[ fl ags ] || c reateFlags ( flags )  ) : {};
  1001  
  1002           va r // Actua l callback  list
  1003                    list  = [],
  1004                    // S tack of fi re calls f or repeata ble lists
  1005                    stac k = [],
  1006                    // L ast fire v alue (for  non-forget table list s)
  1007                    memo ry,
  1008                    // F lag to kno w if list  is current ly firing
  1009                    firi ng,
  1010                    // F irst callb ack to fir e (used in ternally b y add and  fireWith)
  1011                    firi ngStart,
  1012                    // E nd of the  loop when  firing
  1013                    firi ngLength,
  1014                    // I ndex of cu rrently fi ring callb ack (modif ied by rem ove if nee ded)
  1015                    firi ngIndex,
  1016                    // A dd one or  several ca llbacks to  the list
  1017                    add  = function ( args ) {
  1018                             var i,
  1019                                      length,
  1020                                      elem,
  1021                                      type,
  1022                                      actual;
  1023                             for (  i = 0, len gth = args .length; i  < length;  i++ ) {
  1024                                      elem = a rgs[ i ];
  1025                                      type = j Query.type ( elem );
  1026                                      if ( typ e === "arr ay" ) {
  1027                                               // Inspect  recursive ly
  1028                                               add( elem  );
  1029                                      } else i f ( type = == "functi on" ) {
  1030                                               // Add if  not in uni que mode a nd callbac k is not i n
  1031                                               if ( !flag s.unique | | !self.ha s( elem )  ) {
  1032                                                       li st.push( e lem );
  1033                                               }
  1034                                      }
  1035                             }
  1036                    },
  1037                    // F ire callba cks
  1038                    fire  = functio n( context , args ) {
  1039                             args =  args || [ ];
  1040                             memory  = !flags. memory ||  [ context,  args ];
  1041                             firing  = true;
  1042                             firing Index = fi ringStart  || 0;
  1043                             firing Start = 0;
  1044                             firing Length = l ist.length ;
  1045                             for (  ; list &&  firingInde x < firing Length; fi ringIndex+ + ) {
  1046                                      if ( lis t[ firingI ndex ].app ly( contex t, args )  === false  && flags.s topOnFalse  ) {
  1047                                               memory = t rue; // Ma rk as halt ed
  1048                                               break;
  1049                                      }
  1050                             }
  1051                             firing  = false;
  1052                             if ( l ist ) {
  1053                                      if ( !fl ags.once )  {
  1054                                               if ( stack  && stack. length ) {
  1055                                                       me mory = sta ck.shift() ;
  1056                                                       se lf.fireWit h( memory[  0 ], memo ry[ 1 ] );
  1057                                               }
  1058                                      } else i f ( memory  === true  ) {
  1059                                               self.disab le();
  1060                                      } else {
  1061                                               list = [];
  1062                                      }
  1063                             }
  1064                    },
  1065                    // A ctual Call backs obje ct
  1066                    self  = {
  1067                             // Add  a callbac k or a col lection of  callbacks  to the li st
  1068                             add: f unction()  {
  1069                                      if ( lis t ) {
  1070                                               var length  = list.le ngth;
  1071                                               add( argum ents );
  1072                                               // Do we n eed to add  the callb acks to th e
  1073                                               // current  firing ba tch?
  1074                                               if ( firin g ) {
  1075                                                       fi ringLength  = list.le ngth;
  1076                                               // With me mory, if w e're not f iring then
  1077                                               // we shou ld call ri ght away,  unless pre vious
  1078                                               // firing  was halted  (stopOnFa lse)
  1079                                               } else if  ( memory & & memory ! == true )  {
  1080                                                       fi ringStart  = length;
  1081                                                       fi re( memory [ 0 ], mem ory[ 1 ] ) ;
  1082                                               }
  1083                                      }
  1084                                      return t his;
  1085                             },
  1086                             // Rem ove a call back from  the list
  1087                             remove : function () {
  1088                                      if ( lis t ) {
  1089                                               var args =  arguments ,
  1090                                                       ar gIndex = 0 ,
  1091                                                       ar gLength =  args.lengt h;
  1092                                               for ( ; ar gIndex < a rgLength ;  argIndex+ + ) {
  1093                                                       fo r ( var i  = 0; i < l ist.length ; i++ ) {
  1094                                                                if (  args[ arg Index ] == = list[ i  ] ) {
  1095                                                                         // Han dle firing Index and  firingLeng th
  1096                                                                         if ( f iring ) {
  1097                                                                                  if ( i < = firingLe ngth ) {
  1098                                                                                           firingLeng th--;
  1099                                                                                           if ( i <=  firingInde x ) {
  1100                                                                                                   fi ringIndex- -;
  1101                                                                                           }
  1102                                                                                  }
  1103                                                                         }
  1104                                                                         // Rem ove the el ement
  1105                                                                         list.s plice( i-- , 1 );
  1106                                                                         // If  we have so me unicity  property  then
  1107                                                                         // we  only need  to do this  once
  1108                                                                         if ( f lags.uniqu e ) {
  1109                                                                                  break;
  1110                                                                         }
  1111                                                                }
  1112                                                       }
  1113                                               }
  1114                                      }
  1115                                      return t his;
  1116                             },
  1117                             // Con trol if a  given call back is in  the list
  1118                             has: f unction( f n ) {
  1119                                      if ( lis t ) {
  1120                                               var i = 0,
  1121                                                       le ngth = lis t.length;
  1122                                               for ( ; i  < length;  i++ ) {
  1123                                                       if  ( fn ===  list[ i ]  ) {
  1124                                                                retu rn true;
  1125                                                       }
  1126                                               }
  1127                                      }
  1128                                      return f alse;
  1129                             },
  1130                             // Rem ove all ca llbacks fr om the lis t
  1131                             empty:  function( ) {
  1132                                      list = [ ];
  1133                                      return t his;
  1134                             },
  1135                             // Hav e the list  do nothin g anymore
  1136                             disabl e: functio n() {
  1137                                      list = s tack = mem ory = unde fined;
  1138                                      return t his;
  1139                             },
  1140                             // Is  it disable d?
  1141                             disabl ed: functi on() {
  1142                                      return ! list;
  1143                             },
  1144                             // Loc k the list  in its cu rrent stat e
  1145                             lock:  function()  {
  1146                                      stack =  undefined;
  1147                                      if ( !me mory || me mory === t rue ) {
  1148                                               self.disab le();
  1149                                      }
  1150                                      return t his;
  1151                             },
  1152                             // Is  it locked?
  1153                             locked : function () {
  1154                                      return ! stack;
  1155                             },
  1156                             // Cal l all call backs with  the given  context a nd argumen ts
  1157                             fireWi th: functi on( contex t, args )  {
  1158                                      if ( sta ck ) {
  1159                                               if ( firin g ) {
  1160                                                       if  ( !flags. once ) {
  1161                                                                stac k.push( [  context, a rgs ] );
  1162                                                       }
  1163                                               } else if  ( !( flags .once && m emory ) )  {
  1164                                                       fi re( contex t, args );
  1165                                               }
  1166                                      }
  1167                                      return t his;
  1168                             },
  1169                             // Cal l all the  callbacks  with the g iven argum ents
  1170                             fire:  function()  {
  1171                                      self.fir eWith( thi s, argumen ts );
  1172                                      return t his;
  1173                             },
  1174                             // To  know if th e callback s have alr eady been  called at  least once
  1175                             fired:  function( ) {
  1176                                      return ! !memory;
  1177                             }
  1178                    };
  1179  
  1180           re turn self;
  1181   };
  1182  
  1183  
  1184  
  1185  
  1186   var // Sta tic refere nce to sli ce
  1187           sl iceDeferre d = [].sli ce;
  1188  
  1189   jQuery.ext end({
  1190  
  1191           De ferred: fu nction( fu nc ) {
  1192                    var  doneList =  jQuery.Ca llbacks( " once memor y" ),
  1193                             failLi st = jQuer y.Callback s( "once m emory" ),
  1194                             progre ssList = j Query.Call backs( "me mory" ),
  1195                             state  = "pending ",
  1196                             lists  = {
  1197                                      resolve:  doneList,
  1198                                      reject:  failList,
  1199                                      notify:  progressLi st
  1200                             },
  1201                             promis e = {
  1202                                      done: do neList.add ,
  1203                                      fail: fa ilList.add ,
  1204                                      progress : progress List.add,
  1205  
  1206                                      state: f unction()  {
  1207                                               return sta te;
  1208                                      },
  1209  
  1210                                      // Depre cated
  1211                                      isResolv ed: doneLi st.fired,
  1212                                      isReject ed: failLi st.fired,
  1213  
  1214                                      then: fu nction( do neCallback s, failCal lbacks, pr ogressCall backs ) {
  1215                                               deferred.d one( doneC allbacks ) .fail( fai lCallbacks  ).progres s( progres sCallbacks  );
  1216                                               return thi s;
  1217                                      },
  1218                                      always:  function()  {
  1219                                               deferred.d one.apply(  deferred,  arguments  ).fail.ap ply( defer red, argum ents );
  1220                                               return thi s;
  1221                                      },
  1222                                      pipe: fu nction( fn Done, fnFa il, fnProg ress ) {
  1223                                               return jQu ery.Deferr ed(functio n( newDefe r ) {
  1224                                                       jQ uery.each(  {
  1225                                                                done : [ fnDone , "resolve " ],
  1226                                                                fail : [ fnFail , "reject"  ],
  1227                                                                prog ress: [ fn Progress,  "notify" ]
  1228                                                       },  function(  handler,  data ) {
  1229                                                                var  fn = data[  0 ],
  1230                                                                         action  = data[ 1  ],
  1231                                                                         return ed;
  1232                                                                if (  jQuery.is Function(  fn ) ) {
  1233                                                                         deferr ed[ handle r ](functi on() {
  1234                                                                                  returned  = fn.appl y( this, a rguments ) ;
  1235                                                                                  if ( ret urned && j Query.isFu nction( re turned.pro mise ) ) {
  1236                                                                                           returned.p romise().t hen( newDe fer.resolv e, newDefe r.reject,  newDefer.n otify );
  1237                                                                                  } else {
  1238                                                                                           newDefer[  action + " With" ]( t his === de ferred ? n ewDefer :  this, [ re turned ] ) ;
  1239                                                                                  }
  1240                                                                         });
  1241                                                                } el se {
  1242                                                                         deferr ed[ handle r ]( newDe fer[ actio n ] );
  1243                                                                }
  1244                                                       }) ;
  1245                                               }).promise ();
  1246                                      },
  1247                                      // Get a  promise f or this de ferred
  1248                                      // If ob j is provi ded, the p romise asp ect is add ed to the  object
  1249                                      promise:  function(  obj ) {
  1250                                               if ( obj = = null ) {
  1251                                                       ob j = promis e;
  1252                                               } else {
  1253                                                       fo r ( var ke y in promi se ) {
  1254                                                                obj[  key ] = p romise[ ke y ];
  1255                                                       }
  1256                                               }
  1257                                               return obj ;
  1258                                      }
  1259                             },
  1260                             deferr ed = promi se.promise ({}),
  1261                             key;
  1262  
  1263                    for  ( key in l ists ) {
  1264                             deferr ed[ key ]  = lists[ k ey ].fire;
  1265                             deferr ed[ key +  "With" ] =  lists[ ke y ].fireWi th;
  1266                    }
  1267  
  1268                    // H andle stat e
  1269                    defe rred.done(  function( ) {
  1270                             state  = "resolve d";
  1271                    }, f ailList.di sable, pro gressList. lock ).fai l( functio n() {
  1272                             state  = "rejecte d";
  1273                    }, d oneList.di sable, pro gressList. lock );
  1274  
  1275                    // C all given  func if an y
  1276                    if (  func ) {
  1277                             func.c all( defer red, defer red );
  1278                    }
  1279  
  1280                    // A ll done!
  1281                    retu rn deferre d;
  1282           },
  1283  
  1284           //  Deferred  helper
  1285           wh en: functi on( firstP aram ) {
  1286                    var  args = sli ceDeferred .call( arg uments, 0  ),
  1287                             i = 0,
  1288                             length  = args.le ngth,
  1289                             pValue s = new Ar ray( lengt h ),
  1290                             count  = length,
  1291                             pCount  = length,
  1292                             deferr ed = lengt h <= 1 &&  firstParam  && jQuery .isFunctio n( firstPa ram.promis e ) ?
  1293                                      firstPar am :
  1294                                      jQuery.D eferred(),
  1295                             promis e = deferr ed.promise ();
  1296                    func tion resol veFunc( i  ) {
  1297                             return  function(  value ) {
  1298                                      args[ i  ] = argume nts.length  > 1 ? sli ceDeferred .call( arg uments, 0  ) : value;
  1299                                      if ( !(  --count )  ) {
  1300                                               deferred.r esolveWith ( deferred , args );
  1301                                      }
  1302                             };
  1303                    }
  1304                    func tion progr essFunc( i  ) {
  1305                             return  function(  value ) {
  1306                                      pValues[  i ] = arg uments.len gth > 1 ?  sliceDefer red.call(  arguments,  0 ) : val ue;
  1307                                      deferred .notifyWit h( promise , pValues  );
  1308                             };
  1309                    }
  1310                    if (  length >  1 ) {
  1311                             for (  ; i < leng th; i++ )  {
  1312                                      if ( arg s[ i ] &&  args[ i ]. promise &&  jQuery.is Function(  args[ i ]. promise )  ) {
  1313                                               args[ i ]. promise(). then( reso lveFunc(i) , deferred .reject, p rogressFun c(i) );
  1314                                      } else {
  1315                                               --count;
  1316                                      }
  1317                             }
  1318                             if ( ! count ) {
  1319                                      deferred .resolveWi th( deferr ed, args ) ;
  1320                             }
  1321                    } el se if ( de ferred !==  firstPara m ) {
  1322                             deferr ed.resolve With( defe rred, leng th ? [ fir stParam ]  : [] );
  1323                    }
  1324                    retu rn promise ;
  1325           }
  1326   });
  1327  
  1328  
  1329  
  1330  
  1331   jQuery.sup port = (fu nction() {
  1332  
  1333           va r support,
  1334                    all,
  1335                    a,
  1336                    sele ct,
  1337                    opt,
  1338                    inpu t,
  1339                    marg inDiv,
  1340                    frag ment,
  1341                    tds,
  1342                    even ts,
  1343                    even tName,
  1344                    i,
  1345                    isSu pported,
  1346                    div  = document .createEle ment( "div " ),
  1347                    docu mentElemen t = docume nt.documen tElement;
  1348  
  1349           //  Prelimina ry tests
  1350           di v.setAttri bute("clas sName", "t ");
  1351           di v.innerHTM L = "   <l ink/><tabl e></table> <a href='/ a' style=' top:1px;fl oat:left;o pacity:.55 ;'>a</a><i nput type= 'checkbox' />";
  1352  
  1353           al l = div.ge tElementsB yTagName(  "*" );
  1354           a  = div.getE lementsByT agName( "a " )[ 0 ];
  1355  
  1356           //  Can't get  basic tes t support
  1357           if  ( !all ||  !all.leng th || !a )  {
  1358                    retu rn {};
  1359           }
  1360  
  1361           //  First bat ch of supp orts tests
  1362           se lect = doc ument.crea teElement(  "select"  );
  1363           op t = select .appendChi ld( docume nt.createE lement("op tion") );
  1364           in put = div. getElement sByTagName ( "input"  )[ 0 ];
  1365  
  1366           su pport = {
  1367                    // I E strips l eading whi tespace wh en .innerH TML is use d
  1368                    lead ingWhitesp ace: ( div .firstChil d.nodeType  === 3 ),
  1369  
  1370                    // M ake sure t hat tbody  elements a ren't auto matically  inserted
  1371                    // I E will ins ert them i nto empty  tables
  1372                    tbod y: !div.ge tElementsB yTagName(" tbody").le ngth,
  1373  
  1374                    // M ake sure t hat link e lements ge t serializ ed correct ly by inne rHTML
  1375                    // T his requir es a wrapp er element  in IE
  1376                    html Serialize:  !!div.get ElementsBy TagName("l ink").leng th,
  1377  
  1378                    // G et the sty le informa tion from  getAttribu te
  1379                    // ( IE uses .c ssText ins tead)
  1380                    styl e: /top/.t est( a.get Attribute( "style") ) ,
  1381  
  1382                    // M ake sure t hat URLs a ren't mani pulated
  1383                    // ( IE normali zes it by  default)
  1384                    href Normalized : ( a.getA ttribute(" href") ===  "/a" ),
  1385  
  1386                    // M ake sure t hat elemen t opacity  exists
  1387                    // ( IE uses fi lter inste ad)
  1388                    // U se a regex  to work a round a We bKit issue . See #514 5
  1389                    opac ity: /^0.5 5/.test( a .style.opa city ),
  1390  
  1391                    // V erify styl e float ex istence
  1392                    // ( IE uses st yleFloat i nstead of  cssFloat)
  1393                    cssF loat: !!a. style.cssF loat,
  1394  
  1395                    // M ake sure t hat if no  value is s pecified f or a check box
  1396                    // t hat it def aults to " on".
  1397                    // ( WebKit def aults to " " instead)
  1398                    chec kOn: ( inp ut.value = == "on" ),
  1399  
  1400                    // M ake sure t hat a sele cted-by-de fault opti on has a w orking sel ected prop erty.
  1401                    // ( WebKit def aults to f alse inste ad of true , IE too,  if it's in  an optgro up)
  1402                    optS elected: o pt.selecte d,
  1403  
  1404                    // T est setAtt ribute on  camelCase  class. If  it works,  we need at trFixes wh en doing g et/setAttr ibute (ie6 /7)
  1405                    getS etAttribut e: div.cla ssName !==  "t",
  1406  
  1407                    // T ests for e nctype sup port on a  form(#6743 )
  1408                    enct ype: !!doc ument.crea teElement( "form").en ctype,
  1409  
  1410                    // M akes sure  cloning an  html5 ele ment does  not cause  problems
  1411                    // W here outer HTML is un defined, t his still  works
  1412                    html 5Clone: do cument.cre ateElement ("nav").cl oneNode( t rue ).oute rHTML !==  "<:nav></: nav>",
  1413  
  1414                    // W ill be def ined later
  1415                    subm itBubbles:  true,
  1416                    chan geBubbles:  true,
  1417                    focu sinBubbles : false,
  1418                    dele teExpando:  true,
  1419                    noCl oneEvent:  true,
  1420                    inli neBlockNee dsLayout:  false,
  1421                    shri nkWrapBloc ks: false,
  1422                    reli ableMargin Right: tru e
  1423           };
  1424  
  1425           //  Make sure  checked s tatus is p roperly cl oned
  1426           in put.checke d = true;
  1427           su pport.noCl oneChecked  = input.c loneNode(  true ).che cked;
  1428  
  1429           //  Make sure  that the  options in side disab led select s aren't m arked as d isabled
  1430           //  (WebKit m arks them  as disable d)
  1431           se lect.disab led = true ;
  1432           su pport.optD isabled =  !opt.disab led;
  1433  
  1434           //  Test to s ee if it's  possible  to delete  an expando  from an e lement
  1435           //  Fails in  Internet E xplorer
  1436           tr y {
  1437                    dele te div.tes t;
  1438           }  catch( e )  {
  1439                    supp ort.delete Expando =  false;
  1440           }
  1441  
  1442           if  ( !div.ad dEventList ener && di v.attachEv ent && div .fireEvent  ) {
  1443                    div. attachEven t( "onclic k", functi on() {
  1444                             // Clo ning a nod e shouldn' t copy ove r any
  1445                             // bou nd event h andlers (I E does thi s)
  1446                             suppor t.noCloneE vent = fal se;
  1447                    });
  1448                    div. cloneNode(  true ).fi reEvent( " onclick" ) ;
  1449           }
  1450  
  1451           //  Check if  a radio ma intains it s value
  1452           //  after bei ng appende d to the D OM
  1453           in put = docu ment.creat eElement(" input");
  1454           in put.value  = "t";
  1455           in put.setAtt ribute("ty pe", "radi o");
  1456           su pport.radi oValue = i nput.value  === "t";
  1457  
  1458           in put.setAtt ribute("ch ecked", "c hecked");
  1459           di v.appendCh ild( input  );
  1460           fr agment = d ocument.cr eateDocume ntFragment ();
  1461           fr agment.app endChild(  div.lastCh ild );
  1462  
  1463           //  WebKit do esn't clon e checked  state corr ectly in f ragments
  1464           su pport.chec kClone = f ragment.cl oneNode( t rue ).clon eNode( tru e ).lastCh ild.checke d;
  1465  
  1466           //  Check if  a disconne cted check box will r etain its  checked
  1467           //  value of  true after  appended  to the DOM  (IE6/7)
  1468           su pport.appe ndChecked  = input.ch ecked;
  1469  
  1470           fr agment.rem oveChild(  input );
  1471           fr agment.app endChild(  div );
  1472  
  1473           di v.innerHTM L = "";
  1474  
  1475           //  Check if  div with e xplicit wi dth and no  margin-ri ght incorr ectly
  1476           //  gets comp uted margi n-right ba sed on wid th of cont ainer. For  more
  1477           //  info see  bug #3333
  1478           //  Fails in  WebKit bef ore Feb 20 11 nightli es
  1479           //  WebKit Bu g 13343 -  getCompute dStyle ret urns wrong  value for  margin-ri ght
  1480           if  ( window. getCompute dStyle ) {
  1481                    marg inDiv = do cument.cre ateElement ( "div" );
  1482                    marg inDiv.styl e.width =  "0";
  1483                    marg inDiv.styl e.marginRi ght = "0";
  1484                    div. style.widt h = "2px";
  1485                    div. appendChil d( marginD iv );
  1486                    supp ort.reliab leMarginRi ght =
  1487                             ( pars eInt( ( wi ndow.getCo mputedStyl e( marginD iv, null )  || { marg inRight: 0  } ).margi nRight, 10  ) || 0 )  === 0;
  1488           }
  1489  
  1490           //  Technique  from Juri y Zaytsev
  1491           //  http://pe rfectionki lls.com/de tecting-ev ent-suppor t-without- browser-sn iffing/
  1492           //  We only c are about  the case w here non-s tandard ev ent system s
  1493           //  are used,  namely in  IE. Short -circuitin g here hel ps us to
  1494           //  avoid an  eval call  (in setAtt ribute) wh ich can ca use CSP
  1495           //  to go hay wire. See:  https://d eveloper.m ozilla.org /en/Securi ty/CSP
  1496           if  ( div.att achEvent )  {
  1497                    for(  i in {
  1498                             submit : 1,
  1499                             change : 1,
  1500                             focusi n: 1
  1501                    }) {
  1502                             eventN ame = "on"  + i;
  1503                             isSupp orted = (  eventName  in div );
  1504                             if ( ! isSupporte d ) {
  1505                                      div.setA ttribute(  eventName,  "return;"  );
  1506                                      isSuppor ted = ( ty peof div[  eventName  ] === "fun ction" );
  1507                             }
  1508                             suppor t[ i + "Bu bbles" ] =  isSupport ed;
  1509                    }
  1510           }
  1511  
  1512           fr agment.rem oveChild(  div );
  1513  
  1514           //  Null elem ents to av oid leaks  in IE
  1515           fr agment = s elect = op t = margin Div = div  = input =  null;
  1516  
  1517           //  Run tests  that need  a body at  doc ready
  1518           jQ uery(funct ion() {
  1519                    var  container,  outer, in ner, table , td, offs etSupport,
  1520                             conMar ginTop, pt lm, vb, st yle, html,
  1521                             body =  document. getElement sByTagName ("body")[0 ];
  1522  
  1523                    if (  !body ) {
  1524                             // Ret urn for fr ameset doc s that don 't have a  body
  1525                             return ;
  1526                    }
  1527  
  1528                    conM arginTop =  1;
  1529                    ptlm  = "positi on:absolut e;top:0;le ft:0;width :1px;heigh t:1px;marg in:0;";
  1530                    vb =  "visibili ty:hidden; border:0;" ;
  1531                    styl e = "style ='" + ptlm  + "border :5px solid  #000;padd ing:0;'";
  1532                    html  = "<div "  + style +  "><div></ div></div> " +
  1533                             "<tabl e " + styl e + " cell padding='0 ' cellspac ing='0'>"  +
  1534                             "<tr>< td></td></ tr></table >";
  1535  
  1536                    cont ainer = do cument.cre ateElement ("div");
  1537                    cont ainer.styl e.cssText  = vb + "wi dth:0;heig ht:0;posit ion:static ;top:0;mar gin-top:"  + conMargi nTop + "px ";
  1538                    body .insertBef ore( conta iner, body .firstChil d );
  1539  
  1540                    // C onstruct t he test el ement
  1541                    div  = document .createEle ment("div" );
  1542                    cont ainer.appe ndChild( d iv );
  1543  
  1544                    // C heck if ta ble cells  still have  offsetWid th/Height  when they  are set
  1545                    // t o display: none and t here are s till other  visible t able cells  in a
  1546                    // t able row;  if so, off setWidth/H eight are  not reliab le for use  when
  1547                    // d etermining  if an ele ment has b een hidden  directly  using
  1548                    // d isplay:non e (it is s till safe  to use off sets if a  parent ele ment is
  1549                    // h idden; don  safety go ggles and  see bug #4 512 for mo re informa tion).
  1550                    // ( only IE 8  fails this  test)
  1551                    div. innerHTML  = "<table> <tr><td st yle='paddi ng:0;borde r:0;displa y:none'></ td><td>t</ td></tr></ table>";
  1552                    tds  = div.getE lementsByT agName( "t d" );
  1553                    isSu pported =  ( tds[ 0 ] .offsetHei ght === 0  );
  1554  
  1555                    tds[  0 ].style .display =  "";
  1556                    tds[  1 ].style .display =  "none";
  1557  
  1558                    // C heck if em pty table  cells stil l have off setWidth/H eight
  1559                    // ( IE <= 8 fa il this te st)
  1560                    supp ort.reliab leHiddenOf fsets = is Supported  && ( tds[  0 ].offset Height ===  0 );
  1561  
  1562                    // F igure out  if the W3C  box model  works as  expected
  1563                    div. innerHTML  = "";
  1564                    div. style.widt h = div.st yle.paddin gLeft = "1 px";
  1565                    jQue ry.boxMode l = suppor t.boxModel  = div.off setWidth = == 2;
  1566  
  1567                    if (  typeof di v.style.zo om !== "un defined" )  {
  1568                             // Che ck if nati vely block -level ele ments act  like inlin e-block
  1569                             // ele ments when  setting t heir displ ay to 'inl ine' and g iving
  1570                             // the m layout
  1571                             // (IE  < 8 does  this)
  1572                             div.st yle.displa y = "inlin e";
  1573                             div.st yle.zoom =  1;
  1574                             suppor t.inlineBl ockNeedsLa yout = ( d iv.offsetW idth === 2  );
  1575  
  1576                             // Che ck if elem ents with  layout shr ink-wrap t heir child ren
  1577                             // (IE  6 does th is)
  1578                             div.st yle.displa y = "";
  1579                             div.in nerHTML =  "<div styl e='width:4 px;'></div >";
  1580                             suppor t.shrinkWr apBlocks =  ( div.off setWidth ! == 2 );
  1581                    }
  1582  
  1583                    div. style.cssT ext = ptlm  + vb;
  1584                    div. innerHTML  = html;
  1585  
  1586                    oute r = div.fi rstChild;
  1587                    inne r = outer. firstChild ;
  1588                    td =  outer.nex tSibling.f irstChild. firstChild ;
  1589  
  1590                    offs etSupport  = {
  1591                             doesNo tAddBorder : ( inner. offsetTop  !== 5 ),
  1592                             doesAd dBorderFor TableAndCe lls: ( td. offsetTop  === 5 )
  1593                    };
  1594  
  1595                    inne r.style.po sition = " fixed";
  1596                    inne r.style.to p = "20px" ;
  1597  
  1598                    // s afari subt racts pare nt border  width here  which is  5px
  1599                    offs etSupport. fixedPosit ion = ( in ner.offset Top === 20  || inner. offsetTop  === 15 );
  1600                    inne r.style.po sition = i nner.style .top = "";
  1601  
  1602                    oute r.style.ov erflow = " hidden";
  1603                    oute r.style.po sition = " relative";
  1604  
  1605                    offs etSupport. subtractsB orderForOv erflowNotV isible = (  inner.off setTop ===  -5 );
  1606                    offs etSupport. doesNotInc ludeMargin InBodyOffs et = ( bod y.offsetTo p !== conM arginTop ) ;
  1607  
  1608                    body .removeChi ld( contai ner );
  1609                    div   = contain er = null;
  1610  
  1611                    jQue ry.extend(  support,  offsetSupp ort );
  1612           }) ;
  1613  
  1614           re turn suppo rt;
  1615   })();
  1616  
  1617  
  1618  
  1619  
  1620   var rbrace  = /^(?:\{ .*\}|\[.*\ ])$/,
  1621           rm ultiDash =  /([A-Z])/ g;
  1622  
  1623   jQuery.ext end({
  1624           ca che: {},
  1625  
  1626           //  Please us e with cau tion
  1627           uu id: 0,
  1628  
  1629           //  Unique fo r each cop y of jQuer y on the p age
  1630           //  Non-digit s removed  to match r inlinejQue ry
  1631           ex pando: "jQ uery" + (  jQuery.fn. jquery + M ath.random () ).repla ce( /\D/g,  "" ),
  1632  
  1633           //  The follo wing eleme nts throw  uncatchabl e exceptio ns if you
  1634           //  attempt t o add expa ndo proper ties to th em.
  1635           no Data: {
  1636                    "emb ed": true,
  1637                    // B an all obj ects excep t for Flas h (which h andle expa ndos)
  1638                    "obj ect": "cls id:D27CDB6 E-AE6D-11c f-96B8-444 553540000" ,
  1639                    "app let": true
  1640           },
  1641  
  1642           ha sData: fun ction( ele m ) {
  1643                    elem  = elem.no deType ? j Query.cach e[ elem[jQ uery.expan do] ] : el em[ jQuery .expando ] ;
  1644                    retu rn !!elem  && !isEmpt yDataObjec t( elem );
  1645           },
  1646  
  1647           da ta: functi on( elem,  name, data , pvt /* I nternal Us e Only */  ) {
  1648                    if (  !jQuery.a cceptData(  elem ) )  {
  1649                             return ;
  1650                    }
  1651  
  1652                    var  privateCac he, thisCa che, ret,
  1653                             intern alKey = jQ uery.expan do,
  1654                             getByN ame = type of name == = "string" ,
  1655  
  1656                             // We  have to ha ndle DOM n odes and J S objects  differentl y because  IE6-7
  1657                             // can 't GC obje ct referen ces proper ly across  the DOM-JS  boundary
  1658                             isNode  = elem.no deType,
  1659  
  1660                             // Onl y DOM node s need the  global jQ uery cache ; JS objec t data is
  1661                             // att ached dire ctly to th e object s o GC can o ccur autom atically
  1662                             cache  = isNode ?  jQuery.ca che : elem ,
  1663  
  1664                             // Onl y defining  an ID for  JS object s if its c ache alrea dy exists  allows
  1665                             // the  code to s hortcut on  the same  path as a  DOM node w ith no cac he
  1666                             id = i sNode ? el em[ intern alKey ] :  elem[ inte rnalKey ]  && interna lKey,
  1667                             isEven ts = name  === "event s";
  1668  
  1669                    // A void doing  any more  work than  we need to  when tryi ng to get  data on an
  1670                    // o bject that  has no da ta at all
  1671                    if (  (!id || ! cache[id]  || (!isEve nts && !pv t && !cach e[id].data )) && getB yName && d ata === un defined )  {
  1672                             return ;
  1673                    }
  1674  
  1675                    if (  !id ) {
  1676                             // Onl y DOM node s need a n ew unique  ID for eac h element  since thei r data
  1677                             // end s up in th e global c ache
  1678                             if ( i sNode ) {
  1679                                      elem[ in ternalKey  ] = id = + +jQuery.uu id;
  1680                             } else  {
  1681                                      id = int ernalKey;
  1682                             }
  1683                    }
  1684  
  1685                    if (  !cache[ i d ] ) {
  1686                             cache[  id ] = {} ;
  1687  
  1688                             // Avo ids exposi ng jQuery  metadata o n plain JS  objects w hen the ob ject
  1689                             // is  serialized  using JSO N.stringif y
  1690                             if ( ! isNode ) {
  1691                                      cache[ i d ].toJSON  = jQuery. noop;
  1692                             }
  1693                    }
  1694  
  1695                    // A n object c an be pass ed to jQue ry.data in stead of a  key/value  pair; thi s gets
  1696                    // s hallow cop ied over o nto the ex isting cac he
  1697                    if (  typeof na me === "ob ject" || t ypeof name  === "func tion" ) {
  1698                             if ( p vt ) {
  1699                                      cache[ i d ] = jQue ry.extend(  cache[ id  ], name ) ;
  1700                             } else  {
  1701                                      cache[ i d ].data =  jQuery.ex tend( cach e[ id ].da ta, name ) ;
  1702                             }
  1703                    }
  1704  
  1705                    priv ateCache =  thisCache  = cache[  id ];
  1706  
  1707                    // j Query data () is stor ed in a se parate obj ect inside  the objec t's intern al data
  1708                    // c ache in or der to avo id key col lisions be tween inte rnal data  and user-d efined
  1709                    // d ata.
  1710                    if (  !pvt ) {
  1711                             if ( ! thisCache. data ) {
  1712                                      thisCach e.data = { };
  1713                             }
  1714  
  1715                             thisCa che = this Cache.data ;
  1716                    }
  1717  
  1718                    if (  data !==  undefined  ) {
  1719                             thisCa che[ jQuer y.camelCas e( name )  ] = data;
  1720                    }
  1721  
  1722                    // U sers shoul d not atte mpt to ins pect the i nternal ev ents objec t using jQ uery.data,
  1723                    // i t is undoc umented an d subject  to change.  But does  anyone lis ten? No.
  1724                    if (  isEvents  && !thisCa che[ name  ] ) {
  1725                             return  privateCa che.events ;
  1726                    }
  1727  
  1728                    // C heck for b oth conver ted-to-cam el and non -converted  data prop erty names
  1729                    // I f a data p roperty wa s specifie d
  1730                    if (  getByName  ) {
  1731  
  1732                             // Fir st Try to  find as-is  property  data
  1733                             ret =  thisCache[  name ];
  1734  
  1735                             // Tes t for null |undefined  property  data
  1736                             if ( r et == null  ) {
  1737  
  1738                                      // Try t o find the  camelCase d property
  1739                                      ret = th isCache[ j Query.came lCase( nam e ) ];
  1740                             }
  1741                    } el se {
  1742                             ret =  thisCache;
  1743                    }
  1744  
  1745                    retu rn ret;
  1746           },
  1747  
  1748           re moveData:  function(  elem, name , pvt /* I nternal Us e Only */  ) {
  1749                    if (  !jQuery.a cceptData(  elem ) )  {
  1750                             return ;
  1751                    }
  1752  
  1753                    var  thisCache,  i, l,
  1754  
  1755                             // Ref erence to  internal d ata cache  key
  1756                             intern alKey = jQ uery.expan do,
  1757  
  1758                             isNode  = elem.no deType,
  1759  
  1760                             // See  jQuery.da ta for mor e informat ion
  1761                             cache  = isNode ?  jQuery.ca che : elem ,
  1762  
  1763                             // See  jQuery.da ta for mor e informat ion
  1764                             id = i sNode ? el em[ intern alKey ] :  internalKe y;
  1765  
  1766                    // I f there is  already n o cache en try for th is object,  there is  no
  1767                    // p urpose in  continuing
  1768                    if (  !cache[ i d ] ) {
  1769                             return ;
  1770                    }
  1771  
  1772                    if (  name ) {
  1773  
  1774                             thisCa che = pvt  ? cache[ i d ] : cach e[ id ].da ta;
  1775  
  1776                             if ( t hisCache )  {
  1777  
  1778                                      // Suppo rt array o r space se parated st ring names  for data  keys
  1779                                      if ( !jQ uery.isArr ay( name )  ) {
  1780  
  1781                                               // try the  string as  a key bef ore any ma nipulation
  1782                                               if ( name  in thisCac he ) {
  1783                                                       na me = [ nam e ];
  1784                                               } else {
  1785  
  1786                                                       //  split the  camel cas ed version  by spaces  unless a  key with t he spaces  exists
  1787                                                       na me = jQuer y.camelCas e( name );
  1788                                                       if  ( name in  thisCache  ) {
  1789                                                                name  = [ name  ];
  1790                                                       }  else {
  1791                                                                name  = name.sp lit( " " ) ;
  1792                                                       }
  1793                                               }
  1794                                      }
  1795  
  1796                                      for ( i  = 0, l = n ame.length ; i < l; i ++ ) {
  1797                                               delete thi sCache[ na me[i] ];
  1798                                      }
  1799  
  1800                                      // If th ere is no  data left  in the cac he, we wan t to conti nue
  1801                                      // and l et the cac he object  itself get  destroyed
  1802                                      if ( !(  pvt ? isEm ptyDataObj ect : jQue ry.isEmpty Object )(  thisCache  ) ) {
  1803                                               return;
  1804                                      }
  1805                             }
  1806                    }
  1807  
  1808                    // S ee jQuery. data for m ore inform ation
  1809                    if (  !pvt ) {
  1810                             delete  cache[ id  ].data;
  1811  
  1812                             // Don 't destroy  the paren t cache un less the i nternal da ta object
  1813                             // had  been the  only thing  left in i t
  1814                             if ( ! isEmptyDat aObject(ca che[ id ])  ) {
  1815                                      return;
  1816                             }
  1817                    }
  1818  
  1819                    // B rowsers th at fail ex pando dele tion also  refuse to  delete exp andos on
  1820                    // t he window,  but it wi ll allow i t on all o ther JS ob jects; oth er browser s
  1821                    // d on't care
  1822                    // E nsure that  `cache` i s not a wi ndow objec t #10080
  1823                    if (  jQuery.su pport.dele teExpando  || !cache. setInterva l ) {
  1824                             delete  cache[ id  ];
  1825                    } el se {
  1826                             cache[  id ] = nu ll;
  1827                    }
  1828  
  1829                    // W e destroye d the cach e and need  to elimin ate the ex pando on t he node to  avoid
  1830                    // f alse looku ps in the  cache for  entries th at no long er exist
  1831                    if (  isNode )  {
  1832                             // IE  does not a llow us to  delete ex pando prop erties fro m nodes,
  1833                             // nor  does it h ave a remo veAttribut e function  on Docume nt nodes;
  1834                             // we  must handl e all of t hese cases
  1835                             if ( j Query.supp ort.delete Expando )  {
  1836                                      delete e lem[ inter nalKey ];
  1837                             } else  if ( elem .removeAtt ribute ) {
  1838                                      elem.rem oveAttribu te( intern alKey );
  1839                             } else  {
  1840                                      elem[ in ternalKey  ] = null;
  1841                             }
  1842                    }
  1843           },
  1844  
  1845           //  For inter nal use on ly.
  1846           _d ata: funct ion( elem,  name, dat a ) {
  1847                    retu rn jQuery. data( elem , name, da ta, true ) ;
  1848           },
  1849  
  1850           //  A method  for determ ining if a  DOM node  can handle  the data  expando
  1851           ac ceptData:  function(  elem ) {
  1852                    if (  elem.node Name ) {
  1853                             var ma tch = jQue ry.noData[  elem.node Name.toLow erCase() ] ;
  1854  
  1855                             if ( m atch ) {
  1856                                      return ! (match ===  true || e lem.getAtt ribute("cl assid") != = match);
  1857                             }
  1858                    }
  1859  
  1860                    retu rn true;
  1861           }
  1862   });
  1863  
  1864   jQuery.fn. extend({
  1865           da ta: functi on( key, v alue ) {
  1866                    var  parts, att r, name,
  1867                             data =  null;
  1868  
  1869                    if (  typeof ke y === "und efined" )  {
  1870                             if ( t his.length  ) {
  1871                                      data = j Query.data ( this[0]  );
  1872  
  1873                                      if ( thi s[0].nodeT ype === 1  && !jQuery ._data( th is[0], "pa rsedAttrs"  ) ) {
  1874                                               attr = thi s[0].attri butes;
  1875                                               for ( var  i = 0, l =  attr.leng th; i < l;  i++ ) {
  1876                                                       na me = attr[ i].name;
  1877  
  1878                                                       if  ( name.in dexOf( "da ta-" ) ===  0 ) {
  1879                                                                name  = jQuery. camelCase(  name.subs tring(5) ) ;
  1880  
  1881                                                                data Attr( this [0], name,  data[ nam e ] );
  1882                                                       }
  1883                                               }
  1884                                               jQuery._da ta( this[0 ], "parsed Attrs", tr ue );
  1885                                      }
  1886                             }
  1887  
  1888                             return  data;
  1889  
  1890                    } el se if ( ty peof key = == "object " ) {
  1891                             return  this.each (function( ) {
  1892                                      jQuery.d ata( this,  key );
  1893                             });
  1894                    }
  1895  
  1896                    part s = key.sp lit(".");
  1897                    part s[1] = par ts[1] ? ". " + parts[ 1] : "";
  1898  
  1899                    if (  value ===  undefined  ) {
  1900                             data =  this.trig gerHandler ("getData"  + parts[1 ] + "!", [ parts[0]]) ;
  1901  
  1902                             // Try  to fetch  any intern ally store d data fir st
  1903                             if ( d ata === un defined &&  this.leng th ) {
  1904                                      data = j Query.data ( this[0],  key );
  1905                                      data = d ataAttr( t his[0], ke y, data );
  1906                             }
  1907  
  1908                             return  data ===  undefined  && parts[1 ] ?
  1909                                      this.dat a( parts[0 ] ) :
  1910                                      data;
  1911  
  1912                    } el se {
  1913                             return  this.each (function( ) {
  1914                                      var self  = jQuery(  this ),
  1915                                               args = [ p arts[0], v alue ];
  1916  
  1917                                      self.tri ggerHandle r( "setDat a" + parts [1] + "!",  args );
  1918                                      jQuery.d ata( this,  key, valu e );
  1919                                      self.tri ggerHandle r( "change Data" + pa rts[1] + " !", args ) ;
  1920                             });
  1921                    }
  1922           },
  1923  
  1924           re moveData:  function(  key ) {
  1925                    retu rn this.ea ch(functio n() {
  1926                             jQuery .removeDat a( this, k ey );
  1927                    });
  1928           }
  1929   });
  1930  
  1931   function d ataAttr( e lem, key,  data ) {
  1932           //  If nothin g was foun d internal ly, try to  fetch any
  1933           //  data from  the HTML5  data-* at tribute
  1934           if  ( data == = undefine d && elem. nodeType = == 1 ) {
  1935  
  1936                    var  name = "da ta-" + key .replace(  rmultiDash , "-$1" ). toLowerCas e();
  1937  
  1938                    data  = elem.ge tAttribute ( name );
  1939  
  1940                    if (  typeof da ta === "st ring" ) {
  1941                             try {
  1942                                      data = d ata === "t rue" ? tru e :
  1943                                      data ===  "false" ?  false :
  1944                                      data ===  "null" ?  null :
  1945                                      jQuery.i sNumeric(  data ) ? p arseFloat(  data ) :
  1946                                               rbrace.tes t( data )  ? jQuery.p arseJSON(  data ) :
  1947                                               data;
  1948                             } catc h( e ) {}
  1949  
  1950                             // Mak e sure we  set the da ta so it i sn't chang ed later
  1951                             jQuery .data( ele m, key, da ta );
  1952  
  1953                    } el se {
  1954                             data =  undefined ;
  1955                    }
  1956           }
  1957  
  1958           re turn data;
  1959   }
  1960  
  1961   // checks  a cache ob ject for e mptiness
  1962   function i sEmptyData Object( ob j ) {
  1963           fo r ( var na me in obj  ) {
  1964  
  1965                    // i f the publ ic data ob ject is em pty, the p rivate is  still empt y
  1966                    if (  name ===  "data" &&  jQuery.isE mptyObject ( obj[name ] ) ) {
  1967                             contin ue;
  1968                    }
  1969                    if (  name !==  "toJSON" )  {
  1970                             return  false;
  1971                    }
  1972           }
  1973  
  1974           re turn true;
  1975   }
  1976  
  1977  
  1978  
  1979  
  1980   function h andleQueue MarkDefer(  elem, typ e, src ) {
  1981           va r deferDat aKey = typ e + "defer ",
  1982                    queu eDataKey =  type + "q ueue",
  1983                    mark DataKey =  type + "ma rk",
  1984                    defe r = jQuery ._data( el em, deferD ataKey );
  1985           if  ( defer & &
  1986                    ( sr c === "que ue" || !jQ uery._data (elem, que ueDataKey)  ) &&
  1987                    ( sr c === "mar k" || !jQu ery._data( elem, mark DataKey) )  ) {
  1988                    // G ive room f or hard-co ded callba cks to fir e first
  1989                    // a nd eventua lly mark/q ueue somet hing else  on the ele ment
  1990                    setT imeout( fu nction() {
  1991                             if ( ! jQuery._da ta( elem,  queueDataK ey ) &&
  1992                                      !jQuery. _data( ele m, markDat aKey ) ) {
  1993                                      jQuery.r emoveData(  elem, def erDataKey,  true );
  1994                                      defer.fi re();
  1995                             }
  1996                    }, 0  );
  1997           }
  1998   }
  1999  
  2000   jQuery.ext end({
  2001  
  2002           _m ark: funct ion( elem,  type ) {
  2003                    if (  elem ) {
  2004                             type =  ( type ||  "fx" ) +  "mark";
  2005                             jQuery ._data( el em, type,  (jQuery._d ata( elem,  type ) ||  0) + 1 );
  2006                    }
  2007           },
  2008  
  2009           _u nmark: fun ction( for ce, elem,  type ) {
  2010                    if (  force !==  true ) {
  2011                             type =  elem;
  2012                             elem =  force;
  2013                             force  = false;
  2014                    }
  2015                    if (  elem ) {
  2016                             type =  type || " fx";
  2017                             var ke y = type +  "mark",
  2018                                      count =  force ? 0  : ( (jQuer y._data( e lem, key )  || 1) - 1  );
  2019                             if ( c ount ) {
  2020                                      jQuery._ data( elem , key, cou nt );
  2021                             } else  {
  2022                                      jQuery.r emoveData(  elem, key , true );
  2023                                      handleQu eueMarkDef er( elem,  type, "mar k" );
  2024                             }
  2025                    }
  2026           },
  2027  
  2028           qu eue: funct ion( elem,  type, dat a ) {
  2029                    var  q;
  2030                    if (  elem ) {
  2031                             type =  ( type ||  "fx" ) +  "queue";
  2032                             q = jQ uery._data ( elem, ty pe );
  2033  
  2034                             // Spe ed up dequ eue by get ting out q uickly if  this is ju st a looku p
  2035                             if ( d ata ) {
  2036                                      if ( !q  || jQuery. isArray(da ta) ) {
  2037                                               q = jQuery ._data( el em, type,  jQuery.mak eArray(dat a) );
  2038                                      } else {
  2039                                               q.push( da ta );
  2040                                      }
  2041                             }
  2042                             return  q || [];
  2043                    }
  2044           },
  2045  
  2046           de queue: fun ction( ele m, type )  {
  2047                    type  = type ||  "fx";
  2048  
  2049                    var  queue = jQ uery.queue ( elem, ty pe ),
  2050                             fn = q ueue.shift (),
  2051                             hooks  = {};
  2052  
  2053                    // I f the fx q ueue is de queued, al ways remov e the prog ress senti nel
  2054                    if (  fn === "i nprogress"  ) {
  2055                             fn = q ueue.shift ();
  2056                    }
  2057  
  2058                    if (  fn ) {
  2059                             // Add  a progres s sentinel  to preven t the fx q ueue from  being
  2060                             // aut omatically  dequeued
  2061                             if ( t ype === "f x" ) {
  2062                                      queue.un shift( "in progress"  );
  2063                             }
  2064  
  2065                             jQuery ._data( el em, type +  ".run", h ooks );
  2066                             fn.cal l( elem, f unction()  {
  2067                                      jQuery.d equeue( el em, type ) ;
  2068                             }, hoo ks );
  2069                    }
  2070  
  2071                    if (  !queue.le ngth ) {
  2072                             jQuery .removeDat a( elem, t ype + "que ue " + typ e + ".run" , true );
  2073                             handle QueueMarkD efer( elem , type, "q ueue" );
  2074                    }
  2075           }
  2076   });
  2077  
  2078   jQuery.fn. extend({
  2079           qu eue: funct ion( type,  data ) {
  2080                    if (  typeof ty pe !== "st ring" ) {
  2081                             data =  type;
  2082                             type =  "fx";
  2083                    }
  2084  
  2085                    if (  data ===  undefined  ) {
  2086                             return  jQuery.qu eue( this[ 0], type ) ;
  2087                    }
  2088                    retu rn this.ea ch(functio n() {
  2089                             var qu eue = jQue ry.queue(  this, type , data );
  2090  
  2091                             if ( t ype === "f x" && queu e[0] !== " inprogress " ) {
  2092                                      jQuery.d equeue( th is, type ) ;
  2093                             }
  2094                    });
  2095           },
  2096           de queue: fun ction( typ e ) {
  2097                    retu rn this.ea ch(functio n() {
  2098                             jQuery .dequeue(  this, type  );
  2099                    });
  2100           },
  2101           //  Based off  of the pl ugin by Cl int Helfer s, with pe rmission.
  2102           //  http://bl indsignals .com/index .php/2009/ 07/jquery- delay/
  2103           de lay: funct ion( time,  type ) {
  2104                    time  = jQuery. fx ? jQuer y.fx.speed s[ time ]  || time :  time;
  2105                    type  = type ||  "fx";
  2106  
  2107                    retu rn this.qu eue( type,  function(  next, hoo ks ) {
  2108                             var ti meout = se tTimeout(  next, time  );
  2109                             hooks. stop = fun ction() {
  2110                                      clearTim eout( time out );
  2111                             };
  2112                    });
  2113           },
  2114           cl earQueue:  function(  type ) {
  2115                    retu rn this.qu eue( type  || "fx", [ ] );
  2116           },
  2117           //  Get a pro mise resol ved when q ueues of a  certain t ype
  2118           //  are empti ed (fx is  the type b y default)
  2119           pr omise: fun ction( typ e, object  ) {
  2120                    if (  typeof ty pe !== "st ring" ) {
  2121                             object  = type;
  2122                             type =  undefined ;
  2123                    }
  2124                    type  = type ||  "fx";
  2125                    var  defer = jQ uery.Defer red(),
  2126                             elemen ts = this,
  2127                             i = el ements.len gth,
  2128                             count  = 1,
  2129                             deferD ataKey = t ype + "def er",
  2130                             queueD ataKey = t ype + "que ue",
  2131                             markDa taKey = ty pe + "mark ",
  2132                             tmp;
  2133                    func tion resol ve() {
  2134                             if ( ! ( --count  ) ) {
  2135                                      defer.re solveWith(  elements,  [ element s ] );
  2136                             }
  2137                    }
  2138                    whil e( i-- ) {
  2139                             if ((  tmp = jQue ry.data( e lements[ i  ], deferD ataKey, un defined, t rue ) ||
  2140                                               ( jQuery.d ata( eleme nts[ i ],  queueDataK ey, undefi ned, true  ) ||
  2141                                                       jQ uery.data(  elements[  i ], mark DataKey, u ndefined,  true ) ) & &
  2142                                               jQuery.dat a( element s[ i ], de ferDataKey , jQuery.C allbacks(  "once memo ry" ), tru e ) )) {
  2143                                      count++;
  2144                                      tmp.add(  resolve ) ;
  2145                             }
  2146                    }
  2147                    reso lve();
  2148                    retu rn defer.p romise();
  2149           }
  2150   });
  2151  
  2152  
  2153  
  2154  
  2155   var rclass  = /[\n\t\ r]/g,
  2156           rs pace = /\s +/,
  2157           rr eturn = /\ r/g,
  2158           rt ype = /^(? :button|in put)$/i,
  2159           rf ocusable =  /^(?:butt on|input|o bject|sele ct|textare a)$/i,
  2160           rc lickable =  /^a(?:rea )?$/i,
  2161           rb oolean = / ^(?:autofo cus|autopl ay|async|c hecked|con trols|defe r|disabled |hidden|lo op|multipl e|open|rea donly|requ ired|scope d|selected )$/i,
  2162           ge tSetAttrib ute = jQue ry.support .getSetAtt ribute,
  2163           no deHook, bo olHook, fi xSpecified ;
  2164  
  2165   jQuery.fn. extend({
  2166           at tr: functi on( name,  value ) {
  2167                    retu rn jQuery. access( th is, name,  value, tru e, jQuery. attr );
  2168           },
  2169  
  2170           re moveAttr:  function(  name ) {
  2171                    retu rn this.ea ch(functio n() {
  2172                             jQuery .removeAtt r( this, n ame );
  2173                    });
  2174           },
  2175  
  2176           pr op: functi on( name,  value ) {
  2177                    retu rn jQuery. access( th is, name,  value, tru e, jQuery. prop );
  2178           },
  2179  
  2180           re moveProp:  function(  name ) {
  2181                    name  = jQuery. propFix[ n ame ] || n ame;
  2182                    retu rn this.ea ch(functio n() {
  2183                             // try /catch han dles cases  where IE  balks (suc h as remov ing a prop erty on wi ndow)
  2184                             try {
  2185                                      this[ na me ] = und efined;
  2186                                      delete t his[ name  ];
  2187                             } catc h( e ) {}
  2188                    });
  2189           },
  2190  
  2191           ad dClass: fu nction( va lue ) {
  2192                    var  classNames , i, l, el em,
  2193                             setCla ss, c, cl;
  2194  
  2195                    if (  jQuery.is Function(  value ) )  {
  2196                             return  this.each (function(  j ) {
  2197                                      jQuery(  this ).add Class( val ue.call(th is, j, thi s.classNam e) );
  2198                             });
  2199                    }
  2200  
  2201                    if (  value &&  typeof val ue === "st ring" ) {
  2202                             classN ames = val ue.split(  rspace );
  2203  
  2204                             for (  i = 0, l =  this.leng th; i < l;  i++ ) {
  2205                                      elem = t his[ i ];
  2206  
  2207                                      if ( ele m.nodeType  === 1 ) {
  2208                                               if ( !elem .className  && classN ames.lengt h === 1 )  {
  2209                                                       el em.classNa me = value ;
  2210  
  2211                                               } else {
  2212                                                       se tClass = "  " + elem. className  + " ";
  2213  
  2214                                                       fo r ( c = 0,  cl = clas sNames.len gth; c < c l; c++ ) {
  2215                                                                if (  !~setClas s.indexOf(  " " + cla ssNames[ c  ] + " " )  ) {
  2216                                                                         setCla ss += clas sNames[ c  ] + " ";
  2217                                                                }
  2218                                                       }
  2219                                                       el em.classNa me = jQuer y.trim( se tClass );
  2220                                               }
  2221                                      }
  2222                             }
  2223                    }
  2224  
  2225                    retu rn this;
  2226           },
  2227  
  2228           re moveClass:  function(  value ) {
  2229                    var  classNames , i, l, el em, classN ame, c, cl ;
  2230  
  2231                    if (  jQuery.is Function(  value ) )  {
  2232                             return  this.each (function(  j ) {
  2233                                      jQuery(  this ).rem oveClass(  value.call (this, j,  this.class Name) );
  2234                             });
  2235                    }
  2236  
  2237                    if (  (value &&  typeof va lue === "s tring") ||  value ===  undefined  ) {
  2238                             classN ames = ( v alue || ""  ).split(  rspace );
  2239  
  2240                             for (  i = 0, l =  this.leng th; i < l;  i++ ) {
  2241                                      elem = t his[ i ];
  2242  
  2243                                      if ( ele m.nodeType  === 1 &&  elem.class Name ) {
  2244                                               if ( value  ) {
  2245                                                       cl assName =  (" " + ele m.classNam e + " ").r eplace( rc lass, " "  );
  2246                                                       fo r ( c = 0,  cl = clas sNames.len gth; c < c l; c++ ) {
  2247                                                                clas sName = cl assName.re place(" "  + classNam es[ c ] +  " ", " ");
  2248                                                       }
  2249                                                       el em.classNa me = jQuer y.trim( cl assName );
  2250  
  2251                                               } else {
  2252                                                       el em.classNa me = "";
  2253                                               }
  2254                                      }
  2255                             }
  2256                    }
  2257  
  2258                    retu rn this;
  2259           },
  2260  
  2261           to ggleClass:  function(  value, st ateVal ) {
  2262                    var  type = typ eof value,
  2263                             isBool  = typeof  stateVal = == "boolea n";
  2264  
  2265                    if (  jQuery.is Function(  value ) )  {
  2266                             return  this.each (function(  i ) {
  2267                                      jQuery(  this ).tog gleClass(  value.call (this, i,  this.class Name, stat eVal), sta teVal );
  2268                             });
  2269                    }
  2270  
  2271                    retu rn this.ea ch(functio n() {
  2272                             if ( t ype === "s tring" ) {
  2273                                      // toggl e individu al class n ames
  2274                                      var clas sName,
  2275                                               i = 0,
  2276                                               self = jQu ery( this  ),
  2277                                               state = st ateVal,
  2278                                               classNames  = value.s plit( rspa ce );
  2279  
  2280                                      while (  (className  = classNa mes[ i++ ] ) ) {
  2281                                               // check e ach classN ame given,  space sep erated lis t
  2282                                               state = is Bool ? sta te : !self .hasClass(  className  );
  2283                                               self[ stat e ? "addCl ass" : "re moveClass"  ]( classN ame );
  2284                                      }
  2285  
  2286                             } else  if ( type  === "unde fined" ||  type === " boolean" )  {
  2287                                      if ( thi s.classNam e ) {
  2288                                               // store c lassName i f set
  2289                                               jQuery._da ta( this,  "__classNa me__", thi s.classNam e );
  2290                                      }
  2291  
  2292                                      // toggl e whole cl assName
  2293                                      this.cla ssName = t his.classN ame || val ue === fal se ? "" :  jQuery._da ta( this,  "__classNa me__" ) ||  "";
  2294                             }
  2295                    });
  2296           },
  2297  
  2298           ha sClass: fu nction( se lector ) {
  2299                    var  className  = " " + se lector + "  ",
  2300                             i = 0,
  2301                             l = th is.length;
  2302                    for  ( ; i < l;  i++ ) {
  2303                             if ( t his[i].nod eType ===  1 && (" "  + this[i]. className  + " ").rep lace(rclas s, " ").in dexOf( cla ssName ) >  -1 ) {
  2304                                      return t rue;
  2305                             }
  2306                    }
  2307  
  2308                    retu rn false;
  2309           },
  2310  
  2311           va l: functio n( value )  {
  2312                    var  hooks, ret , isFuncti on,
  2313                             elem =  this[0];
  2314  
  2315                    if (  !argument s.length )  {
  2316                             if ( e lem ) {
  2317                                      hooks =  jQuery.val Hooks[ ele m.nodeName .toLowerCa se() ] ||  jQuery.val Hooks[ ele m.type ];
  2318  
  2319                                      if ( hoo ks && "get " in hooks  && (ret =  hooks.get ( elem, "v alue" )) ! == undefin ed ) {
  2320                                               return ret ;
  2321                                      }
  2322  
  2323                                      ret = el em.value;
  2324  
  2325                                      return t ypeof ret  === "strin g" ?
  2326                                               // handle  most commo n string c ases
  2327                                               ret.replac e(rreturn,  "") :
  2328                                               // handle  cases wher e value is  null/unde f or numbe r
  2329                                               ret == nul l ? "" : r et;
  2330                             }
  2331  
  2332                             return ;
  2333                    }
  2334  
  2335                    isFu nction = j Query.isFu nction( va lue );
  2336  
  2337                    retu rn this.ea ch(functio n( i ) {
  2338                             var se lf = jQuer y(this), v al;
  2339  
  2340                             if ( t his.nodeTy pe !== 1 )  {
  2341                                      return;
  2342                             }
  2343  
  2344                             if ( i sFunction  ) {
  2345                                      val = va lue.call(  this, i, s elf.val()  );
  2346                             } else  {
  2347                                      val = va lue;
  2348                             }
  2349  
  2350                             // Tre at null/un defined as  ""; conve rt numbers  to string
  2351                             if ( v al == null  ) {
  2352                                      val = "" ;
  2353                             } else  if ( type of val ===  "number"  ) {
  2354                                      val += " ";
  2355                             } else  if ( jQue ry.isArray ( val ) )  {
  2356                                      val = jQ uery.map(v al, functi on ( value  ) {
  2357                                               return val ue == null  ? "" : va lue + "";
  2358                                      });
  2359                             }
  2360  
  2361                             hooks  = jQuery.v alHooks[ t his.nodeNa me.toLower Case() ] | | jQuery.v alHooks[ t his.type ] ;
  2362  
  2363                             // If  set return s undefine d, fall ba ck to norm al setting
  2364                             if ( ! hooks || ! ("set" in  hooks) ||  hooks.set(  this, val , "value"  ) === unde fined ) {
  2365                                      this.val ue = val;
  2366                             }
  2367                    });
  2368           }
  2369   });
  2370  
  2371   jQuery.ext end({
  2372           va lHooks: {
  2373                    opti on: {
  2374                             get: f unction( e lem ) {
  2375                                      // attri butes.valu e is undef ined in Bl ackberry 4 .7 but
  2376                                      // uses  .value. Se e #6932
  2377                                      var val  = elem.att ributes.va lue;
  2378                                      return ! val || val .specified  ? elem.va lue : elem .text;
  2379                             }
  2380                    },
  2381                    sele ct: {
  2382                             get: f unction( e lem ) {
  2383                                      var valu e, i, max,  option,
  2384                                               index = el em.selecte dIndex,
  2385                                               values = [ ],
  2386                                               options =  elem.optio ns,
  2387                                               one = elem .type ===  "select-on e";
  2388  
  2389                                      // Nothi ng was sel ected
  2390                                      if ( ind ex < 0 ) {
  2391                                               return nul l;
  2392                                      }
  2393  
  2394                                      // Loop  through al l the sele cted optio ns
  2395                                      i = one  ? index :  0;
  2396                                      max = on e ? index  + 1 : opti ons.length ;
  2397                                      for ( ;  i < max; i ++ ) {
  2398                                               option = o ptions[ i  ];
  2399  
  2400                                               // Don't r eturn opti ons that a re disable d or in a  disabled o ptgroup
  2401                                               if ( optio n.selected  && (jQuer y.support. optDisable d ? !optio n.disabled  : option. getAttribu te("disabl ed") === n ull) &&
  2402                                                                (!op tion.paren tNode.disa bled || !j Query.node Name( opti on.parentN ode, "optg roup" )) )  {
  2403  
  2404                                                       //  Get the s pecific va lue for th e option
  2405                                                       va lue = jQue ry( option  ).val();
  2406  
  2407                                                       //  We don't  need an ar ray for on e selects
  2408                                                       if  ( one ) {
  2409                                                                retu rn value;
  2410                                                       }
  2411  
  2412                                                       //  Multi-Sel ects retur n an array
  2413                                                       va lues.push(  value );
  2414                                               }
  2415                                      }
  2416  
  2417                                      // Fixes  Bug #2551  -- select .val() bro ken in IE  after form .reset()
  2418                                      if ( one  && !value s.length & & options. length ) {
  2419                                               return jQu ery( optio ns[ index  ] ).val();
  2420                                      }
  2421  
  2422                                      return v alues;
  2423                             },
  2424  
  2425                             set: f unction( e lem, value  ) {
  2426                                      var valu es = jQuer y.makeArra y( value ) ;
  2427  
  2428                                      jQuery(e lem).find( "option"). each(funct ion() {
  2429                                               this.selec ted = jQue ry.inArray ( jQuery(t his).val() , values )  >= 0;
  2430                                      });
  2431  
  2432                                      if ( !va lues.lengt h ) {
  2433                                               elem.selec tedIndex =  -1;
  2434                                      }
  2435                                      return v alues;
  2436                             }
  2437                    }
  2438           },
  2439  
  2440           at trFn: {
  2441                    val:  true,
  2442                    css:  true,
  2443                    html : true,
  2444                    text : true,
  2445                    data : true,
  2446                    widt h: true,
  2447                    heig ht: true,
  2448                    offs et: true
  2449           },
  2450  
  2451           at tr: functi on( elem,  name, valu e, pass )  {
  2452                    var  ret, hooks , notxml,
  2453                             nType  = elem.nod eType;
  2454  
  2455                    // d on't get/s et attribu tes on tex t, comment  and attri bute nodes
  2456                    if (  !elem ||  nType ===  3 || nType  === 8 ||  nType ===  2 ) {
  2457                             return ;
  2458                    }
  2459  
  2460                    if (  pass && n ame in jQu ery.attrFn  ) {
  2461                             return  jQuery( e lem )[ nam e ]( value  );
  2462                    }
  2463  
  2464                    // F allback to  prop when  attribute s are not  supported
  2465                    if (  typeof el em.getAttr ibute ===  "undefined " ) {
  2466                             return  jQuery.pr op( elem,  name, valu e );
  2467                    }
  2468  
  2469                    notx ml = nType  !== 1 ||  !jQuery.is XMLDoc( el em );
  2470  
  2471                    // A ll attribu tes are lo wercase
  2472                    // G rab necess ary hook i f one is d efined
  2473                    if (  notxml )  {
  2474                             name =  name.toLo werCase();
  2475                             hooks  = jQuery.a ttrHooks[  name ] ||  ( rboolean .test( nam e ) ? bool Hook : nod eHook );
  2476                    }
  2477  
  2478                    if (  value !==  undefined  ) {
  2479  
  2480                             if ( v alue === n ull ) {
  2481                                      jQuery.r emoveAttr(  elem, nam e );
  2482                                      return;
  2483  
  2484                             } else  if ( hook s && "set"  in hooks  && notxml  && (ret =  hooks.set(  elem, val ue, name ) ) !== unde fined ) {
  2485                                      return r et;
  2486  
  2487                             } else  {
  2488                                      elem.set Attribute(  name, ""  + value );
  2489                                      return v alue;
  2490                             }
  2491  
  2492                    } el se if ( ho oks && "ge t" in hook s && notxm l && (ret  = hooks.ge t( elem, n ame )) !==  null ) {
  2493                             return  ret;
  2494  
  2495                    } el se {
  2496  
  2497                             ret =  elem.getAt tribute( n ame );
  2498  
  2499                             // Non -existent  attributes  return nu ll, we nor malize to  undefined
  2500                             return  ret === n ull ?
  2501                                      undefine d :
  2502                                      ret;
  2503                    }
  2504           },
  2505  
  2506           re moveAttr:  function(  elem, valu e ) {
  2507                    var  propName,  attrNames,  name, l,
  2508                             i = 0;
  2509  
  2510                    if (  value &&  elem.nodeT ype === 1  ) {
  2511                             attrNa mes = valu e.toLowerC ase().spli t( rspace  );
  2512                             l = at trNames.le ngth;
  2513  
  2514                             for (  ; i < l; i ++ ) {
  2515                                      name = a ttrNames[  i ];
  2516  
  2517                                      if ( nam e ) {
  2518                                               propName =  jQuery.pr opFix[ nam e ] || nam e;
  2519  
  2520                                               // See #96 99 for exp lanation o f this app roach (set ting first , then rem oval)
  2521                                               jQuery.att r( elem, n ame, "" );
  2522                                               elem.remov eAttribute ( getSetAt tribute ?  name : pro pName );
  2523  
  2524                                               // Set cor responding  property  to false f or boolean  attribute s
  2525                                               if ( rbool ean.test(  name ) &&  propName i n elem ) {
  2526                                                       el em[ propNa me ] = fal se;
  2527                                               }
  2528                                      }
  2529                             }
  2530                    }
  2531           },
  2532  
  2533           at trHooks: {
  2534                    type : {
  2535                             set: f unction( e lem, value  ) {
  2536                                      // We ca n't allow  the type p roperty to  be change d (since i t causes p roblems in  IE)
  2537                                      if ( rty pe.test( e lem.nodeNa me ) && el em.parentN ode ) {
  2538                                               jQuery.err or( "type  property c an't be ch anged" );
  2539                                      } else i f ( !jQuer y.support. radioValue  && value  === "radio " && jQuer y.nodeName (elem, "in put") ) {
  2540                                               // Setting  the type  on a radio  button af ter the va lue resets  the value  in IE6-9
  2541                                               // Reset v alue to it 's default  in case t ype is set  after val ue
  2542                                               // This is  for eleme nt creatio n
  2543                                               var val =  elem.value ;
  2544                                               elem.setAt tribute( " type", val ue );
  2545                                               if ( val )  {
  2546                                                       el em.value =  val;
  2547                                               }
  2548                                               return val ue;
  2549                                      }
  2550                             }
  2551                    },
  2552                    // U se the val ue propert y for back  compat
  2553                    // U se the nod eHook for  button ele ments in I E6/7 (#195 4)
  2554                    valu e: {
  2555                             get: f unction( e lem, name  ) {
  2556                                      if ( nod eHook && j Query.node Name( elem , "button"  ) ) {
  2557                                               return nod eHook.get(  elem, nam e );
  2558                                      }
  2559                                      return n ame in ele m ?
  2560                                               elem.value  :
  2561                                               null;
  2562                             },
  2563                             set: f unction( e lem, value , name ) {
  2564                                      if ( nod eHook && j Query.node Name( elem , "button"  ) ) {
  2565                                               return nod eHook.set(  elem, val ue, name ) ;
  2566                                      }
  2567                                      // Does  not return  so that s etAttribut e is also  used
  2568                                      elem.val ue = value ;
  2569                             }
  2570                    }
  2571           },
  2572  
  2573           pr opFix: {
  2574                    tabi ndex: "tab Index",
  2575                    read only: "rea dOnly",
  2576                    "for ": "htmlFo r",
  2577                    "cla ss": "clas sName",
  2578                    maxl ength: "ma xLength",
  2579                    cell spacing: " cellSpacin g",
  2580                    cell padding: " cellPaddin g",
  2581                    rows pan: "rowS pan",
  2582                    cols pan: "colS pan",
  2583                    usem ap: "useMa p",
  2584                    fram eborder: " frameBorde r",
  2585                    cont enteditabl e: "conten tEditable"
  2586           },
  2587  
  2588           pr op: functi on( elem,  name, valu e ) {
  2589                    var  ret, hooks , notxml,
  2590                             nType  = elem.nod eType;
  2591  
  2592                    // d on't get/s et propert ies on tex t, comment  and attri bute nodes
  2593                    if (  !elem ||  nType ===  3 || nType  === 8 ||  nType ===  2 ) {
  2594                             return ;
  2595                    }
  2596  
  2597                    notx ml = nType  !== 1 ||  !jQuery.is XMLDoc( el em );
  2598  
  2599                    if (  notxml )  {
  2600                             // Fix  name and  attach hoo ks
  2601                             name =  jQuery.pr opFix[ nam e ] || nam e;
  2602                             hooks  = jQuery.p ropHooks[  name ];
  2603                    }
  2604  
  2605                    if (  value !==  undefined  ) {
  2606                             if ( h ooks && "s et" in hoo ks && (ret  = hooks.s et( elem,  value, nam e )) !== u ndefined )  {
  2607                                      return r et;
  2608  
  2609                             } else  {
  2610                                      return (  elem[ nam e ] = valu e );
  2611                             }
  2612  
  2613                    } el se {
  2614                             if ( h ooks && "g et" in hoo ks && (ret  = hooks.g et( elem,  name )) != = null ) {
  2615                                      return r et;
  2616  
  2617                             } else  {
  2618                                      return e lem[ name  ];
  2619                             }
  2620                    }
  2621           },
  2622  
  2623           pr opHooks: {
  2624                    tabI ndex: {
  2625                             get: f unction( e lem ) {
  2626                                      // elem. tabIndex d oesn't alw ays return  the corre ct value w hen it has n't been e xplicitly  set
  2627                                      // http: //fluidpro ject.org/b log/2008/0 1/09/getti ng-setting -and-remov ing-tabind ex-values- with-javas cript/
  2628                                      var attr ibuteNode  = elem.get AttributeN ode("tabin dex");
  2629  
  2630                                      return a ttributeNo de && attr ibuteNode. specified  ?
  2631                                               parseInt(  attributeN ode.value,  10 ) :
  2632                                               rfocusable .test( ele m.nodeName  ) || rcli ckable.tes t( elem.no deName ) & & elem.hre f ?
  2633                                                       0  :
  2634                                                       un defined;
  2635                             }
  2636                    }
  2637           }
  2638   });
  2639  
  2640   // Add the  tabIndex  propHook t o attrHook s for back -compat (d ifferent c ase is int entional)
  2641   jQuery.att rHooks.tab index = jQ uery.propH ooks.tabIn dex;
  2642  
  2643   // Hook fo r boolean  attributes
  2644   boolHook =  {
  2645           ge t: functio n( elem, n ame ) {
  2646                    // A lign boole an attribu tes with c orrespondi ng propert ies
  2647                    // F all back t o attribut e presence  where som e booleans  are not s upported
  2648                    var  attrNode,
  2649                             proper ty = jQuer y.prop( el em, name ) ;
  2650                    retu rn propert y === true  || typeof  property  !== "boole an" && ( a ttrNode =  elem.getAt tributeNod e(name) )  && attrNod e.nodeValu e !== fals e ?
  2651                             name.t oLowerCase () :
  2652                             undefi ned;
  2653           },
  2654           se t: functio n( elem, v alue, name  ) {
  2655                    var  propName;
  2656                    if (  value ===  false ) {
  2657                             // Rem ove boolea n attribut es when se t to false
  2658                             jQuery .removeAtt r( elem, n ame );
  2659                    } el se {
  2660                             // val ue is true  since we  know at th is point i t's type b oolean and  not false
  2661                             // Set  boolean a ttributes  to the sam e name and  set the D OM propert y
  2662                             propNa me = jQuer y.propFix[  name ] ||  name;
  2663                             if ( p ropName in  elem ) {
  2664                                      // Only  set the ID L specific ally if it  already e xists on t he element
  2665                                      elem[ pr opName ] =  true;
  2666                             }
  2667  
  2668                             elem.s etAttribut e( name, n ame.toLowe rCase() );
  2669                    }
  2670                    retu rn name;
  2671           }
  2672   };
  2673  
  2674   // IE6/7 d o not supp ort gettin g/setting  some attri butes with  get/setAt tribute
  2675   if ( !getS etAttribut e ) {
  2676  
  2677           fi xSpecified  = {
  2678                    name : true,
  2679                    id:  true
  2680           };
  2681  
  2682           //  Use this  for any at tribute in  IE6/7
  2683           //  This fixe s almost e very IE6/7  issue
  2684           no deHook = j Query.valH ooks.butto n = {
  2685                    get:  function(  elem, nam e ) {
  2686                             var re t;
  2687                             ret =  elem.getAt tributeNod e( name );
  2688                             return  ret && (  fixSpecifi ed[ name ]  ? ret.nod eValue !==  "" : ret. specified  ) ?
  2689                                      ret.node Value :
  2690                                      undefine d;
  2691                    },
  2692                    set:  function(  elem, val ue, name )  {
  2693                             // Set  the exist ing or cre ate a new  attribute  node
  2694                             var re t = elem.g etAttribut eNode( nam e );
  2695                             if ( ! ret ) {
  2696                                      ret = do cument.cre ateAttribu te( name ) ;
  2697                                      elem.set AttributeN ode( ret ) ;
  2698                             }
  2699                             return  ( ret.nod eValue = v alue + ""  );
  2700                    }
  2701           };
  2702  
  2703           //  Apply the  nodeHook  to tabinde x
  2704           jQ uery.attrH ooks.tabin dex.set =  nodeHook.s et;
  2705  
  2706           //  Set width  and heigh t to auto  instead of  0 on empt y string(  Bug #8150  )
  2707           //  This is f or removal s
  2708           jQ uery.each( [ "width",  "height"  ], functio n( i, name  ) {
  2709                    jQue ry.attrHoo ks[ name ]  = jQuery. extend( jQ uery.attrH ooks[ name  ], {
  2710                             set: f unction( e lem, value  ) {
  2711                                      if ( val ue === ""  ) {
  2712                                               elem.setAt tribute( n ame, "auto " );
  2713                                               return val ue;
  2714                                      }
  2715                             }
  2716                    });
  2717           }) ;
  2718  
  2719           //  Set conte nteditable  to false  on removal s(#10429)
  2720           //  Setting t o empty st ring throw s an error  as an inv alid value
  2721           jQ uery.attrH ooks.conte nteditable  = {
  2722                    get:  nodeHook. get,
  2723                    set:  function(  elem, val ue, name )  {
  2724                             if ( v alue === " " ) {
  2725                                      value =  "false";
  2726                             }
  2727                             nodeHo ok.set( el em, value,  name );
  2728                    }
  2729           };
  2730   }
  2731  
  2732  
  2733   // Some at tributes r equire a s pecial cal l on IE
  2734   if ( !jQue ry.support .hrefNorma lized ) {
  2735           jQ uery.each( [ "href",  "src", "wi dth", "hei ght" ], fu nction( i,  name ) {
  2736                    jQue ry.attrHoo ks[ name ]  = jQuery. extend( jQ uery.attrH ooks[ name  ], {
  2737                             get: f unction( e lem ) {
  2738                                      var ret  = elem.get Attribute(  name, 2 ) ;
  2739                                      return r et === nul l ? undefi ned : ret;
  2740                             }
  2741                    });
  2742           }) ;
  2743   }
  2744  
  2745   if ( !jQue ry.support .style ) {
  2746           jQ uery.attrH ooks.style  = {
  2747                    get:  function(  elem ) {
  2748                             // Ret urn undefi ned in the  case of e mpty strin g
  2749                             // Nor malize to  lowercase  since IE u ppercases  css proper ty names
  2750                             return  elem.styl e.cssText. toLowerCas e() || und efined;
  2751                    },
  2752                    set:  function(  elem, val ue ) {
  2753                             return  ( elem.st yle.cssTex t = "" + v alue );
  2754                    }
  2755           };
  2756   }
  2757  
  2758   // Safari  mis-report s the defa ult select ed propert y of an op tion
  2759   // Accessi ng the par ent's sele ctedIndex  property f ixes it
  2760   if ( !jQue ry.support .optSelect ed ) {
  2761           jQ uery.propH ooks.selec ted = jQue ry.extend(  jQuery.pr opHooks.se lected, {
  2762                    get:  function(  elem ) {
  2763                             var pa rent = ele m.parentNo de;
  2764  
  2765                             if ( p arent ) {
  2766                                      parent.s electedInd ex;
  2767  
  2768                                      // Make  sure that  it also wo rks with o ptgroups,  see #5701
  2769                                      if ( par ent.parent Node ) {
  2770                                               parent.par entNode.se lectedInde x;
  2771                                      }
  2772                             }
  2773                             return  null;
  2774                    }
  2775           }) ;
  2776   }
  2777  
  2778   // IE6/7 c all enctyp e encoding
  2779   if ( !jQue ry.support .enctype )  {
  2780           jQ uery.propF ix.enctype  = "encodi ng";
  2781   }
  2782  
  2783   // Radios  and checkb oxes gette r/setter
  2784   if ( !jQue ry.support .checkOn )  {
  2785           jQ uery.each( [ "radio",  "checkbox " ], funct ion() {
  2786                    jQue ry.valHook s[ this ]  = {
  2787                             get: f unction( e lem ) {
  2788                                      // Handl e the case  where in  Webkit ""  is returne d instead  of "on" if  a value i sn't speci fied
  2789                                      return e lem.getAtt ribute("va lue") ===  null ? "on " : elem.v alue;
  2790                             }
  2791                    };
  2792           }) ;
  2793   }
  2794   jQuery.eac h([ "radio ", "checkb ox" ], fun ction() {
  2795           jQ uery.valHo oks[ this  ] = jQuery .extend( j Query.valH ooks[ this  ], {
  2796                    set:  function(  elem, val ue ) {
  2797                             if ( j Query.isAr ray( value  ) ) {
  2798                                      return (  elem.chec ked = jQue ry.inArray ( jQuery(e lem).val() , value )  >= 0 );
  2799                             }
  2800                    }
  2801           }) ;
  2802   });
  2803  
  2804  
  2805  
  2806  
  2807   var rformE lems = /^( ?:textarea |input|sel ect)$/i,
  2808           rt ypenamespa ce = /^([^ \.]*)?(?:\ .(.+))?$/,
  2809           rh overHack =  /\bhover( \.\S+)?\b/ ,
  2810           rk eyEvent =  /^key/,
  2811           rm ouseEvent  = /^(?:mou se|context menu)|clic k/,
  2812           rf ocusMorph  = /^(?:foc usinfocus| focusoutbl ur)$/,
  2813           rq uickIs = / ^(\w*)(?:# ([\w\-]+)) ?(?:\.([\w \-]+))?$/,
  2814           qu ickParse =  function(  selector  ) {
  2815                    var  quick = rq uickIs.exe c( selecto r );
  2816                    if (  quick ) {
  2817                             //   0   1    2    3
  2818                             // [ _ , tag, id,  class ]
  2819                             quick[ 1] = ( qui ck[1] || " " ).toLowe rCase();
  2820                             quick[ 3] = quick [3] && new  RegExp( " (?:^|\\s)"  + quick[3 ] + "(?:\\ s|$)" );
  2821                    }
  2822                    retu rn quick;
  2823           },
  2824           qu ickIs = fu nction( el em, m ) {
  2825                    var  attrs = el em.attribu tes || {};
  2826                    retu rn (
  2827                             (!m[1]  || elem.n odeName.to LowerCase( ) === m[1] ) &&
  2828                             (!m[2]  || (attrs .id || {}) .value ===  m[2]) &&
  2829                             (!m[3]  || m[3].t est( (attr s[ "class"  ] || {}). value ))
  2830                    );
  2831           },
  2832           ho verHack =  function(  events ) {
  2833                    retu rn jQuery. event.spec ial.hover  ? events :  events.re place( rho verHack, " mouseenter $1 mousele ave$1" );
  2834           };
  2835  
  2836   /*
  2837    * Helper  functions  for managi ng events  -- not par t of the p ublic inte rface.
  2838    * Props t o Dean Edw ards' addE vent libra ry for man y of the i deas.
  2839    */
  2840   jQuery.eve nt = {
  2841  
  2842           ad d: functio n( elem, t ypes, hand ler, data,  selector  ) {
  2843  
  2844                    var  elemData,  eventHandl e, events,
  2845                             t, tns , type, na mespaces,  handleObj,
  2846                             handle ObjIn, qui ck, handle rs, specia l;
  2847  
  2848                    // D on't attac h events t o noData o r text/com ment nodes  (allow pl ain object s tho)
  2849                    if (  elem.node Type === 3  || elem.n odeType == = 8 || !ty pes || !ha ndler || ! (elemData  = jQuery._ data( elem  )) ) {
  2850                             return ;
  2851                    }
  2852  
  2853                    // C aller can  pass in an  object of  custom da ta in lieu  of the ha ndler
  2854                    if (  handler.h andler ) {
  2855                             handle ObjIn = ha ndler;
  2856                             handle r = handle ObjIn.hand ler;
  2857                    }
  2858  
  2859                    // M ake sure t hat the ha ndler has  a unique I D, used to  find/remo ve it late r
  2860                    if (  !handler. guid ) {
  2861                             handle r.guid = j Query.guid ++;
  2862                    }
  2863  
  2864                    // I nit the el ement's ev ent struct ure and ma in handler , if this  is the fir st
  2865                    even ts = elemD ata.events ;
  2866                    if (  !events )  {
  2867                             elemDa ta.events  = events =  {};
  2868                    }
  2869                    even tHandle =  elemData.h andle;
  2870                    if (  !eventHan dle ) {
  2871                             elemDa ta.handle  = eventHan dle = func tion( e )  {
  2872                                      // Disca rd the sec ond event  of a jQuer y.event.tr igger() an d
  2873                                      // when  an event i s called a fter a pag e has unlo aded
  2874                                      return t ypeof jQue ry !== "un defined" & & (!e || j Query.even t.triggere d !== e.ty pe) ?
  2875                                               jQuery.eve nt.dispatc h.apply( e ventHandle .elem, arg uments ) :
  2876                                               undefined;
  2877                             };
  2878                             // Add  elem as a  property  of the han dle fn to  prevent a  memory lea k with IE  non-native  events
  2879                             eventH andle.elem  = elem;
  2880                    }
  2881  
  2882                    // H andle mult iple event s separate d by a spa ce
  2883                    // j Query(...) .bind("mou seover mou seout", fn );
  2884                    type s = jQuery .trim( hov erHack(typ es) ).spli t( " " );
  2885                    for  ( t = 0; t  < types.l ength; t++  ) {
  2886  
  2887                             tns =  rtypenames pace.exec(  types[t]  ) || [];
  2888                             type =  tns[1];
  2889                             namesp aces = ( t ns[2] || " " ).split(  "." ).sor t();
  2890  
  2891                             // If  event chan ges its ty pe, use th e special  event hand lers for t he changed  type
  2892                             specia l = jQuery .event.spe cial[ type  ] || {};
  2893  
  2894                             // If  selector d efined, de termine sp ecial even t api type , otherwis e given ty pe
  2895                             type =  ( selecto r ? specia l.delegate Type : spe cial.bindT ype ) || t ype;
  2896  
  2897                             // Upd ate specia l based on  newly res et type
  2898                             specia l = jQuery .event.spe cial[ type  ] || {};
  2899  
  2900                             // han dleObj is  passed to  all event  handlers
  2901                             handle Obj = jQue ry.extend( {
  2902                                      type: ty pe,
  2903                                      origType : tns[1],
  2904                                      data: da ta,
  2905                                      handler:  handler,
  2906                                      guid: ha ndler.guid ,
  2907                                      selector : selector ,
  2908                                      quick: q uickParse(  selector  ),
  2909                                      namespac e: namespa ces.join(" .")
  2910                             }, han dleObjIn ) ;
  2911  
  2912                             // Ini t the even t handler  queue if w e're the f irst
  2913                             handle rs = event s[ type ];
  2914                             if ( ! handlers )  {
  2915                                      handlers  = events[  type ] =  [];
  2916                                      handlers .delegateC ount = 0;
  2917  
  2918                                      // Only  use addEve ntListener /attachEve nt if the  special ev ents handl er returns  false
  2919                                      if ( !sp ecial.setu p || speci al.setup.c all( elem,  data, nam espaces, e ventHandle  ) === fal se ) {
  2920                                               // Bind th e global e vent handl er to the  element
  2921                                               if ( elem. addEventLi stener ) {
  2922                                                       el em.addEven tListener(  type, eve ntHandle,  false );
  2923  
  2924                                               } else if  ( elem.att achEvent )  {
  2925                                                       el em.attachE vent( "on"  + type, e ventHandle  );
  2926                                               }
  2927                                      }
  2928                             }
  2929  
  2930                             if ( s pecial.add  ) {
  2931                                      special. add.call(  elem, hand leObj );
  2932  
  2933                                      if ( !ha ndleObj.ha ndler.guid  ) {
  2934                                               handleObj. handler.gu id = handl er.guid;
  2935                                      }
  2936                             }
  2937  
  2938                             // Add  to the el ement's ha ndler list , delegate s in front
  2939                             if ( s elector )  {
  2940                                      handlers .splice( h andlers.de legateCoun t++, 0, ha ndleObj );
  2941                             } else  {
  2942                                      handlers .push( han dleObj );
  2943                             }
  2944  
  2945                             // Kee p track of  which eve nts have e ver been u sed, for e vent optim ization
  2946                             jQuery .event.glo bal[ type  ] = true;
  2947                    }
  2948  
  2949                    // N ullify ele m to preve nt memory  leaks in I E
  2950                    elem  = null;
  2951           },
  2952  
  2953           gl obal: {},
  2954  
  2955           //  Detach an  event or  set of eve nts from a n element
  2956           re move: func tion( elem , types, h andler, se lector, ma ppedTypes  ) {
  2957  
  2958                    var  elemData =  jQuery.ha sData( ele m ) && jQu ery._data(  elem ),
  2959                             t, tns , type, or igType, na mespaces,  origCount,
  2960                             j, eve nts, speci al, handle , eventTyp e, handleO bj;
  2961  
  2962                    if (  !elemData  || !(even ts = elemD ata.events ) ) {
  2963                             return ;
  2964                    }
  2965  
  2966                    // O nce for ea ch type.na mespace in  types; ty pe may be  omitted
  2967                    type s = jQuery .trim( hov erHack( ty pes || ""  ) ).split( " ");
  2968                    for  ( t = 0; t  < types.l ength; t++  ) {
  2969                             tns =  rtypenames pace.exec(  types[t]  ) || [];
  2970                             type =  origType  = tns[1];
  2971                             namesp aces = tns [2];
  2972  
  2973                             // Unb ind all ev ents (on t his namesp ace, if pr ovided) fo r the elem ent
  2974                             if ( ! type ) {
  2975                                      for ( ty pe in even ts ) {
  2976                                               jQuery.eve nt.remove(  elem, typ e + types[  t ], hand ler, selec tor, true  );
  2977                                      }
  2978                                      continue ;
  2979                             }
  2980  
  2981                             specia l = jQuery .event.spe cial[ type  ] || {};
  2982                             type =  ( selecto r? special .delegateT ype : spec ial.bindTy pe ) || ty pe;
  2983                             eventT ype = even ts[ type ]  || [];
  2984                             origCo unt = even tType.leng th;
  2985                             namesp aces = nam espaces ?  new RegExp ("(^|\\.)"  + namespa ces.split( ".").sort( ).join("\\ .(?:.*\\.) ?") + "(\\ .|$)") : n ull;
  2986  
  2987                             // Rem ove matchi ng events
  2988                             for (  j = 0; j <  eventType .length; j ++ ) {
  2989                                      handleOb j = eventT ype[ j ];
  2990  
  2991                                      if ( ( m appedTypes  || origTy pe === han dleObj.ori gType ) &&
  2992                                                ( !handle r || handl er.guid == = handleOb j.guid ) & &
  2993                                                ( !namesp aces || na mespaces.t est( handl eObj.names pace ) ) & &
  2994                                                ( !select or || sele ctor === h andleObj.s elector ||  selector  === "**" & & handleOb j.selector  ) ) {
  2995                                               eventType. splice( j- -, 1 );
  2996  
  2997                                               if ( handl eObj.selec tor ) {
  2998                                                       ev entType.de legateCoun t--;
  2999                                               }
  3000                                               if ( speci al.remove  ) {
  3001                                                       sp ecial.remo ve.call( e lem, handl eObj );
  3002                                               }
  3003                                      }
  3004                             }
  3005  
  3006                             // Rem ove generi c event ha ndler if w e removed  something  and no mor e handlers  exist
  3007                             // (av oids poten tial for e ndless rec ursion dur ing remova l of speci al event h andlers)
  3008                             if ( e ventType.l ength ===  0 && origC ount !== e ventType.l ength ) {
  3009                                      if ( !sp ecial.tear down || sp ecial.tear down.call(  elem, nam espaces )  === false  ) {
  3010                                               jQuery.rem oveEvent(  elem, type , elemData .handle );
  3011                                      }
  3012  
  3013                                      delete e vents[ typ e ];
  3014                             }
  3015                    }
  3016  
  3017                    // R emove the  expando if  it's no l onger used
  3018                    if (  jQuery.is EmptyObjec t( events  ) ) {
  3019                             handle  = elemDat a.handle;
  3020                             if ( h andle ) {
  3021                                      handle.e lem = null ;
  3022                             }
  3023  
  3024                             // rem oveData al so checks  for emptin ess and cl ears the e xpando if  empty
  3025                             // so  use it ins tead of de lete
  3026                             jQuery .removeDat a( elem, [  "events",  "handle"  ], true );
  3027                    }
  3028           },
  3029  
  3030           //  Events th at are saf e to short -circuit i f no handl ers are at tached.
  3031           //  Native DO M events s hould not  be added,  they may h ave inline  handlers.
  3032           cu stomEvent:  {
  3033                    "get Data": tru e,
  3034                    "set Data": tru e,
  3035                    "cha ngeData":  true
  3036           },
  3037  
  3038           tr igger: fun ction( eve nt, data,  elem, only Handlers )  {
  3039                    // D on't do ev ents on te xt and com ment nodes
  3040                    if (  elem && ( elem.nodeT ype === 3  || elem.no deType ===  8) ) {
  3041                             return ;
  3042                    }
  3043  
  3044                    // E vent objec t or event  type
  3045                    var  type = eve nt.type ||  event,
  3046                             namesp aces = [],
  3047                             cache,  exclusive , i, cur,  old, ontyp e, special , handle,  eventPath,  bubbleTyp e;
  3048  
  3049                    // f ocus/blur  morphs to  focusin/ou t; ensure  we're not  firing the m right no w
  3050                    if (  rfocusMor ph.test( t ype + jQue ry.event.t riggered )  ) {
  3051                             return ;
  3052                    }
  3053  
  3054                    if (  type.inde xOf( "!" )  >= 0 ) {
  3055                             // Exc lusive eve nts trigge r only for  the exact  event (no  namespace s)
  3056                             type =  type.slic e(0, -1);
  3057                             exclus ive = true ;
  3058                    }
  3059  
  3060                    if (  type.inde xOf( "." )  >= 0 ) {
  3061                             // Nam espaced tr igger; cre ate a rege xp to matc h event ty pe in hand le()
  3062                             namesp aces = typ e.split(". ");
  3063                             type =  namespace s.shift();
  3064                             namesp aces.sort( );
  3065                    }
  3066  
  3067                    if (  (!elem ||  jQuery.ev ent.custom Event[ typ e ]) && !j Query.even t.global[  type ] ) {
  3068                             // No  jQuery han dlers for  this event  type, and  it can't  have inlin e handlers
  3069                             return ;
  3070                    }
  3071  
  3072                    // C aller can  pass in an  Event, Ob ject, or j ust an eve nt type st ring
  3073                    even t = typeof  event ===  "object"  ?
  3074                             // jQu ery.Event  object
  3075                             event[  jQuery.ex pando ] ?  event :
  3076                             // Obj ect litera l
  3077                             new jQ uery.Event ( type, ev ent ) :
  3078                             // Jus t the even t type (st ring)
  3079                             new jQ uery.Event ( type );
  3080  
  3081                    even t.type = t ype;
  3082                    even t.isTrigge r = true;
  3083                    even t.exclusiv e = exclus ive;
  3084                    even t.namespac e = namesp aces.join(  "." );
  3085                    even t.namespac e_re = eve nt.namespa ce? new Re gExp("(^|\ \.)" + nam espaces.jo in("\\.(?: .*\\.)?")  + "(\\.|$) ") : null;
  3086                    onty pe = type. indexOf( " :" ) < 0 ?  "on" + ty pe : "";
  3087  
  3088                    // H andle a gl obal trigg er
  3089                    if (  !elem ) {
  3090  
  3091                             // TOD O: Stop ta unting the  data cach e; remove  global eve nts and al ways attac h to docum ent
  3092                             cache  = jQuery.c ache;
  3093                             for (  i in cache  ) {
  3094                                      if ( cac he[ i ].ev ents && ca che[ i ].e vents[ typ e ] ) {
  3095                                               jQuery.eve nt.trigger ( event, d ata, cache [ i ].hand le.elem, t rue );
  3096                                      }
  3097                             }
  3098                             return ;
  3099                    }
  3100  
  3101                    // C lean up th e event in  case it i s being re used
  3102                    even t.result =  undefined ;
  3103                    if (  !event.ta rget ) {
  3104                             event. target = e lem;
  3105                    }
  3106  
  3107                    // C lone any i ncoming da ta and pre pend the e vent, crea ting the h andler arg  list
  3108                    data  = data !=  null ? jQ uery.makeA rray( data  ) : [];
  3109                    data .unshift(  event );
  3110  
  3111                    // A llow speci al events  to draw ou tside the  lines
  3112                    spec ial = jQue ry.event.s pecial[ ty pe ] || {} ;
  3113                    if (  special.t rigger &&  special.tr igger.appl y( elem, d ata ) ===  false ) {
  3114                             return ;
  3115                    }
  3116  
  3117                    // D etermine e vent propa gation pat h in advan ce, per W3 C events s pec (#9951 )
  3118                    // B ubble up t o document , then to  window; wa tch for a  global own erDocument  var (#972 4)
  3119                    even tPath = [[  elem, spe cial.bindT ype || typ e ]];
  3120                    if (  !onlyHand lers && !s pecial.noB ubble && ! jQuery.isW indow( ele m ) ) {
  3121  
  3122                             bubble Type = spe cial.deleg ateType ||  type;
  3123                             cur =  rfocusMorp h.test( bu bbleType +  type ) ?  elem : ele m.parentNo de;
  3124                             old =  null;
  3125                             for (  ; cur; cur  = cur.par entNode )  {
  3126                                      eventPat h.push([ c ur, bubble Type ]);
  3127                                      old = cu r;
  3128                             }
  3129  
  3130                             // Onl y add wind ow if we g ot to docu ment (e.g. , not plai n obj or d etached DO M)
  3131                             if ( o ld && old  === elem.o wnerDocume nt ) {
  3132                                      eventPat h.push([ o ld.default View || ol d.parentWi ndow || wi ndow, bubb leType ]);
  3133                             }
  3134                    }
  3135  
  3136                    // F ire handle rs on the  event path
  3137                    for  ( i = 0; i  < eventPa th.length  && !event. isPropagat ionStopped (); i++ )  {
  3138  
  3139                             cur =  eventPath[ i][0];
  3140                             event. type = eve ntPath[i][ 1];
  3141  
  3142                             handle  = ( jQuer y._data( c ur, "event s" ) || {}  )[ event. type ] &&  jQuery._da ta( cur, " handle" );
  3143                             if ( h andle ) {
  3144                                      handle.a pply( cur,  data );
  3145                             }
  3146                             // Not e that thi s is a bar e JS funct ion and no t a jQuery  handler
  3147                             handle  = ontype  && cur[ on type ];
  3148                             if ( h andle && j Query.acce ptData( cu r ) && han dle.apply(  cur, data  ) === fal se ) {
  3149                                      event.pr eventDefau lt();
  3150                             }
  3151                    }
  3152                    even t.type = t ype;
  3153  
  3154                    // I f nobody p revented t he default  action, d o it now
  3155                    if (  !onlyHand lers && !e vent.isDef aultPreven ted() ) {
  3156  
  3157                             if ( ( !special._ default ||  special._ default.ap ply( elem. ownerDocum ent, data  ) === fals e) &&
  3158                                      !(type = == "click"  && jQuery .nodeName(  elem, "a"  )) && jQu ery.accept Data( elem  ) ) {
  3159  
  3160                                      // Call  a native D OM method  on the tar get with t he same na me name as  the event .
  3161                                      // Can't  use an .i sFunction( ) check he re because  IE6/7 fai ls that te st.
  3162                                      // Don't  do defaul t actions  on window,  that's wh ere global  variables  be (#6170 )
  3163                                      // IE<9  dies on fo cus/blur t o hidden e lement (#1 486)
  3164                                      if ( ont ype && ele m[ type ]  && ((type  !== "focus " && type  !== "blur" ) || event .target.of fsetWidth  !== 0) &&  !jQuery.is Window( el em ) ) {
  3165  
  3166                                               // Don't r e-trigger  an onFOO e vent when  we call it s FOO() me thod
  3167                                               old = elem [ ontype ] ;
  3168  
  3169                                               if ( old )  {
  3170                                                       el em[ ontype  ] = null;
  3171                                               }
  3172  
  3173                                               // Prevent  re-trigge ring of th e same eve nt, since  we already  bubbled i t above
  3174                                               jQuery.eve nt.trigger ed = type;
  3175                                               elem[ type  ]();
  3176                                               jQuery.eve nt.trigger ed = undef ined;
  3177  
  3178                                               if ( old )  {
  3179                                                       el em[ ontype  ] = old;
  3180                                               }
  3181                                      }
  3182                             }
  3183                    }
  3184  
  3185                    retu rn event.r esult;
  3186           },
  3187  
  3188           di spatch: fu nction( ev ent ) {
  3189  
  3190                    // M ake a writ able jQuer y.Event fr om the nat ive event  object
  3191                    even t = jQuery .event.fix ( event ||  window.ev ent );
  3192  
  3193                    var  handlers =  ( (jQuery ._data( th is, "event s" ) || {}  )[ event. type ] ||  []),
  3194                             delega teCount =  handlers.d elegateCou nt,
  3195                             args =  [].slice. call( argu ments, 0 ) ,
  3196                             run_al l = !event .exclusive  && !event .namespace ,
  3197                             handle rQueue = [ ],
  3198                             i, j,  cur, jqcur , ret, sel Match, mat ched, matc hes, handl eObj, sel,  related;
  3199  
  3200                    // U se the fix -ed jQuery .Event rat her than t he (read-o nly) nativ e event
  3201                    args [0] = even t;
  3202                    even t.delegate Target = t his;
  3203  
  3204                    // D etermine h andlers th at should  run if the re are del egated eve nts
  3205                    // A void disab led elemen ts in IE ( #6911) and  non-left- click bubb ling in Fi refox (#38 61)
  3206                    if (  delegateC ount && !e vent.targe t.disabled  && !(even t.button & & event.ty pe === "cl ick") ) {
  3207  
  3208                             // Pre generate a  single jQ uery objec t for reus e with .is ()
  3209                             jqcur  = jQuery(t his);
  3210                             jqcur. context =  this.owner Document | | this;
  3211  
  3212                             for (  cur = even t.target;  cur != thi s; cur = c ur.parentN ode || thi s ) {
  3213                                      selMatch  = {};
  3214                                      matches  = [];
  3215                                      jqcur[0]  = cur;
  3216                                      for ( i  = 0; i < d elegateCou nt; i++ )  {
  3217                                               handleObj  = handlers [ i ];
  3218                                               sel = hand leObj.sele ctor;
  3219  
  3220                                               if ( selMa tch[ sel ]  === undef ined ) {
  3221                                                       se lMatch[ se l ] = (
  3222                                                                hand leObj.quic k ? quickI s( cur, ha ndleObj.qu ick ) : jq cur.is( se l )
  3223                                                       );
  3224                                               }
  3225                                               if ( selMa tch[ sel ]  ) {
  3226                                                       ma tches.push ( handleOb j );
  3227                                               }
  3228                                      }
  3229                                      if ( mat ches.lengt h ) {
  3230                                               handlerQue ue.push({  elem: cur,  matches:  matches }) ;
  3231                                      }
  3232                             }
  3233                    }
  3234  
  3235                    // A dd the rem aining (di rectly-bou nd) handle rs
  3236                    if (  handlers. length > d elegateCou nt ) {
  3237                             handle rQueue.pus h({ elem:  this, matc hes: handl ers.slice(  delegateC ount ) });
  3238                    }
  3239  
  3240                    // R un delegat es first;  they may w ant to sto p propagat ion beneat h us
  3241                    for  ( i = 0; i  < handler Queue.leng th && !eve nt.isPropa gationStop ped(); i++  ) {
  3242                             matche d = handle rQueue[ i  ];
  3243                             event. currentTar get = matc hed.elem;
  3244  
  3245                             for (  j = 0; j <  matched.m atches.len gth && !ev ent.isImme diatePropa gationStop ped(); j++  ) {
  3246                                      handleOb j = matche d.matches[  j ];
  3247  
  3248                                      // Trigg ered event  must eith er 1) be n on-exclusi ve and hav e no names pace, or
  3249                                      // 2) ha ve namespa ce(s) a su bset or eq ual to tho se in the  bound even t (both ca n have no  namespace) .
  3250                                      if ( run _all || (! event.name space && ! handleObj. namespace)  || event. namespace_ re && even t.namespac e_re.test(  handleObj .namespace  ) ) {
  3251  
  3252                                               event.data  = handleO bj.data;
  3253                                               event.hand leObj = ha ndleObj;
  3254  
  3255                                               ret = ( (j Query.even t.special[  handleObj .origType  ] || {}).h andle || h andleObj.h andler )
  3256                                                                .app ly( matche d.elem, ar gs );
  3257  
  3258                                               if ( ret ! == undefin ed ) {
  3259                                                       ev ent.result  = ret;
  3260                                                       if  ( ret ===  false ) {
  3261                                                                even t.preventD efault();
  3262                                                                even t.stopProp agation();
  3263                                                       }
  3264                                               }
  3265                                      }
  3266                             }
  3267                    }
  3268  
  3269                    retu rn event.r esult;
  3270           },
  3271  
  3272           //  Includes  some event  props sha red by Key Event and  MouseEvent
  3273           //  *** attrC hange attr Name relat edNode src Element  a re not nor malized, n on-W3C, de precated,  will be re moved in 1 .8 ***
  3274           pr ops: "attr Change att rName rela tedNode sr cElement a ltKey bubb les cancel able ctrlK ey current Target eve ntPhase me taKey rela tedTarget  shiftKey t arget time Stamp view  which".sp lit(" "),
  3275  
  3276           fi xHooks: {} ,
  3277  
  3278           ke yHooks: {
  3279                    prop s: "char c harCode ke y keyCode" .split(" " ),
  3280                    filt er: functi on( event,  original  ) {
  3281  
  3282                             // Add  which for  key event s
  3283                             if ( e vent.which  == null )  {
  3284                                      event.wh ich = orig inal.charC ode != nul l ? origin al.charCod e : origin al.keyCode ;
  3285                             }
  3286  
  3287                             return  event;
  3288                    }
  3289           },
  3290  
  3291           mo useHooks:  {
  3292                    prop s: "button  buttons c lientX cli entY fromE lement off setX offse tY pageX p ageY scree nX screenY  toElement ".split("  "),
  3293                    filt er: functi on( event,  original  ) {
  3294                             var ev entDoc, do c, body,
  3295                                      button =  original. button,
  3296                                      fromElem ent = orig inal.fromE lement;
  3297  
  3298                             // Cal culate pag eX/Y if mi ssing and  clientX/Y  available
  3299                             if ( e vent.pageX  == null & & original .clientX ! = null ) {
  3300                                      eventDoc  = event.t arget.owne rDocument  || documen t;
  3301                                      doc = ev entDoc.doc umentEleme nt;
  3302                                      body = e ventDoc.bo dy;
  3303  
  3304                                      event.pa geX = orig inal.clien tX + ( doc  && doc.sc rollLeft | | body &&  body.scrol lLeft || 0  ) - ( doc  && doc.cl ientLeft | | body &&  body.clien tLeft || 0  );
  3305                                      event.pa geY = orig inal.clien tY + ( doc  && doc.sc rollTop  | | body &&  body.scrol lTop  || 0  ) - ( doc  && doc.cl ientTop  | | body &&  body.clien tTop  || 0  );
  3306                             }
  3307  
  3308                             // Add  relatedTa rget, if n ecessary
  3309                             if ( ! event.rela tedTarget  && fromEle ment ) {
  3310                                      event.re latedTarge t = fromEl ement ===  event.targ et ? origi nal.toElem ent : from Element;
  3311                             }
  3312  
  3313                             // Add  which for  click: 1  === left;  2 === midd le; 3 ===  right
  3314                             // Not e: button  is not nor malized, s o don't us e it
  3315                             if ( ! event.whic h && butto n !== unde fined ) {
  3316                                      event.wh ich = ( bu tton & 1 ?  1 : ( but ton & 2 ?  3 : ( butt on & 4 ? 2  : 0 ) ) ) ;
  3317                             }
  3318  
  3319                             return  event;
  3320                    }
  3321           },
  3322  
  3323           fi x: functio n( event )  {
  3324                    if (  event[ jQ uery.expan do ] ) {
  3325                             return  event;
  3326                    }
  3327  
  3328                    // C reate a wr itable cop y of the e vent objec t and norm alize some  propertie s
  3329                    var  i, prop,
  3330                             origin alEvent =  event,
  3331                             fixHoo k = jQuery .event.fix Hooks[ eve nt.type ]  || {},
  3332                             copy =  fixHook.p rops ? thi s.props.co ncat( fixH ook.props  ) : this.p rops;
  3333  
  3334                    even t = jQuery .Event( or iginalEven t );
  3335  
  3336                    for  ( i = copy .length; i ; ) {
  3337                             prop =  copy[ --i  ];
  3338                             event[  prop ] =  originalEv ent[ prop  ];
  3339                    }
  3340  
  3341                    // F ix target  property,  if necessa ry (#1925,  IE 6/7/8  & Safari2)
  3342                    if (  !event.ta rget ) {
  3343                             event. target = o riginalEve nt.srcElem ent || doc ument;
  3344                    }
  3345  
  3346                    // T arget shou ld not be  a text nod e (#504, S afari)
  3347                    if (  event.tar get.nodeTy pe === 3 )  {
  3348                             event. target = e vent.targe t.parentNo de;
  3349                    }
  3350  
  3351                    // F or mouse/k ey events;  add metaK ey if it's  not there  (#3368, I E6/7/8)
  3352                    if (  event.met aKey === u ndefined )  {
  3353                             event. metaKey =  event.ctrl Key;
  3354                    }
  3355  
  3356                    retu rn fixHook .filter? f ixHook.fil ter( event , original Event ) :  event;
  3357           },
  3358  
  3359           sp ecial: {
  3360                    read y: {
  3361                             // Mak e sure the  ready eve nt is setu p
  3362                             setup:  jQuery.bi ndReady
  3363                    },
  3364  
  3365                    load : {
  3366                             // Pre vent trigg ered image .load even ts from bu bbling to  window.loa d
  3367                             noBubb le: true
  3368                    },
  3369  
  3370                    focu s: {
  3371                             delega teType: "f ocusin"
  3372                    },
  3373                    blur : {
  3374                             delega teType: "f ocusout"
  3375                    },
  3376  
  3377                    befo reunload:  {
  3378                             setup:  function(  data, nam espaces, e ventHandle  ) {
  3379                                      // We on ly want to  do this s pecial cas e on windo ws
  3380                                      if ( jQu ery.isWind ow( this )  ) {
  3381                                               this.onbef oreunload  = eventHan dle;
  3382                                      }
  3383                             },
  3384  
  3385                             teardo wn: functi on( namesp aces, even tHandle )  {
  3386                                      if ( thi s.onbefore unload ===  eventHand le ) {
  3387                                               this.onbef oreunload  = null;
  3388                                      }
  3389                             }
  3390                    }
  3391           },
  3392  
  3393           si mulate: fu nction( ty pe, elem,  event, bub ble ) {
  3394                    // P iggyback o n a donor  event to s imulate a  different  one.
  3395                    // F ake origin alEvent to  avoid don or's stopP ropagation , but if t he
  3396                    // s imulated e vent preve nts defaul t then we  do the sam e on the d onor.
  3397                    var  e = jQuery .extend(
  3398                             new jQ uery.Event (),
  3399                             event,
  3400                             { type : type,
  3401                                      isSimula ted: true,
  3402                                      original Event: {}
  3403                             }
  3404                    );
  3405                    if (  bubble )  {
  3406                             jQuery .event.tri gger( e, n ull, elem  );
  3407                    } el se {
  3408                             jQuery .event.dis patch.call ( elem, e  );
  3409                    }
  3410                    if (  e.isDefau ltPrevente d() ) {
  3411                             event. preventDef ault();
  3412                    }
  3413           }
  3414   };
  3415  
  3416   // Some pl ugins are  using, but  it's undo cumented/d eprecated  and will b e removed.
  3417   // The 1.7  special e vent inter face shoul d provide  all the ho oks needed  now.
  3418   jQuery.eve nt.handle  = jQuery.e vent.dispa tch;
  3419  
  3420   jQuery.rem oveEvent =  document. removeEven tListener  ?
  3421           fu nction( el em, type,  handle ) {
  3422                    if (  elem.remo veEventLis tener ) {
  3423                             elem.r emoveEvent Listener(  type, hand le, false  );
  3424                    }
  3425           }  :
  3426           fu nction( el em, type,  handle ) {
  3427                    if (  elem.deta chEvent )  {
  3428                             elem.d etachEvent ( "on" + t ype, handl e );
  3429                    }
  3430           };
  3431  
  3432   jQuery.Eve nt = funct ion( src,  props ) {
  3433           //  Allow ins tantiation  without t he 'new' k eyword
  3434           if  ( !(this  instanceof  jQuery.Ev ent) ) {
  3435                    retu rn new jQu ery.Event(  src, prop s );
  3436           }
  3437  
  3438           //  Event obj ect
  3439           if  ( src &&  src.type )  {
  3440                    this .originalE vent = src ;
  3441                    this .type = sr c.type;
  3442  
  3443                    // E vents bubb ling up th e document  may have  been marke d as preve nted
  3444                    // b y a handle r lower do wn the tre e; reflect  the corre ct value.
  3445                    this .isDefault Prevented  = ( src.de faultPreve nted || sr c.returnVa lue === fa lse ||
  3446                             src.ge tPreventDe fault && s rc.getPrev entDefault () ) ? ret urnTrue :  returnFals e;
  3447  
  3448           //  Event typ e
  3449           }  else {
  3450                    this .type = sr c;
  3451           }
  3452  
  3453           //  Put expli citly prov ided prope rties onto  the event  object
  3454           if  ( props )  {
  3455                    jQue ry.extend(  this, pro ps );
  3456           }
  3457  
  3458           //  Create a  timestamp  if incomin g event do esn't have  one
  3459           th is.timeSta mp = src & & src.time Stamp || j Query.now( );
  3460  
  3461           //  Mark it a s fixed
  3462           th is[ jQuery .expando ]  = true;
  3463   };
  3464  
  3465   function r eturnFalse () {
  3466           re turn false ;
  3467   }
  3468   function r eturnTrue( ) {
  3469           re turn true;
  3470   }
  3471  
  3472   // jQuery. Event is b ased on DO M3 Events  as specifi ed by the  ECMAScript  Language  Binding
  3473   // http:// www.w3.org /TR/2003/W D-DOM-Leve l-3-Events -20030331/ ecma-scrip t-binding. html
  3474   jQuery.Eve nt.prototy pe = {
  3475           pr eventDefau lt: functi on() {
  3476                    this .isDefault Prevented  = returnTr ue;
  3477  
  3478                    var  e = this.o riginalEve nt;
  3479                    if (  !e ) {
  3480                             return ;
  3481                    }
  3482  
  3483                    // i f preventD efault exi sts run it  on the or iginal eve nt
  3484                    if (  e.prevent Default )  {
  3485                             e.prev entDefault ();
  3486  
  3487                    // o therwise s et the ret urnValue p roperty of  the origi nal event  to false ( IE)
  3488                    } el se {
  3489                             e.retu rnValue =  false;
  3490                    }
  3491           },
  3492           st opPropagat ion: funct ion() {
  3493                    this .isPropaga tionStoppe d = return True;
  3494  
  3495                    var  e = this.o riginalEve nt;
  3496                    if (  !e ) {
  3497                             return ;
  3498                    }
  3499                    // i f stopProp agation ex ists run i t on the o riginal ev ent
  3500                    if (  e.stopPro pagation )  {
  3501                             e.stop Propagatio n();
  3502                    }
  3503                    // o therwise s et the can celBubble  property o f the orig inal event  to true ( IE)
  3504                    e.ca ncelBubble  = true;
  3505           },
  3506           st opImmediat ePropagati on: functi on() {
  3507                    this .isImmedia tePropagat ionStopped  = returnT rue;
  3508                    this .stopPropa gation();
  3509           },
  3510           is DefaultPre vented: re turnFalse,
  3511           is Propagatio nStopped:  returnFals e,
  3512           is ImmediateP ropagation Stopped: r eturnFalse
  3513   };
  3514  
  3515   // Create  mouseenter /leave eve nts using  mouseover/ out and ev ent-time c hecks
  3516   jQuery.eac h({
  3517           mo useenter:  "mouseover ",
  3518           mo useleave:  "mouseout"
  3519   }, functio n( orig, f ix ) {
  3520           jQ uery.event .special[  orig ] = {
  3521                    dele gateType:  fix,
  3522                    bind Type: fix,
  3523  
  3524                    hand le: functi on( event  ) {
  3525                             var ta rget = thi s,
  3526                                      related  = event.re latedTarge t,
  3527                                      handleOb j = event. handleObj,
  3528                                      selector  = handleO bj.selecto r,
  3529                                      ret;
  3530  
  3531                             // For  mousenter /leave cal l the hand ler if rel ated is ou tside the  target.
  3532                             // NB:  No relate dTarget if  the mouse  left/ente red the br owser wind ow
  3533                             if ( ! related ||  (related  !== target  && !jQuer y.contains ( target,  related ))  ) {
  3534                                      event.ty pe = handl eObj.origT ype;
  3535                                      ret = ha ndleObj.ha ndler.appl y( this, a rguments ) ;
  3536                                      event.ty pe = fix;
  3537                             }
  3538                             return  ret;
  3539                    }
  3540           };
  3541   });
  3542  
  3543   // IE subm it delegat ion
  3544   if ( !jQue ry.support .submitBub bles ) {
  3545  
  3546           jQ uery.event .special.s ubmit = {
  3547                    setu p: functio n() {
  3548                             // Onl y need thi s for dele gated form  submit ev ents
  3549                             if ( j Query.node Name( this , "form" )  ) {
  3550                                      return f alse;
  3551                             }
  3552  
  3553                             // Laz y-add a su bmit handl er when a  descendant  form may  potentiall y be submi tted
  3554                             jQuery .event.add ( this, "c lick._subm it keypres s._submit" , function ( e ) {
  3555                                      // Node  name check  avoids a  VML-relate d crash in  IE (#9807 )
  3556                                      var elem  = e.targe t,
  3557                                               form = jQu ery.nodeNa me( elem,  "input" )  || jQuery. nodeName(  elem, "but ton" ) ? e lem.form :  undefined ;
  3558                                      if ( for m && !form ._submit_a ttached )  {
  3559                                               jQuery.eve nt.add( fo rm, "submi t._submit" , function ( event )  {
  3560                                                       //  If form w as submitt ed by the  user, bubb le the eve nt up the  tree
  3561                                                       if  ( this.pa rentNode & & !event.i sTrigger )  {
  3562                                                                jQue ry.event.s imulate( " submit", t his.parent Node, even t, true );
  3563                                                       }
  3564                                               });
  3565                                               form._subm it_attache d = true;
  3566                                      }
  3567                             });
  3568                             // ret urn undefi ned since  we don't n eed an eve nt listene r
  3569                    },
  3570  
  3571                    tear down: func tion() {
  3572                             // Onl y need thi s for dele gated form  submit ev ents
  3573                             if ( j Query.node Name( this , "form" )  ) {
  3574                                      return f alse;
  3575                             }
  3576  
  3577                             // Rem ove delega ted handle rs; cleanD ata eventu ally reaps  submit ha ndlers att ached abov e
  3578                             jQuery .event.rem ove( this,  "._submit " );
  3579                    }
  3580           };
  3581   }
  3582  
  3583   // IE chan ge delegat ion and ch eckbox/rad io fix
  3584   if ( !jQue ry.support .changeBub bles ) {
  3585  
  3586           jQ uery.event .special.c hange = {
  3587  
  3588                    setu p: functio n() {
  3589  
  3590                             if ( r formElems. test( this .nodeName  ) ) {
  3591                                      // IE do esn't fire  change on  a check/r adio until  blur; tri gger it on  click
  3592                                      // after  a propert ychange. E at the blu r-change i n special. change.han dle.
  3593                                      // This  still fire s onchange  a second  time for c heck/radio  after blu r.
  3594                                      if ( thi s.type ===  "checkbox " || this. type === " radio" ) {
  3595                                               jQuery.eve nt.add( th is, "prope rtychange. _change",  function(  event ) {
  3596                                                       if  ( event.o riginalEve nt.propert yName ===  "checked"  ) {
  3597                                                                this ._just_cha nged = tru e;
  3598                                                       }
  3599                                               });
  3600                                               jQuery.eve nt.add( th is, "click ._change",  function(  event ) {
  3601                                                       if  ( this._j ust_change d && !even t.isTrigge r ) {
  3602                                                                this ._just_cha nged = fal se;
  3603                                                                jQue ry.event.s imulate( " change", t his, event , true );
  3604                                                       }
  3605                                               });
  3606                                      }
  3607                                      return f alse;
  3608                             }
  3609                             // Del egated eve nt; lazy-a dd a chang e handler  on descend ant inputs
  3610                             jQuery .event.add ( this, "b eforeactiv ate._chang e", functi on( e ) {
  3611                                      var elem  = e.targe t;
  3612  
  3613                                      if ( rfo rmElems.te st( elem.n odeName )  && !elem._ change_att ached ) {
  3614                                               jQuery.eve nt.add( el em, "chang e._change" , function ( event )  {
  3615                                                       if  ( this.pa rentNode & & !event.i sSimulated  && !event .isTrigger  ) {
  3616                                                                jQue ry.event.s imulate( " change", t his.parent Node, even t, true );
  3617                                                       }
  3618                                               });
  3619                                               elem._chan ge_attache d = true;
  3620                                      }
  3621                             });
  3622                    },
  3623  
  3624                    hand le: functi on( event  ) {
  3625                             var el em = event .target;
  3626  
  3627                             // Swa llow nativ e change e vents from  checkbox/ radio, we  already tr iggered th em above
  3628                             if ( t his !== el em || even t.isSimula ted || eve nt.isTrigg er || (ele m.type !==  "radio" & & elem.typ e !== "che ckbox") )  {
  3629                                      return e vent.handl eObj.handl er.apply(  this, argu ments );
  3630                             }
  3631                    },
  3632  
  3633                    tear down: func tion() {
  3634                             jQuery .event.rem ove( this,  "._change " );
  3635  
  3636                             return  rformElem s.test( th is.nodeNam e );
  3637                    }
  3638           };
  3639   }
  3640  
  3641   // Create  "bubbling"  focus and  blur even ts
  3642   if ( !jQue ry.support .focusinBu bbles ) {
  3643           jQ uery.each( { focus: " focusin",  blur: "foc usout" },  function(  orig, fix  ) {
  3644  
  3645                    // A ttach a si ngle captu ring handl er while s omeone wan ts focusin /focusout
  3646                    var  attaches =  0,
  3647                             handle r = functi on( event  ) {
  3648                                      jQuery.e vent.simul ate( fix,  event.targ et, jQuery .event.fix ( event ),  true );
  3649                             };
  3650  
  3651                    jQue ry.event.s pecial[ fi x ] = {
  3652                             setup:  function( ) {
  3653                                      if ( att aches++ == = 0 ) {
  3654                                               document.a ddEventLis tener( ori g, handler , true );
  3655                                      }
  3656                             },
  3657                             teardo wn: functi on() {
  3658                                      if ( --a ttaches == = 0 ) {
  3659                                               document.r emoveEvent Listener(  orig, hand ler, true  );
  3660                                      }
  3661                             }
  3662                    };
  3663           }) ;
  3664   }
  3665  
  3666   jQuery.fn. extend({
  3667  
  3668           on : function ( types, s elector, d ata, fn, / *INTERNAL* / one ) {
  3669                    var  origFn, ty pe;
  3670  
  3671                    // T ypes can b e a map of  types/han dlers
  3672                    if (  typeof ty pes === "o bject" ) {
  3673                             // ( t ypes-Objec t, selecto r, data )
  3674                             if ( t ypeof sele ctor !== " string" )  {
  3675                                      // ( typ es-Object,  data )
  3676                                      data = s elector;
  3677                                      selector  = undefin ed;
  3678                             }
  3679                             for (  type in ty pes ) {
  3680                                      this.on(  type, sel ector, dat a, types[  type ], on e );
  3681                             }
  3682                             return  this;
  3683                    }
  3684  
  3685                    if (  data == n ull && fn  == null )  {
  3686                             // ( t ypes, fn )
  3687                             fn = s elector;
  3688                             data =  selector  = undefine d;
  3689                    } el se if ( fn  == null )  {
  3690                             if ( t ypeof sele ctor === " string" )  {
  3691                                      // ( typ es, select or, fn )
  3692                                      fn = dat a;
  3693                                      data = u ndefined;
  3694                             } else  {
  3695                                      // ( typ es, data,  fn )
  3696                                      fn = dat a;
  3697                                      data = s elector;
  3698                                      selector  = undefin ed;
  3699                             }
  3700                    }
  3701                    if (  fn === fa lse ) {
  3702                             fn = r eturnFalse ;
  3703                    } el se if ( !f n ) {
  3704                             return  this;
  3705                    }
  3706  
  3707                    if (  one === 1  ) {
  3708                             origFn  = fn;
  3709                             fn = f unction( e vent ) {
  3710                                      // Can u se an empt y set, sin ce event c ontains th e info
  3711                                      jQuery() .off( even t );
  3712                                      return o rigFn.appl y( this, a rguments ) ;
  3713                             };
  3714                             // Use  same guid  so caller  can remov e using or igFn
  3715                             fn.gui d = origFn .guid || (  origFn.gu id = jQuer y.guid++ ) ;
  3716                    }
  3717                    retu rn this.ea ch( functi on() {
  3718                             jQuery .event.add ( this, ty pes, fn, d ata, selec tor );
  3719                    });
  3720           },
  3721           on e: functio n( types,  selector,  data, fn )  {
  3722                    retu rn this.on .call( thi s, types,  selector,  data, fn,  1 );
  3723           },
  3724           of f: functio n( types,  selector,  fn ) {
  3725                    if (  types &&  types.prev entDefault  && types. handleObj  ) {
  3726                             // ( e vent )  di spatched j Query.Even t
  3727                             var ha ndleObj =  types.hand leObj;
  3728                             jQuery ( types.de legateTarg et ).off(
  3729                                      handleOb j.namespac e? handleO bj.type +  "." + hand leObj.name space : ha ndleObj.ty pe,
  3730                                      handleOb j.selector ,
  3731                                      handleOb j.handler
  3732                             );
  3733                             return  this;
  3734                    }
  3735                    if (  typeof ty pes === "o bject" ) {
  3736                             // ( t ypes-objec t [, selec tor] )
  3737                             for (  var type i n types )  {
  3738                                      this.off ( type, se lector, ty pes[ type  ] );
  3739                             }
  3740                             return  this;
  3741                    }
  3742                    if (  selector  === false  || typeof  selector = == "functi on" ) {
  3743                             // ( t ypes [, fn ] )
  3744                             fn = s elector;
  3745                             select or = undef ined;
  3746                    }
  3747                    if (  fn === fa lse ) {
  3748                             fn = r eturnFalse ;
  3749                    }
  3750                    retu rn this.ea ch(functio n() {
  3751                             jQuery .event.rem ove( this,  types, fn , selector  );
  3752                    });
  3753           },
  3754  
  3755           bi nd: functi on( types,  data, fn  ) {
  3756                    retu rn this.on ( types, n ull, data,  fn );
  3757           },
  3758           un bind: func tion( type s, fn ) {
  3759                    retu rn this.of f( types,  null, fn ) ;
  3760           },
  3761  
  3762           li ve: functi on( types,  data, fn  ) {
  3763                    jQue ry( this.c ontext ).o n( types,  this.selec tor, data,  fn );
  3764                    retu rn this;
  3765           },
  3766           di e: functio n( types,  fn ) {
  3767                    jQue ry( this.c ontext ).o ff( types,  this.sele ctor || "* *", fn );
  3768                    retu rn this;
  3769           },
  3770  
  3771           de legate: fu nction( se lector, ty pes, data,  fn ) {
  3772                    retu rn this.on ( types, s elector, d ata, fn );
  3773           },
  3774           un delegate:  function(  selector,  types, fn  ) {
  3775                    // (  namespace  ) or ( se lector, ty pes [, fn]  )
  3776                    retu rn argumen ts.length  == 1? this .off( sele ctor, "**"  ) : this. off( types , selector , fn );
  3777           },
  3778  
  3779           tr igger: fun ction( typ e, data )  {
  3780                    retu rn this.ea ch(functio n() {
  3781                             jQuery .event.tri gger( type , data, th is );
  3782                    });
  3783           },
  3784           tr iggerHandl er: functi on( type,  data ) {
  3785                    if (  this[0] )  {
  3786                             return  jQuery.ev ent.trigge r( type, d ata, this[ 0], true ) ;
  3787                    }
  3788           },
  3789  
  3790           to ggle: func tion( fn )  {
  3791                    // S ave refere nce to arg uments for  access in  closure
  3792                    var  args = arg uments,
  3793                             guid =  fn.guid | | jQuery.g uid++,
  3794                             i = 0,
  3795                             toggle r = functi on( event  ) {
  3796                                      // Figur e out whic h function  to execut e
  3797                                      var last Toggle = (  jQuery._d ata( this,  "lastTogg le" + fn.g uid ) || 0  ) % i;
  3798                                      jQuery._ data( this , "lastTog gle" + fn. guid, last Toggle + 1  );
  3799  
  3800                                      // Make  sure that  clicks sto p
  3801                                      event.pr eventDefau lt();
  3802  
  3803                                      // and e xecute the  function
  3804                                      return a rgs[ lastT oggle ].ap ply( this,  arguments  ) || fals e;
  3805                             };
  3806  
  3807                    // l ink all th e function s, so any  of them ca n unbind t his click  handler
  3808                    togg ler.guid =  guid;
  3809                    whil e ( i < ar gs.length  ) {
  3810                             args[  i++ ].guid  = guid;
  3811                    }
  3812  
  3813                    retu rn this.cl ick( toggl er );
  3814           },
  3815  
  3816           ho ver: funct ion( fnOve r, fnOut )  {
  3817                    retu rn this.mo useenter(  fnOver ).m ouseleave(  fnOut ||  fnOver );
  3818           }
  3819   });
  3820  
  3821   jQuery.eac h( ("blur  focus focu sin focuso ut load re size scrol l unload c lick dblcl ick " +
  3822           "m ousedown m ouseup mou semove mou seover mou seout mous eenter mou seleave "  +
  3823           "c hange sele ct submit  keydown ke ypress key up error c ontextmenu ").split("  "), funct ion( i, na me ) {
  3824  
  3825           //  Handle ev ent bindin g
  3826           jQ uery.fn[ n ame ] = fu nction( da ta, fn ) {
  3827                    if (  fn == nul l ) {
  3828                             fn = d ata;
  3829                             data =  null;
  3830                    }
  3831  
  3832                    retu rn argumen ts.length  > 0 ?
  3833                             this.o n( name, n ull, data,  fn ) :
  3834                             this.t rigger( na me );
  3835           };
  3836  
  3837           if  ( jQuery. attrFn ) {
  3838                    jQue ry.attrFn[  name ] =  true;
  3839           }
  3840  
  3841           if  ( rkeyEve nt.test( n ame ) ) {
  3842                    jQue ry.event.f ixHooks[ n ame ] = jQ uery.event .keyHooks;
  3843           }
  3844  
  3845           if  ( rmouseE vent.test(  name ) )  {
  3846                    jQue ry.event.f ixHooks[ n ame ] = jQ uery.event .mouseHook s;
  3847           }
  3848   });
  3849  
  3850  
  3851  
  3852   /*!
  3853    * Sizzle  CSS Select or Engine
  3854    *  Copyri ght 2011,  The Dojo F oundation
  3855    *  Releas ed under t he MIT, BS D, and GPL  Licenses.
  3856    *  More i nformation : http://s izzlejs.co m/
  3857    */
  3858   (function( ){
  3859  
  3860   var chunke r = /((?:\ ((?:\([^() ]+\)|[^()] +)+\)|\[(? :\[[^\[\]] *\]|['"][^ '"]*['"]|[ ^\[\]'"]+) +\]|\\.|[^  >+~,(\[\\ ]+)+|[>+~] )(\s*,\s*) ?((?:.|\r| \n)*)/g,
  3861           ex pando = "s izcache" +  (Math.ran dom() + '' ).replace( '.', ''),
  3862           do ne = 0,
  3863           to String = O bject.prot otype.toSt ring,
  3864           ha sDuplicate  = false,
  3865           ba seHasDupli cate = tru e,
  3866           rB ackslash =  /\\/g,
  3867           rR eturn = /\ r\n/g,
  3868           rN onWord = / \W/;
  3869  
  3870   // Here we  check if  the JavaSc ript engin e is using  some sort  of
  3871   // optimiz ation wher e it does  not always  call our  comparisio n
  3872   // functio n. If that  is the ca se, discar d the hasD uplicate v alue.
  3873   //   Thus  far that i ncludes Go ogle Chrom e.
  3874   [0, 0].sor t(function () {
  3875           ba seHasDupli cate = fal se;
  3876           re turn 0;
  3877   });
  3878  
  3879   var Sizzle  = functio n( selecto r, context , results,  seed ) {
  3880           re sults = re sults || [ ];
  3881           co ntext = co ntext || d ocument;
  3882  
  3883           va r origCont ext = cont ext;
  3884  
  3885           if  ( context .nodeType  !== 1 && c ontext.nod eType !==  9 ) {
  3886                    retu rn [];
  3887           }
  3888           
  3889           if  ( !select or || type of selecto r !== "str ing" ) {
  3890                    retu rn results ;
  3891           }
  3892  
  3893           va r m, set,  checkSet,  extra, ret , cur, pop , i,
  3894                    prun e = true,
  3895                    cont extXML = S izzle.isXM L( context  ),
  3896                    part s = [],
  3897                    soFa r = select or;
  3898           
  3899           //  Reset the  position  of the chu nker regex p (start f rom head)
  3900           do  {
  3901                    chun ker.exec(  "" );
  3902                    m =  chunker.ex ec( soFar  );
  3903  
  3904                    if (  m ) {
  3905                             soFar  = m[3];
  3906                    
  3907                             parts. push( m[1]  );
  3908                    
  3909                             if ( m [2] ) {
  3910                                      extra =  m[3];
  3911                                      break;
  3912                             }
  3913                    }
  3914           }  while ( m  );
  3915  
  3916           if  ( parts.l ength > 1  && origPOS .exec( sel ector ) )  {
  3917  
  3918                    if (  parts.len gth === 2  && Expr.re lative[ pa rts[0] ] )  {
  3919                             set =  posProcess ( parts[0]  + parts[1 ], context , seed );
  3920  
  3921                    } el se {
  3922                             set =  Expr.relat ive[ parts [0] ] ?
  3923                                      [ contex t ] :
  3924                                      Sizzle(  parts.shif t(), conte xt );
  3925  
  3926                             while  ( parts.le ngth ) {
  3927                                      selector  = parts.s hift();
  3928  
  3929                                      if ( Exp r.relative [ selector  ] ) {
  3930                                               selector + = parts.sh ift();
  3931                                      }
  3932                                      
  3933                                      set = po sProcess(  selector,  set, seed  );
  3934                             }
  3935                    }
  3936  
  3937           }  else {
  3938                    // T ake a shor tcut and s et the con text if th e root sel ector is a n ID
  3939                    // ( but not if  it'll be  faster if  the inner  selector i s an ID)
  3940                    if (  !seed &&  parts.leng th > 1 &&  context.no deType ===  9 && !con textXML &&
  3941                                      Expr.mat ch.ID.test (parts[0])  && !Expr. match.ID.t est(parts[ parts.leng th - 1]) )  {
  3942  
  3943                             ret =  Sizzle.fin d( parts.s hift(), co ntext, con textXML );
  3944                             contex t = ret.ex pr ?
  3945                                      Sizzle.f ilter( ret .expr, ret .set )[0]  :
  3946                                      ret.set[ 0];
  3947                    }
  3948  
  3949                    if (  context )  {
  3950                             ret =  seed ?
  3951                                      { expr:  parts.pop( ), set: ma keArray(se ed) } :
  3952                                      Sizzle.f ind( parts .pop(), pa rts.length  === 1 &&  (parts[0]  === "~" ||  parts[0]  === "+") & & context. parentNode  ? context .parentNod e : contex t, context XML );
  3953  
  3954                             set =  ret.expr ?
  3955                                      Sizzle.f ilter( ret .expr, ret .set ) :
  3956                                      ret.set;
  3957  
  3958                             if ( p arts.lengt h > 0 ) {
  3959                                      checkSet  = makeArr ay( set );
  3960  
  3961                             } else  {
  3962                                      prune =  false;
  3963                             }
  3964  
  3965                             while  ( parts.le ngth ) {
  3966                                      cur = pa rts.pop();
  3967                                      pop = cu r;
  3968  
  3969                                      if ( !Ex pr.relativ e[ cur ] )  {
  3970                                               cur = "";
  3971                                      } else {
  3972                                               pop = part s.pop();
  3973                                      }
  3974  
  3975                                      if ( pop  == null )  {
  3976                                               pop = cont ext;
  3977                                      }
  3978  
  3979                                      Expr.rel ative[ cur  ]( checkS et, pop, c ontextXML  );
  3980                             }
  3981  
  3982                    } el se {
  3983                             checkS et = parts  = [];
  3984                    }
  3985           }
  3986  
  3987           if  ( !checkS et ) {
  3988                    chec kSet = set ;
  3989           }
  3990  
  3991           if  ( !checkS et ) {
  3992                    Sizz le.error(  cur || sel ector );
  3993           }
  3994  
  3995           if  ( toStrin g.call(che ckSet) ===  "[object  Array]" )  {
  3996                    if (  !prune )  {
  3997                             result s.push.app ly( result s, checkSe t );
  3998  
  3999                    } el se if ( co ntext && c ontext.nod eType ===  1 ) {
  4000                             for (  i = 0; che ckSet[i] ! = null; i+ + ) {
  4001                                      if ( che ckSet[i] & & (checkSe t[i] === t rue || che ckSet[i].n odeType == = 1 && Siz zle.contai ns(context , checkSet [i])) ) {
  4002                                               results.pu sh( set[i]  );
  4003                                      }
  4004                             }
  4005  
  4006                    } el se {
  4007                             for (  i = 0; che ckSet[i] ! = null; i+ + ) {
  4008                                      if ( che ckSet[i] & & checkSet [i].nodeTy pe === 1 )  {
  4009                                               results.pu sh( set[i]  );
  4010                                      }
  4011                             }
  4012                    }
  4013  
  4014           }  else {
  4015                    make Array( che ckSet, res ults );
  4016           }
  4017  
  4018           if  ( extra )  {
  4019                    Sizz le( extra,  origConte xt, result s, seed );
  4020                    Sizz le.uniqueS ort( resul ts );
  4021           }
  4022  
  4023           re turn resul ts;
  4024   };
  4025  
  4026   Sizzle.uni queSort =  function(  results )  {
  4027           if  ( sortOrd er ) {
  4028                    hasD uplicate =  baseHasDu plicate;
  4029                    resu lts.sort(  sortOrder  );
  4030  
  4031                    if (  hasDuplic ate ) {
  4032                             for (  var i = 1;  i < resul ts.length;  i++ ) {
  4033                                      if ( res ults[i] == = results[  i - 1 ] )  {
  4034                                               results.sp lice( i--,  1 );
  4035                                      }
  4036                             }
  4037                    }
  4038           }
  4039  
  4040           re turn resul ts;
  4041   };
  4042  
  4043   Sizzle.mat ches = fun ction( exp r, set ) {
  4044           re turn Sizzl e( expr, n ull, null,  set );
  4045   };
  4046  
  4047   Sizzle.mat chesSelect or = funct ion( node,  expr ) {
  4048           re turn Sizzl e( expr, n ull, null,  [node] ). length > 0 ;
  4049   };
  4050  
  4051   Sizzle.fin d = functi on( expr,  context, i sXML ) {
  4052           va r set, i,  len, match , type, le ft;
  4053  
  4054           if  ( !expr )  {
  4055                    retu rn [];
  4056           }
  4057  
  4058           fo r ( i = 0,  len = Exp r.order.le ngth; i <  len; i++ )  {
  4059                    type  = Expr.or der[i];
  4060                    
  4061                    if (  (match =  Expr.leftM atch[ type  ].exec( e xpr )) ) {
  4062                             left =  match[1];
  4063                             match. splice( 1,  1 );
  4064  
  4065                             if ( l eft.substr ( left.len gth - 1 )  !== "\\" )  {
  4066                                      match[1]  = (match[ 1] || ""). replace( r Backslash,  "" );
  4067                                      set = Ex pr.find[ t ype ]( mat ch, contex t, isXML ) ;
  4068  
  4069                                      if ( set  != null )  {
  4070                                               expr = exp r.replace(  Expr.matc h[ type ],  "" );
  4071                                               break;
  4072                                      }
  4073                             }
  4074                    }
  4075           }
  4076  
  4077           if  ( !set )  {
  4078                    set  = typeof c ontext.get ElementsBy TagName != = "undefin ed" ?
  4079                             contex t.getEleme ntsByTagNa me( "*" )  :
  4080                             [];
  4081           }
  4082  
  4083           re turn { set : set, exp r: expr };
  4084   };
  4085  
  4086   Sizzle.fil ter = func tion( expr , set, inp lace, not  ) {
  4087           va r match, a nyFound,
  4088                    type , found, i tem, filte r, left,
  4089                    i, p ass,
  4090                    old  = expr,
  4091                    resu lt = [],
  4092                    curL oop = set,
  4093                    isXM LFilter =  set && set [0] && Siz zle.isXML(  set[0] );
  4094  
  4095           wh ile ( expr  && set.le ngth ) {
  4096                    for  ( type in  Expr.filte r ) {
  4097                             if ( ( match = Ex pr.leftMat ch[ type ] .exec( exp r )) != nu ll && matc h[2] ) {
  4098                                      filter =  Expr.filt er[ type ] ;
  4099                                      left = m atch[1];
  4100  
  4101                                      anyFound  = false;
  4102  
  4103                                      match.sp lice(1,1);
  4104  
  4105                                      if ( lef t.substr(  left.lengt h - 1 ) == = "\\" ) {
  4106                                               continue;
  4107                                      }
  4108  
  4109                                      if ( cur Loop === r esult ) {
  4110                                               result = [ ];
  4111                                      }
  4112  
  4113                                      if ( Exp r.preFilte r[ type ]  ) {
  4114                                               match = Ex pr.preFilt er[ type ] ( match, c urLoop, in place, res ult, not,  isXMLFilte r );
  4115  
  4116                                               if ( !matc h ) {
  4117                                                       an yFound = f ound = tru e;
  4118  
  4119                                               } else if  ( match == = true ) {
  4120                                                       co ntinue;
  4121                                               }
  4122                                      }
  4123  
  4124                                      if ( mat ch ) {
  4125                                               for ( i =  0; (item =  curLoop[i ]) != null ; i++ ) {
  4126                                                       if  ( item )  {
  4127                                                                foun d = filter ( item, ma tch, i, cu rLoop );
  4128                                                                pass  = not ^ f ound;
  4129  
  4130                                                                if (  inplace & & found !=  null ) {
  4131                                                                         if ( p ass ) {
  4132                                                                                  anyFound  = true;
  4133  
  4134                                                                         } else  {
  4135                                                                                  curLoop[ i] = false ;
  4136                                                                         }
  4137  
  4138                                                                } el se if ( pa ss ) {
  4139                                                                         result .push( ite m );
  4140                                                                         anyFou nd = true;
  4141                                                                }
  4142                                                       }
  4143                                               }
  4144                                      }
  4145  
  4146                                      if ( fou nd !== und efined ) {
  4147                                               if ( !inpl ace ) {
  4148                                                       cu rLoop = re sult;
  4149                                               }
  4150  
  4151                                               expr = exp r.replace(  Expr.matc h[ type ],  "" );
  4152  
  4153                                               if ( !anyF ound ) {
  4154                                                       re turn [];
  4155                                               }
  4156  
  4157                                               break;
  4158                                      }
  4159                             }
  4160                    }
  4161  
  4162                    // I mproper ex pression
  4163                    if (  expr ===  old ) {
  4164                             if ( a nyFound ==  null ) {
  4165                                      Sizzle.e rror( expr  );
  4166  
  4167                             } else  {
  4168                                      break;
  4169                             }
  4170                    }
  4171  
  4172                    old  = expr;
  4173           }
  4174  
  4175           re turn curLo op;
  4176   };
  4177  
  4178   Sizzle.err or = funct ion( msg )  {
  4179           th row new Er ror( "Synt ax error,  unrecogniz ed express ion: " + m sg );
  4180   };
  4181  
  4182   /**
  4183    * Utility  function  for retrei ving the t ext value  of an arra y of DOM n odes
  4184    * @param  {Array|Ele ment} elem
  4185    */
  4186   var getTex t = Sizzle .getText =  function(  elem ) {
  4187       var i,  node,
  4188                    node Type = ele m.nodeType ,
  4189                    ret  = "";
  4190  
  4191           if  ( nodeTyp e ) {
  4192                    if (  nodeType  === 1 || n odeType == = 9 ) {
  4193                             // Use  textConte nt || inne rText for  elements
  4194                             if ( t ypeof elem .textConte nt === 'st ring' ) {
  4195                                      return e lem.textCo ntent;
  4196                             } else  if ( type of elem.in nerText == = 'string'  ) {
  4197                                      // Repla ce IE's ca rriage ret urns
  4198                                      return e lem.innerT ext.replac e( rReturn , '' );
  4199                             } else  {
  4200                                      // Trave rse it's c hildren
  4201                                      for ( el em = elem. firstChild ; elem; el em = elem. nextSiblin g) {
  4202                                               ret += get Text( elem  );
  4203                                      }
  4204                             }
  4205                    } el se if ( no deType ===  3 || node Type === 4  ) {
  4206                             return  elem.node Value;
  4207                    }
  4208           }  else {
  4209  
  4210                    // I f no nodeT ype, this  is expecte d to be an  array
  4211                    for  ( i = 0; ( node = ele m[i]); i++  ) {
  4212                             // Do  not traver se comment  nodes
  4213                             if ( n ode.nodeTy pe !== 8 )  {
  4214                                      ret += g etText( no de );
  4215                             }
  4216                    }
  4217           }
  4218           re turn ret;
  4219   };
  4220  
  4221   var Expr =  Sizzle.se lectors =  {
  4222           or der: [ "ID ", "NAME",  "TAG" ],
  4223  
  4224           ma tch: {
  4225                    ID:  /#((?:[\w\ u00c0-\uFF FF\-]|\\.) +)/,
  4226                    CLAS S: /\.((?: [\w\u00c0- \uFFFF\-]| \\.)+)/,
  4227                    NAME : /\[name= ['"]*((?:[ \w\u00c0-\ uFFFF\-]|\ \.)+)['"]* \]/,
  4228                    ATTR : /\[\s*(( ?:[\w\u00c 0-\uFFFF\- ]|\\.)+)\s *(?:(\S?=) \s*(?:(['" ])(.*?)\3| (#?(?:[\w\ u00c0-\uFF FF\-]|\\.) *)|)|)\s*\ ]/,
  4229                    TAG:  /^((?:[\w \u00c0-\uF FFF\*\-]|\ \.)+)/,
  4230                    CHIL D: /:(only |nth|last| first)-chi ld(?:\(\s* (even|odd| (?:[+\-]?\ d+|(?:[+\- ]?\d*)?n\s *(?:[+\-]\ s*\d+)?))\ s*\))?/,
  4231                    POS:  /:(nth|eq |gt|lt|fir st|last|ev en|odd)(?: \((\d*)\)) ?(?=[^\-]| $)/,
  4232                    PSEU DO: /:((?: [\w\u00c0- \uFFFF\-]| \\.)+)(?:\ ((['"]?)(( ?:\([^\)]+ \)|[^\(\)] *)+)\2\))? /
  4233           },
  4234  
  4235           le ftMatch: { },
  4236  
  4237           at trMap: {
  4238                    "cla ss": "clas sName",
  4239                    "for ": "htmlFo r"
  4240           },
  4241  
  4242           at trHandle:  {
  4243                    href : function ( elem ) {
  4244                             return  elem.getA ttribute(  "href" );
  4245                    },
  4246                    type : function ( elem ) {
  4247                             return  elem.getA ttribute(  "type" );
  4248                    }
  4249           },
  4250  
  4251           re lative: {
  4252                    "+":  function( checkSet,  part){
  4253                             var is PartStr =  typeof par t === "str ing",
  4254                                      isTag =  isPartStr  && !rNonWo rd.test( p art ),
  4255                                      isPartSt rNotTag =  isPartStr  && !isTag;
  4256  
  4257                             if ( i sTag ) {
  4258                                      part = p art.toLowe rCase();
  4259                             }
  4260  
  4261                             for (  var i = 0,  l = check Set.length , elem; i  < l; i++ )  {
  4262                                      if ( (el em = check Set[i]) )  {
  4263                                               while ( (e lem = elem .previousS ibling) &&  elem.node Type !== 1  ) {}
  4264  
  4265                                               checkSet[i ] = isPart StrNotTag  || elem &&  elem.node Name.toLow erCase() = == part ?
  4266                                                       el em || fals e :
  4267                                                       el em === par t;
  4268                                      }
  4269                             }
  4270  
  4271                             if ( i sPartStrNo tTag ) {
  4272                                      Sizzle.f ilter( par t, checkSe t, true );
  4273                             }
  4274                    },
  4275  
  4276                    ">":  function(  checkSet,  part ) {
  4277                             var el em,
  4278                                      isPartSt r = typeof  part ===  "string",
  4279                                      i = 0,
  4280                                      l = chec kSet.lengt h;
  4281  
  4282                             if ( i sPartStr & & !rNonWor d.test( pa rt ) ) {
  4283                                      part = p art.toLowe rCase();
  4284  
  4285                                      for ( ;  i < l; i++  ) {
  4286                                               elem = che ckSet[i];
  4287  
  4288                                               if ( elem  ) {
  4289                                                       va r parent =  elem.pare ntNode;
  4290                                                       ch eckSet[i]  = parent.n odeName.to LowerCase( ) === part  ? parent  : false;
  4291                                               }
  4292                                      }
  4293  
  4294                             } else  {
  4295                                      for ( ;  i < l; i++  ) {
  4296                                               elem = che ckSet[i];
  4297  
  4298                                               if ( elem  ) {
  4299                                                       ch eckSet[i]  = isPartSt r ?
  4300                                                                elem .parentNod e :
  4301                                                                elem .parentNod e === part ;
  4302                                               }
  4303                                      }
  4304  
  4305                                      if ( isP artStr ) {
  4306                                               Sizzle.fil ter( part,  checkSet,  true );
  4307                                      }
  4308                             }
  4309                    },
  4310  
  4311                    "":  function(c heckSet, p art, isXML ){
  4312                             var no deCheck,
  4313                                      doneName  = done++,
  4314                                      checkFn  = dirCheck ;
  4315  
  4316                             if ( t ypeof part  === "stri ng" && !rN onWord.tes t( part )  ) {
  4317                                      part = p art.toLowe rCase();
  4318                                      nodeChec k = part;
  4319                                      checkFn  = dirNodeC heck;
  4320                             }
  4321  
  4322                             checkF n( "parent Node", par t, doneNam e, checkSe t, nodeChe ck, isXML  );
  4323                    },
  4324  
  4325                    "~":  function(  checkSet,  part, isX ML ) {
  4326                             var no deCheck,
  4327                                      doneName  = done++,
  4328                                      checkFn  = dirCheck ;
  4329  
  4330                             if ( t ypeof part  === "stri ng" && !rN onWord.tes t( part )  ) {
  4331                                      part = p art.toLowe rCase();
  4332                                      nodeChec k = part;
  4333                                      checkFn  = dirNodeC heck;
  4334                             }
  4335  
  4336                             checkF n( "previo usSibling" , part, do neName, ch eckSet, no deCheck, i sXML );
  4337                    }
  4338           },
  4339  
  4340           fi nd: {
  4341                    ID:  function(  match, con text, isXM L ) {
  4342                             if ( t ypeof cont ext.getEle mentById ! == "undefi ned" && !i sXML ) {
  4343                                      var m =  context.ge tElementBy Id(match[1 ]);
  4344                                      // Check  parentNod e to catch  when Blac kberry 4.6  returns
  4345                                      // nodes  that are  no longer  in the doc ument #696 3
  4346                                      return m  && m.pare ntNode ? [ m] : [];
  4347                             }
  4348                    },
  4349  
  4350                    NAME : function ( match, c ontext ) {
  4351                             if ( t ypeof cont ext.getEle mentsByNam e !== "und efined" )  {
  4352                                      var ret  = [],
  4353                                               results =  context.ge tElementsB yName( mat ch[1] );
  4354  
  4355                                      for ( va r i = 0, l  = results .length; i  < l; i++  ) {
  4356                                               if ( resul ts[i].getA ttribute(" name") ===  match[1]  ) {
  4357                                                       re t.push( re sults[i] ) ;
  4358                                               }
  4359                                      }
  4360  
  4361                                      return r et.length  === 0 ? nu ll : ret;
  4362                             }
  4363                    },
  4364  
  4365                    TAG:  function(  match, co ntext ) {
  4366                             if ( t ypeof cont ext.getEle mentsByTag Name !== " undefined"  ) {
  4367                                      return c ontext.get ElementsBy TagName( m atch[1] );
  4368                             }
  4369                    }
  4370           },
  4371           pr eFilter: {
  4372                    CLAS S: functio n( match,  curLoop, i nplace, re sult, not,  isXML ) {
  4373                             match  = " " + ma tch[1].rep lace( rBac kslash, ""  ) + " ";
  4374  
  4375                             if ( i sXML ) {
  4376                                      return m atch;
  4377                             }
  4378  
  4379                             for (  var i = 0,  elem; (el em = curLo op[i]) !=  null; i++  ) {
  4380                                      if ( ele m ) {
  4381                                               if ( not ^  (elem.cla ssName &&  (" " + ele m.classNam e + " ").r eplace(/[\ t\n\r]/g,  " ").index Of(match)  >= 0) ) {
  4382                                                       if  ( !inplac e ) {
  4383                                                                resu lt.push( e lem );
  4384                                                       }
  4385  
  4386                                               } else if  ( inplace  ) {
  4387                                                       cu rLoop[i] =  false;
  4388                                               }
  4389                                      }
  4390                             }
  4391  
  4392                             return  false;
  4393                    },
  4394  
  4395                    ID:  function(  match ) {
  4396                             return  match[1]. replace( r Backslash,  "" );
  4397                    },
  4398  
  4399                    TAG:  function(  match, cu rLoop ) {
  4400                             return  match[1]. replace( r Backslash,  "" ).toLo werCase();
  4401                    },
  4402  
  4403                    CHIL D: functio n( match )  {
  4404                             if ( m atch[1] == = "nth" )  {
  4405                                      if ( !ma tch[2] ) {
  4406                                               Sizzle.err or( match[ 0] );
  4407                                      }
  4408  
  4409                                      match[2]  = match[2 ].replace( /^\+|\s*/g , '');
  4410  
  4411                                      // parse  equations  like 'eve n', 'odd',  '5', '2n' , '3n+2',  '4n-1', '- n+6'
  4412                                      var test  = /(-?)(\ d*)(?:n([+ \-]?\d*))? /.exec(
  4413                                               match[2] = == "even"  && "2n" ||  match[2]  === "odd"  && "2n+1"  ||
  4414                                               !/\D/.test ( match[2]  ) && "0n+ " + match[ 2] || matc h[2]);
  4415  
  4416                                      // calcu late the n umbers (fi rst)n+(las t) includi ng if they  are negat ive
  4417                                      match[2]  = (test[1 ] + (test[ 2] || 1))  - 0;
  4418                                      match[3]  = test[3]  - 0;
  4419                             }
  4420                             else i f ( match[ 2] ) {
  4421                                      Sizzle.e rror( matc h[0] );
  4422                             }
  4423  
  4424                             // TOD O: Move to  normal ca ching syst em
  4425                             match[ 0] = done+ +;
  4426  
  4427                             return  match;
  4428                    },
  4429  
  4430                    ATTR : function ( match, c urLoop, in place, res ult, not,  isXML ) {
  4431                             var na me = match [1] = matc h[1].repla ce( rBacks lash, "" ) ;
  4432                             
  4433                             if ( ! isXML && E xpr.attrMa p[name] )  {
  4434                                      match[1]  = Expr.at trMap[name ];
  4435                             }
  4436  
  4437                             // Han dle if an  un-quoted  value was  used
  4438                             match[ 4] = ( mat ch[4] || m atch[5] ||  "" ).repl ace( rBack slash, ""  );
  4439  
  4440                             if ( m atch[2] == = "~=" ) {
  4441                                      match[4]  = " " + m atch[4] +  " ";
  4442                             }
  4443  
  4444                             return  match;
  4445                    },
  4446  
  4447                    PSEU DO: functi on( match,  curLoop,  inplace, r esult, not  ) {
  4448                             if ( m atch[1] == = "not" )  {
  4449                                      // If we 're dealin g with a c omplex exp ression, o r a simple  one
  4450                                      if ( ( c hunker.exe c(match[3] ) || "" ). length > 1  || /^\w/. test(match [3]) ) {
  4451                                               match[3] =  Sizzle(ma tch[3], nu ll, null,  curLoop);
  4452  
  4453                                      } else {
  4454                                               var ret =  Sizzle.fil ter(match[ 3], curLoo p, inplace , true ^ n ot);
  4455  
  4456                                               if ( !inpl ace ) {
  4457                                                       re sult.push. apply( res ult, ret ) ;
  4458                                               }
  4459  
  4460                                               return fal se;
  4461                                      }
  4462  
  4463                             } else  if ( Expr .match.POS .test( mat ch[0] ) ||  Expr.matc h.CHILD.te st( match[ 0] ) ) {
  4464                                      return t rue;
  4465                             }
  4466                             
  4467                             return  match;
  4468                    },
  4469  
  4470                    POS:  function(  match ) {
  4471                             match. unshift( t rue );
  4472  
  4473                             return  match;
  4474                    }
  4475           },
  4476           
  4477           fi lters: {
  4478                    enab led: funct ion( elem  ) {
  4479                             return  elem.disa bled === f alse && el em.type != = "hidden" ;
  4480                    },
  4481  
  4482                    disa bled: func tion( elem  ) {
  4483                             return  elem.disa bled === t rue;
  4484                    },
  4485  
  4486                    chec ked: funct ion( elem  ) {
  4487                             return  elem.chec ked === tr ue;
  4488                    },
  4489                    
  4490                    sele cted: func tion( elem  ) {
  4491                             // Acc essing thi s property  makes sel ected-by-d efault
  4492                             // opt ions in Sa fari work  properly
  4493                             if ( e lem.parent Node ) {
  4494                                      elem.par entNode.se lectedInde x;
  4495                             }
  4496                             
  4497                             return  elem.sele cted === t rue;
  4498                    },
  4499  
  4500                    pare nt: functi on( elem )  {
  4501                             return  !!elem.fi rstChild;
  4502                    },
  4503  
  4504                    empt y: functio n( elem )  {
  4505                             return  !elem.fir stChild;
  4506                    },
  4507  
  4508                    has:  function(  elem, i,  match ) {
  4509                             return  !!Sizzle(  match[3],  elem ).le ngth;
  4510                    },
  4511  
  4512                    head er: functi on( elem )  {
  4513                             return  (/h\d/i). test( elem .nodeName  );
  4514                    },
  4515  
  4516                    text : function ( elem ) {
  4517                             var at tr = elem. getAttribu te( "type"  ), type =  elem.type ;
  4518                             // IE6  and 7 wil l map elem .type to ' text' for  new HTML5  types (sea rch, etc) 
  4519                             // use  getAttrib ute instea d to test  this case
  4520                             return  elem.node Name.toLow erCase() = == "input"  && "text"  === type  && ( attr  === type | | attr ===  null );
  4521                    },
  4522  
  4523                    radi o: functio n( elem )  {
  4524                             return  elem.node Name.toLow erCase() = == "input"  && "radio " === elem .type;
  4525                    },
  4526  
  4527                    chec kbox: func tion( elem  ) {
  4528                             return  elem.node Name.toLow erCase() = == "input"  && "check box" === e lem.type;
  4529                    },
  4530  
  4531                    file : function ( elem ) {
  4532                             return  elem.node Name.toLow erCase() = == "input"  && "file"  === elem. type;
  4533                    },
  4534  
  4535                    pass word: func tion( elem  ) {
  4536                             return  elem.node Name.toLow erCase() = == "input"  && "passw ord" === e lem.type;
  4537                    },
  4538  
  4539                    subm it: functi on( elem )  {
  4540                             var na me = elem. nodeName.t oLowerCase ();
  4541                             return  (name ===  "input" | | name ===  "button")  && "submi t" === ele m.type;
  4542                    },
  4543  
  4544                    imag e: functio n( elem )  {
  4545                             return  elem.node Name.toLow erCase() = == "input"  && "image " === elem .type;
  4546                    },
  4547  
  4548                    rese t: functio n( elem )  {
  4549                             var na me = elem. nodeName.t oLowerCase ();
  4550                             return  (name ===  "input" | | name ===  "button")  && "reset " === elem .type;
  4551                    },
  4552  
  4553                    butt on: functi on( elem )  {
  4554                             var na me = elem. nodeName.t oLowerCase ();
  4555                             return  name ===  "input" &&  "button"  === elem.t ype || nam e === "but ton";
  4556                    },
  4557  
  4558                    inpu t: functio n( elem )  {
  4559                             return  (/input|s elect|text area|butto n/i).test(  elem.node Name );
  4560                    },
  4561  
  4562                    focu s: functio n( elem )  {
  4563                             return  elem ===  elem.owner Document.a ctiveEleme nt;
  4564                    }
  4565           },
  4566           se tFilters:  {
  4567                    firs t: functio n( elem, i  ) {
  4568                             return  i === 0;
  4569                    },
  4570  
  4571                    last : function ( elem, i,  match, ar ray ) {
  4572                             return  i === arr ay.length  - 1;
  4573                    },
  4574  
  4575                    even : function ( elem, i  ) {
  4576                             return  i % 2 ===  0;
  4577                    },
  4578  
  4579                    odd:  function(  elem, i )  {
  4580                             return  i % 2 ===  1;
  4581                    },
  4582  
  4583                    lt:  function(  elem, i, m atch ) {
  4584                             return  i < match [3] - 0;
  4585                    },
  4586  
  4587                    gt:  function(  elem, i, m atch ) {
  4588                             return  i > match [3] - 0;
  4589                    },
  4590  
  4591                    nth:  function(  elem, i,  match ) {
  4592                             return  match[3]  - 0 === i;
  4593                    },
  4594  
  4595                    eq:  function(  elem, i, m atch ) {
  4596                             return  match[3]  - 0 === i;
  4597                    }
  4598           },
  4599           fi lter: {
  4600                    PSEU DO: functi on( elem,  match, i,  array ) {
  4601                             var na me = match [1],
  4602                                      filter =  Expr.filt ers[ name  ];
  4603  
  4604                             if ( f ilter ) {
  4605                                      return f ilter( ele m, i, matc h, array ) ;
  4606  
  4607                             } else  if ( name  === "cont ains" ) {
  4608                                      return ( elem.textC ontent ||  elem.inner Text || ge tText([ el em ]) || " ").indexOf (match[3])  >= 0;
  4609  
  4610                             } else  if ( name  === "not"  ) {
  4611                                      var not  = match[3] ;
  4612  
  4613                                      for ( va r j = 0, l  = not.len gth; j < l ; j++ ) {
  4614                                               if ( not[j ] === elem  ) {
  4615                                                       re turn false ;
  4616                                               }
  4617                                      }
  4618  
  4619                                      return t rue;
  4620  
  4621                             } else  {
  4622                                      Sizzle.e rror( name  );
  4623                             }
  4624                    },
  4625  
  4626                    CHIL D: functio n( elem, m atch ) {
  4627                             var fi rst, last,
  4628                                      doneName , parent,  cache,
  4629                                      count, d iff,
  4630                                      type = m atch[1],
  4631                                      node = e lem;
  4632  
  4633                             switch  ( type )  {
  4634                                      case "on ly":
  4635                                      case "fi rst":
  4636                                               while ( (n ode = node .previousS ibling) )   {
  4637                                                       if  ( node.no deType ===  1 ) { 
  4638                                                                retu rn false; 
  4639                                                       }
  4640                                               }
  4641  
  4642                                               if ( type  === "first " ) { 
  4643                                                       re turn true;  
  4644                                               }
  4645  
  4646                                               node = ele m;
  4647  
  4648                                      case "la st":
  4649                                               while ( (n ode = node .nextSibli ng) )       {
  4650                                                       if  ( node.no deType ===  1 ) { 
  4651                                                                retu rn false; 
  4652                                                       }
  4653                                               }
  4654  
  4655                                               return tru e;
  4656  
  4657                                      case "nt h":
  4658                                               first = ma tch[2];
  4659                                               last = mat ch[3];
  4660  
  4661                                               if ( first  === 1 &&  last === 0  ) {
  4662                                                       re turn true;
  4663                                               }
  4664                                              
  4665                                               doneName =  match[0];
  4666                                               parent = e lem.parent Node;
  4667           
  4668                                               if ( paren t && (pare nt[ expand o ] !== do neName ||  !elem.node Index) ) {
  4669                                                       co unt = 0;
  4670                                                       
  4671                                                       fo r ( node =  parent.fi rstChild;  node; node  = node.ne xtSibling  ) {
  4672                                                                if (  node.node Type === 1  ) {
  4673                                                                         node.n odeIndex =  ++count;
  4674                                                                }
  4675                                                       } 
  4676  
  4677                                                       pa rent[ expa ndo ] = do neName;
  4678                                               }
  4679                                              
  4680                                               diff = ele m.nodeInde x - last;
  4681  
  4682                                               if ( first  === 0 ) {
  4683                                                       re turn diff  === 0;
  4684  
  4685                                               } else {
  4686                                                       re turn ( dif f % first  === 0 && d iff / firs t >= 0 );
  4687                                               }
  4688                             }
  4689                    },
  4690  
  4691                    ID:  function(  elem, matc h ) {
  4692                             return  elem.node Type === 1  && elem.g etAttribut e("id") == = match;
  4693                    },
  4694  
  4695                    TAG:  function(  elem, mat ch ) {
  4696                             return  (match == = "*" && e lem.nodeTy pe === 1)  || !!elem. nodeName & & elem.nod eName.toLo werCase()  === match;
  4697                    },
  4698                    
  4699                    CLAS S: functio n( elem, m atch ) {
  4700                             return  (" " + (e lem.classN ame || ele m.getAttri bute("clas s")) + " " )
  4701                                      .indexOf ( match )  > -1;
  4702                    },
  4703  
  4704                    ATTR : function ( elem, ma tch ) {
  4705                             var na me = match [1],
  4706                                      result =  Sizzle.at tr ?
  4707                                               Sizzle.att r( elem, n ame ) :
  4708                                               Expr.attrH andle[ nam e ] ?
  4709                                               Expr.attrH andle[ nam e ]( elem  ) :
  4710                                               elem[ name  ] != null  ?
  4711                                                       el em[ name ]  :
  4712                                                       el em.getAttr ibute( nam e ),
  4713                                      value =  result + " ",
  4714                                      type = m atch[2],
  4715                                      check =  match[4];
  4716  
  4717                             return  result ==  null ?
  4718                                      type ===  "!=" :
  4719                                      !type &&  Sizzle.at tr ?
  4720                                      result ! = null :
  4721                                      type ===  "=" ?
  4722                                      value == = check :
  4723                                      type ===  "*=" ?
  4724                                      value.in dexOf(chec k) >= 0 :
  4725                                      type ===  "~=" ?
  4726                                      (" " + v alue + " " ).indexOf( check) >=  0 :
  4727                                      !check ?
  4728                                      value &&  result != = false :
  4729                                      type ===  "!=" ?
  4730                                      value != = check :
  4731                                      type ===  "^=" ?
  4732                                      value.in dexOf(chec k) === 0 :
  4733                                      type ===  "$=" ?
  4734                                      value.su bstr(value .length -  check.leng th) === ch eck :
  4735                                      type ===  "|=" ?
  4736                                      value == = check ||  value.sub str(0, che ck.length  + 1) === c heck + "-"  :
  4737                                      false;
  4738                    },
  4739  
  4740                    POS:  function(  elem, mat ch, i, arr ay ) {
  4741                             var na me = match [2],
  4742                                      filter =  Expr.setF ilters[ na me ];
  4743  
  4744                             if ( f ilter ) {
  4745                                      return f ilter( ele m, i, matc h, array ) ;
  4746                             }
  4747                    }
  4748           }
  4749   };
  4750  
  4751   var origPO S = Expr.m atch.POS,
  4752           fe scape = fu nction(all , num){
  4753                    retu rn "\\" +  (num - 0 +  1);
  4754           };
  4755  
  4756   for ( var  type in Ex pr.match )  {
  4757           Ex pr.match[  type ] = n ew RegExp(  Expr.matc h[ type ]. source + ( /(?![^\[]* \])(?![^\( ]*\))/.sou rce) );
  4758           Ex pr.leftMat ch[ type ]  = new Reg Exp( /(^(? :.|\r|\n)* ?)/.source  + Expr.ma tch[ type  ].source.r eplace(/\\ (\d+)/g, f escape) );
  4759   }
  4760  
  4761   var makeAr ray = func tion( arra y, results  ) {
  4762           ar ray = Arra y.prototyp e.slice.ca ll( array,  0 );
  4763  
  4764           if  ( results  ) {
  4765                    resu lts.push.a pply( resu lts, array  );
  4766                    retu rn results ;
  4767           }
  4768           
  4769           re turn array ;
  4770   };
  4771  
  4772   // Perform  a simple  check to d etermine i f the brow ser is cap able of
  4773   // convert ing a Node List to an  array usi ng builtin  methods.
  4774   // Also ve rifies tha t the retu rned array  holds DOM  nodes
  4775   // (which  is not the  case in t he Blackbe rry browse r)
  4776   try {
  4777           Ar ray.protot ype.slice. call( docu ment.docum entElement .childNode s, 0 )[0]. nodeType;
  4778  
  4779   // Provide  a fallbac k method i f it does  not work
  4780   } catch( e  ) {
  4781           ma keArray =  function(  array, res ults ) {
  4782                    var  i = 0,
  4783                             ret =  results ||  [];
  4784  
  4785                    if (  toString. call(array ) === "[ob ject Array ]" ) {
  4786                             Array. prototype. push.apply ( ret, arr ay );
  4787  
  4788                    } el se {
  4789                             if ( t ypeof arra y.length = == "number " ) {
  4790                                      for ( va r l = arra y.length;  i < l; i++  ) {
  4791                                               ret.push(  array[i] ) ;
  4792                                      }
  4793  
  4794                             } else  {
  4795                                      for ( ;  array[i];  i++ ) {
  4796                                               ret.push(  array[i] ) ;
  4797                                      }
  4798                             }
  4799                    }
  4800  
  4801                    retu rn ret;
  4802           };
  4803   }
  4804  
  4805   var sortOr der, sibli ngCheck;
  4806  
  4807   if ( docum ent.docume ntElement. compareDoc umentPosit ion ) {
  4808           so rtOrder =  function(  a, b ) {
  4809                    if (  a === b )  {
  4810                             hasDup licate = t rue;
  4811                             return  0;
  4812                    }
  4813  
  4814                    if (  !a.compar eDocumentP osition ||  !b.compar eDocumentP osition )  {
  4815                             return  a.compare DocumentPo sition ? - 1 : 1;
  4816                    }
  4817  
  4818                    retu rn a.compa reDocument Position(b ) & 4 ? -1  : 1;
  4819           };
  4820  
  4821   } else {
  4822           so rtOrder =  function(  a, b ) {
  4823                    // T he nodes a re identic al, we can  exit earl y
  4824                    if (  a === b )  {
  4825                             hasDup licate = t rue;
  4826                             return  0;
  4827  
  4828                    // F allback to  using sou rceIndex ( in IE) if  it's avail able on bo th nodes
  4829                    } el se if ( a. sourceInde x && b.sou rceIndex )  {
  4830                             return  a.sourceI ndex - b.s ourceIndex ;
  4831                    }
  4832  
  4833                    var  al, bl,
  4834                             ap = [ ],
  4835                             bp = [ ],
  4836                             aup =  a.parentNo de,
  4837                             bup =  b.parentNo de,
  4838                             cur =  aup;
  4839  
  4840                    // I f the node s are sibl ings (or i dentical)  we can do  a quick ch eck
  4841                    if (  aup === b up ) {
  4842                             return  siblingCh eck( a, b  );
  4843  
  4844                    // I f no paren ts were fo und then t he nodes a re disconn ected
  4845                    } el se if ( !a up ) {
  4846                             return  -1;
  4847  
  4848                    } el se if ( !b up ) {
  4849                             return  1;
  4850                    }
  4851  
  4852                    // O therwise t hey're som ewhere els e in the t ree so we  need
  4853                    // t o build up  a full li st of the  parentNode s for comp arison
  4854                    whil e ( cur )  {
  4855                             ap.uns hift( cur  );
  4856                             cur =  cur.parent Node;
  4857                    }
  4858  
  4859                    cur  = bup;
  4860  
  4861                    whil e ( cur )  {
  4862                             bp.uns hift( cur  );
  4863                             cur =  cur.parent Node;
  4864                    }
  4865  
  4866                    al =  ap.length ;
  4867                    bl =  bp.length ;
  4868  
  4869                    // S tart walki ng down th e tree loo king for a  discrepan cy
  4870                    for  ( var i =  0; i < al  && i < bl;  i++ ) {
  4871                             if ( a p[i] !== b p[i] ) {
  4872                                      return s iblingChec k( ap[i],  bp[i] );
  4873                             }
  4874                    }
  4875  
  4876                    // W e ended so meplace up  the tree  so do a si bling chec k
  4877                    retu rn i === a l ?
  4878                             siblin gCheck( a,  bp[i], -1  ) :
  4879                             siblin gCheck( ap [i], b, 1  );
  4880           };
  4881  
  4882           si blingCheck  = functio n( a, b, r et ) {
  4883                    if (  a === b )  {
  4884                             return  ret;
  4885                    }
  4886  
  4887                    var  cur = a.ne xtSibling;
  4888  
  4889                    whil e ( cur )  {
  4890                             if ( c ur === b )  {
  4891                                      return - 1;
  4892                             }
  4893  
  4894                             cur =  cur.nextSi bling;
  4895                    }
  4896  
  4897                    retu rn 1;
  4898           };
  4899   }
  4900  
  4901   // Check t o see if t he browser  returns e lements by  name when
  4902   // queryin g by getEl ementById  (and provi de a worka round)
  4903   (function( ){
  4904           //  We're goi ng to inje ct a fake  input elem ent with a  specified  name
  4905           va r form = d ocument.cr eateElemen t("div"),
  4906                    id =  "script"  + (new Dat e()).getTi me(),
  4907                    root  = documen t.document Element;
  4908  
  4909           fo rm.innerHT ML = "<a n ame='" + i d + "'/>";
  4910  
  4911           //  Inject it  into the  root eleme nt, check  its status , and remo ve it quic kly
  4912           ro ot.insertB efore( for m, root.fi rstChild ) ;
  4913  
  4914           //  The worka round has  to do addi tional che cks after  a getEleme ntById
  4915           //  Which slo ws things  down for o ther brows ers (hence  the branc hing)
  4916           if  ( documen t.getEleme ntById( id  ) ) {
  4917                    Expr .find.ID =  function(  match, co ntext, isX ML ) {
  4918                             if ( t ypeof cont ext.getEle mentById ! == "undefi ned" && !i sXML ) {
  4919                                      var m =  context.ge tElementBy Id(match[1 ]);
  4920  
  4921                                      return m  ?
  4922                                               m.id === m atch[1] ||  typeof m. getAttribu teNode !==  "undefine d" && m.ge tAttribute Node("id") .nodeValue  === match [1] ?
  4923                                                       [m ] :
  4924                                                       un defined :
  4925                                               [];
  4926                             }
  4927                    };
  4928  
  4929                    Expr .filter.ID  = functio n( elem, m atch ) {
  4930                             var no de = typeo f elem.get AttributeN ode !== "u ndefined"  && elem.ge tAttribute Node("id") ;
  4931  
  4932                             return  elem.node Type === 1  && node & & node.nod eValue ===  match;
  4933                    };
  4934           }
  4935  
  4936           ro ot.removeC hild( form  );
  4937  
  4938           //  release m emory in I E
  4939           ro ot = form  = null;
  4940   })();
  4941  
  4942   (function( ){
  4943           //  Check to  see if the  browser r eturns onl y elements
  4944           //  when doin g getEleme ntsByTagNa me("*")
  4945  
  4946           //  Create a  fake eleme nt
  4947           va r div = do cument.cre ateElement ("div");
  4948           di v.appendCh ild( docum ent.create Comment("" ) );
  4949  
  4950           //  Make sure  no commen ts are fou nd
  4951           if  ( div.get ElementsBy TagName("* ").length  > 0 ) {
  4952                    Expr .find.TAG  = function ( match, c ontext ) {
  4953                             var re sults = co ntext.getE lementsByT agName( ma tch[1] );
  4954  
  4955                             // Fil ter out po ssible com ments
  4956                             if ( m atch[1] == = "*" ) {
  4957                                      var tmp  = [];
  4958  
  4959                                      for ( va r i = 0; r esults[i];  i++ ) {
  4960                                               if ( resul ts[i].node Type === 1  ) {
  4961                                                       tm p.push( re sults[i] ) ;
  4962                                               }
  4963                                      }
  4964  
  4965                                      results  = tmp;
  4966                             }
  4967  
  4968                             return  results;
  4969                    };
  4970           }
  4971  
  4972           //  Check to  see if an  attribute  returns no rmalized h ref attrib utes
  4973           di v.innerHTM L = "<a hr ef='#'></a >";
  4974  
  4975           if  ( div.fir stChild &&  typeof di v.firstChi ld.getAttr ibute !==  "undefined " &&
  4976                             div.fi rstChild.g etAttribut e("href")  !== "#" )  {
  4977  
  4978                    Expr .attrHandl e.href = f unction( e lem ) {
  4979                             return  elem.getA ttribute(  "href", 2  );
  4980                    };
  4981           }
  4982  
  4983           //  release m emory in I E
  4984           di v = null;
  4985   })();
  4986  
  4987   if ( docum ent.queryS electorAll  ) {
  4988           (f unction(){
  4989                    var  oldSizzle  = Sizzle,
  4990                             div =  document.c reateEleme nt("div"),
  4991                             id = " __sizzle__ ";
  4992  
  4993                    div. innerHTML  = "<p clas s='TEST'>< /p>";
  4994  
  4995                    // S afari can' t handle u ppercase o r unicode  characters  when
  4996                    // i n quirks m ode.
  4997                    if (  div.query SelectorAl l && div.q uerySelect orAll(".TE ST").lengt h === 0 )  {
  4998                             return ;
  4999                    }
  5000           
  5001                    Sizz le = funct ion( query , context,  extra, se ed ) {
  5002                             contex t = contex t || docum ent;
  5003  
  5004                             // Onl y use quer ySelectorA ll on non- XML docume nts
  5005                             // (ID  selectors  don't wor k in non-H TML docume nts)
  5006                             if ( ! seed && !S izzle.isXM L(context)  ) {
  5007                                      // See i f we find  a selector  to speed  up
  5008                                      var matc h = /^(\w+ $)|^\.([\w \-]+$)|^#( [\w\-]+$)/ .exec( que ry );
  5009                                      
  5010                                      if ( mat ch && (con text.nodeT ype === 1  || context .nodeType  === 9) ) {
  5011                                               // Speed-u p: Sizzle( "TAG")
  5012                                               if ( match [1] ) {
  5013                                                       re turn makeA rray( cont ext.getEle mentsByTag Name( quer y ), extra  );
  5014                                              
  5015                                               // Speed-u p: Sizzle( ".CLASS")
  5016                                               } else if  ( match[2]  && Expr.f ind.CLASS  && context .getElemen tsByClassN ame ) {
  5017                                                       re turn makeA rray( cont ext.getEle mentsByCla ssName( ma tch[2] ),  extra );
  5018                                               }
  5019                                      }
  5020                                      
  5021                                      if ( con text.nodeT ype === 9  ) {
  5022                                               // Speed-u p: Sizzle( "body")
  5023                                               // The bod y element  only exist s once, op timize fin ding it
  5024                                               if ( query  === "body " && conte xt.body )  {
  5025                                                       re turn makeA rray( [ co ntext.body  ], extra  );
  5026                                                       
  5027                                               // Speed-u p: Sizzle( "#ID")
  5028                                               } else if  ( match &&  match[3]  ) {
  5029                                                       va r elem = c ontext.get ElementByI d( match[3 ] );
  5030  
  5031                                                       //  Check par entNode to  catch whe n Blackber ry 4.6 ret urns
  5032                                                       //  nodes tha t are no l onger in t he documen t #6963
  5033                                                       if  ( elem &&  elem.pare ntNode ) {
  5034                                                                // H andle the  case where  IE and Op era return  items
  5035                                                                // b y name ins tead of ID
  5036                                                                if (  elem.id = == match[3 ] ) {
  5037                                                                         return  makeArray ( [ elem ] , extra );
  5038                                                                }
  5039                                                                
  5040                                                       }  else {
  5041                                                                retu rn makeArr ay( [], ex tra );
  5042                                                       }
  5043                                               }
  5044                                              
  5045                                               try {
  5046                                                       re turn makeA rray( cont ext.queryS electorAll (query), e xtra );
  5047                                               } catch(qs aError) {}
  5048  
  5049                                      // qSA w orks stran gely on El ement-root ed queries
  5050                                      // We ca n work aro und this b y specifyi ng an extr a ID on th e root
  5051                                      // and w orking up  from there  (Thanks t o Andrew D upont for  the techni que)
  5052                                      // IE 8  doesn't wo rk on obje ct element s
  5053                                      } else i f ( contex t.nodeType  === 1 &&  context.no deName.toL owerCase()  !== "obje ct" ) {
  5054                                               var oldCon text = con text,
  5055                                                       ol d = contex t.getAttri bute( "id"  ),
  5056                                                       ni d = old ||  id,
  5057                                                       ha sParent =  context.pa rentNode,
  5058                                                       re lativeHier archySelec tor = /^\s *[+~]/.tes t( query ) ;
  5059  
  5060                                               if ( !old  ) {
  5061                                                       co ntext.setA ttribute(  "id", nid  );
  5062                                               } else {
  5063                                                       ni d = nid.re place( /'/ g, "\\$&"  );
  5064                                               }
  5065                                               if ( relat iveHierarc hySelector  && hasPar ent ) {
  5066                                                       co ntext = co ntext.pare ntNode;
  5067                                               }
  5068  
  5069                                               try {
  5070                                                       if  ( !relati veHierarch ySelector  || hasPare nt ) {
  5071                                                                retu rn makeArr ay( contex t.querySel ectorAll(  "[id='" +  nid + "']  " + query  ), extra ) ;
  5072                                                       }
  5073  
  5074                                               } catch(ps eudoError)  {
  5075                                               } finally  {
  5076                                                       if  ( !old )  {
  5077                                                                oldC ontext.rem oveAttribu te( "id" ) ;
  5078                                                       }
  5079                                               }
  5080                                      }
  5081                             }
  5082                    
  5083                             return  oldSizzle (query, co ntext, ext ra, seed);
  5084                    };
  5085  
  5086                    for  ( var prop  in oldSiz zle ) {
  5087                             Sizzle [ prop ] =  oldSizzle [ prop ];
  5088                    }
  5089  
  5090                    // r elease mem ory in IE
  5091                    div  = null;
  5092           }) ();
  5093   }
  5094  
  5095   (function( ){
  5096           va r html = d ocument.do cumentElem ent,
  5097                    matc hes = html .matchesSe lector ||  html.mozMa tchesSelec tor || htm l.webkitMa tchesSelec tor || htm l.msMatche sSelector;
  5098  
  5099           if  ( matches  ) {
  5100                    // C heck to se e if it's  possible t o do match esSelector
  5101                    // o n a discon nected nod e (IE 9 fa ils this)
  5102                    var  disconnect edMatch =  !matches.c all( docum ent.create Element( " div" ), "d iv" ),
  5103                             pseudo Works = fa lse;
  5104  
  5105                    try  {
  5106                             // Thi s should f ail with a n exceptio n
  5107                             // Gec ko does no t error, r eturns fal se instead
  5108                             matche s.call( do cument.doc umentEleme nt, "[test !='']:sizz le" );
  5109           
  5110                    } ca tch( pseud oError ) {
  5111                             pseudo Works = tr ue;
  5112                    }
  5113  
  5114                    Sizz le.matches Selector =  function(  node, exp r ) {
  5115                             // Mak e sure tha t attribut e selector s are quot ed
  5116                             expr =  expr.repl ace(/\=\s* ([^'"\]]*) \s*\]/g, " ='$1']");
  5117  
  5118                             if ( ! Sizzle.isX ML( node )  ) {
  5119                                      try { 
  5120                                               if ( pseud oWorks ||  !Expr.matc h.PSEUDO.t est( expr  ) && !/!=/ .test( exp r ) ) {
  5121                                                       va r ret = ma tches.call ( node, ex pr );
  5122  
  5123                                                       //  IE 9's ma tchesSelec tor return s false on  disconnec ted nodes
  5124                                                       if  ( ret ||  !disconnec tedMatch | |
  5125                                                                         // As  well, disc onnected n odes are s aid to be  in a docum ent
  5126                                                                         // fra gment in I E 9, so ch eck for th at
  5127                                                                         node.d ocument &&  node.docu ment.nodeT ype !== 11  ) {
  5128                                                                retu rn ret;
  5129                                                       }
  5130                                               }
  5131                                      } catch( e) {}
  5132                             }
  5133  
  5134                             return  Sizzle(ex pr, null,  null, [nod e]).length  > 0;
  5135                    };
  5136           }
  5137   })();
  5138  
  5139   (function( ){
  5140           va r div = do cument.cre ateElement ("div");
  5141  
  5142           di v.innerHTM L = "<div  class='tes t e'></div ><div clas s='test'>< /div>";
  5143  
  5144           //  Opera can 't find a  second cla ssname (in  9.6)
  5145           //  Also, mak e sure tha t getEleme ntsByClass Name actua lly exists
  5146           if  ( !div.ge tElementsB yClassName  || div.ge tElementsB yClassName ("e").leng th === 0 )  {
  5147                    retu rn;
  5148           }
  5149  
  5150           //  Safari ca ches class  attribute s, doesn't  catch cha nges (in 3 .2)
  5151           di v.lastChil d.classNam e = "e";
  5152  
  5153           if  ( div.get ElementsBy ClassName( "e").lengt h === 1 )  {
  5154                    retu rn;
  5155           }
  5156           
  5157           Ex pr.order.s plice(1, 0 , "CLASS") ;
  5158           Ex pr.find.CL ASS = func tion( matc h, context , isXML )  {
  5159                    if (  typeof co ntext.getE lementsByC lassName ! == "undefi ned" && !i sXML ) {
  5160                             return  context.g etElements ByClassNam e(match[1] );
  5161                    }
  5162           };
  5163  
  5164           //  release m emory in I E
  5165           di v = null;
  5166   })();
  5167  
  5168   function d irNodeChec k( dir, cu r, doneNam e, checkSe t, nodeChe ck, isXML  ) {
  5169           fo r ( var i  = 0, l = c heckSet.le ngth; i <  l; i++ ) {
  5170                    var  elem = che ckSet[i];
  5171  
  5172                    if (  elem ) {
  5173                             var ma tch = fals e;
  5174  
  5175                             elem =  elem[dir] ;
  5176  
  5177                             while  ( elem ) {
  5178                                      if ( ele m[ expando  ] === don eName ) {
  5179                                               match = ch eckSet[ele m.sizset];
  5180                                               break;
  5181                                      }
  5182  
  5183                                      if ( ele m.nodeType  === 1 &&  !isXML ){
  5184                                               elem[ expa ndo ] = do neName;
  5185                                               elem.sizse t = i;
  5186                                      }
  5187  
  5188                                      if ( ele m.nodeName .toLowerCa se() === c ur ) {
  5189                                               match = el em;
  5190                                               break;
  5191                                      }
  5192  
  5193                                      elem = e lem[dir];
  5194                             }
  5195  
  5196                             checkS et[i] = ma tch;
  5197                    }
  5198           }
  5199   }
  5200  
  5201   function d irCheck( d ir, cur, d oneName, c heckSet, n odeCheck,  isXML ) {
  5202           fo r ( var i  = 0, l = c heckSet.le ngth; i <  l; i++ ) {
  5203                    var  elem = che ckSet[i];
  5204  
  5205                    if (  elem ) {
  5206                             var ma tch = fals e;
  5207                             
  5208                             elem =  elem[dir] ;
  5209  
  5210                             while  ( elem ) {
  5211                                      if ( ele m[ expando  ] === don eName ) {
  5212                                               match = ch eckSet[ele m.sizset];
  5213                                               break;
  5214                                      }
  5215  
  5216                                      if ( ele m.nodeType  === 1 ) {
  5217                                               if ( !isXM L ) {
  5218                                                       el em[ expand o ] = done Name;
  5219                                                       el em.sizset  = i;
  5220                                               }
  5221  
  5222                                               if ( typeo f cur !==  "string" )  {
  5223                                                       if  ( elem == = cur ) {
  5224                                                                matc h = true;
  5225                                                                brea k;
  5226                                                       }
  5227  
  5228                                               } else if  ( Sizzle.f ilter( cur , [elem] ) .length >  0 ) {
  5229                                                       ma tch = elem ;
  5230                                                       br eak;
  5231                                               }
  5232                                      }
  5233  
  5234                                      elem = e lem[dir];
  5235                             }
  5236  
  5237                             checkS et[i] = ma tch;
  5238                    }
  5239           }
  5240   }
  5241  
  5242   if ( docum ent.docume ntElement. contains )  {
  5243           Si zzle.conta ins = func tion( a, b  ) {
  5244                    retu rn a !== b  && (a.con tains ? a. contains(b ) : true);
  5245           };
  5246  
  5247   } else if  ( document .documentE lement.com pareDocume ntPosition  ) {
  5248           Si zzle.conta ins = func tion( a, b  ) {
  5249                    retu rn !!(a.co mpareDocum entPositio n(b) & 16) ;
  5250           };
  5251  
  5252   } else {
  5253           Si zzle.conta ins = func tion() {
  5254                    retu rn false;
  5255           };
  5256   }
  5257  
  5258   Sizzle.isX ML = funct ion( elem  ) {
  5259           //  documentE lement is  verified f or cases w here it do esn't yet  exist
  5260           //  (such as  loading if rames in I E - #4833)  
  5261           va r document Element =  (elem ? el em.ownerDo cument ||  elem : 0). documentEl ement;
  5262  
  5263           re turn docum entElement  ? documen tElement.n odeName != = "HTML" :  false;
  5264   };
  5265  
  5266   var posPro cess = fun ction( sel ector, con text, seed  ) {
  5267           va r match,
  5268                    tmpS et = [],
  5269                    late r = "",
  5270                    root  = context .nodeType  ? [context ] : contex t;
  5271  
  5272           //  Position  selectors  must be do ne after t he filter
  5273           //  And so mu st :not(po sitional)  so we move  all PSEUD Os to the  end
  5274           wh ile ( (mat ch = Expr. match.PSEU DO.exec( s elector ))  ) {
  5275                    late r += match [0];
  5276                    sele ctor = sel ector.repl ace( Expr. match.PSEU DO, "" );
  5277           }
  5278  
  5279           se lector = E xpr.relati ve[selecto r] ? selec tor + "*"  : selector ;
  5280  
  5281           fo r ( var i  = 0, l = r oot.length ; i < l; i ++ ) {
  5282                    Sizz le( select or, root[i ], tmpSet,  seed );
  5283           }
  5284  
  5285           re turn Sizzl e.filter(  later, tmp Set );
  5286   };
  5287  
  5288   // EXPOSE
  5289   // Overrid e sizzle a ttribute r etrieval
  5290   Sizzle.att r = jQuery .attr;
  5291   Sizzle.sel ectors.att rMap = {};
  5292   jQuery.fin d = Sizzle ;
  5293   jQuery.exp r = Sizzle .selectors ;
  5294   jQuery.exp r[":"] = j Query.expr .filters;
  5295   jQuery.uni que = Sizz le.uniqueS ort;
  5296   jQuery.tex t = Sizzle .getText;
  5297   jQuery.isX MLDoc = Si zzle.isXML ;
  5298   jQuery.con tains = Si zzle.conta ins;
  5299  
  5300  
  5301   })();
  5302  
  5303  
  5304   var runtil  = /Until$ /,
  5305           rp arentsprev  = /^(?:pa rents|prev Until|prev All)/,
  5306           //  Note: Thi s RegExp s hould be i mproved, o r likely p ulled from  Sizzle
  5307           rm ultiselect or = /,/,
  5308           is Simple = / ^.[^:#\[\. ,]*$/,
  5309           sl ice = Arra y.prototyp e.slice,
  5310           PO S = jQuery .expr.matc h.POS,
  5311           //  methods g uaranteed  to produce  a unique  set when s tarting fr om a uniqu e set
  5312           gu aranteedUn ique = {
  5313                    chil dren: true ,
  5314                    cont ents: true ,
  5315                    next : true,
  5316                    prev : true
  5317           };
  5318  
  5319   jQuery.fn. extend({
  5320           fi nd: functi on( select or ) {
  5321                    var  self = thi s,
  5322                             i, l;
  5323  
  5324                    if (  typeof se lector !==  "string"  ) {
  5325                             return  jQuery( s elector ). filter(fun ction() {
  5326                                      for ( i  = 0, l = s elf.length ; i < l; i ++ ) {
  5327                                               if ( jQuer y.contains ( self[ i  ], this )  ) {
  5328                                                       re turn true;
  5329                                               }
  5330                                      }
  5331                             });
  5332                    }
  5333  
  5334                    var  ret = this .pushStack ( "", "fin d", select or ),
  5335                             length , n, r;
  5336  
  5337                    for  ( i = 0, l  = this.le ngth; i <  l; i++ ) {
  5338                             length  = ret.len gth;
  5339                             jQuery .find( sel ector, thi s[i], ret  );
  5340  
  5341                             if ( i  > 0 ) {
  5342                                      // Make  sure that  the result s are uniq ue
  5343                                      for ( n  = length;  n < ret.le ngth; n++  ) {
  5344                                               for ( r =  0; r < len gth; r++ )  {
  5345                                                       if  ( ret[r]  === ret[n]  ) {
  5346                                                                ret. splice(n-- , 1);
  5347                                                                brea k;
  5348                                                       }
  5349                                               }
  5350                                      }
  5351                             }
  5352                    }
  5353  
  5354                    retu rn ret;
  5355           },
  5356  
  5357           ha s: functio n( target  ) {
  5358                    var  targets =  jQuery( ta rget );
  5359                    retu rn this.fi lter(funct ion() {
  5360                             for (  var i = 0,  l = targe ts.length;  i < l; i+ + ) {
  5361                                      if ( jQu ery.contai ns( this,  targets[i]  ) ) {
  5362                                               return tru e;
  5363                                      }
  5364                             }
  5365                    });
  5366           },
  5367  
  5368           no t: functio n( selecto r ) {
  5369                    retu rn this.pu shStack( w innow(this , selector , false),  "not", sel ector);
  5370           },
  5371  
  5372           fi lter: func tion( sele ctor ) {
  5373                    retu rn this.pu shStack( w innow(this , selector , true), " filter", s elector );
  5374           },
  5375  
  5376           is : function ( selector  ) {
  5377                    retu rn !!selec tor && ( 
  5378                             typeof  selector  === "strin g" ?
  5379                                      // If th is is a po sitional s elector, c heck membe rship in t he returne d set
  5380                                      // so $( "p:first") .is("p:las t") won't  return tru e for a do c with two  "p".
  5381                                      POS.test ( selector  ) ? 
  5382                                               jQuery( se lector, th is.context  ).index(  this[0] )  >= 0 :
  5383                                               jQuery.fil ter( selec tor, this  ).length >  0 :
  5384                                      this.fil ter( selec tor ).leng th > 0 );
  5385           },
  5386  
  5387           cl osest: fun ction( sel ectors, co ntext ) {
  5388                    var  ret = [],  i, l, cur  = this[0];
  5389                    
  5390                    // A rray (depr ecated as  of jQuery  1.7)
  5391                    if (  jQuery.is Array( sel ectors ) )  {
  5392                             var le vel = 1;
  5393  
  5394                             while  ( cur && c ur.ownerDo cument &&  cur !== co ntext ) {
  5395                                      for ( i  = 0; i < s electors.l ength; i++  ) {
  5396  
  5397                                               if ( jQuer y( cur ).i s( selecto rs[ i ] )  ) {
  5398                                                       re t.push({ s elector: s electors[  i ], elem:  cur, leve l: level } );
  5399                                               }
  5400                                      }
  5401  
  5402                                      cur = cu r.parentNo de;
  5403                                      level++;
  5404                             }
  5405  
  5406                             return  ret;
  5407                    }
  5408  
  5409                    // S tring
  5410                    var  pos = POS. test( sele ctors ) ||  typeof se lectors != = "string"  ?
  5411                                      jQuery(  selectors,  context | | this.con text ) :
  5412                                      0;
  5413  
  5414                    for  ( i = 0, l  = this.le ngth; i <  l; i++ ) {
  5415                             cur =  this[i];
  5416  
  5417                             while  ( cur ) {
  5418                                      if ( pos  ? pos.ind ex(cur) >  -1 : jQuer y.find.mat chesSelect or(cur, se lectors) )  {
  5419                                               ret.push(  cur );
  5420                                               break;
  5421  
  5422                                      } else {
  5423                                               cur = cur. parentNode ;
  5424                                               if ( !cur  || !cur.ow nerDocumen t || cur = == context  || cur.no deType ===  11 ) {
  5425                                                       br eak;
  5426                                               }
  5427                                      }
  5428                             }
  5429                    }
  5430  
  5431                    ret  = ret.leng th > 1 ? j Query.uniq ue( ret )  : ret;
  5432  
  5433                    retu rn this.pu shStack( r et, "close st", selec tors );
  5434           },
  5435  
  5436           //  Determine  the posit ion of an  element wi thin
  5437           //  the match ed set of  elements
  5438           in dex: funct ion( elem  ) {
  5439  
  5440                    // N o argument , return i ndex in pa rent
  5441                    if (  !elem ) {
  5442                             return  ( this[0]  && this[0 ].parentNo de ) ? thi s.prevAll( ).length :  -1;
  5443                    }
  5444  
  5445                    // i ndex in se lector
  5446                    if (  typeof el em === "st ring" ) {
  5447                             return  jQuery.in Array( thi s[0], jQue ry( elem )  );
  5448                    }
  5449  
  5450                    // L ocate the  position o f the desi red elemen t
  5451                    retu rn jQuery. inArray(
  5452                             // If  it receive s a jQuery  object, t he first e lement is  used
  5453                             elem.j query ? el em[0] : el em, this ) ;
  5454           },
  5455  
  5456           ad d: functio n( selecto r, context  ) {
  5457                    var  set = type of selecto r === "str ing" ?
  5458                                      jQuery(  selector,  context )  :
  5459                                      jQuery.m akeArray(  selector & & selector .nodeType  ? [ select or ] : sel ector ),
  5460                             all =  jQuery.mer ge( this.g et(), set  );
  5461  
  5462                    retu rn this.pu shStack( i sDisconnec ted( set[0 ] ) || isD isconnecte d( all[0]  ) ?
  5463                             all :
  5464                             jQuery .unique( a ll ) );
  5465           },
  5466  
  5467           an dSelf: fun ction() {
  5468                    retu rn this.ad d( this.pr evObject ) ;
  5469           }
  5470   });
  5471  
  5472   // A painf ully simpl e check to  see if an  element i s disconne cted
  5473   // from a  document ( should be  improved,  where feas ible).
  5474   function i sDisconnec ted( node  ) {
  5475           re turn !node  || !node. parentNode  || node.p arentNode. nodeType = == 11;
  5476   }
  5477  
  5478   jQuery.eac h({
  5479           pa rent: func tion( elem  ) {
  5480                    var  parent = e lem.parent Node;
  5481                    retu rn parent  && parent. nodeType ! == 11 ? pa rent : nul l;
  5482           },
  5483           pa rents: fun ction( ele m ) {
  5484                    retu rn jQuery. dir( elem,  "parentNo de" );
  5485           },
  5486           pa rentsUntil : function ( elem, i,  until ) {
  5487                    retu rn jQuery. dir( elem,  "parentNo de", until  );
  5488           },
  5489           ne xt: functi on( elem )  {
  5490                    retu rn jQuery. nth( elem,  2, "nextS ibling" );
  5491           },
  5492           pr ev: functi on( elem )  {
  5493                    retu rn jQuery. nth( elem,  2, "previ ousSibling " );
  5494           },
  5495           ne xtAll: fun ction( ele m ) {
  5496                    retu rn jQuery. dir( elem,  "nextSibl ing" );
  5497           },
  5498           pr evAll: fun ction( ele m ) {
  5499                    retu rn jQuery. dir( elem,  "previous Sibling" ) ;
  5500           },
  5501           ne xtUntil: f unction( e lem, i, un til ) {
  5502                    retu rn jQuery. dir( elem,  "nextSibl ing", unti l );
  5503           },
  5504           pr evUntil: f unction( e lem, i, un til ) {
  5505                    retu rn jQuery. dir( elem,  "previous Sibling",  until );
  5506           },
  5507           si blings: fu nction( el em ) {
  5508                    retu rn jQuery. sibling( e lem.parent Node.first Child, ele m );
  5509           },
  5510           ch ildren: fu nction( el em ) {
  5511                    retu rn jQuery. sibling( e lem.firstC hild );
  5512           },
  5513           co ntents: fu nction( el em ) {
  5514                    retu rn jQuery. nodeName(  elem, "ifr ame" ) ?
  5515                             elem.c ontentDocu ment || el em.content Window.doc ument :
  5516                             jQuery .makeArray ( elem.chi ldNodes );
  5517           }
  5518   }, functio n( name, f n ) {
  5519           jQ uery.fn[ n ame ] = fu nction( un til, selec tor ) {
  5520                    var  ret = jQue ry.map( th is, fn, un til );
  5521  
  5522                    if (  !runtil.t est( name  ) ) {
  5523                             select or = until ;
  5524                    }
  5525  
  5526                    if (  selector  && typeof  selector = == "string " ) {
  5527                             ret =  jQuery.fil ter( selec tor, ret ) ;
  5528                    }
  5529  
  5530                    ret  = this.len gth > 1 &&  !guarante edUnique[  name ] ? j Query.uniq ue( ret )  : ret;
  5531  
  5532                    if (  (this.len gth > 1 ||  rmultisel ector.test ( selector  )) && rpa rentsprev. test( name  ) ) {
  5533                             ret =  ret.revers e();
  5534                    }
  5535  
  5536                    retu rn this.pu shStack( r et, name,  slice.call ( argument s ).join(" ,") );
  5537           };
  5538   });
  5539  
  5540   jQuery.ext end({
  5541           fi lter: func tion( expr , elems, n ot ) {
  5542                    if (  not ) {
  5543                             expr =  ":not(" +  expr + ") ";
  5544                    }
  5545  
  5546                    retu rn elems.l ength ===  1 ?
  5547                             jQuery .find.matc hesSelecto r(elems[0] , expr) ?  [ elems[0]  ] : [] :
  5548                             jQuery .find.matc hes(expr,  elems);
  5549           },
  5550  
  5551           di r: functio n( elem, d ir, until  ) {
  5552                    var  matched =  [],
  5553                             cur =  elem[ dir  ];
  5554  
  5555                    whil e ( cur &&  cur.nodeT ype !== 9  && (until  === undefi ned || cur .nodeType  !== 1 || ! jQuery( cu r ).is( un til )) ) {
  5556                             if ( c ur.nodeTyp e === 1 )  {
  5557                                      matched. push( cur  );
  5558                             }
  5559                             cur =  cur[dir];
  5560                    }
  5561                    retu rn matched ;
  5562           },
  5563  
  5564           nt h: functio n( cur, re sult, dir,  elem ) {
  5565                    resu lt = resul t || 1;
  5566                    var  num = 0;
  5567  
  5568                    for  ( ; cur; c ur = cur[d ir] ) {
  5569                             if ( c ur.nodeTyp e === 1 &&  ++num ===  result )  {
  5570                                      break;
  5571                             }
  5572                    }
  5573  
  5574                    retu rn cur;
  5575           },
  5576  
  5577           si bling: fun ction( n,  elem ) {
  5578                    var  r = [];
  5579  
  5580                    for  ( ; n; n =  n.nextSib ling ) {
  5581                             if ( n .nodeType  === 1 && n  !== elem  ) {
  5582                                      r.push(  n );
  5583                             }
  5584                    }
  5585  
  5586                    retu rn r;
  5587           }
  5588   });
  5589  
  5590   // Impleme nt the ide ntical fun ctionality  for filte r and not
  5591   function w innow( ele ments, qua lifier, ke ep ) {
  5592  
  5593           //  Can't pas s null or  undefined  to indexOf  in Firefo x 4
  5594           //  Set to 0  to skip st ring check
  5595           qu alifier =  qualifier  || 0;
  5596  
  5597           if  ( jQuery. isFunction ( qualifie r ) ) {
  5598                    retu rn jQuery. grep(eleme nts, funct ion( elem,  i ) {
  5599                             var re tVal = !!q ualifier.c all( elem,  i, elem ) ;
  5600                             return  retVal == = keep;
  5601                    });
  5602  
  5603           }  else if (  qualifier. nodeType )  {
  5604                    retu rn jQuery. grep(eleme nts, funct ion( elem,  i ) {
  5605                             return  ( elem == = qualifie r ) === ke ep;
  5606                    });
  5607  
  5608           }  else if (  typeof qua lifier ===  "string"  ) {
  5609                    var  filtered =  jQuery.gr ep(element s, functio n( elem )  {
  5610                             return  elem.node Type === 1 ;
  5611                    });
  5612  
  5613                    if (  isSimple. test( qual ifier ) )  {
  5614                             return  jQuery.fi lter(quali fier, filt ered, !kee p);
  5615                    } el se {
  5616                             qualif ier = jQue ry.filter(  qualifier , filtered  );
  5617                    }
  5618           }
  5619  
  5620           re turn jQuer y.grep(ele ments, fun ction( ele m, i ) {
  5621                    retu rn ( jQuer y.inArray(  elem, qua lifier ) > = 0 ) ===  keep;
  5622           }) ;
  5623   }
  5624  
  5625  
  5626  
  5627  
  5628   function c reateSafeF ragment( d ocument )  {
  5629           va r list = n odeNames.s plit( "|"  ),
  5630           sa feFrag = d ocument.cr eateDocume ntFragment ();
  5631  
  5632           if  ( safeFra g.createEl ement ) {
  5633                    whil e ( list.l ength ) {
  5634                             safeFr ag.createE lement(
  5635                                      list.pop ()
  5636                             );
  5637                    }
  5638           }
  5639           re turn safeF rag;
  5640   }
  5641  
  5642   var nodeNa mes = "abb r|article| aside|audi o|canvas|d atalist|de tails|figc aption|fig ure|footer |" +
  5643                    "hea der|hgroup |mark|mete r|nav|outp ut|progres s|section| summary|ti me|video",
  5644           ri nlinejQuer y = / jQue ry\d+="(?: \d+|null)" /g,
  5645           rl eadingWhit espace = / ^\s+/,
  5646           rx htmlTag =  /<(?!area| br|col|emb ed|hr|img| input|link |meta|para m)(([\w:]+ )[^>]*)\/> /ig,
  5647           rt agName = / <([\w:]+)/ ,
  5648           rt body = /<t body/i,
  5649           rh tml = /<|& #?\w+;/,
  5650           rn oInnerhtml  = /<(?:sc ript|style )/i,
  5651           rn ocache = / <(?:script |object|em bed|option |style)/i,
  5652           rn oshimcache  = new Reg Exp("<(?:"  + nodeNam es + ")",  "i"),
  5653           //  checked=" checked" o r checked
  5654           rc hecked = / checked\s* (?:[^=]|=\ s*.checked .)/i,
  5655           rs criptType  = /\/(java |ecma)scri pt/i,
  5656           rc leanScript  = /^\s*<! (?:\[CDATA \[|\-\-)/,
  5657           wr apMap = {
  5658                    opti on: [ 1, " <select mu ltiple='mu ltiple'>",  "</select >" ],
  5659                    lege nd: [ 1, " <fieldset> ", "</fiel dset>" ],
  5660                    thea d: [ 1, "< table>", " </table>"  ],
  5661                    tr:  [ 2, "<tab le><tbody> ", "</tbod y></table> " ],
  5662                    td:  [ 3, "<tab le><tbody> <tr>", "</ tr></tbody ></table>"  ],
  5663                    col:  [ 2, "<ta ble><tbody ></tbody>< colgroup>" , "</colgr oup></tabl e>" ],
  5664                    area : [ 1, "<m ap>", "</m ap>" ],
  5665                    _def ault: [ 0,  "", "" ]
  5666           },
  5667           sa feFragment  = createS afeFragmen t( documen t );
  5668  
  5669   wrapMap.op tgroup = w rapMap.opt ion;
  5670   wrapMap.tb ody = wrap Map.tfoot  = wrapMap. colgroup =  wrapMap.c aption = w rapMap.the ad;
  5671   wrapMap.th  = wrapMap .td;
  5672  
  5673   // IE can' t serializ e <link> a nd <script > tags nor mally
  5674   if ( !jQue ry.support .htmlSeria lize ) {
  5675           wr apMap._def ault = [ 1 , "div<div >", "</div >" ];
  5676   }
  5677  
  5678   jQuery.fn. extend({
  5679           te xt: functi on( text )  {
  5680                    if (  jQuery.is Function(t ext) ) {
  5681                             return  this.each (function( i) {
  5682                                      var self  = jQuery(  this );
  5683  
  5684                                      self.tex t( text.ca ll(this, i , self.tex t()) );
  5685                             });
  5686                    }
  5687  
  5688                    if (  typeof te xt !== "ob ject" && t ext !== un defined )  {
  5689                             return  this.empt y().append ( (this[0]  && this[0 ].ownerDoc ument || d ocument).c reateTextN ode( text  ) );
  5690                    }
  5691  
  5692                    retu rn jQuery. text( this  );
  5693           },
  5694  
  5695           wr apAll: fun ction( htm l ) {
  5696                    if (  jQuery.is Function(  html ) ) {
  5697                             return  this.each (function( i) {
  5698                                      jQuery(t his).wrapA ll( html.c all(this,  i) );
  5699                             });
  5700                    }
  5701  
  5702                    if (  this[0] )  {
  5703                             // The  elements  to wrap th e target a round
  5704                             var wr ap = jQuer y( html, t his[0].own erDocument  ).eq(0).c lone(true) ;
  5705  
  5706                             if ( t his[0].par entNode )  {
  5707                                      wrap.ins ertBefore(  this[0] ) ;
  5708                             }
  5709  
  5710                             wrap.m ap(functio n() {
  5711                                      var elem  = this;
  5712  
  5713                                      while (  elem.first Child && e lem.firstC hild.nodeT ype === 1  ) {
  5714                                               elem = ele m.firstChi ld;
  5715                                      }
  5716  
  5717                                      return e lem;
  5718                             }).app end( this  );
  5719                    }
  5720  
  5721                    retu rn this;
  5722           },
  5723  
  5724           wr apInner: f unction( h tml ) {
  5725                    if (  jQuery.is Function(  html ) ) {
  5726                             return  this.each (function( i) {
  5727                                      jQuery(t his).wrapI nner( html .call(this , i) );
  5728                             });
  5729                    }
  5730  
  5731                    retu rn this.ea ch(functio n() {
  5732                             var se lf = jQuer y( this ),
  5733                                      contents  = self.co ntents();
  5734  
  5735                             if ( c ontents.le ngth ) {
  5736                                      contents .wrapAll(  html );
  5737  
  5738                             } else  {
  5739                                      self.app end( html  );
  5740                             }
  5741                    });
  5742           },
  5743  
  5744           wr ap: functi on( html )  {
  5745                    var  isFunction  = jQuery. isFunction ( html );
  5746  
  5747                    retu rn this.ea ch(functio n(i) {
  5748                             jQuery ( this ).w rapAll( is Function ?  html.call (this, i)  : html );
  5749                    });
  5750           },
  5751  
  5752           un wrap: func tion() {
  5753                    retu rn this.pa rent().eac h(function () {
  5754                             if ( ! jQuery.nod eName( thi s, "body"  ) ) {
  5755                                      jQuery(  this ).rep laceWith(  this.child Nodes );
  5756                             }
  5757                    }).e nd();
  5758           },
  5759  
  5760           ap pend: func tion() {
  5761                    retu rn this.do mManip(arg uments, tr ue, functi on( elem )  {
  5762                             if ( t his.nodeTy pe === 1 )  {
  5763                                      this.app endChild(  elem );
  5764                             }
  5765                    });
  5766           },
  5767  
  5768           pr epend: fun ction() {
  5769                    retu rn this.do mManip(arg uments, tr ue, functi on( elem )  {
  5770                             if ( t his.nodeTy pe === 1 )  {
  5771                                      this.ins ertBefore(  elem, thi s.firstChi ld );
  5772                             }
  5773                    });
  5774           },
  5775  
  5776           be fore: func tion() {
  5777                    if (  this[0] & & this[0]. parentNode  ) {
  5778                             return  this.domM anip(argum ents, fals e, functio n( elem )  {
  5779                                      this.par entNode.in sertBefore ( elem, th is );
  5780                             });
  5781                    } el se if ( ar guments.le ngth ) {
  5782                             var se t = jQuery .clean( ar guments );
  5783                             set.pu sh.apply(  set, this. toArray()  );
  5784                             return  this.push Stack( set , "before" , argument s );
  5785                    }
  5786           },
  5787  
  5788           af ter: funct ion() {
  5789                    if (  this[0] & & this[0]. parentNode  ) {
  5790                             return  this.domM anip(argum ents, fals e, functio n( elem )  {
  5791                                      this.par entNode.in sertBefore ( elem, th is.nextSib ling );
  5792                             });
  5793                    } el se if ( ar guments.le ngth ) {
  5794                             var se t = this.p ushStack(  this, "aft er", argum ents );
  5795                             set.pu sh.apply(  set, jQuer y.clean(ar guments) ) ;
  5796                             return  set;
  5797                    }
  5798           },
  5799  
  5800           //  keepData  is for int ernal use  only--do n ot documen t
  5801           re move: func tion( sele ctor, keep Data ) {
  5802                    for  ( var i =  0, elem; ( elem = thi s[i]) != n ull; i++ )  {
  5803                             if ( ! selector | | jQuery.f ilter( sel ector, [ e lem ] ).le ngth ) {
  5804                                      if ( !ke epData &&  elem.nodeT ype === 1  ) {
  5805                                               jQuery.cle anData( el em.getElem entsByTagN ame("*") ) ;
  5806                                               jQuery.cle anData( [  elem ] );
  5807                                      }
  5808  
  5809                                      if ( ele m.parentNo de ) {
  5810                                               elem.paren tNode.remo veChild( e lem );
  5811                                      }
  5812                             }
  5813                    }
  5814  
  5815                    retu rn this;
  5816           },
  5817  
  5818           em pty: funct ion() {
  5819                    for  ( var i =  0, elem; ( elem = thi s[i]) != n ull; i++ )  {
  5820                             // Rem ove elemen t nodes an d prevent  memory lea ks
  5821                             if ( e lem.nodeTy pe === 1 )  {
  5822                                      jQuery.c leanData(  elem.getEl ementsByTa gName("*")  );
  5823                             }
  5824  
  5825                             // Rem ove any re maining no des
  5826                             while  ( elem.fir stChild )  {
  5827                                      elem.rem oveChild(  elem.first Child );
  5828                             }
  5829                    }
  5830  
  5831                    retu rn this;
  5832           },
  5833  
  5834           cl one: funct ion( dataA ndEvents,  deepDataAn dEvents )  {
  5835                    data AndEvents  = dataAndE vents == n ull ? fals e : dataAn dEvents;
  5836                    deep DataAndEve nts = deep DataAndEve nts == nul l ? dataAn dEvents :  deepDataAn dEvents;
  5837  
  5838                    retu rn this.ma p( functio n () {
  5839                             return  jQuery.cl one( this,  dataAndEv ents, deep DataAndEve nts );
  5840                    });
  5841           },
  5842  
  5843           ht ml: functi on( value  ) {
  5844                    if (  value ===  undefined  ) {
  5845                             return  this[0] & & this[0]. nodeType = == 1 ?
  5846                                      this[0]. innerHTML. replace(ri nlinejQuer y, "") :
  5847                                      null;
  5848  
  5849                    // S ee if we c an take a  shortcut a nd just us e innerHTM L
  5850                    } el se if ( ty peof value  === "stri ng" && !rn oInnerhtml .test( val ue ) &&
  5851                             (jQuer y.support. leadingWhi tespace ||  !rleading Whitespace .test( val ue )) &&
  5852                             !wrapM ap[ (rtagN ame.exec(  value ) ||  ["", ""]) [1].toLowe rCase() ]  ) {
  5853  
  5854                             value  = value.re place(rxht mlTag, "<$ 1></$2>");
  5855  
  5856                             try {
  5857                                      for ( va r i = 0, l  = this.le ngth; i <  l; i++ ) {
  5858                                               // Remove  element no des and pr event memo ry leaks
  5859                                               if ( this[ i].nodeTyp e === 1 )  {
  5860                                                       jQ uery.clean Data( this [i].getEle mentsByTag Name("*")  );
  5861                                                       th is[i].inne rHTML = va lue;
  5862                                               }
  5863                                      }
  5864  
  5865                             // If  using inne rHTML thro ws an exce ption, use  the fallb ack method
  5866                             } catc h(e) {
  5867                                      this.emp ty().appen d( value ) ;
  5868                             }
  5869  
  5870                    } el se if ( jQ uery.isFun ction( val ue ) ) {
  5871                             this.e ach(functi on(i){
  5872                                      var self  = jQuery(  this );
  5873  
  5874                                      self.htm l( value.c all(this,  i, self.ht ml()) );
  5875                             });
  5876  
  5877                    } el se {
  5878                             this.e mpty().app end( value  );
  5879                    }
  5880  
  5881                    retu rn this;
  5882           },
  5883  
  5884           re placeWith:  function(  value ) {
  5885                    if (  this[0] & & this[0]. parentNode  ) {
  5886                             // Mak e sure tha t the elem ents are r emoved fro m the DOM  before the y are inse rted
  5887                             // thi s can help  fix repla cing a par ent with c hild eleme nts
  5888                             if ( j Query.isFu nction( va lue ) ) {
  5889                                      return t his.each(f unction(i)  {
  5890                                               var self =  jQuery(th is), old =  self.html ();
  5891                                               self.repla ceWith( va lue.call(  this, i, o ld ) );
  5892                                      });
  5893                             }
  5894  
  5895                             if ( t ypeof valu e !== "str ing" ) {
  5896                                      value =  jQuery( va lue ).deta ch();
  5897                             }
  5898  
  5899                             return  this.each (function( ) {
  5900                                      var next  = this.ne xtSibling,
  5901                                               parent = t his.parent Node;
  5902  
  5903                                      jQuery(  this ).rem ove();
  5904  
  5905                                      if ( nex t ) {
  5906                                               jQuery(nex t).before(  value );
  5907                                      } else {
  5908                                               jQuery(par ent).appen d( value ) ;
  5909                                      }
  5910                             });
  5911                    } el se {
  5912                             return  this.leng th ?
  5913                                      this.pus hStack( jQ uery(jQuer y.isFuncti on(value)  ? value()  : value),  "replaceWi th", value  ) :
  5914                                      this;
  5915                    }
  5916           },
  5917  
  5918           de tach: func tion( sele ctor ) {
  5919                    retu rn this.re move( sele ctor, true  );
  5920           },
  5921  
  5922           do mManip: fu nction( ar gs, table,  callback  ) {
  5923                    var  results, f irst, frag ment, pare nt,
  5924                             value  = args[0],
  5925                             script s = [];
  5926  
  5927                    // W e can't cl oneNode fr agments th at contain  checked,  in WebKit
  5928                    if (  !jQuery.s upport.che ckClone &&  arguments .length == = 3 && typ eof value  === "strin g" && rche cked.test(  value ) )  {
  5929                             return  this.each (function( ) {
  5930                                      jQuery(t his).domMa nip( args,  table, ca llback, tr ue );
  5931                             });
  5932                    }
  5933  
  5934                    if (  jQuery.is Function(v alue) ) {
  5935                             return  this.each (function( i) {
  5936                                      var self  = jQuery( this);
  5937                                      args[0]  = value.ca ll(this, i , table ?  self.html( ) : undefi ned);
  5938                                      self.dom Manip( arg s, table,  callback ) ;
  5939                             });
  5940                    }
  5941  
  5942                    if (  this[0] )  {
  5943                             parent  = value & & value.pa rentNode;
  5944  
  5945                             // If  we're in a  fragment,  just use  that inste ad of buil ding a new  one
  5946                             if ( j Query.supp ort.parent Node && pa rent && pa rent.nodeT ype === 11  && parent .childNode s.length = == this.le ngth ) {
  5947                                      results  = { fragme nt: parent  };
  5948  
  5949                             } else  {
  5950                                      results  = jQuery.b uildFragme nt( args,  this, scri pts );
  5951                             }
  5952  
  5953                             fragme nt = resul ts.fragmen t;
  5954  
  5955                             if ( f ragment.ch ildNodes.l ength ===  1 ) {
  5956                                      first =  fragment =  fragment. firstChild ;
  5957                             } else  {
  5958                                      first =  fragment.f irstChild;
  5959                             }
  5960  
  5961                             if ( f irst ) {
  5962                                      table =  table && j Query.node Name( firs t, "tr" );
  5963  
  5964                                      for ( va r i = 0, l  = this.le ngth, last Index = l  - 1; i < l ; i++ ) {
  5965                                               callback.c all(
  5966                                                       ta ble ?
  5967                                                                root (this[i],  first) :
  5968                                                                this [i],
  5969                                                       //  Make sure  that we d o not leak  memory by  inadverte ntly disca rding
  5970                                                       //  the origi nal fragme nt (which  might have  attached  data) inst ead of
  5971                                                       //  using it;  in additi on, use th e original  fragment  object for  the last
  5972                                                       //  item inst ead of fir st because  it can en d up being  emptied i ncorrectly
  5973                                                       //  in certai n situatio ns (Bug #8 070).
  5974                                                       //  Fragments  from the  fragment c ache must  always be  cloned and  never use d
  5975                                                       //  in place.
  5976                                                       re sults.cach eable || (  l > 1 &&  i < lastIn dex ) ?
  5977                                                                jQue ry.clone(  fragment,  true, true  ) :
  5978                                                                frag ment
  5979                                               );
  5980                                      }
  5981                             }
  5982  
  5983                             if ( s cripts.len gth ) {
  5984                                      jQuery.e ach( scrip ts, evalSc ript );
  5985                             }
  5986                    }
  5987  
  5988                    retu rn this;
  5989           }
  5990   });
  5991  
  5992   function r oot( elem,  cur ) {
  5993           re turn jQuer y.nodeName (elem, "ta ble") ?
  5994                    (ele m.getEleme ntsByTagNa me("tbody" )[0] ||
  5995                    elem .appendChi ld(elem.ow nerDocumen t.createEl ement("tbo dy"))) :
  5996                    elem ;
  5997   }
  5998  
  5999   function c loneCopyEv ent( src,  dest ) {
  6000  
  6001           if  ( dest.no deType !==  1 || !jQu ery.hasDat a( src ) )  {
  6002                    retu rn;
  6003           }
  6004  
  6005           va r type, i,  l,
  6006                    oldD ata = jQue ry._data(  src ),
  6007                    curD ata = jQue ry._data(  dest, oldD ata ),
  6008                    even ts = oldDa ta.events;
  6009  
  6010           if  ( events  ) {
  6011                    dele te curData .handle;
  6012                    curD ata.events  = {};
  6013  
  6014                    for  ( type in  events ) {
  6015                             for (  i = 0, l =  events[ t ype ].leng th; i < l;  i++ ) {
  6016                                      jQuery.e vent.add(  dest, type  + ( event s[ type ][  i ].names pace ? "."  : "" ) +  events[ ty pe ][ i ]. namespace,  events[ t ype ][ i ] , events[  type ][ i  ].data );
  6017                             }
  6018                    }
  6019           }
  6020  
  6021           //  make the  cloned pub lic data o bject a co py from th e original
  6022           if  ( curData .data ) {
  6023                    curD ata.data =  jQuery.ex tend( {},  curData.da ta );
  6024           }
  6025   }
  6026  
  6027   function c loneFixAtt ributes( s rc, dest )  {
  6028           va r nodeName ;
  6029  
  6030           //  We do not  need to d o anything  for non-E lements
  6031           if  ( dest.no deType !==  1 ) {
  6032                    retu rn;
  6033           }
  6034  
  6035           //  clearAttr ibutes rem oves the a ttributes,  which we  don't want ,
  6036           //  but also  removes th e attachEv ent events , which we  *do* want
  6037           if  ( dest.cl earAttribu tes ) {
  6038                    dest .clearAttr ibutes();
  6039           }
  6040  
  6041           //  mergeAttr ibutes, in  contrast,  only merg es back on  the
  6042           //  original  attributes , not the  events
  6043           if  ( dest.me rgeAttribu tes ) {
  6044                    dest .mergeAttr ibutes( sr c );
  6045           }
  6046  
  6047           no deName = d est.nodeNa me.toLower Case();
  6048  
  6049           //  IE6-8 fai l to clone  children  inside obj ect elemen ts that us e
  6050           //  the propr ietary cla ssid attri bute value  (rather t han the ty pe
  6051           //  attribute ) to ident ify the ty pe of cont ent to dis play
  6052           if  ( nodeNam e === "obj ect" ) {
  6053                    dest .outerHTML  = src.out erHTML;
  6054  
  6055           }  else if (  nodeName = == "input"  && (src.t ype === "c heckbox" | | src.type  === "radi o") ) {
  6056                    // I E6-8 fails  to persis t the chec ked state  of a clone d checkbox
  6057                    // o r radio bu tton. Wors e, IE6-7 f ail to giv e the clon ed element
  6058                    // a  checked a ppearance  if the def aultChecke d value is n't also s et
  6059                    if (  src.check ed ) {
  6060                             dest.d efaultChec ked = dest .checked =  src.check ed;
  6061                    }
  6062  
  6063                    // I E6-7 get c onfused an d end up s etting the  value of  a cloned
  6064                    // c heckbox/ra dio button  to an emp ty string  instead of  "on"
  6065                    if (  dest.valu e !== src. value ) {
  6066                             dest.v alue = src .value;
  6067                    }
  6068  
  6069           //  IE6-8 fai ls to retu rn the sel ected opti on to the  default se lected
  6070           //  state whe n cloning  options
  6071           }  else if (  nodeName = == "option " ) {
  6072                    dest .selected  = src.defa ultSelecte d;
  6073  
  6074           //  IE6-8 fai ls to set  the defaul tValue to  the correc t value wh en
  6075           //  cloning o ther types  of input  fields
  6076           }  else if (  nodeName = == "input"  || nodeNa me === "te xtarea" )  {
  6077                    dest .defaultVa lue = src. defaultVal ue;
  6078           }
  6079  
  6080           //  Event dat a gets ref erenced in stead of c opied if t he expando
  6081           //  gets copi ed too
  6082           de st.removeA ttribute(  jQuery.exp ando );
  6083   }
  6084  
  6085   jQuery.bui ldFragment  = functio n( args, n odes, scri pts ) {
  6086           va r fragment , cacheabl e, cachere sults, doc ,
  6087           fi rst = args [ 0 ];
  6088  
  6089           //  nodes may  contain e ither an e xplicit do cument obj ect,
  6090           //  a jQuery  collection  or contex t object.
  6091           //  If nodes[ 0] contain s a valid  object to  assign to  doc
  6092           if  ( nodes & & nodes[0]  ) {
  6093                    doc  = nodes[0] .ownerDocu ment || no des[0];
  6094           }
  6095  
  6096           //  Ensure th at an attr  object do esn't inco rrectly st and in as  a document  object
  6097           //  Chrome an d Firefox  seem to al low this t o occur an d will thr ow excepti on
  6098           //  Fixes #89 50
  6099           if  ( !doc.cr eateDocume ntFragment  ) {
  6100                    doc  = document ;
  6101           }
  6102  
  6103           //  Only cach e "small"  (1/2 KB) H TML string s that are  associate d with the  main docu ment
  6104           //  Cloning o ptions los es the sel ected stat e, so don' t cache th em
  6105           //  IE 6 does n't like i t when you  put <obje ct> or <em bed> eleme nts in a f ragment
  6106           //  Also, Web Kit does n ot clone ' checked' a ttributes  on cloneNo de, so don 't cache
  6107           //  Lastly, I E6,7,8 wil l not corr ectly reus e cached f ragments t hat were c reated fro m unknown  elems #105 01
  6108           if  ( args.le ngth === 1  && typeof  first ===  "string"  && first.l ength < 51 2 && doc = == documen t &&
  6109                    firs t.charAt(0 ) === "<"  && !rnocac he.test( f irst ) &&
  6110                    (jQu ery.suppor t.checkClo ne || !rch ecked.test ( first ))  &&
  6111                    (jQu ery.suppor t.html5Clo ne || !rno shimcache. test( firs t )) ) {
  6112  
  6113                    cach eable = tr ue;
  6114  
  6115                    cach eresults =  jQuery.fr agments[ f irst ];
  6116                    if (  cacheresu lts && cac heresults  !== 1 ) {
  6117                             fragme nt = cache results;
  6118                    }
  6119           }
  6120  
  6121           if  ( !fragme nt ) {
  6122                    frag ment = doc .createDoc umentFragm ent();
  6123                    jQue ry.clean(  args, doc,  fragment,  scripts ) ;
  6124           }
  6125  
  6126           if  ( cacheab le ) {
  6127                    jQue ry.fragmen ts[ first  ] = cacher esults ? f ragment :  1;
  6128           }
  6129  
  6130           re turn { fra gment: fra gment, cac heable: ca cheable };
  6131   };
  6132  
  6133   jQuery.fra gments = { };
  6134  
  6135   jQuery.eac h({
  6136           ap pendTo: "a ppend",
  6137           pr ependTo: " prepend",
  6138           in sertBefore : "before" ,
  6139           in sertAfter:  "after",
  6140           re placeAll:  "replaceWi th"
  6141   }, functio n( name, o riginal )  {
  6142           jQ uery.fn[ n ame ] = fu nction( se lector ) {
  6143                    var  ret = [],
  6144                             insert  = jQuery(  selector  ),
  6145                             parent  = this.le ngth === 1  && this[0 ].parentNo de;
  6146  
  6147                    if (  parent &&  parent.no deType ===  11 && par ent.childN odes.lengt h === 1 &&  insert.le ngth === 1  ) {
  6148                             insert [ original  ]( this[0 ] );
  6149                             return  this;
  6150  
  6151                    } el se {
  6152                             for (  var i = 0,  l = inser t.length;  i < l; i++  ) {
  6153                                      var elem s = ( i >  0 ? this.c lone(true)  : this ). get();
  6154                                      jQuery(  insert[i]  )[ origina l ]( elems  );
  6155                                      ret = re t.concat(  elems );
  6156                             }
  6157  
  6158                             return  this.push Stack( ret , name, in sert.selec tor );
  6159                    }
  6160           };
  6161   });
  6162  
  6163   function g etAll( ele m ) {
  6164           if  ( typeof  elem.getEl ementsByTa gName !==  "undefined " ) {
  6165                    retu rn elem.ge tElementsB yTagName(  "*" );
  6166  
  6167           }  else if (  typeof ele m.querySel ectorAll ! == "undefi ned" ) {
  6168                    retu rn elem.qu erySelecto rAll( "*"  );
  6169  
  6170           }  else {
  6171                    retu rn [];
  6172           }
  6173   }
  6174  
  6175   // Used in  clean, fi xes the de faultCheck ed propert y
  6176   function f ixDefaultC hecked( el em ) {
  6177           if  ( elem.ty pe === "ch eckbox" ||  elem.type  === "radi o" ) {
  6178                    elem .defaultCh ecked = el em.checked ;
  6179           }
  6180   }
  6181   // Finds a ll inputs  and passes  them to f ixDefaultC hecked
  6182   function f indInputs(  elem ) {
  6183           va r nodeName  = ( elem. nodeName | | "" ).toL owerCase() ;
  6184           if  ( nodeNam e === "inp ut" ) {
  6185                    fixD efaultChec ked( elem  );
  6186           //  Skip scri pts, get o ther child ren
  6187           }  else if (  nodeName ! == "script " && typeo f elem.get ElementsBy TagName != = "undefin ed" ) {
  6188                    jQue ry.grep( e lem.getEle mentsByTag Name("inpu t"), fixDe faultCheck ed );
  6189           }
  6190   }
  6191  
  6192   // Derived  From: htt p://www.ie css.com/sh improve/ja vascript/s himprove.1 -0-1.js
  6193   function s himCloneNo de( elem )  {
  6194           va r div = do cument.cre ateElement ( "div" );
  6195           sa feFragment .appendChi ld( div );
  6196  
  6197           di v.innerHTM L = elem.o uterHTML;
  6198           re turn div.f irstChild;
  6199   }
  6200  
  6201   jQuery.ext end({
  6202           cl one: funct ion( elem,  dataAndEv ents, deep DataAndEve nts ) {
  6203                    var  srcElement s,
  6204                             destEl ements,
  6205                             i,
  6206                             // IE< =8 does no t properly  clone det ached, unk nown eleme nt nodes
  6207                             clone  = jQuery.s upport.htm l5Clone ||  !rnoshimc ache.test(  "<" + ele m.nodeName  ) ?
  6208                                      elem.clo neNode( tr ue ) :
  6209                                      shimClon eNode( ele m );
  6210  
  6211                    if (  (!jQuery. support.no CloneEvent  || !jQuer y.support. noCloneChe cked) &&
  6212                                      (elem.no deType ===  1 || elem .nodeType  === 11) &&  !jQuery.i sXMLDoc(el em) ) {
  6213                             // IE  copies eve nts bound  via attach Event when  using clo neNode.
  6214                             // Cal ling detac hEvent on  the clone  will also  remove the  events
  6215                             // fro m the orig inal. In o rder to ge t around t his, we us e some
  6216                             // pro prietary m ethods to  clear the  events. Th anks to Mo oTools
  6217                             // guy s for this  hotness.
  6218  
  6219                             cloneF ixAttribut es( elem,  clone );
  6220  
  6221                             // Usi ng Sizzle  here is cr azy slow,  so we use  getElement sByTagName  instead
  6222                             srcEle ments = ge tAll( elem  );
  6223                             destEl ements = g etAll( clo ne );
  6224  
  6225                             // Wei rd iterati on because  IE will r eplace the  length pr operty
  6226                             // wit h an eleme nt if you  are clonin g the body  and one o f the
  6227                             // ele ments on t he page ha s a name o r id of "l ength"
  6228                             for (  i = 0; src Elements[i ]; ++i ) {
  6229                                      // Ensur e that the  destinati on node is  not null;  Fixes #95 87
  6230                                      if ( des tElements[ i] ) {
  6231                                               cloneFixAt tributes(  srcElement s[i], dest Elements[i ] );
  6232                                      }
  6233                             }
  6234                    }
  6235  
  6236                    // C opy the ev ents from  the origin al to the  clone
  6237                    if (  dataAndEv ents ) {
  6238                             cloneC opyEvent(  elem, clon e );
  6239  
  6240                             if ( d eepDataAnd Events ) {
  6241                                      srcEleme nts = getA ll( elem ) ;
  6242                                      destElem ents = get All( clone  );
  6243  
  6244                                      for ( i  = 0; srcEl ements[i];  ++i ) {
  6245                                               cloneCopyE vent( srcE lements[i] , destElem ents[i] );
  6246                                      }
  6247                             }
  6248                    }
  6249  
  6250                    srcE lements =  destElemen ts = null;
  6251  
  6252                    // R eturn the  cloned set
  6253                    retu rn clone;
  6254           },
  6255  
  6256           cl ean: funct ion( elems , context,  fragment,  scripts )  {
  6257                    var  checkScrip tType;
  6258  
  6259                    cont ext = cont ext || doc ument;
  6260  
  6261                    // ! context.cr eateElemen t fails in  IE with a n error bu t returns  typeof 'ob ject'
  6262                    if (  typeof co ntext.crea teElement  === "undef ined" ) {
  6263                             contex t = contex t.ownerDoc ument || c ontext[0]  && context [0].ownerD ocument ||  document;
  6264                    }
  6265  
  6266                    var  ret = [],  j;
  6267  
  6268                    for  ( var i =  0, elem; ( elem = ele ms[i]) !=  null; i++  ) {
  6269                             if ( t ypeof elem  === "numb er" ) {
  6270                                      elem +=  "";
  6271                             }
  6272  
  6273                             if ( ! elem ) {
  6274                                      continue ;
  6275                             }
  6276  
  6277                             // Con vert html  string int o DOM node s
  6278                             if ( t ypeof elem  === "stri ng" ) {
  6279                                      if ( !rh tml.test(  elem ) ) {
  6280                                               elem = con text.creat eTextNode(  elem );
  6281                                      } else {
  6282                                               // Fix "XH TML"-style  tags in a ll browser s
  6283                                               elem = ele m.replace( rxhtmlTag,  "<$1></$2 >");
  6284  
  6285                                               // Trim wh itespace,  otherwise  indexOf wo n't work a s expected
  6286                                               var tag =  ( rtagName .exec( ele m ) || ["" , ""] )[1] .toLowerCa se(),
  6287                                                       wr ap = wrapM ap[ tag ]  || wrapMap ._default,
  6288                                                       de pth = wrap [0],
  6289                                                       di v = contex t.createEl ement("div ");
  6290  
  6291                                               // Append  wrapper el ement to u nknown ele ment safe  doc fragme nt
  6292                                               if ( conte xt === doc ument ) {
  6293                                                       //  Use the f ragment we 've alread y created  for this d ocument
  6294                                                       sa feFragment .appendChi ld( div );
  6295                                               } else {
  6296                                                       //  Use a fra gment crea ted with t he owner d ocument
  6297                                                       cr eateSafeFr agment( co ntext ).ap pendChild(  div );
  6298                                               }
  6299  
  6300                                               // Go to h tml and ba ck, then p eel off ex tra wrappe rs
  6301                                               div.innerH TML = wrap [1] + elem  + wrap[2] ;
  6302  
  6303                                               // Move to  the right  depth
  6304                                               while ( de pth-- ) {
  6305                                                       di v = div.la stChild;
  6306                                               }
  6307  
  6308                                               // Remove  IE's autoi nserted <t body> from  table fra gments
  6309                                               if ( !jQue ry.support .tbody ) {
  6310  
  6311                                                       //  String wa s a <table >, *may* h ave spurio us <tbody>
  6312                                                       va r hasBody  = rtbody.t est(elem),
  6313                                                                tbod y = tag == = "table"  && !hasBod y ?
  6314                                                                         div.fi rstChild & & div.firs tChild.chi ldNodes :
  6315  
  6316                                                                         // Str ing was a  bare <thea d> or <tfo ot>
  6317                                                                         wrap[1 ] === "<ta ble>" && ! hasBody ?
  6318                                                                                  div.chil dNodes :
  6319                                                                                  [];
  6320  
  6321                                                       fo r ( j = tb ody.length  - 1; j >=  0 ; --j )  {
  6322                                                                if (  jQuery.no deName( tb ody[ j ],  "tbody" )  && !tbody[  j ].child Nodes.leng th ) {
  6323                                                                         tbody[  j ].paren tNode.remo veChild( t body[ j ]  );
  6324                                                                }
  6325                                                       }
  6326                                               }
  6327  
  6328                                               // IE comp letely kil ls leading  whitespac e when inn erHTML is  used
  6329                                               if ( !jQue ry.support .leadingWh itespace & & rleading Whitespace .test( ele m ) ) {
  6330                                                       di v.insertBe fore( cont ext.create TextNode(  rleadingWh itespace.e xec(elem)[ 0] ), div. firstChild  );
  6331                                               }
  6332  
  6333                                               elem = div .childNode s;
  6334                                      }
  6335                             }
  6336  
  6337                             // Res ets defaul tChecked f or any rad ios and ch eckboxes
  6338                             // abo ut to be a ppended to  the DOM i n IE 6/7 ( #8060)
  6339                             var le n;
  6340                             if ( ! jQuery.sup port.appen dChecked )  {
  6341                                      if ( ele m[0] && ty peof (len  = elem.len gth) === " number" )  {
  6342                                               for ( j =  0; j < len ; j++ ) {
  6343                                                       fi ndInputs(  elem[j] );
  6344                                               }
  6345                                      } else {
  6346                                               findInputs ( elem );
  6347                                      }
  6348                             }
  6349  
  6350                             if ( e lem.nodeTy pe ) {
  6351                                      ret.push ( elem );
  6352                             } else  {
  6353                                      ret = jQ uery.merge ( ret, ele m );
  6354                             }
  6355                    }
  6356  
  6357                    if (  fragment  ) {
  6358                             checkS criptType  = function ( elem ) {
  6359                                      return ! elem.type  || rscript Type.test(  elem.type  );
  6360                             };
  6361                             for (  i = 0; ret [i]; i++ )  {
  6362                                      if ( scr ipts && jQ uery.nodeN ame( ret[i ], "script " ) && (!r et[i].type  || ret[i] .type.toLo werCase()  === "text/ javascript ") ) {
  6363                                               scripts.pu sh( ret[i] .parentNod e ? ret[i] .parentNod e.removeCh ild( ret[i ] ) : ret[ i] );
  6364  
  6365                                      } else {
  6366                                               if ( ret[i ].nodeType  === 1 ) {
  6367                                                       va r jsTags =  jQuery.gr ep( ret[i] .getElemen tsByTagNam e( "script " ), check ScriptType  );
  6368  
  6369                                                       re t.splice.a pply( ret,  [i + 1, 0 ].concat(  jsTags ) ) ;
  6370                                               }
  6371                                               fragment.a ppendChild ( ret[i] ) ;
  6372                                      }
  6373                             }
  6374                    }
  6375  
  6376                    retu rn ret;
  6377           },
  6378  
  6379           cl eanData: f unction( e lems ) {
  6380                    var  data, id,
  6381                             cache  = jQuery.c ache,
  6382                             specia l = jQuery .event.spe cial,
  6383                             delete Expando =  jQuery.sup port.delet eExpando;
  6384  
  6385                    for  ( var i =  0, elem; ( elem = ele ms[i]) !=  null; i++  ) {
  6386                             if ( e lem.nodeNa me && jQue ry.noData[ elem.nodeN ame.toLowe rCase()] )  {
  6387                                      continue ;
  6388                             }
  6389  
  6390                             id = e lem[ jQuer y.expando  ];
  6391  
  6392                             if ( i d ) {
  6393                                      data = c ache[ id ] ;
  6394  
  6395                                      if ( dat a && data. events ) {
  6396                                               for ( var  type in da ta.events  ) {
  6397                                                       if  ( special [ type ] )  {
  6398                                                                jQue ry.event.r emove( ele m, type );
  6399  
  6400                                                       //  This is a  shortcut  to avoid j Query.even t.remove's  overhead
  6401                                                       }  else {
  6402                                                                jQue ry.removeE vent( elem , type, da ta.handle  );
  6403                                                       }
  6404                                               }
  6405  
  6406                                               // Null th e DOM refe rence to a void IE6/7 /8 leak (# 7054)
  6407                                               if ( data. handle ) {
  6408                                                       da ta.handle. elem = nul l;
  6409                                               }
  6410                                      }
  6411  
  6412                                      if ( del eteExpando  ) {
  6413                                               delete ele m[ jQuery. expando ];
  6414  
  6415                                      } else i f ( elem.r emoveAttri bute ) {
  6416                                               elem.remov eAttribute ( jQuery.e xpando );
  6417                                      }
  6418  
  6419                                      delete c ache[ id ] ;
  6420                             }
  6421                    }
  6422           }
  6423   });
  6424  
  6425   function e valScript(  i, elem )  {
  6426           if  ( elem.sr c ) {
  6427                    jQue ry.ajax({
  6428                             url: e lem.src,
  6429                             async:  false,
  6430                             dataTy pe: "scrip t"
  6431                    });
  6432           }  else {
  6433                    jQue ry.globalE val( ( ele m.text ||  elem.textC ontent ||  elem.inner HTML || ""  ).replace ( rcleanSc ript, "/*$ 0*/" ) );
  6434           }
  6435  
  6436           if  ( elem.pa rentNode )  {
  6437                    elem .parentNod e.removeCh ild( elem  );
  6438           }
  6439   }
  6440  
  6441  
  6442  
  6443  
  6444   var ralpha  = /alpha\ ([^)]*\)/i ,
  6445           ro pacity = / opacity=([ ^)]*)/,
  6446           //  fixed for  IE9, see  #8346
  6447           ru pper = /([ A-Z]|^ms)/ g,
  6448           rn umpx = /^- ?\d+(?:px) ?$/i,
  6449           rn um = /^-?\ d/,
  6450           rr elNum = /^ ([\-+])=([ \-+.\de]+) /,
  6451  
  6452           cs sShow = {  position:  "absolute" , visibili ty: "hidde n", displa y: "block"  },
  6453           cs sWidth = [  "Left", " Right" ],
  6454           cs sHeight =  [ "Top", " Bottom" ],
  6455           cu rCSS,
  6456  
  6457           ge tComputedS tyle,
  6458           cu rrentStyle ;
  6459  
  6460   jQuery.fn. css = func tion( name , value )  {
  6461           //  Setting ' undefined'  is a no-o p
  6462           if  ( argumen ts.length  === 2 && v alue === u ndefined )  {
  6463                    retu rn this;
  6464           }
  6465  
  6466           re turn jQuer y.access(  this, name , value, t rue, funct ion( elem,  name, val ue ) {
  6467                    retu rn value ! == undefin ed ?
  6468                             jQuery .style( el em, name,  value ) :
  6469                             jQuery .css( elem , name );
  6470           }) ;
  6471   };
  6472  
  6473   jQuery.ext end({
  6474           //  Add in st yle proper ty hooks f or overrid ing the de fault
  6475           //  behavior  of getting  and setti ng a style  property
  6476           cs sHooks: {
  6477                    opac ity: {
  6478                             get: f unction( e lem, compu ted ) {
  6479                                      if ( com puted ) {
  6480                                               // We shou ld always  get a numb er back fr om opacity
  6481                                               var ret =  curCSS( el em, "opaci ty", "opac ity" );
  6482                                               return ret  === "" ?  "1" : ret;
  6483  
  6484                                      } else {
  6485                                               return ele m.style.op acity;
  6486                                      }
  6487                             }
  6488                    }
  6489           },
  6490  
  6491           //  Exclude t he followi ng css pro perties to  add px
  6492           cs sNumber: {
  6493                    "fil lOpacity":  true,
  6494                    "fon tWeight":  true,
  6495                    "lin eHeight":  true,
  6496                    "opa city": tru e,
  6497                    "orp hans": tru e,
  6498                    "wid ows": true ,
  6499                    "zIn dex": true ,
  6500                    "zoo m": true
  6501           },
  6502  
  6503           //  Add in pr operties w hose names  you wish  to fix bef ore
  6504           //  setting o r getting  the value
  6505           cs sProps: {
  6506                    // n ormalize f loat css p roperty
  6507                    "flo at": jQuer y.support. cssFloat ?  "cssFloat " : "style Float"
  6508           },
  6509  
  6510           //  Get and s et the sty le propert y on a DOM  Node
  6511           st yle: funct ion( elem,  name, val ue, extra  ) {
  6512                    // D on't set s tyles on t ext and co mment node s
  6513                    if (  !elem ||  elem.nodeT ype === 3  || elem.no deType ===  8 || !ele m.style )  {
  6514                             return ;
  6515                    }
  6516  
  6517                    // M ake sure t hat we're  working wi th the rig ht name
  6518                    var  ret, type,  origName  = jQuery.c amelCase(  name ),
  6519                             style  = elem.sty le, hooks  = jQuery.c ssHooks[ o rigName ];
  6520  
  6521                    name  = jQuery. cssProps[  origName ]  || origNa me;
  6522  
  6523                    // C heck if we 're settin g a value
  6524                    if (  value !==  undefined  ) {
  6525                             type =  typeof va lue;
  6526  
  6527                             // con vert relat ive number  strings ( += or -=)  to relativ e numbers.  #7345
  6528                             if ( t ype === "s tring" &&  (ret = rre lNum.exec(  value ))  ) {
  6529                                      value =  ( +( ret[1 ] + 1) * + ret[2] ) +  parseFloa t( jQuery. css( elem,  name ) );
  6530                                      // Fixes  bug #9237
  6531                                      type = " number";
  6532                             }
  6533  
  6534                             // Mak e sure tha t NaN and  null value s aren't s et. See: # 7116
  6535                             if ( v alue == nu ll || type  === "numb er" && isN aN( value  ) ) {
  6536                                      return;
  6537                             }
  6538  
  6539                             // If  a number w as passed  in, add 'p x' to the  (except fo r certain  CSS proper ties)
  6540                             if ( t ype === "n umber" &&  !jQuery.cs sNumber[ o rigName ]  ) {
  6541                                      value +=  "px";
  6542                             }
  6543  
  6544                             // If  a hook was  provided,  use that  value, oth erwise jus t set the  specified  value
  6545                             if ( ! hooks || ! ("set" in  hooks) ||  (value = h ooks.set(  elem, valu e )) !== u ndefined )  {
  6546                                      // Wrapp ed to prev ent IE fro m throwing  errors wh en 'invali d' values  are provid ed
  6547                                      // Fixes  bug #5509
  6548                                      try {
  6549                                               style[ nam e ] = valu e;
  6550                                      } catch( e) {}
  6551                             }
  6552  
  6553                    } el se {
  6554                             // If  a hook was  provided  get the no n-computed  value fro m there
  6555                             if ( h ooks && "g et" in hoo ks && (ret  = hooks.g et( elem,  false, ext ra )) !==  undefined  ) {
  6556                                      return r et;
  6557                             }
  6558  
  6559                             // Oth erwise jus t get the  value from  the style  object
  6560                             return  style[ na me ];
  6561                    }
  6562           },
  6563  
  6564           cs s: functio n( elem, n ame, extra  ) {
  6565                    var  ret, hooks ;
  6566  
  6567                    // M ake sure t hat we're  working wi th the rig ht name
  6568                    name  = jQuery. camelCase(  name );
  6569                    hook s = jQuery .cssHooks[  name ];
  6570                    name  = jQuery. cssProps[  name ] ||  name;
  6571  
  6572                    // c ssFloat ne eds a spec ial treatm ent
  6573                    if (  name ===  "cssFloat"  ) {
  6574                             name =  "float";
  6575                    }
  6576  
  6577                    // I f a hook w as provide d get the  computed v alue from  there
  6578                    if (  hooks &&  "get" in h ooks && (r et = hooks .get( elem , true, ex tra )) !==  undefined  ) {
  6579                             return  ret;
  6580  
  6581                    // O therwise,  if a way t o get the  computed v alue exist s, use tha t
  6582                    } el se if ( cu rCSS ) {
  6583                             return  curCSS( e lem, name  );
  6584                    }
  6585           },
  6586  
  6587           //  A method  for quickl y swapping  in/out CS S properti es to get  correct ca lculations
  6588           sw ap: functi on( elem,  options, c allback )  {
  6589                    var  old = {};
  6590  
  6591                    // R emember th e old valu es, and in sert the n ew ones
  6592                    for  ( var name  in option s ) {
  6593                             old[ n ame ] = el em.style[  name ];
  6594                             elem.s tyle[ name  ] = optio ns[ name ] ;
  6595                    }
  6596  
  6597                    call back.call(  elem );
  6598  
  6599                    // R evert the  old values
  6600                    for  ( name in  options )  {
  6601                             elem.s tyle[ name  ] = old[  name ];
  6602                    }
  6603           }
  6604   });
  6605  
  6606   // DEPRECA TED, Use j Query.css( ) instead
  6607   jQuery.cur CSS = jQue ry.css;
  6608  
  6609   jQuery.eac h(["height ", "width" ], functio n( i, name  ) {
  6610           jQ uery.cssHo oks[ name  ] = {
  6611                    get:  function(  elem, com puted, ext ra ) {
  6612                             var va l;
  6613  
  6614                             if ( c omputed )  {
  6615                                      if ( ele m.offsetWi dth !== 0  ) {
  6616                                               return get WH( elem,  name, extr a );
  6617                                      } else {
  6618                                               jQuery.swa p( elem, c ssShow, fu nction() {
  6619                                                       va l = getWH(  elem, nam e, extra ) ;
  6620                                               });
  6621                                      }
  6622  
  6623                                      return v al;
  6624                             }
  6625                    },
  6626  
  6627                    set:  function(  elem, val ue ) {
  6628                             if ( r numpx.test ( value )  ) {
  6629                                      // ignor e negative  width and  height va lues #1599
  6630                                      value =  parseFloat ( value );
  6631  
  6632                                      if ( val ue >= 0 )  {
  6633                                               return val ue + "px";
  6634                                      }
  6635  
  6636                             } else  {
  6637                                      return v alue;
  6638                             }
  6639                    }
  6640           };
  6641   });
  6642  
  6643   if ( !jQue ry.support .opacity )  {
  6644           jQ uery.cssHo oks.opacit y = {
  6645                    get:  function(  elem, com puted ) {
  6646                             // IE  uses filte rs for opa city
  6647                             return  ropacity. test( (com puted && e lem.curren tStyle ? e lem.curren tStyle.fil ter : elem .style.fil ter) || ""  ) ?
  6648                                      ( parseF loat( RegE xp.$1 ) /  100 ) + ""  :
  6649                                      computed  ? "1" : " ";
  6650                    },
  6651  
  6652                    set:  function(  elem, val ue ) {
  6653                             var st yle = elem .style,
  6654                                      currentS tyle = ele m.currentS tyle,
  6655                                      opacity  = jQuery.i sNumeric(  value ) ?  "alpha(opa city=" + v alue * 100  + ")" : " ",
  6656                                      filter =  currentSt yle && cur rentStyle. filter ||  style.filt er || "";
  6657  
  6658                             // IE  has troubl e with opa city if it  does not  have layou t
  6659                             // For ce it by s etting the  zoom leve l
  6660                             style. zoom = 1;
  6661  
  6662                             // if  setting op acity to 1 , and no o ther filte rs exist -  attempt t o remove f ilter attr ibute #665 2
  6663                             if ( v alue >= 1  && jQuery. trim( filt er.replace ( ralpha,  "" ) ) ===  "" ) {
  6664  
  6665                                      // Setti ng style.f ilter to n ull, "" &  " " still  leave "fil ter:" in t he cssText
  6666                                      // if "f ilter:" is  present a t all, cle arType is  disabled,  we want to  avoid thi s
  6667                                      // style .removeAtt ribute is  IE Only, b ut so appa rently is  this code  path...
  6668                                      style.re moveAttrib ute( "filt er" );
  6669  
  6670                                      // if th ere there  is no filt er style a pplied in  a css rule , we are d one
  6671                                      if ( cur rentStyle  && !curren tStyle.fil ter ) {
  6672                                               return;
  6673                                      }
  6674                             }
  6675  
  6676                             // oth erwise, se t new filt er values
  6677                             style. filter = r alpha.test ( filter )  ?
  6678                                      filter.r eplace( ra lpha, opac ity ) :
  6679                                      filter +  " " + opa city;
  6680                    }
  6681           };
  6682   }
  6683  
  6684   jQuery(fun ction() {
  6685           //  This hook  cannot be  added unt il DOM rea dy because  the suppo rt test
  6686           //  for it is  not run u ntil after  DOM ready
  6687           if  ( !jQuery .support.r eliableMar ginRight )  {
  6688                    jQue ry.cssHook s.marginRi ght = {
  6689                             get: f unction( e lem, compu ted ) {
  6690                                      // WebKi t Bug 1334 3 - getCom putedStyle  returns w rong value  for margi n-right
  6691                                      // Work  around by  temporaril y setting  element di splay to i nline-bloc k
  6692                                      var ret;
  6693                                      jQuery.s wap( elem,  { "displa y": "inlin e-block" } , function () {
  6694                                               if ( compu ted ) {
  6695                                                       re t = curCSS ( elem, "m argin-righ t", "margi nRight" );
  6696                                               } else {
  6697                                                       re t = elem.s tyle.margi nRight;
  6698                                               }
  6699                                      });
  6700                                      return r et;
  6701                             }
  6702                    };
  6703           }
  6704   });
  6705  
  6706   if ( docum ent.defaul tView && d ocument.de faultView. getCompute dStyle ) {
  6707           ge tComputedS tyle = fun ction( ele m, name )  {
  6708                    var  ret, defau ltView, co mputedStyl e;
  6709  
  6710                    name  = name.re place( rup per, "-$1"  ).toLower Case();
  6711  
  6712                    if (  (defaultV iew = elem .ownerDocu ment.defau ltView) &&
  6713                                      (compute dStyle = d efaultView .getComput edStyle( e lem, null  )) ) {
  6714                             ret =  computedSt yle.getPro pertyValue ( name );
  6715                             if ( r et === ""  && !jQuery .contains(  elem.owne rDocument. documentEl ement, ele m ) ) {
  6716                                      ret = jQ uery.style ( elem, na me );
  6717                             }
  6718                    }
  6719  
  6720                    retu rn ret;
  6721           };
  6722   }
  6723  
  6724   if ( docum ent.docume ntElement. currentSty le ) {
  6725           cu rrentStyle  = functio n( elem, n ame ) {
  6726                    var  left, rsLe ft, uncomp uted,
  6727                             ret =  elem.curre ntStyle &&  elem.curr entStyle[  name ],
  6728                             style  = elem.sty le;
  6729  
  6730                    // A void setti ng ret to  empty stri ng here
  6731                    // s o we don't  default t o auto
  6732                    if (  ret === n ull && sty le && (unc omputed =  style[ nam e ]) ) {
  6733                             ret =  uncomputed ;
  6734                    }
  6735  
  6736                    // F rom the aw esome hack  by Dean E dwards
  6737                    // h ttp://erik .eae.net/a rchives/20 07/07/27/1 8.54.15/#c omment-102 291
  6738  
  6739                    // I f we're no t dealing  with a reg ular pixel  number
  6740                    // b ut a numbe r that has  a weird e nding, we  need to co nvert it t o pixels
  6741                    if (  !rnumpx.t est( ret )  && rnum.t est( ret )  ) {
  6742  
  6743                             // Rem ember the  original v alues
  6744                             left =  style.lef t;
  6745                             rsLeft  = elem.ru ntimeStyle  && elem.r untimeStyl e.left;
  6746  
  6747                             // Put  in the ne w values t o get a co mputed val ue out
  6748                             if ( r sLeft ) {
  6749                                      elem.run timeStyle. left = ele m.currentS tyle.left;
  6750                             }
  6751                             style. left = nam e === "fon tSize" ? " 1em" : ( r et || 0 );
  6752                             ret =  style.pixe lLeft + "p x";
  6753  
  6754                             // Rev ert the ch anged valu es
  6755                             style. left = lef t;
  6756                             if ( r sLeft ) {
  6757                                      elem.run timeStyle. left = rsL eft;
  6758                             }
  6759                    }
  6760  
  6761                    retu rn ret ===  "" ? "aut o" : ret;
  6762           };
  6763   }
  6764  
  6765   curCSS = g etComputed Style || c urrentStyl e;
  6766  
  6767   function g etWH( elem , name, ex tra ) {
  6768  
  6769           //  Start wit h offset p roperty
  6770           va r val = na me === "wi dth" ? ele m.offsetWi dth : elem .offsetHei ght,
  6771                    whic h = name = == "width"  ? cssWidt h : cssHei ght,
  6772                    i =  0,
  6773                    len  = which.le ngth;
  6774  
  6775           if  ( val > 0  ) {
  6776                    if (  extra !==  "border"  ) {
  6777                             for (  ; i < len;  i++ ) {
  6778                                      if ( !ex tra ) {
  6779                                               val -= par seFloat( j Query.css(  elem, "pa dding" + w hich[ i ]  ) ) || 0;
  6780                                      }
  6781                                      if ( ext ra === "ma rgin" ) {
  6782                                               val += par seFloat( j Query.css(  elem, ext ra + which [ i ] ) )  || 0;
  6783                                      } else {
  6784                                               val -= par seFloat( j Query.css(  elem, "bo rder" + wh ich[ i ] +  "Width" )  ) || 0;
  6785                                      }
  6786                             }
  6787                    }
  6788  
  6789                    retu rn val + " px";
  6790           }
  6791  
  6792           //  Fall back  to comput ed then un computed c ss if nece ssary
  6793           va l = curCSS ( elem, na me, name ) ;
  6794           if  ( val < 0  || val ==  null ) {
  6795                    val  = elem.sty le[ name ]  || 0;
  6796           }
  6797           //  Normalize  "", auto,  and prepa re for ext ra
  6798           va l = parseF loat( val  ) || 0;
  6799  
  6800           //  Add paddi ng, border , margin
  6801           if  ( extra )  {
  6802                    for  ( ; i < le n; i++ ) {
  6803                             val +=  parseFloa t( jQuery. css( elem,  "padding"  + which[  i ] ) ) ||  0;
  6804                             if ( e xtra !== " padding" )  {
  6805                                      val += p arseFloat(  jQuery.cs s( elem, " border" +  which[ i ]  + "Width"  ) ) || 0;
  6806                             }
  6807                             if ( e xtra === " margin" )  {
  6808                                      val += p arseFloat(  jQuery.cs s( elem, e xtra + whi ch[ i ] )  ) || 0;
  6809                             }
  6810                    }
  6811           }
  6812  
  6813           re turn val +  "px";
  6814   }
  6815  
  6816   if ( jQuer y.expr &&  jQuery.exp r.filters  ) {
  6817           jQ uery.expr. filters.hi dden = fun ction( ele m ) {
  6818                    var  width = el em.offsetW idth,
  6819                             height  = elem.of fsetHeight ;
  6820  
  6821                    retu rn ( width  === 0 &&  height ===  0 ) || (! jQuery.sup port.relia bleHiddenO ffsets &&  ((elem.sty le && elem .style.dis play) || j Query.css(  elem, "di splay" ))  === "none" );
  6822           };
  6823  
  6824           jQ uery.expr. filters.vi sible = fu nction( el em ) {
  6825                    retu rn !jQuery .expr.filt ers.hidden ( elem );
  6826           };
  6827   }
  6828  
  6829  
  6830  
  6831  
  6832   var r20 =  /%20/g,
  6833           rb racket = / \[\]$/,
  6834           rC RLF = /\r? \n/g,
  6835           rh ash = /#.* $/,
  6836           rh eaders = / ^(.*?):[ \ t]*([^\r\n ]*)\r?$/mg , // IE le aves an \r  character  at EOL
  6837           ri nput = /^( ?:color|da te|datetim e|datetime -local|ema il|hidden| month|numb er|passwor d|range|se arch|tel|t ext|time|u rl|week)$/ i,
  6838           //  #7653, #8 125, #8152 : local pr otocol det ection
  6839           rl ocalProtoc ol = /^(?: about|app| app\-stora ge|.+\-ext ension|fil e|res|widg et):$/,
  6840           rn oContent =  /^(?:GET| HEAD)$/,
  6841           rp rotocol =  /^\/\//,
  6842           rq uery = /\? /,
  6843           rs cript = /< script\b[^ <]*(?:(?!< \/script>) <[^<]*)*<\ /script>/g i,
  6844           rs electTexta rea = /^(? :select|te xtarea)/i,
  6845           rs pacesAjax  = /\s+/,
  6846           rt s = /([?&] )_=[^&]*/,
  6847           ru rl = /^([\ w\+\.\-]+: )(?:\/\/([ ^\/?#:]*)( ?::(\d+))? )?/,
  6848  
  6849           //  Keep a co py of the  old load m ethod
  6850           _l oad = jQue ry.fn.load ,
  6851  
  6852           /*  Prefilter s
  6853            *  1) They a re useful  to introdu ce custom  dataTypes  (see ajax/ jsonp.js f or an exam ple)
  6854            *  2) These  are called :
  6855            *     - BEFO RE asking  for a tran sport
  6856            *     - AFTE R param se rializatio n (s.data  is a strin g if s.pro cessData i s true)
  6857            *  3) key is  the dataT ype
  6858            *  4) the ca tchall sym bol "*" ca n be used
  6859            *  5) execut ion will s tart with  transport  dataType a nd THEN co ntinue dow n to "*" i f needed
  6860            * /
  6861           pr efilters =  {},
  6862  
  6863           /*  Transport s bindings
  6864            *  1) key is  the dataT ype
  6865            *  2) the ca tchall sym bol "*" ca n be used
  6866            *  3) select ion will s tart with  transport  dataType a nd THEN go  to "*" if  needed
  6867            * /
  6868           tr ansports =  {},
  6869  
  6870           //  Document  location
  6871           aj axLocation ,
  6872  
  6873           //  Document  location s egments
  6874           aj axLocParts ,
  6875  
  6876           //  Avoid com ment-prolo g char seq uence (#10 098); must  appease l int and ev ade compre ssion
  6877           al lTypes = [ "*/"] + [" *"];
  6878  
  6879   // #8138,  IE may thr ow an exce ption when  accessing
  6880   // a field  from wind ow.locatio n if docum ent.domain  has been  set
  6881   try {
  6882           aj axLocation  = locatio n.href;
  6883   } catch( e  ) {
  6884           //  Use the h ref attrib ute of an  A element
  6885           //  since IE  will modif y it given  document. location
  6886           aj axLocation  = documen t.createEl ement( "a"  );
  6887           aj axLocation .href = "" ;
  6888           aj axLocation  = ajaxLoc ation.href ;
  6889   }
  6890  
  6891   // Segment  location  into parts
  6892   ajaxLocPar ts = rurl. exec( ajax Location.t oLowerCase () ) || [] ;
  6893  
  6894   // Base "c onstructor " for jQue ry.ajaxPre filter and  jQuery.aj axTranspor t
  6895   function a ddToPrefil tersOrTran sports( st ructure )  {
  6896  
  6897           //  dataTypeE xpression  is optiona l and defa ults to "* "
  6898           re turn funct ion( dataT ypeExpress ion, func  ) {
  6899  
  6900                    if (  typeof da taTypeExpr ession !==  "string"  ) {
  6901                             func =  dataTypeE xpression;
  6902                             dataTy peExpressi on = "*";
  6903                    }
  6904  
  6905                    if (  jQuery.is Function(  func ) ) {
  6906                             var da taTypes =  dataTypeEx pression.t oLowerCase ().split(  rspacesAja x ),
  6907                                      i = 0,
  6908                                      length =  dataTypes .length,
  6909                                      dataType ,
  6910                                      list,
  6911                                      placeBef ore;
  6912  
  6913                             // For  each data Type in th e dataType Expression
  6914                             for (  ; i < leng th; i++ )  {
  6915                                      dataType  = dataTyp es[ i ];
  6916                                      // We co ntrol if w e're asked  to add be fore
  6917                                      // any e xisting el ement
  6918                                      placeBef ore = /^\+ /.test( da taType );
  6919                                      if ( pla ceBefore )  {
  6920                                               dataType =  dataType. substr( 1  ) || "*";
  6921                                      }
  6922                                      list = s tructure[  dataType ]  = structu re[ dataTy pe ] || [] ;
  6923                                      // then  we add to  the struct ure accord ingly
  6924                                      list[ pl aceBefore  ? "unshift " : "push"  ]( func ) ;
  6925                             }
  6926                    }
  6927           };
  6928   }
  6929  
  6930   // Base in spection f unction fo r prefilte rs and tra nsports
  6931   function i nspectPref iltersOrTr ansports(  structure,  options,  originalOp tions, jqX HR,
  6932                    data Type /* in ternal */,  inspected  /* intern al */ ) {
  6933  
  6934           da taType = d ataType ||  options.d ataTypes[  0 ];
  6935           in spected =  inspected  || {};
  6936  
  6937           in spected[ d ataType ]  = true;
  6938  
  6939           va r list = s tructure[  dataType ] ,
  6940                    i =  0,
  6941                    leng th = list  ? list.len gth : 0,
  6942                    exec uteOnly =  ( structur e === pref ilters ),
  6943                    sele ction;
  6944  
  6945           fo r ( ; i <  length &&  ( executeO nly || !se lection );  i++ ) {
  6946                    sele ction = li st[ i ]( o ptions, or iginalOpti ons, jqXHR  );
  6947                    // I f we got r edirected  to another  dataType
  6948                    // w e try ther e if execu ting only  and not do ne already
  6949                    if (  typeof se lection == = "string"  ) {
  6950                             if ( ! executeOnl y || inspe cted[ sele ction ] )  {
  6951                                      selectio n = undefi ned;
  6952                             } else  {
  6953                                      options. dataTypes. unshift( s election ) ;
  6954                                      selectio n = inspec tPrefilter sOrTranspo rts(
  6955                                                       st ructure, o ptions, or iginalOpti ons, jqXHR , selectio n, inspect ed );
  6956                             }
  6957                    }
  6958           }
  6959           //  If we're  only execu ting or no thing was  selected
  6960           //  we try th e catchall  dataType  if not don e already
  6961           if  ( ( execu teOnly ||  !selection  ) && !ins pected[ "* " ] ) {
  6962                    sele ction = in spectPrefi ltersOrTra nsports(
  6963                                      structur e, options , original Options, j qXHR, "*",  inspected  );
  6964           }
  6965           //  unnecessa ry when on ly executi ng (prefil ters)
  6966           //  but it'll  be ignore d by the c aller in t hat case
  6967           re turn selec tion;
  6968   }
  6969  
  6970   // A speci al extend  for ajax o ptions
  6971   // that ta kes "flat"  options ( not to be  deep exten ded)
  6972   // Fixes # 9887
  6973   function a jaxExtend(  target, s rc ) {
  6974           va r key, dee p,
  6975                    flat Options =  jQuery.aja xSettings. flatOption s || {};
  6976           fo r ( key in  src ) {
  6977                    if (  src[ key  ] !== unde fined ) {
  6978                             ( flat Options[ k ey ] ? tar get : ( de ep || ( de ep = {} )  ) )[ key ]  = src[ ke y ];
  6979                    }
  6980           }
  6981           if  ( deep )  {
  6982                    jQue ry.extend(  true, tar get, deep  );
  6983           }
  6984   }
  6985  
  6986   jQuery.fn. extend({
  6987           lo ad: functi on( url, p arams, cal lback ) {
  6988                    if (  typeof ur l !== "str ing" && _l oad ) {
  6989                             return  _load.app ly( this,  arguments  );
  6990  
  6991                    // D on't do a  request if  no elemen ts are bei ng request ed
  6992                    } el se if ( !t his.length  ) {
  6993                             return  this;
  6994                    }
  6995  
  6996                    var  off = url. indexOf( "  " );
  6997                    if (  off >= 0  ) {
  6998                             var se lector = u rl.slice(  off, url.l ength );
  6999                             url =  url.slice(  0, off );
  7000                    }
  7001  
  7002                    // D efault to  a GET requ est
  7003                    var  type = "GE T";
  7004  
  7005                    // I f the seco nd paramet er was pro vided
  7006                    if (  params )  {
  7007                             // If  it's a fun ction
  7008                             if ( j Query.isFu nction( pa rams ) ) {
  7009                                      // We as sume that  it's the c allback
  7010                                      callback  = params;
  7011                                      params =  undefined ;
  7012  
  7013                             // Oth erwise, bu ild a para m string
  7014                             } else  if ( type of params  === "objec t" ) {
  7015                                      params =  jQuery.pa ram( param s, jQuery. ajaxSettin gs.traditi onal );
  7016                                      type = " POST";
  7017                             }
  7018                    }
  7019  
  7020                    var  self = thi s;
  7021  
  7022                    // R equest the  remote do cument
  7023                    jQue ry.ajax({
  7024                             url: u rl,
  7025                             type:  type,
  7026                             dataTy pe: "html" ,
  7027                             data:  params,
  7028                             // Com plete call back (resp onseText i s used int ernally)
  7029                             comple te: functi on( jqXHR,  status, r esponseTex t ) {
  7030                                      // Store  the respo nse as spe cified by  the jqXHR  object
  7031                                      response Text = jqX HR.respons eText;
  7032                                      // If su ccessful,  inject the  HTML into  all the m atched ele ments
  7033                                      if ( jqX HR.isResol ved() ) {
  7034                                               // #4825:  Get the ac tual respo nse in cas e
  7035                                               // a dataF ilter is p resent in  ajaxSettin gs
  7036                                               jqXHR.done (function(  r ) {
  7037                                                       re sponseText  = r;
  7038                                               });
  7039                                               // See if  a selector  was speci fied
  7040                                               self.html(  selector  ?
  7041                                                       //  Create a  dummy div  to hold th e results
  7042                                                       jQ uery("<div >")
  7043                                                                // i nject the  contents o f the docu ment in, r emoving th e scripts
  7044                                                                // t o avoid an y 'Permiss ion Denied ' errors i n IE
  7045                                                                .app end(respon seText.rep lace(rscri pt, ""))
  7046  
  7047                                                                // L ocate the  specified  elements
  7048                                                                .fin d(selector ) :
  7049  
  7050                                                       //  If not, j ust inject  the full  result
  7051                                                       re sponseText  );
  7052                                      }
  7053  
  7054                                      if ( cal lback ) {
  7055                                               self.each(  callback,  [ respons eText, sta tus, jqXHR  ] );
  7056                                      }
  7057                             }
  7058                    });
  7059  
  7060                    retu rn this;
  7061           },
  7062  
  7063           se rialize: f unction()  {
  7064                    retu rn jQuery. param( thi s.serializ eArray() ) ;
  7065           },
  7066  
  7067           se rializeArr ay: functi on() {
  7068                    retu rn this.ma p(function (){
  7069                             return  this.elem ents ? jQu ery.makeAr ray( this. elements )  : this;
  7070                    })
  7071                    .fil ter(functi on(){
  7072                             return  this.name  && !this. disabled & &
  7073                                      ( this.c hecked ||  rselectTex tarea.test ( this.nod eName ) ||
  7074                                               rinput.tes t( this.ty pe ) );
  7075                    })
  7076                    .map (function(  i, elem ) {
  7077                             var va l = jQuery ( this ).v al();
  7078  
  7079                             return  val == nu ll ?
  7080                                      null :
  7081                                      jQuery.i sArray( va l ) ?
  7082                                               jQuery.map ( val, fun ction( val , i ){
  7083                                                       re turn { nam e: elem.na me, value:  val.repla ce( rCRLF,  "\r\n" )  };
  7084                                               }) :
  7085                                               { name: el em.name, v alue: val. replace( r CRLF, "\r\ n" ) };
  7086                    }).g et();
  7087           }
  7088   });
  7089  
  7090   // Attach  a bunch of  functions  for handl ing common  AJAX even ts
  7091   jQuery.eac h( "ajaxSt art ajaxSt op ajaxCom plete ajax Error ajax Success aj axSend".sp lit( " " ) , function ( i, o ){
  7092           jQ uery.fn[ o  ] = funct ion( f ){
  7093                    retu rn this.on ( o, f );
  7094           };
  7095   });
  7096  
  7097   jQuery.eac h( [ "get" , "post" ] , function ( i, metho d ) {
  7098           jQ uery[ meth od ] = fun ction( url , data, ca llback, ty pe ) {
  7099                    // s hift argum ents if da ta argumen t was omit ted
  7100                    if (  jQuery.is Function(  data ) ) {
  7101                             type =  type || c allback;
  7102                             callba ck = data;
  7103                             data =  undefined ;
  7104                    }
  7105  
  7106                    retu rn jQuery. ajax({
  7107                             type:  method,
  7108                             url: u rl,
  7109                             data:  data,
  7110                             succes s: callbac k,
  7111                             dataTy pe: type
  7112                    });
  7113           };
  7114   });
  7115  
  7116   jQuery.ext end({
  7117  
  7118           ge tScript: f unction( u rl, callba ck ) {
  7119                    retu rn jQuery. get( url,  undefined,  callback,  "script"  );
  7120           },
  7121  
  7122           ge tJSON: fun ction( url , data, ca llback ) {
  7123                    retu rn jQuery. get( url,  data, call back, "jso n" );
  7124           },
  7125  
  7126           //  Creates a  full fled ged settin gs object  into targe t
  7127           //  with both  ajaxSetti ngs and se ttings fie lds.
  7128           //  If target  is omitte d, writes  into ajaxS ettings.
  7129           aj axSetup: f unction( t arget, set tings ) {
  7130                    if (  settings  ) {
  7131                             // Bui lding a se ttings obj ect
  7132                             ajaxEx tend( targ et, jQuery .ajaxSetti ngs );
  7133                    } el se {
  7134                             // Ext ending aja xSettings
  7135                             settin gs = targe t;
  7136                             target  = jQuery. ajaxSettin gs;
  7137                    }
  7138                    ajax Extend( ta rget, sett ings );
  7139                    retu rn target;
  7140           },
  7141  
  7142           aj axSettings : {
  7143                    url:  ajaxLocat ion,
  7144                    isLo cal: rloca lProtocol. test( ajax LocParts[  1 ] ),
  7145                    glob al: true,
  7146                    type : "GET",
  7147                    cont entType: " applicatio n/x-www-fo rm-urlenco ded",
  7148                    proc essData: t rue,
  7149                    asyn c: true,
  7150                    /*
  7151                    time out: 0,
  7152                    data : null,
  7153                    data Type: null ,
  7154                    user name: null ,
  7155                    pass word: null ,
  7156                    cach e: null,
  7157                    trad itional: f alse,
  7158                    head ers: {},
  7159                    */
  7160  
  7161                    acce pts: {
  7162                             xml: " applicatio n/xml, tex t/xml",
  7163                             html:  "text/html ",
  7164                             text:  "text/plai n",
  7165                             json:  "applicati on/json, t ext/javasc ript",
  7166                             "*": a llTypes
  7167                    },
  7168  
  7169                    cont ents: {
  7170                             xml: / xml/,
  7171                             html:  /html/,
  7172                             json:  /json/
  7173                    },
  7174  
  7175                    resp onseFields : {
  7176                             xml: " responseXM L",
  7177                             text:  "responseT ext"
  7178                    },
  7179  
  7180                    // L ist of dat a converte rs
  7181                    // 1 ) key form at is "sou rce_type d estination _type" (a  single spa ce in-betw een)
  7182                    // 2 ) the catc hall symbo l "*" can  be used fo r source_t ype
  7183                    conv erters: {
  7184  
  7185                             // Con vert anyth ing to tex t
  7186                             "* tex t": window .String,
  7187  
  7188                             // Tex t to html  (true = no  transform ation)
  7189                             "text  html": tru e,
  7190  
  7191                             // Eva luate text  as a json  expressio n
  7192                             "text  json": jQu ery.parseJ SON,
  7193  
  7194                             // Par se text as  xml
  7195                             "text  xml": jQue ry.parseXM L
  7196                    },
  7197  
  7198                    // F or options  that shou ldn't be d eep extend ed:
  7199                    // y ou can add  your own  custom opt ions here  if
  7200                    // a nd when yo u create o ne that sh ouldn't be
  7201                    // d eep extend ed (see aj axExtend)
  7202                    flat Options: {
  7203                             contex t: true,
  7204                             url: t rue
  7205                    }
  7206           },
  7207  
  7208           aj axPrefilte r: addToPr efiltersOr Transports ( prefilte rs ),
  7209           aj axTranspor t: addToPr efiltersOr Transports ( transpor ts ),
  7210  
  7211           //  Main meth od
  7212           aj ax: functi on( url, o ptions ) {
  7213  
  7214                    // I f url is a n object,  simulate p re-1.5 sig nature
  7215                    if (  typeof ur l === "obj ect" ) {
  7216                             option s = url;
  7217                             url =  undefined;
  7218                    }
  7219  
  7220                    // F orce optio ns to be a n object
  7221                    opti ons = opti ons || {};
  7222  
  7223                    var  // Create  the final  options ob ject
  7224                             s = jQ uery.ajaxS etup( {},  options ),
  7225                             // Cal lbacks con text
  7226                             callba ckContext  = s.contex t || s,
  7227                             // Con text for g lobal even ts
  7228                             // It' s the call backContex t if one w as provide d in the o ptions
  7229                             // and  if it's a  DOM node  or a jQuer y collecti on
  7230                             global EventConte xt = callb ackContext  !== s &&
  7231                                      ( callba ckContext. nodeType | | callback Context in stanceof j Query ) ?
  7232                                                       jQ uery( call backContex t ) : jQue ry.event,
  7233                             // Def erreds
  7234                             deferr ed = jQuer y.Deferred (),
  7235                             comple teDeferred  = jQuery. Callbacks(  "once mem ory" ),
  7236                             // Sta tus-depend ent callba cks
  7237                             status Code = s.s tatusCode  || {},
  7238                             // ifM odified ke y
  7239                             ifModi fiedKey,
  7240                             // Hea ders (they  are sent  all at onc e)
  7241                             reques tHeaders =  {},
  7242                             reques tHeadersNa mes = {},
  7243                             // Res ponse head ers
  7244                             respon seHeadersS tring,
  7245                             respon seHeaders,
  7246                             // tra nsport
  7247                             transp ort,
  7248                             // tim eout handl e
  7249                             timeou tTimer,
  7250                             // Cro ss-domain  detection  vars
  7251                             parts,
  7252                             // The  jqXHR sta te
  7253                             state  = 0,
  7254                             // To  know if gl obal event s are to b e dispatch ed
  7255                             fireGl obals,
  7256                             // Loo p variable
  7257                             i,
  7258                             // Fak e xhr
  7259                             jqXHR  = {
  7260  
  7261                                      readySta te: 0,
  7262  
  7263                                      // Cache s the head er
  7264                                      setReque stHeader:  function(  name, valu e ) {
  7265                                               if ( !stat e ) {
  7266                                                       va r lname =  name.toLow erCase();
  7267                                                       na me = reque stHeadersN ames[ lnam e ] = requ estHeaders Names[ lna me ] || na me;
  7268                                                       re questHeade rs[ name ]  = value;
  7269                                               }
  7270                                               return thi s;
  7271                                      },
  7272  
  7273                                      // Raw s tring
  7274                                      getAllRe sponseHead ers: funct ion() {
  7275                                               return sta te === 2 ?  responseH eadersStri ng : null;
  7276                                      },
  7277  
  7278                                      // Build s headers  hashtable  if needed
  7279                                      getRespo nseHeader:  function(  key ) {
  7280                                               var match;
  7281                                               if ( state  === 2 ) {
  7282                                                       if  ( !respon seHeaders  ) {
  7283                                                                resp onseHeader s = {};
  7284                                                                whil e( ( match  = rheader s.exec( re sponseHead ersString  ) ) ) {
  7285                                                                         respon seHeaders[  match[1]. toLowerCas e() ] = ma tch[ 2 ];
  7286                                                                }
  7287                                                       }
  7288                                                       ma tch = resp onseHeader s[ key.toL owerCase()  ];
  7289                                               }
  7290                                               return mat ch === und efined ? n ull : matc h;
  7291                                      },
  7292  
  7293                                      // Overr ides respo nse conten t-type hea der
  7294                                      override MimeType:  function(  type ) {
  7295                                               if ( !stat e ) {
  7296                                                       s. mimeType =  type;
  7297                                               }
  7298                                               return thi s;
  7299                                      },
  7300  
  7301                                      // Cance l the requ est
  7302                                      abort: f unction( s tatusText  ) {
  7303                                               statusText  = statusT ext || "ab ort";
  7304                                               if ( trans port ) {
  7305                                                       tr ansport.ab ort( statu sText );
  7306                                               }
  7307                                               done( 0, s tatusText  );
  7308                                               return thi s;
  7309                                      }
  7310                             };
  7311  
  7312                    // C allback fo r when eve rything is  done
  7313                    // I t is defin ed here be cause jsli nt complai ns if it i s declared
  7314                    // a t the end  of the fun ction (whi ch would b e more log ical and r eadable)
  7315                    func tion done(  status, n ativeStatu sText, res ponses, he aders ) {
  7316  
  7317                             // Cal led once
  7318                             if ( s tate === 2  ) {
  7319                                      return;
  7320                             }
  7321  
  7322                             // Sta te is "don e" now
  7323                             state  = 2;
  7324  
  7325                             // Cle ar timeout  if it exi sts
  7326                             if ( t imeoutTime r ) {
  7327                                      clearTim eout( time outTimer ) ;
  7328                             }
  7329  
  7330                             // Der eference t ransport f or early g arbage col lection
  7331                             // (no  matter ho w long the  jqXHR obj ect will b e used)
  7332                             transp ort = unde fined;
  7333  
  7334                             // Cac he respons e headers
  7335                             respon seHeadersS tring = he aders || " ";
  7336  
  7337                             // Set  readyStat e
  7338                             jqXHR. readyState  = status  > 0 ? 4 :  0;
  7339  
  7340                             var is Success,
  7341                                      success,
  7342                                      error,
  7343                                      statusTe xt = nativ eStatusTex t,
  7344                                      response  = respons es ? ajaxH andleRespo nses( s, j qXHR, resp onses ) :  undefined,
  7345                                      lastModi fied,
  7346                                      etag;
  7347  
  7348                             // If  successful , handle t ype chaini ng
  7349                             if ( s tatus >= 2 00 && stat us < 300 | | status = == 304 ) {
  7350  
  7351                                      // Set t he If-Modi fied-Since  and/or If -None-Matc h header,  if in ifMo dified mod e.
  7352                                      if ( s.i fModified  ) {
  7353  
  7354                                               if ( ( las tModified  = jqXHR.ge tResponseH eader( "La st-Modifie d" ) ) ) {
  7355                                                       jQ uery.lastM odified[ i fModifiedK ey ] = las tModified;
  7356                                               }
  7357                                               if ( ( eta g = jqXHR. getRespons eHeader( " Etag" ) )  ) {
  7358                                                       jQ uery.etag[  ifModifie dKey ] = e tag;
  7359                                               }
  7360                                      }
  7361  
  7362                                      // If no t modified
  7363                                      if ( sta tus === 30 4 ) {
  7364  
  7365                                               statusText  = "notmod ified";
  7366                                               isSuccess  = true;
  7367  
  7368                                      // If we  have data
  7369                                      } else {
  7370  
  7371                                               try {
  7372                                                       su ccess = aj axConvert(  s, respon se );
  7373                                                       st atusText =  "success" ;
  7374                                                       is Success =  true;
  7375                                               } catch(e)  {
  7376                                                       //  We have a  parsererr or
  7377                                                       st atusText =  "parserer ror";
  7378                                                       er ror = e;
  7379                                               }
  7380                                      }
  7381                             } else  {
  7382                                      // We ex tract erro r from sta tusText
  7383                                      // then  normalize  statusText  and statu s for non- aborts
  7384                                      error =  statusText ;
  7385                                      if ( !st atusText | | status )  {
  7386                                               statusText  = "error" ;
  7387                                               if ( statu s < 0 ) {
  7388                                                       st atus = 0;
  7389                                               }
  7390                                      }
  7391                             }
  7392  
  7393                             // Set  data for  the fake x hr object
  7394                             jqXHR. status = s tatus;
  7395                             jqXHR. statusText  = "" + (  nativeStat usText ||  statusText  );
  7396  
  7397                             // Suc cess/Error
  7398                             if ( i sSuccess )  {
  7399                                      deferred .resolveWi th( callba ckContext,  [ success , statusTe xt, jqXHR  ] );
  7400                             } else  {
  7401                                      deferred .rejectWit h( callbac kContext,  [ jqXHR, s tatusText,  error ] ) ;
  7402                             }
  7403  
  7404                             // Sta tus-depend ent callba cks
  7405                             jqXHR. statusCode ( statusCo de );
  7406                             status Code = und efined;
  7407  
  7408                             if ( f ireGlobals  ) {
  7409                                      globalEv entContext .trigger(  "ajax" + (  isSuccess  ? "Succes s" : "Erro r" ),
  7410                                                       [  jqXHR, s,  isSuccess  ? success  : error ]  );
  7411                             }
  7412  
  7413                             // Com plete
  7414                             comple teDeferred .fireWith(  callbackC ontext, [  jqXHR, sta tusText ]  );
  7415  
  7416                             if ( f ireGlobals  ) {
  7417                                      globalEv entContext .trigger(  "ajaxCompl ete", [ jq XHR, s ] ) ;
  7418                                      // Handl e the glob al AJAX co unter
  7419                                      if ( !(  --jQuery.a ctive ) )  {
  7420                                               jQuery.eve nt.trigger ( "ajaxSto p" );
  7421                                      }
  7422                             }
  7423                    }
  7424  
  7425                    // A ttach defe rreds
  7426                    defe rred.promi se( jqXHR  );
  7427                    jqXH R.success  = jqXHR.do ne;
  7428                    jqXH R.error =  jqXHR.fail ;
  7429                    jqXH R.complete  = complet eDeferred. add;
  7430  
  7431                    // S tatus-depe ndent call backs
  7432                    jqXH R.statusCo de = funct ion( map )  {
  7433                             if ( m ap ) {
  7434                                      var tmp;
  7435                                      if ( sta te < 2 ) {
  7436                                               for ( tmp  in map ) {
  7437                                                       st atusCode[  tmp ] = [  statusCode [tmp], map [tmp] ];
  7438                                               }
  7439                                      } else {
  7440                                               tmp = map[  jqXHR.sta tus ];
  7441                                               jqXHR.then ( tmp, tmp  );
  7442                                      }
  7443                             }
  7444                             return  this;
  7445                    };
  7446  
  7447                    // R emove hash  character  (#7531: a nd string  promotion)
  7448                    // A dd protoco l if not p rovided (# 5866: IE7  issue with  protocol- less urls)
  7449                    // W e also use  the url p arameter i f availabl e
  7450                    s.ur l = ( ( ur l || s.url  ) + "" ). replace( r hash, "" ) .replace(  rprotocol,  ajaxLocPa rts[ 1 ] +  "//" );
  7451  
  7452                    // E xtract dat aTypes lis t
  7453                    s.da taTypes =  jQuery.tri m( s.dataT ype || "*"  ).toLower Case().spl it( rspace sAjax );
  7454  
  7455                    // D etermine i f a cross- domain req uest is in  order
  7456                    if (  s.crossDo main == nu ll ) {
  7457                             parts  = rurl.exe c( s.url.t oLowerCase () );
  7458                             s.cros sDomain =  !!( parts  &&
  7459                                      ( parts[  1 ] != aj axLocParts [ 1 ] || p arts[ 2 ]  != ajaxLoc Parts[ 2 ]  ||
  7460                                               ( parts[ 3  ] || ( pa rts[ 1 ] = == "http:"  ? 80 : 44 3 ) ) !=
  7461                                                       (  ajaxLocPar ts[ 3 ] ||  ( ajaxLoc Parts[ 1 ]  === "http :" ? 80 :  443 ) ) )
  7462                             );
  7463                    }
  7464  
  7465                    // C onvert dat a if not a lready a s tring
  7466                    if (  s.data &&  s.process Data && ty peof s.dat a !== "str ing" ) {
  7467                             s.data  = jQuery. param( s.d ata, s.tra ditional ) ;
  7468                    }
  7469  
  7470                    // A pply prefi lters
  7471                    insp ectPrefilt ersOrTrans ports( pre filters, s , options,  jqXHR );
  7472  
  7473                    // I f request  was aborte d inside a  prefiler,  stop ther e
  7474                    if (  state ===  2 ) {
  7475                             return  false;
  7476                    }
  7477  
  7478                    // W e can fire  global ev ents as of  now if as ked to
  7479                    fire Globals =  s.global;
  7480  
  7481                    // U ppercase t he type
  7482                    s.ty pe = s.typ e.toUpperC ase();
  7483  
  7484                    // D etermine i f request  has conten t
  7485                    s.ha sContent =  !rnoConte nt.test( s .type );
  7486  
  7487                    // W atch for a  new set o f requests
  7488                    if (  fireGloba ls && jQue ry.active+ + === 0 )  {
  7489                             jQuery .event.tri gger( "aja xStart" );
  7490                    }
  7491  
  7492                    // M ore option s handling  for reque sts with n o content
  7493                    if (  !s.hasCon tent ) {
  7494  
  7495                             // If  data is av ailable, a ppend data  to url
  7496                             if ( s .data ) {
  7497                                      s.url +=  ( rquery. test( s.ur l ) ? "&"  : "?" ) +  s.data;
  7498                                      // #9682 : remove d ata so tha t it's not  used in a n eventual  retry
  7499                                      delete s .data;
  7500                             }
  7501  
  7502                             // Get  ifModifie dKey befor e adding t he anti-ca che parame ter
  7503                             ifModi fiedKey =  s.url;
  7504  
  7505                             // Add  anti-cach e in url i f needed
  7506                             if ( s .cache ===  false ) {
  7507  
  7508                                      var ts =  jQuery.no w(),
  7509                                               // try rep lacing _=  if it is t here
  7510                                               ret = s.ur l.replace(  rts, "$1_ =" + ts );
  7511  
  7512                                      // if no thing was  replaced,  add timest amp to the  end
  7513                                      s.url =  ret + ( (  ret === s. url ) ? (  rquery.tes t( s.url )  ? "&" : " ?" ) + "_= " + ts : " " );
  7514                             }
  7515                    }
  7516  
  7517                    // S et the cor rect heade r, if data  is being  sent
  7518                    if (  s.data &&  s.hasCont ent && s.c ontentType  !== false  || option s.contentT ype ) {
  7519                             jqXHR. setRequest Header( "C ontent-Typ e", s.cont entType );
  7520                    }
  7521  
  7522                    // S et the If- Modified-S ince and/o r If-None- Match head er, if in  ifModified  mode.
  7523                    if (  s.ifModif ied ) {
  7524                             ifModi fiedKey =  ifModified Key || s.u rl;
  7525                             if ( j Query.last Modified[  ifModified Key ] ) {
  7526                                      jqXHR.se tRequestHe ader( "If- Modified-S ince", jQu ery.lastMo dified[ if ModifiedKe y ] );
  7527                             }
  7528                             if ( j Query.etag [ ifModifi edKey ] )  {
  7529                                      jqXHR.se tRequestHe ader( "If- None-Match ", jQuery. etag[ ifMo difiedKey  ] );
  7530                             }
  7531                    }
  7532  
  7533                    // S et the Acc epts heade r for the  server, de pending on  the dataT ype
  7534                    jqXH R.setReque stHeader(
  7535                             "Accep t",
  7536                             s.data Types[ 0 ]  && s.acce pts[ s.dat aTypes[0]  ] ?
  7537                                      s.accept s[ s.dataT ypes[0] ]  + ( s.data Types[ 0 ]  !== "*" ?  ", " + al lTypes + " ; q=0.01"  : "" ) :
  7538                                      s.accept s[ "*" ]
  7539                    );
  7540  
  7541                    // C heck for h eaders opt ion
  7542                    for  ( i in s.h eaders ) {
  7543                             jqXHR. setRequest Header( i,  s.headers [ i ] );
  7544                    }
  7545  
  7546                    // A llow custo m headers/ mimetypes  and early  abort
  7547                    if (  s.beforeS end && ( s .beforeSen d.call( ca llbackCont ext, jqXHR , s ) ===  false || s tate === 2  ) ) {
  7548                                      // Abort  if not do ne already
  7549                                      jqXHR.ab ort();
  7550                                      return f alse;
  7551  
  7552                    }
  7553  
  7554                    // I nstall cal lbacks on  deferreds
  7555                    for  ( i in { s uccess: 1,  error: 1,  complete:  1 } ) {
  7556                             jqXHR[  i ]( s[ i  ] );
  7557                    }
  7558  
  7559                    // G et transpo rt
  7560                    tran sport = in spectPrefi ltersOrTra nsports( t ransports,  s, option s, jqXHR ) ;
  7561  
  7562                    // I f no trans port, we a uto-abort
  7563                    if (  !transpor t ) {
  7564                             done(  -1, "No Tr ansport" ) ;
  7565                    } el se {
  7566                             jqXHR. readyState  = 1;
  7567                             // Sen d global e vent
  7568                             if ( f ireGlobals  ) {
  7569                                      globalEv entContext .trigger(  "ajaxSend" , [ jqXHR,  s ] );
  7570                             }
  7571                             // Tim eout
  7572                             if ( s .async &&  s.timeout  > 0 ) {
  7573                                      timeoutT imer = set Timeout( f unction(){
  7574                                               jqXHR.abor t( "timeou t" );
  7575                                      }, s.tim eout );
  7576                             }
  7577  
  7578                             try {
  7579                                      state =  1;
  7580                                      transpor t.send( re questHeade rs, done ) ;
  7581                             } catc h (e) {
  7582                                      // Propa gate excep tion as er ror if not  done
  7583                                      if ( sta te < 2 ) {
  7584                                               done( -1,  e );
  7585                                      // Simpl y rethrow  otherwise
  7586                                      } else {
  7587                                               throw e;
  7588                                      }
  7589                             }
  7590                    }
  7591  
  7592                    retu rn jqXHR;
  7593           },
  7594  
  7595           //  Serialize  an array  of form el ements or  a set of
  7596           //  key/value s into a q uery strin g
  7597           pa ram: funct ion( a, tr aditional  ) {
  7598                    var  s = [],
  7599                             add =  function(  key, value  ) {
  7600                                      // If va lue is a f unction, i nvoke it a nd return  its value
  7601                                      value =  jQuery.isF unction( v alue ) ? v alue() : v alue;
  7602                                      s[ s.len gth ] = en codeURICom ponent( ke y ) + "="  + encodeUR IComponent ( value );
  7603                             };
  7604  
  7605                    // S et traditi onal to tr ue for jQu ery <= 1.3 .2 behavio r.
  7606                    if (  tradition al === und efined ) {
  7607                             tradit ional = jQ uery.ajaxS ettings.tr aditional;
  7608                    }
  7609  
  7610                    // I f an array  was passe d in, assu me that it  is an arr ay of form  elements.
  7611                    if (  jQuery.is Array( a )  || ( a.jq uery && !j Query.isPl ainObject(  a ) ) ) {
  7612                             // Ser ialize the  form elem ents
  7613                             jQuery .each( a,  function()  {
  7614                                      add( thi s.name, th is.value ) ;
  7615                             });
  7616  
  7617                    } el se {
  7618                             // If  traditiona l, encode  the "old"  way (the w ay 1.3.2 o r older
  7619                             // did  it), othe rwise enco de params  recursivel y.
  7620                             for (  var prefix  in a ) {
  7621                                      buildPar ams( prefi x, a[ pref ix ], trad itional, a dd );
  7622                             }
  7623                    }
  7624  
  7625                    // R eturn the  resulting  serializat ion
  7626                    retu rn s.join(  "&" ).rep lace( r20,  "+" );
  7627           }
  7628   });
  7629  
  7630   function b uildParams ( prefix,  obj, tradi tional, ad d ) {
  7631           if  ( jQuery. isArray( o bj ) ) {
  7632                    // S erialize a rray item.
  7633                    jQue ry.each( o bj, functi on( i, v )  {
  7634                             if ( t raditional  || rbrack et.test( p refix ) )  {
  7635                                      // Treat  each arra y item as  a scalar.
  7636                                      add( pre fix, v );
  7637  
  7638                             } else  {
  7639                                      // If ar ray item i s non-scal ar (array  or object) , encode i ts
  7640                                      // numer ic index t o resolve  deserializ ation ambi guity issu es.
  7641                                      // Note  that rack  (as of 1.0 .0) can't  currently  deserializ e
  7642                                      // neste d arrays p roperly, a nd attempt ing to do  so may cau se
  7643                                      // a ser ver error.  Possible  fixes are  to modify  rack's
  7644                                      // deser ialization  algorithm  or to pro vide an op tion or fl ag
  7645                                      // to fo rce array  serializat ion to be  shallow.
  7646                                      buildPar ams( prefi x + "[" +  ( typeof v  === "obje ct" || jQu ery.isArra y(v) ? i :  "" ) + "] ", v, trad itional, a dd );
  7647                             }
  7648                    });
  7649  
  7650           }  else if (  !tradition al && obj  != null &&  typeof ob j === "obj ect" ) {
  7651                    // S erialize o bject item .
  7652                    for  ( var name  in obj )  {
  7653                             buildP arams( pre fix + "["  + name + " ]", obj[ n ame ], tra ditional,  add );
  7654                    }
  7655  
  7656           }  else {
  7657                    // S erialize s calar item .
  7658                    add(  prefix, o bj );
  7659           }
  7660   }
  7661  
  7662   // This is  still on  the jQuery  object...  for now
  7663   // Want to  move this  to jQuery .ajax some  day
  7664   jQuery.ext end({
  7665  
  7666           //  Counter f or holding  the numbe r of activ e queries
  7667           ac tive: 0,
  7668  
  7669           //  Last-Modi fied heade r cache fo r next req uest
  7670           la stModified : {},
  7671           et ag: {}
  7672  
  7673   });
  7674  
  7675   /* Handles  responses  to an aja x request:
  7676    * - sets  all respon seXXX fiel ds accordi ngly
  7677    * - finds  the right  dataType  (mediates  between co ntent-type  and expec ted dataTy pe)
  7678    * - retur ns the cor responding  response
  7679    */
  7680   function a jaxHandleR esponses(  s, jqXHR,  responses  ) {
  7681  
  7682           va r contents  = s.conte nts,
  7683                    data Types = s. dataTypes,
  7684                    resp onseFields  = s.respo nseFields,
  7685                    ct,
  7686                    type ,
  7687                    fina lDataType,
  7688                    firs tDataType;
  7689  
  7690           //  Fill resp onseXXX fi elds
  7691           fo r ( type i n response Fields ) {
  7692                    if (  type in r esponses )  {
  7693                             jqXHR[  responseF ields[type ] ] = resp onses[ typ e ];
  7694                    }
  7695           }
  7696  
  7697           //  Remove au to dataTyp e and get  content-ty pe in the  process
  7698           wh ile( dataT ypes[ 0 ]  === "*" )  {
  7699                    data Types.shif t();
  7700                    if (  ct === un defined )  {
  7701                             ct = s .mimeType  || jqXHR.g etResponse Header( "c ontent-typ e" );
  7702                    }
  7703           }
  7704  
  7705           //  Check if  we're deal ing with a  known con tent-type
  7706           if  ( ct ) {
  7707                    for  ( type in  contents )  {
  7708                             if ( c ontents[ t ype ] && c ontents[ t ype ].test ( ct ) ) {
  7709                                      dataType s.unshift(  type );
  7710                                      break;
  7711                             }
  7712                    }
  7713           }
  7714  
  7715           //  Check to  see if we  have a res ponse for  the expect ed dataTyp e
  7716           if  ( dataTyp es[ 0 ] in  responses  ) {
  7717                    fina lDataType  = dataType s[ 0 ];
  7718           }  else {
  7719                    // T ry convert ible dataT ypes
  7720                    for  ( type in  responses  ) {
  7721                             if ( ! dataTypes[  0 ] || s. converters [ type + "  " + dataT ypes[0] ]  ) {
  7722                                      finalDat aType = ty pe;
  7723                                      break;
  7724                             }
  7725                             if ( ! firstDataT ype ) {
  7726                                      firstDat aType = ty pe;
  7727                             }
  7728                    }
  7729                    // O r just use  first one
  7730                    fina lDataType  = finalDat aType || f irstDataTy pe;
  7731           }
  7732  
  7733           //  If we fou nd a dataT ype
  7734           //  We add th e dataType  to the li st if need ed
  7735           //  and retur n the corr esponding  response
  7736           if  ( finalDa taType ) {
  7737                    if (  finalData Type !== d ataTypes[  0 ] ) {
  7738                             dataTy pes.unshif t( finalDa taType );
  7739                    }
  7740                    retu rn respons es[ finalD ataType ];
  7741           }
  7742   }
  7743  
  7744   // Chain c onversions  given the  request a nd the ori ginal resp onse
  7745   function a jaxConvert ( s, respo nse ) {
  7746  
  7747           //  Apply the  dataFilte r if provi ded
  7748           if  ( s.dataF ilter ) {
  7749                    resp onse = s.d ataFilter(  response,  s.dataTyp e );
  7750           }
  7751  
  7752           va r dataType s = s.data Types,
  7753                    conv erters = { },
  7754                    i,
  7755                    key,
  7756                    leng th = dataT ypes.lengt h,
  7757                    tmp,
  7758                    // C urrent and  previous  dataTypes
  7759                    curr ent = data Types[ 0 ] ,
  7760                    prev ,
  7761                    // C onversion  expression
  7762                    conv ersion,
  7763                    // C onversion  function
  7764                    conv ,
  7765                    // C onversion  functions  (transitiv e conversi on)
  7766                    conv 1,
  7767                    conv 2;
  7768  
  7769           //  For each  dataType i n the chai n
  7770           fo r ( i = 1;  i < lengt h; i++ ) {
  7771  
  7772                    // C reate conv erters map
  7773                    // w ith lowerc ased keys
  7774                    if (  i === 1 )  {
  7775                             for (  key in s.c onverters  ) {
  7776                                      if ( typ eof key == = "string"  ) {
  7777                                               converters [ key.toLo werCase()  ] = s.conv erters[ ke y ];
  7778                                      }
  7779                             }
  7780                    }
  7781  
  7782                    // G et the dat aTypes
  7783                    prev  = current ;
  7784                    curr ent = data Types[ i ] ;
  7785  
  7786                    // I f current  is auto da taType, up date it to  prev
  7787                    if (  current = == "*" ) {
  7788                             curren t = prev;
  7789                    // I f no auto  and dataTy pes are ac tually dif ferent
  7790                    } el se if ( pr ev !== "*"  && prev ! == current  ) {
  7791  
  7792                             // Get  the conve rter
  7793                             conver sion = pre v + " " +  current;
  7794                             conv =  converter s[ convers ion ] || c onverters[  "* " + cu rrent ];
  7795  
  7796                             // If  there is n o direct c onverter,  search tra nsitively
  7797                             if ( ! conv ) {
  7798                                      conv2 =  undefined;
  7799                                      for ( co nv1 in con verters )  {
  7800                                               tmp = conv 1.split( "  " );
  7801                                               if ( tmp[  0 ] === pr ev || tmp[  0 ] === " *" ) {
  7802                                                       co nv2 = conv erters[ tm p[1] + " "  + current  ];
  7803                                                       if  ( conv2 )  {
  7804                                                                conv 1 = conver ters[ conv 1 ];
  7805                                                                if (  conv1 ===  true ) {
  7806                                                                         conv =  conv2;
  7807                                                                } el se if ( co nv2 === tr ue ) {
  7808                                                                         conv =  conv1;
  7809                                                                }
  7810                                                                brea k;
  7811                                                       }
  7812                                               }
  7813                                      }
  7814                             }
  7815                             // If  we found n o converte r, dispatc h an error
  7816                             if ( ! ( conv ||  conv2 ) )  {
  7817                                      jQuery.e rror( "No  conversion  from " +  conversion .replace("  "," to ")  );
  7818                             }
  7819                             // If  found conv erter is n ot an equi valence
  7820                             if ( c onv !== tr ue ) {
  7821                                      // Conve rt with 1  or 2 conve rters acco rdingly
  7822                                      response  = conv ?  conv( resp onse ) : c onv2( conv 1(response ) );
  7823                             }
  7824                    }
  7825           }
  7826           re turn respo nse;
  7827   }
  7828  
  7829  
  7830  
  7831  
  7832   var jsc =  jQuery.now (),
  7833           js re = /(\=) \?(&|$)|\? \?/i;
  7834  
  7835   // Default  jsonp set tings
  7836   jQuery.aja xSetup({
  7837           js onp: "call back",
  7838           js onpCallbac k: functio n() {
  7839                    retu rn jQuery. expando +  "_" + ( js c++ );
  7840           }
  7841   });
  7842  
  7843   // Detect,  normalize  options a nd install  callbacks  for jsonp  requests
  7844   jQuery.aja xPrefilter ( "json js onp", func tion( s, o riginalSet tings, jqX HR ) {
  7845  
  7846           va r inspectD ata = s.co ntentType  === "appli cation/x-w ww-form-ur lencoded"  &&
  7847                    ( ty peof s.dat a === "str ing" );
  7848  
  7849           if  ( s.dataT ypes[ 0 ]  === "jsonp " ||
  7850                    s.js onp !== fa lse && ( j sre.test(  s.url ) ||
  7851                                      inspectD ata && jsr e.test( s. data ) ) )  {
  7852  
  7853                    var  responseCo ntainer,
  7854                             jsonpC allback =  s.jsonpCal lback =
  7855                                      jQuery.i sFunction(  s.jsonpCa llback ) ?  s.jsonpCa llback() :  s.jsonpCa llback,
  7856                             previo us = windo w[ jsonpCa llback ],
  7857                             url =  s.url,
  7858                             data =  s.data,
  7859                             replac e = "$1" +  jsonpCall back + "$2 ";
  7860  
  7861                    if (  s.jsonp ! == false )  {
  7862                             url =  url.replac e( jsre, r eplace );
  7863                             if ( s .url === u rl ) {
  7864                                      if ( ins pectData )  {
  7865                                               data = dat a.replace(  jsre, rep lace );
  7866                                      }
  7867                                      if ( s.d ata === da ta ) {
  7868                                               // Add cal lback manu ally
  7869                                               url += (/\ ?/.test( u rl ) ? "&"  : "?") +  s.jsonp +  "=" + json pCallback;
  7870                                      }
  7871                             }
  7872                    }
  7873  
  7874                    s.ur l = url;
  7875                    s.da ta = data;
  7876  
  7877                    // I nstall cal lback
  7878                    wind ow[ jsonpC allback ]  = function ( response  ) {
  7879                             respon seContaine r = [ resp onse ];
  7880                    };
  7881  
  7882                    // C lean-up fu nction
  7883                    jqXH R.always(f unction()  {
  7884                             // Set  callback  back to pr evious val ue
  7885                             window [ jsonpCal lback ] =  previous;
  7886                             // Cal l if it wa s a functi on and we  have a res ponse
  7887                             if ( r esponseCon tainer &&  jQuery.isF unction( p revious )  ) {
  7888                                      window[  jsonpCallb ack ]( res ponseConta iner[ 0 ]  );
  7889                             }
  7890                    });
  7891  
  7892                    // U se data co nverter to  retrieve  json after  script ex ecution
  7893                    s.co nverters[" script jso n"] = func tion() {
  7894                             if ( ! responseCo ntainer )  {
  7895                                      jQuery.e rror( json pCallback  + " was no t called"  );
  7896                             }
  7897                             return  responseC ontainer[  0 ];
  7898                    };
  7899  
  7900                    // f orce json  dataType
  7901                    s.da taTypes[ 0  ] = "json ";
  7902  
  7903                    // D elegate to  script
  7904                    retu rn "script ";
  7905           }
  7906   });
  7907  
  7908  
  7909  
  7910  
  7911   // Install  script da taType
  7912   jQuery.aja xSetup({
  7913           ac cepts: {
  7914                    scri pt: "text/ javascript , applicat ion/javasc ript, appl ication/ec mascript,  applicatio n/x-ecmasc ript"
  7915           },
  7916           co ntents: {
  7917                    scri pt: /javas cript|ecma script/
  7918           },
  7919           co nverters:  {
  7920                    "tex t script":  function(  text ) {
  7921                             jQuery .globalEva l( text );
  7922                             return  text;
  7923                    }
  7924           }
  7925   });
  7926  
  7927   // Handle  cache's sp ecial case  and globa l
  7928   jQuery.aja xPrefilter ( "script" , function ( s ) {
  7929           if  ( s.cache  === undef ined ) {
  7930                    s.ca che = fals e;
  7931           }
  7932           if  ( s.cross Domain ) {
  7933                    s.ty pe = "GET" ;
  7934                    s.gl obal = fal se;
  7935           }
  7936   });
  7937  
  7938   // Bind sc ript tag h ack transp ort
  7939   jQuery.aja xTransport ( "script" , function (s) {
  7940  
  7941           //  This tran sport only  deals wit h cross do main reque sts
  7942           if  ( s.cross Domain ) {
  7943  
  7944                    var  script,
  7945                             head =  document. head || do cument.get ElementsBy TagName( " head" )[0]  || docume nt.documen tElement;
  7946  
  7947                    retu rn {
  7948  
  7949                             send:  function(  _, callbac k ) {
  7950  
  7951                                      script =  document. createElem ent( "scri pt" );
  7952  
  7953                                      script.a sync = "as ync";
  7954  
  7955                                      if ( s.s criptChars et ) {
  7956                                               script.cha rset = s.s criptChars et;
  7957                                      }
  7958  
  7959                                      script.s rc = s.url ;
  7960  
  7961                                      // Attac h handlers  for all b rowsers
  7962                                      script.o nload = sc ript.onrea dystatecha nge = func tion( _, i sAbort ) {
  7963  
  7964                                               if ( isAbo rt || !scr ipt.readyS tate || /l oaded|comp lete/.test ( script.r eadyState  ) ) {
  7965  
  7966                                                       //  Handle me mory leak  in IE
  7967                                                       sc ript.onloa d = script .onreadyst atechange  = null;
  7968  
  7969                                                       //  Remove th e script
  7970                                                       if  ( head &&  script.pa rentNode )  {
  7971                                                                head .removeChi ld( script  );
  7972                                                       }
  7973  
  7974                                                       //  Dereferen ce the scr ipt
  7975                                                       sc ript = und efined;
  7976  
  7977                                                       //  Callback  if not abo rt
  7978                                                       if  ( !isAbor t ) {
  7979                                                                call back( 200,  "success"  );
  7980                                                       }
  7981                                               }
  7982                                      };
  7983                                      // Use i nsertBefor e instead  of appendC hild  to c ircumvent  an IE6 bug .
  7984                                      // This  arises whe n a base n ode is use d (#2709 a nd #4378).
  7985                                      head.ins ertBefore(  script, h ead.firstC hild );
  7986                             },
  7987  
  7988                             abort:  function( ) {
  7989                                      if ( scr ipt ) {
  7990                                               script.onl oad( 0, 1  );
  7991                                      }
  7992                             }
  7993                    };
  7994           }
  7995   });
  7996  
  7997  
  7998  
  7999  
  8000   var // #52 80: Intern et Explore r will kee p connecti ons alive  if we don' t abort on  unload
  8001           xh rOnUnloadA bort = win dow.Active XObject ?  function()  {
  8002                    // A bort all p ending req uests
  8003                    for  ( var key  in xhrCall backs ) {
  8004                             xhrCal lbacks[ ke y ]( 0, 1  );
  8005                    }
  8006           }  : false,
  8007           xh rId = 0,
  8008           xh rCallbacks ;
  8009  
  8010   // Functio ns to crea te xhrs
  8011   function c reateStand ardXHR() {
  8012           tr y {
  8013                    retu rn new win dow.XMLHtt pRequest() ;
  8014           }  catch( e )  {}
  8015   }
  8016  
  8017   function c reateActiv eXHR() {
  8018           tr y {
  8019                    retu rn new win dow.Active XObject( " Microsoft. XMLHTTP" ) ;
  8020           }  catch( e )  {}
  8021   }
  8022  
  8023   // Create  the reques t object
  8024   // (This i s still at tached to  ajaxSettin gs for bac kward comp atibility)
  8025   jQuery.aja xSettings. xhr = wind ow.ActiveX Object ?
  8026           /*  Microsoft  failed to  properly
  8027            *  implement  the XMLHt tpRequest  in IE7 (ca n't reques t local fi les),
  8028            *  so we use  the Activ eXObject w hen it is  available
  8029            *  Additiona lly XMLHtt pRequest c an be disa bled in IE 7/IE8 so
  8030            *  we need a  fallback.
  8031            * /
  8032           fu nction() {
  8033                    retu rn !this.i sLocal &&  createStan dardXHR()  || createA ctiveXHR() ;
  8034           }  :
  8035           //  For all o ther brows ers, use t he standar d XMLHttpR equest obj ect
  8036           cr eateStanda rdXHR;
  8037  
  8038   // Determi ne support  propertie s
  8039   (function(  xhr ) {
  8040           jQ uery.exten d( jQuery. support, {
  8041                    ajax : !!xhr,
  8042                    cors : !!xhr &&  ( "withCr edentials"  in xhr )
  8043           }) ;
  8044   })( jQuery .ajaxSetti ngs.xhr()  );
  8045  
  8046   // Create  transport  if the bro wser can p rovide an  xhr
  8047   if ( jQuer y.support. ajax ) {
  8048  
  8049           jQ uery.ajaxT ransport(f unction( s  ) {
  8050                    // C ross domai n only all owed if su pported th rough XMLH ttpRequest
  8051                    if (  !s.crossD omain || j Query.supp ort.cors )  {
  8052  
  8053                             var ca llback;
  8054  
  8055                             return  {
  8056                                      send: fu nction( he aders, com plete ) {
  8057  
  8058                                               // Get a n ew xhr
  8059                                               var xhr =  s.xhr(),
  8060                                                       ha ndle,
  8061                                                       i;
  8062  
  8063                                               // Open th e socket
  8064                                               // Passing  null user name, gene rates a lo gin popup  on Opera ( #2865)
  8065                                               if ( s.use rname ) {
  8066                                                       xh r.open( s. type, s.ur l, s.async , s.userna me, s.pass word );
  8067                                               } else {
  8068                                                       xh r.open( s. type, s.ur l, s.async  );
  8069                                               }
  8070  
  8071                                               // Apply c ustom fiel ds if prov ided
  8072                                               if ( s.xhr Fields ) {
  8073                                                       fo r ( i in s .xhrFields  ) {
  8074                                                                xhr[  i ] = s.x hrFields[  i ];
  8075                                                       }
  8076                                               }
  8077  
  8078                                               // Overrid e mime typ e if neede d
  8079                                               if ( s.mim eType && x hr.overrid eMimeType  ) {
  8080                                                       xh r.override MimeType(  s.mimeType  );
  8081                                               }
  8082  
  8083                                               // X-Reque sted-With  header
  8084                                               // For cro ss-domain  requests,  seeing as  conditions  for a pre flight are
  8085                                               // akin to  a jigsaw  puzzle, we  simply ne ver set it  to be sur e.
  8086                                               // (it can  always be  set on a  per-reques t basis or  even usin g ajaxSetu p)
  8087                                               // For sam e-domain r equests, w on't chang e header i f already  provided.
  8088                                               if ( !s.cr ossDomain  && !header s["X-Reque sted-With" ] ) {
  8089                                                       he aders[ "X- Requested- With" ] =  "XMLHttpRe quest";
  8090                                               }
  8091  
  8092                                               // Need an  extra try /catch for  cross dom ain reques ts in Fire fox 3
  8093                                               try {
  8094                                                       fo r ( i in h eaders ) {
  8095                                                                xhr. setRequest Header( i,  headers[  i ] );
  8096                                                       }
  8097                                               } catch( _  ) {}
  8098  
  8099                                               // Do send  the reque st
  8100                                               // This ma y raise an  exception  which is  actually
  8101                                               // handled  in jQuery .ajax (so  no try/cat ch here)
  8102                                               xhr.send(  ( s.hasCon tent && s. data ) ||  null );
  8103  
  8104                                               // Listene r
  8105                                               callback =  function(  _, isAbor t ) {
  8106  
  8107                                                       va r status,
  8108                                                                stat usText,
  8109                                                                resp onseHeader s,
  8110                                                                resp onses,
  8111                                                                xml;
  8112  
  8113                                                       //  Firefox t hrows exce ptions whe n accessin g properti es
  8114                                                       //  of an xhr  when a ne twork erro r occured
  8115                                                       //  http://he lpful.knob s-dials.co m/index.ph p/Componen t_returned _failure_c ode:_0x800 40111_(NS_ ERROR_NOT_ AVAILABLE)
  8116                                                       tr y {
  8117  
  8118                                                                // W as never c alled and  is aborted  or comple te
  8119                                                                if (  callback  && ( isAbo rt || xhr. readyState  === 4 ) )  {
  8120  
  8121                                                                         // Onl y called o nce
  8122                                                                         callba ck = undef ined;
  8123  
  8124                                                                         // Do  not keep a s active a nymore
  8125                                                                         if ( h andle ) {
  8126                                                                                  xhr.onre adystatech ange = jQu ery.noop;
  8127                                                                                  if ( xhr OnUnloadAb ort ) {
  8128                                                                                           delete xhr Callbacks[  handle ];
  8129                                                                                  }
  8130                                                                         }
  8131  
  8132                                                                         // If  it's an ab ort
  8133                                                                         if ( i sAbort ) {
  8134                                                                                  // Abort  it manual ly if need ed
  8135                                                                                  if ( xhr .readyStat e !== 4 )  {
  8136                                                                                           xhr.abort( );
  8137                                                                                  }
  8138                                                                         } else  {
  8139                                                                                  status =  xhr.statu s;
  8140                                                                                  response Headers =  xhr.getAll ResponseHe aders();
  8141                                                                                  response s = {};
  8142                                                                                  xml = xh r.response XML;
  8143  
  8144                                                                                  // Const ruct respo nse list
  8145                                                                                  if ( xml  && xml.do cumentElem ent /* #49 58 */ ) {
  8146                                                                                           responses. xml = xml;
  8147                                                                                  }
  8148                                                                                  response s.text = x hr.respons eText;
  8149  
  8150                                                                                  // Firef ox throws  an excepti on when ac cessing
  8151                                                                                  // statu sText for  faulty cro ss-domain  requests
  8152                                                                                  try {
  8153                                                                                           statusText  = xhr.sta tusText;
  8154                                                                                  } catch(  e ) {
  8155                                                                                           // We norm alize with  Webkit gi ving an em pty status Text
  8156                                                                                           statusText  = "";
  8157                                                                                  }
  8158  
  8159                                                                                  // Filte r status f or non sta ndard beha viors
  8160  
  8161                                                                                  // If th e request  is local a nd we have  data: ass ume a succ ess
  8162                                                                                  // (succ ess with n o data won 't get not ified, tha t's the be st we
  8163                                                                                  // can d o given cu rrent impl ementation s)
  8164                                                                                  if ( !st atus && s. isLocal &&  !s.crossD omain ) {
  8165                                                                                           status = r esponses.t ext ? 200  : 404;
  8166                                                                                  // IE -  #1450: som etimes ret urns 1223  when it sh ould be 20 4
  8167                                                                                  } else i f ( status  === 1223  ) {
  8168                                                                                           status = 2 04;
  8169                                                                                  }
  8170                                                                         }
  8171                                                                }
  8172                                                       }  catch( fir efoxAccess Exception  ) {
  8173                                                                if (  !isAbort  ) {
  8174                                                                         comple te( -1, fi refoxAcces sException  );
  8175                                                                }
  8176                                                       }
  8177  
  8178                                                       //  Call comp lete if ne eded
  8179                                                       if  ( respons es ) {
  8180                                                                comp lete( stat us, status Text, resp onses, res ponseHeade rs );
  8181                                                       }
  8182                                               };
  8183  
  8184                                               // if we'r e in sync  mode or it 's in cach e
  8185                                               // and has  been retr ieved dire ctly (IE6  & IE7)
  8186                                               // we need  to manual ly fire th e callback
  8187                                               if ( !s.as ync || xhr .readyStat e === 4 )  {
  8188                                                       ca llback();
  8189                                               } else {
  8190                                                       ha ndle = ++x hrId;
  8191                                                       if  ( xhrOnUn loadAbort  ) {
  8192                                                                // C reate the  active xhr s callback s list if  needed
  8193                                                                // a nd attach  the unload  handler
  8194                                                                if (  !xhrCallb acks ) {
  8195                                                                         xhrCal lbacks = { };
  8196                                                                         jQuery ( window ) .unload( x hrOnUnload Abort );
  8197                                                                }
  8198                                                                // A dd to list  of active  xhrs call backs
  8199                                                                xhrC allbacks[  handle ] =  callback;
  8200                                                       }
  8201                                                       xh r.onreadys tatechange  = callbac k;
  8202                                               }
  8203                                      },
  8204  
  8205                                      abort: f unction()  {
  8206                                               if ( callb ack ) {
  8207                                                       ca llback(0,1 );
  8208                                               }
  8209                                      }
  8210                             };
  8211                    }
  8212           }) ;
  8213   }
  8214  
  8215  
  8216  
  8217  
  8218   var elemdi splay = {} ,
  8219           if rame, ifra meDoc,
  8220           rf xtypes = / ^(?:toggle |show|hide )$/,
  8221           rf xnum = /^( [+\-]=)?([ \d+.\-]+)( [a-z%]*)$/ i,
  8222           ti merId,
  8223           fx Attrs = [
  8224                    // h eight anim ations
  8225                    [ "h eight", "m arginTop",  "marginBo ttom", "pa ddingTop",  "paddingB ottom" ],
  8226                    // w idth anima tions
  8227                    [ "w idth", "ma rginLeft",  "marginRi ght", "pad dingLeft",  "paddingR ight" ],
  8228                    // o pacity ani mations
  8229                    [ "o pacity" ]
  8230           ],
  8231           fx Now;
  8232  
  8233   jQuery.fn. extend({
  8234           sh ow: functi on( speed,  easing, c allback )  {
  8235                    var  elem, disp lay;
  8236  
  8237                    if (  speed ||  speed ===  0 ) {
  8238                             return  this.anim ate( genFx ("show", 3 ), speed,  easing, ca llback );
  8239  
  8240                    } el se {
  8241                             for (  var i = 0,  j = this. length; i  < j; i++ )  {
  8242                                      elem = t his[ i ];
  8243  
  8244                                      if ( ele m.style )  {
  8245                                               display =  elem.style .display;
  8246  
  8247                                               // Reset t he inline  display of  this elem ent to lea rn if it i s
  8248                                               // being h idden by c ascaded ru les or not
  8249                                               if ( !jQue ry._data(e lem, "oldd isplay") & & display  === "none"  ) {
  8250                                                       di splay = el em.style.d isplay = " ";
  8251                                               }
  8252  
  8253                                               // Set ele ments whic h have bee n overridd en with di splay: non e
  8254                                               // in a st ylesheet t o whatever  the defau lt browser  style is
  8255                                               // for suc h an eleme nt
  8256                                               if ( displ ay === ""  && jQuery. css(elem,  "display")  === "none " ) {
  8257                                                       jQ uery._data ( elem, "o lddisplay" , defaultD isplay(ele m.nodeName ) );
  8258                                               }
  8259                                      }
  8260                             }
  8261  
  8262                             // Set  the displ ay of most  of the el ements in  a second l oop
  8263                             // to  avoid the  constant r eflow
  8264                             for (  i = 0; i <  j; i++ )  {
  8265                                      elem = t his[ i ];
  8266  
  8267                                      if ( ele m.style )  {
  8268                                               display =  elem.style .display;
  8269  
  8270                                               if ( displ ay === ""  || display  === "none " ) {
  8271                                                       el em.style.d isplay = j Query._dat a( elem, " olddisplay " ) || "";
  8272                                               }
  8273                                      }
  8274                             }
  8275  
  8276                             return  this;
  8277                    }
  8278           },
  8279  
  8280           hi de: functi on( speed,  easing, c allback )  {
  8281                    if (  speed ||  speed ===  0 ) {
  8282                             return  this.anim ate( genFx ("hide", 3 ), speed,  easing, ca llback);
  8283  
  8284                    } el se {
  8285                             var el em, displa y,
  8286                                      i = 0,
  8287                                      j = this .length;
  8288  
  8289                             for (  ; i < j; i ++ ) {
  8290                                      elem = t his[i];
  8291                                      if ( ele m.style )  {
  8292                                               display =  jQuery.css ( elem, "d isplay" );
  8293  
  8294                                               if ( displ ay !== "no ne" && !jQ uery._data ( elem, "o lddisplay"  ) ) {
  8295                                                       jQ uery._data ( elem, "o lddisplay" , display  );
  8296                                               }
  8297                                      }
  8298                             }
  8299  
  8300                             // Set  the displ ay of the  elements i n a second  loop
  8301                             // to  avoid the  constant r eflow
  8302                             for (  i = 0; i <  j; i++ )  {
  8303                                      if ( thi s[i].style  ) {
  8304                                               this[i].st yle.displa y = "none" ;
  8305                                      }
  8306                             }
  8307  
  8308                             return  this;
  8309                    }
  8310           },
  8311  
  8312           //  Save the  old toggle  function
  8313           _t oggle: jQu ery.fn.tog gle,
  8314  
  8315           to ggle: func tion( fn,  fn2, callb ack ) {
  8316                    var  bool = typ eof fn ===  "boolean" ;
  8317  
  8318                    if (  jQuery.is Function(f n) && jQue ry.isFunct ion(fn2) )  {
  8319                             this._ toggle.app ly( this,  arguments  );
  8320  
  8321                    } el se if ( fn  == null | | bool ) {
  8322                             this.e ach(functi on() {
  8323                                      var stat e = bool ?  fn : jQue ry(this).i s(":hidden ");
  8324                                      jQuery(t his)[ stat e ? "show"  : "hide"  ]();
  8325                             });
  8326  
  8327                    } el se {
  8328                             this.a nimate(gen Fx("toggle ", 3), fn,  fn2, call back);
  8329                    }
  8330  
  8331                    retu rn this;
  8332           },
  8333  
  8334           fa deTo: func tion( spee d, to, eas ing, callb ack ) {
  8335                    retu rn this.fi lter(":hid den").css( "opacity",  0).show() .end()
  8336                                               .animate({ opacity: t o}, speed,  easing, c allback);
  8337           },
  8338  
  8339           an imate: fun ction( pro p, speed,  easing, ca llback ) {
  8340                    var  optall = j Query.spee d( speed,  easing, ca llback );
  8341  
  8342                    if (  jQuery.is EmptyObjec t( prop )  ) {
  8343                             return  this.each ( optall.c omplete, [  false ] ) ;
  8344                    }
  8345  
  8346                    // D o not chan ge referen ced proper ties as pe r-property  easing wi ll be lost
  8347                    prop  = jQuery. extend( {} , prop );
  8348  
  8349                    func tion doAni mation() {
  8350                             // XXX  'this' do es not alw ays have a  nodeName  when runni ng the
  8351                             // tes t suite
  8352  
  8353                             if ( o ptall.queu e === fals e ) {
  8354                                      jQuery._ mark( this  );
  8355                             }
  8356  
  8357                             var op t = jQuery .extend( { }, optall  ),
  8358                                      isElemen t = this.n odeType == = 1,
  8359                                      hidden =  isElement  && jQuery (this).is( ":hidden") ,
  8360                                      name, va l, p, e,
  8361                                      parts, s tart, end,  unit,
  8362                                      method;
  8363  
  8364                             // wil l store pe r property  easing an d be used  to determi ne when an  animation  is comple te
  8365                             opt.an imatedProp erties = { };
  8366  
  8367                             for (  p in prop  ) {
  8368  
  8369                                      // prope rty name n ormalizati on
  8370                                      name = j Query.came lCase( p ) ;
  8371                                      if ( p ! == name )  {
  8372                                               prop[ name  ] = prop[  p ];
  8373                                               delete pro p[ p ];
  8374                                      }
  8375  
  8376                                      val = pr op[ name ] ;
  8377  
  8378                                      // easin g resoluti on: per pr operty > o pt.special Easing > o pt.easing  > 'swing'  (default)
  8379                                      if ( jQu ery.isArra y( val ) )  {
  8380                                               opt.animat edProperti es[ name ]  = val[ 1  ];
  8381                                               val = prop [ name ] =  val[ 0 ];
  8382                                      } else {
  8383                                               opt.animat edProperti es[ name ]  = opt.spe cialEasing  && opt.sp ecialEasin g[ name ]  || opt.eas ing || 'sw ing';
  8384                                      }
  8385  
  8386                                      if ( val  === "hide " && hidde n || val = == "show"  && !hidden  ) {
  8387                                               return opt .complete. call( this  );
  8388                                      }
  8389  
  8390                                      if ( isE lement &&  ( name ===  "height"  || name == = "width"  ) ) {
  8391                                               // Make su re that no thing snea ks out
  8392                                               // Record  all 3 over flow attri butes beca use IE doe s not
  8393                                               // change  the overfl ow attribu te when ov erflowX an d
  8394                                               // overflo wY are set  to the sa me value
  8395                                               opt.overfl ow = [ thi s.style.ov erflow, th is.style.o verflowX,  this.style .overflowY  ];
  8396  
  8397                                               // Set dis play prope rty to inl ine-block  for height /width
  8398                                               // animati ons on inl ine elemen ts that ar e having w idth/heigh t animated
  8399                                               if ( jQuer y.css( thi s, "displa y" ) === " inline" &&
  8400                                                                jQue ry.css( th is, "float " ) === "n one" ) {
  8401  
  8402                                                       //  inline-le vel elemen ts accept  inline-blo ck;
  8403                                                       //  block-lev el element s need to  be inline  with layou t
  8404                                                       if  ( !jQuery .support.i nlineBlock NeedsLayou t || defau ltDisplay(  this.node Name ) ===  "inline"  ) {
  8405                                                                this .style.dis play = "in line-block ";
  8406  
  8407                                                       }  else {
  8408                                                                this .style.zoo m = 1;
  8409                                                       }
  8410                                               }
  8411                                      }
  8412                             }
  8413  
  8414                             if ( o pt.overflo w != null  ) {
  8415                                      this.sty le.overflo w = "hidde n";
  8416                             }
  8417  
  8418                             for (  p in prop  ) {
  8419                                      e = new  jQuery.fx(  this, opt , p );
  8420                                      val = pr op[ p ];
  8421  
  8422                                      if ( rfx types.test ( val ) )  {
  8423  
  8424                                               // Tracks  whether to  show or h ide based  on private
  8425                                               // data at tached to  the elemen t
  8426                                               method = j Query._dat a( this, " toggle" +  p ) || ( v al === "to ggle" ? hi dden ? "sh ow" : "hid e" : 0 );
  8427                                               if ( metho d ) {
  8428                                                       jQ uery._data ( this, "t oggle" + p , method = == "show"  ? "hide" :  "show" );
  8429                                                       e[  method ]( );
  8430                                               } else {
  8431                                                       e[  val ]();
  8432                                               }
  8433  
  8434                                      } else {
  8435                                               parts = rf xnum.exec(  val );
  8436                                               start = e. cur();
  8437  
  8438                                               if ( parts  ) {
  8439                                                       en d = parseF loat( part s[2] );
  8440                                                       un it = parts [3] || ( j Query.cssN umber[ p ]  ? "" : "p x" );
  8441  
  8442                                                       //  We need t o compute  starting v alue
  8443                                                       if  ( unit != = "px" ) {
  8444                                                                jQue ry.style(  this, p, ( end || 1)  + unit);
  8445                                                                star t = ( (end  || 1) / e .cur() ) *  start;
  8446                                                                jQue ry.style(  this, p, s tart + uni t);
  8447                                                       }
  8448  
  8449                                                       //  If a +=/- = token wa s provided , we're do ing a rela tive anima tion
  8450                                                       if  ( parts[1 ] ) {
  8451                                                                end  = ( (parts [ 1 ] ===  "-=" ? -1  : 1) * end  ) + start ;
  8452                                                       }
  8453  
  8454                                                       e. custom( st art, end,  unit );
  8455  
  8456                                               } else {
  8457                                                       e. custom( st art, val,  "" );
  8458                                               }
  8459                                      }
  8460                             }
  8461  
  8462                             // For  JS strict  complianc e
  8463                             return  true;
  8464                    }
  8465  
  8466                    retu rn optall. queue ===  false ?
  8467                             this.e ach( doAni mation ) :
  8468                             this.q ueue( opta ll.queue,  doAnimatio n );
  8469           },
  8470  
  8471           st op: functi on( type,  clearQueue , gotoEnd  ) {
  8472                    if (  typeof ty pe !== "st ring" ) {
  8473                             gotoEn d = clearQ ueue;
  8474                             clearQ ueue = typ e;
  8475                             type =  undefined ;
  8476                    }
  8477                    if (  clearQueu e && type  !== false  ) {
  8478                             this.q ueue( type  || "fx",  [] );
  8479                    }
  8480  
  8481                    retu rn this.ea ch(functio n() {
  8482                             var in dex,
  8483                                      hadTimer s = false,
  8484                                      timers =  jQuery.ti mers,
  8485                                      data = j Query._dat a( this );
  8486  
  8487                             // cle ar marker  counters i f we know  they won't  be
  8488                             if ( ! gotoEnd )  {
  8489                                      jQuery._ unmark( tr ue, this ) ;
  8490                             }
  8491  
  8492                             functi on stopQue ue( elem,  data, inde x ) {
  8493                                      var hook s = data[  index ];
  8494                                      jQuery.r emoveData(  elem, ind ex, true ) ;
  8495                                      hooks.st op( gotoEn d );
  8496                             }
  8497  
  8498                             if ( t ype == nul l ) {
  8499                                      for ( in dex in dat a ) {
  8500                                               if ( data[  index ] & & data[ in dex ].stop  && index. indexOf(". run") ===  index.leng th - 4 ) {
  8501                                                       st opQueue( t his, data,  index );
  8502                                               }
  8503                                      }
  8504                             } else  if ( data [ index =  type + ".r un" ] && d ata[ index  ].stop ){
  8505                                      stopQueu e( this, d ata, index  );
  8506                             }
  8507  
  8508                             for (  index = ti mers.lengt h; index-- ; ) {
  8509                                      if ( tim ers[ index  ].elem == = this &&  (type == n ull || tim ers[ index  ].queue = == type) )  {
  8510                                               if ( gotoE nd ) {
  8511  
  8512                                                       //  force the  next step  to be the  last
  8513                                                       ti mers[ inde x ]( true  );
  8514                                               } else {
  8515                                                       ti mers[ inde x ].saveSt ate();
  8516                                               }
  8517                                               hadTimers  = true;
  8518                                               timers.spl ice( index , 1 );
  8519                                      }
  8520                             }
  8521  
  8522                             // sta rt the nex t in the q ueue if th e last ste p wasn't f orced
  8523                             // tim ers curren tly will c all their  complete c allbacks,  which will  dequeue
  8524                             // but  only if t hey were g otoEnd
  8525                             if ( ! ( gotoEnd  && hadTime rs ) ) {
  8526                                      jQuery.d equeue( th is, type ) ;
  8527                             }
  8528                    });
  8529           }
  8530  
  8531   });
  8532  
  8533   // Animati ons create d synchron ously will  run synch ronously
  8534   function c reateFxNow () {
  8535           se tTimeout(  clearFxNow , 0 );
  8536           re turn ( fxN ow = jQuer y.now() );
  8537   }
  8538  
  8539   function c learFxNow( ) {
  8540           fx Now = unde fined;
  8541   }
  8542  
  8543   // Generat e paramete rs to crea te a stand ard animat ion
  8544   function g enFx( type , num ) {
  8545           va r obj = {} ;
  8546  
  8547           jQ uery.each(  fxAttrs.c oncat.appl y([], fxAt trs.slice(  0, num )) , function () {
  8548                    obj[  this ] =  type;
  8549           }) ;
  8550  
  8551           re turn obj;
  8552   }
  8553  
  8554   // Generat e shortcut s for cust om animati ons
  8555   jQuery.eac h({
  8556           sl ideDown: g enFx( "sho w", 1 ),
  8557           sl ideUp: gen Fx( "hide" , 1 ),
  8558           sl ideToggle:  genFx( "t oggle", 1  ),
  8559           fa deIn: { op acity: "sh ow" },
  8560           fa deOut: { o pacity: "h ide" },
  8561           fa deToggle:  { opacity:  "toggle"  }
  8562   }, functio n( name, p rops ) {
  8563           jQ uery.fn[ n ame ] = fu nction( sp eed, easin g, callbac k ) {
  8564                    retu rn this.an imate( pro ps, speed,  easing, c allback );
  8565           };
  8566   });
  8567  
  8568   jQuery.ext end({
  8569           sp eed: funct ion( speed , easing,  fn ) {
  8570                    var  opt = spee d && typeo f speed == = "object"  ? jQuery. extend( {} , speed )  : {
  8571                             comple te: fn ||  !fn && eas ing ||
  8572                                      jQuery.i sFunction(  speed ) & & speed,
  8573                             durati on: speed,
  8574                             easing : fn && ea sing || ea sing && !j Query.isFu nction( ea sing ) &&  easing
  8575                    };
  8576  
  8577                    opt. duration =  jQuery.fx .off ? 0 :  typeof op t.duration  === "numb er" ? opt. duration :
  8578                             opt.du ration in  jQuery.fx. speeds ? j Query.fx.s peeds[ opt .duration  ] : jQuery .fx.speeds ._default;
  8579  
  8580                    // n ormalize o pt.queue -  true/unde fined/null  -> "fx"
  8581                    if (  opt.queue  == null | | opt.queu e === true  ) {
  8582                             opt.qu eue = "fx" ;
  8583                    }
  8584  
  8585                    // Q ueueing
  8586                    opt. old = opt. complete;
  8587  
  8588                    opt. complete =  function(  noUnmark  ) {
  8589                             if ( j Query.isFu nction( op t.old ) )  {
  8590                                      opt.old. call( this  );
  8591                             }
  8592  
  8593                             if ( o pt.queue )  {
  8594                                      jQuery.d equeue( th is, opt.qu eue );
  8595                             } else  if ( noUn mark !== f alse ) {
  8596                                      jQuery._ unmark( th is );
  8597                             }
  8598                    };
  8599  
  8600                    retu rn opt;
  8601           },
  8602  
  8603           ea sing: {
  8604                    line ar: functi on( p, n,  firstNum,  diff ) {
  8605                             return  firstNum  + diff * p ;
  8606                    },
  8607                    swin g: functio n( p, n, f irstNum, d iff ) {
  8608                             return  ( ( -Math .cos( p*Ma th.PI ) /  2 ) + 0.5  ) * diff +  firstNum;
  8609                    }
  8610           },
  8611  
  8612           ti mers: [],
  8613  
  8614           fx : function ( elem, op tions, pro p ) {
  8615                    this .options =  options;
  8616                    this .elem = el em;
  8617                    this .prop = pr op;
  8618  
  8619                    opti ons.orig =  options.o rig || {};
  8620           }
  8621  
  8622   });
  8623  
  8624   jQuery.fx. prototype  = {
  8625           //  Simple fu nction for  setting a  style val ue
  8626           up date: func tion() {
  8627                    if (  this.opti ons.step )  {
  8628                             this.o ptions.ste p.call( th is.elem, t his.now, t his );
  8629                    }
  8630  
  8631                    ( jQ uery.fx.st ep[ this.p rop ] || j Query.fx.s tep._defau lt )( this  );
  8632           },
  8633  
  8634           //  Get the c urrent siz e
  8635           cu r: functio n() {
  8636                    if (  this.elem [ this.pro p ] != nul l && (!thi s.elem.sty le || this .elem.styl e[ this.pr op ] == nu ll) ) {
  8637                             return  this.elem [ this.pro p ];
  8638                    }
  8639  
  8640                    var  parsed,
  8641                             r = jQ uery.css(  this.elem,  this.prop  );
  8642                    // E mpty strin gs, null,  undefined  and "auto"  are conve rted to 0,
  8643                    // c omplex val ues such a s "rotate( 1rad)" are  returned  as is,
  8644                    // s imple valu es such as  "10px" ar e parsed t o Float.
  8645                    retu rn isNaN(  parsed = p arseFloat(  r ) ) ? ! r || r ===  "auto" ?  0 : r : pa rsed;
  8646           },
  8647  
  8648           //  Start an  animation  from one n umber to a nother
  8649           cu stom: func tion( from , to, unit  ) {
  8650                    var  self = thi s,
  8651                             fx = j Query.fx;
  8652  
  8653                    this .startTime  = fxNow | | createFx Now();
  8654                    this .end = to;
  8655                    this .now = thi s.start =  from;
  8656                    this .pos = thi s.state =  0;
  8657                    this .unit = un it || this .unit || (  jQuery.cs sNumber[ t his.prop ]  ? "" : "p x" );
  8658  
  8659                    func tion t( go toEnd ) {
  8660                             return  self.step ( gotoEnd  );
  8661                    }
  8662  
  8663                    t.qu eue = this .options.q ueue;
  8664                    t.el em = this. elem;
  8665                    t.sa veState =  function()  {
  8666                             if ( s elf.option s.hide &&  jQuery._da ta( self.e lem, "fxsh ow" + self .prop ) == = undefine d ) {
  8667                                      jQuery._ data( self .elem, "fx show" + se lf.prop, s elf.start  );
  8668                             }
  8669                    };
  8670  
  8671                    if (  t() && jQ uery.timer s.push(t)  && !timerI d ) {
  8672                             timerI d = setInt erval( fx. tick, fx.i nterval );
  8673                    }
  8674           },
  8675  
  8676           //  Simple 's how' funct ion
  8677           sh ow: functi on() {
  8678                    var  dataShow =  jQuery._d ata( this. elem, "fxs how" + thi s.prop );
  8679  
  8680                    // R emember wh ere we sta rted, so t hat we can  go back t o it later
  8681                    this .options.o rig[ this. prop ] = d ataShow ||  jQuery.st yle( this. elem, this .prop );
  8682                    this .options.s how = true ;
  8683  
  8684                    // B egin the a nimation
  8685                    // M ake sure t hat we sta rt at a sm all width/ height to  avoid any  flash of c ontent
  8686                    if (  dataShow  !== undefi ned ) {
  8687                             // Thi s show is  picking up  where a p revious hi de or show  left off
  8688                             this.c ustom( thi s.cur(), d ataShow );
  8689                    } el se {
  8690                             this.c ustom( thi s.prop ===  "width" | | this.pro p === "hei ght" ? 1 :  0, this.c ur() );
  8691                    }
  8692  
  8693                    // S tart by sh owing the  element
  8694                    jQue ry( this.e lem ).show ();
  8695           },
  8696  
  8697           //  Simple 'h ide' funct ion
  8698           hi de: functi on() {
  8699                    // R emember wh ere we sta rted, so t hat we can  go back t o it later
  8700                    this .options.o rig[ this. prop ] = j Query._dat a( this.el em, "fxsho w" + this. prop ) ||  jQuery.sty le( this.e lem, this. prop );
  8701                    this .options.h ide = true ;
  8702  
  8703                    // B egin the a nimation
  8704                    this .custom( t his.cur(),  0 );
  8705           },
  8706  
  8707           //  Each step  of an ani mation
  8708           st ep: functi on( gotoEn d ) {
  8709                    var  p, n, comp lete,
  8710                             t = fx Now || cre ateFxNow() ,
  8711                             done =  true,
  8712                             elem =  this.elem ,
  8713                             option s = this.o ptions;
  8714  
  8715                    if (  gotoEnd | | t >= opt ions.durat ion + this .startTime  ) {
  8716                             this.n ow = this. end;
  8717                             this.p os = this. state = 1;
  8718                             this.u pdate();
  8719  
  8720                             option s.animated Properties [ this.pro p ] = true ;
  8721  
  8722                             for (  p in optio ns.animate dPropertie s ) {
  8723                                      if ( opt ions.anima tedPropert ies[ p ] ! == true )  {
  8724                                               done = fal se;
  8725                                      }
  8726                             }
  8727  
  8728                             if ( d one ) {
  8729                                      // Reset  the overf low
  8730                                      if ( opt ions.overf low != nul l && !jQue ry.support .shrinkWra pBlocks )  {
  8731  
  8732                                               jQuery.eac h( [ "", " X", "Y" ],  function(  index, va lue ) {
  8733                                                       el em.style[  "overflow"  + value ]  = options .overflow[  index ];
  8734                                               });
  8735                                      }
  8736  
  8737                                      // Hide  the elemen t if the " hide" oper ation was  done
  8738                                      if ( opt ions.hide  ) {
  8739                                               jQuery( el em ).hide( );
  8740                                      }
  8741  
  8742                                      // Reset  the prope rties, if  the item h as been hi dden or sh own
  8743                                      if ( opt ions.hide  || options .show ) {
  8744                                               for ( p in  options.a nimatedPro perties )  {
  8745                                                       jQ uery.style ( elem, p,  options.o rig[ p ] ) ;
  8746                                                       jQ uery.remov eData( ele m, "fxshow " + p, tru e );
  8747                                                       //  Toggle da ta is no l onger need ed
  8748                                                       jQ uery.remov eData( ele m, "toggle " + p, tru e );
  8749                                               }
  8750                                      }
  8751  
  8752                                      // Execu te the com plete func tion
  8753                                      // in th e event th at the com plete func tion throw s an excep tion
  8754                                      // we mu st ensure  it won't b e called t wice. #568 4
  8755  
  8756                                      complete  = options .complete;
  8757                                      if ( com plete ) {
  8758  
  8759                                               options.co mplete = f alse;
  8760                                               complete.c all( elem  );
  8761                                      }
  8762                             }
  8763  
  8764                             return  false;
  8765  
  8766                    } el se {
  8767                             // cla ssical eas ing cannot  be used w ith an Inf inity dura tion
  8768                             if ( o ptions.dur ation == I nfinity )  {
  8769                                      this.now  = t;
  8770                             } else  {
  8771                                      n = t -  this.start Time;
  8772                                      this.sta te = n / o ptions.dur ation;
  8773  
  8774                                      // Perfo rm the eas ing functi on, defaul ts to swin g
  8775                                      this.pos  = jQuery. easing[ op tions.anim atedProper ties[this. prop] ]( t his.state,  n, 0, 1,  options.du ration );
  8776                                      this.now  = this.st art + ( (t his.end -  this.start ) * this.p os );
  8777                             }
  8778                             // Per form the n ext step o f the anim ation
  8779                             this.u pdate();
  8780                    }
  8781  
  8782                    retu rn true;
  8783           }
  8784   };
  8785  
  8786   jQuery.ext end( jQuer y.fx, {
  8787           ti ck: functi on() {
  8788                    var  timer,
  8789                             timers  = jQuery. timers,
  8790                             i = 0;
  8791  
  8792                    for  ( ; i < ti mers.lengt h; i++ ) {
  8793                             timer  = timers[  i ];
  8794                             // Che cks the ti mer has no t already  been remov ed
  8795                             if ( ! timer() &&  timers[ i  ] === tim er ) {
  8796                                      timers.s plice( i-- , 1 );
  8797                             }
  8798                    }
  8799  
  8800                    if (  !timers.l ength ) {
  8801                             jQuery .fx.stop() ;
  8802                    }
  8803           },
  8804  
  8805           in terval: 13 ,
  8806  
  8807           st op: functi on() {
  8808                    clea rInterval(  timerId ) ;
  8809                    time rId = null ;
  8810           },
  8811  
  8812           sp eeds: {
  8813                    slow : 600,
  8814                    fast : 200,
  8815                    // D efault spe ed
  8816                    _def ault: 400
  8817           },
  8818  
  8819           st ep: {
  8820                    opac ity: funct ion( fx )  {
  8821                             jQuery .style( fx .elem, "op acity", fx .now );
  8822                    },
  8823  
  8824                    _def ault: func tion( fx )  {
  8825                             if ( f x.elem.sty le && fx.e lem.style[  fx.prop ]  != null )  {
  8826                                      fx.elem. style[ fx. prop ] = f x.now + fx .unit;
  8827                             } else  {
  8828                                      fx.elem[  fx.prop ]  = fx.now;
  8829                             }
  8830                    }
  8831           }
  8832   });
  8833  
  8834   // Adds wi dth/height  step func tions
  8835   // Do not  set anythi ng below 0
  8836   jQuery.eac h([ "width ", "height " ], funct ion( i, pr op ) {
  8837           jQ uery.fx.st ep[ prop ]  = functio n( fx ) {
  8838                    jQue ry.style(  fx.elem, p rop, Math. max(0, fx. now) + fx. unit );
  8839           };
  8840   });
  8841  
  8842   if ( jQuer y.expr &&  jQuery.exp r.filters  ) {
  8843           jQ uery.expr. filters.an imated = f unction( e lem ) {
  8844                    retu rn jQuery. grep(jQuer y.timers,  function(  fn ) {
  8845                             return  elem ===  fn.elem;
  8846                    }).l ength;
  8847           };
  8848   }
  8849  
  8850   // Try to  restore th e default  display va lue of an  element
  8851   function d efaultDisp lay( nodeN ame ) {
  8852  
  8853           if  ( !elemdi splay[ nod eName ] )  {
  8854  
  8855                    var  body = doc ument.body ,
  8856                             elem =  jQuery( " <" + nodeN ame + ">"  ).appendTo ( body ),
  8857                             displa y = elem.c ss( "displ ay" );
  8858                    elem .remove();
  8859  
  8860                    // I f the simp le way fai ls,
  8861                    // g et element 's real de fault disp lay by att aching it  to a temp  iframe
  8862                    if (  display = == "none"  || display  === "" )  {
  8863                             // No  iframe to  use yet, s o create i t
  8864                             if ( ! iframe ) {
  8865                                      iframe =  document. createElem ent( "ifra me" );
  8866                                      iframe.f rameBorder  = iframe. width = if rame.heigh t = 0;
  8867                             }
  8868  
  8869                             body.a ppendChild ( iframe ) ;
  8870  
  8871                             // Cre ate a cach eable copy  of the if rame docum ent on fir st call.
  8872                             // IE  and Opera  will allow  us to reu se the ifr ameDoc wit hout re-wr iting the  fake HTML
  8873                             // doc ument to i t; WebKit  & Firefox  won't allo w reusing  the iframe  document.
  8874                             if ( ! iframeDoc  || !iframe .createEle ment ) {
  8875                                      iframeDo c = ( ifra me.content Window ||  iframe.con tentDocume nt ).docum ent;
  8876                                      iframeDo c.write( (  document. compatMode  === "CSS1 Compat" ?  "<!doctype  html>" :  "" ) + "<h tml><body> " );
  8877                                      iframeDo c.close();
  8878                             }
  8879  
  8880                             elem =  iframeDoc .createEle ment( node Name );
  8881  
  8882                             iframe Doc.body.a ppendChild ( elem );
  8883  
  8884                             displa y = jQuery .css( elem , "display " );
  8885                             body.r emoveChild ( iframe ) ;
  8886                    }
  8887  
  8888                    // S tore the c orrect def ault displ ay
  8889                    elem display[ n odeName ]  = display;
  8890           }
  8891  
  8892           re turn elemd isplay[ no deName ];
  8893   }
  8894  
  8895  
  8896  
  8897  
  8898   var rtable  = /^t(?:a ble|d|h)$/ i,
  8899           rr oot = /^(? :body|html )$/i;
  8900  
  8901   if ( "getB oundingCli entRect" i n document .documentE lement ) {
  8902           jQ uery.fn.of fset = fun ction( opt ions ) {
  8903                    var  elem = thi s[0], box;
  8904  
  8905                    if (  options )  {
  8906                             return  this.each (function(  i ) {
  8907                                      jQuery.o ffset.setO ffset( thi s, options , i );
  8908                             });
  8909                    }
  8910  
  8911                    if (  !elem ||  !elem.owne rDocument  ) {
  8912                             return  null;
  8913                    }
  8914  
  8915                    if (  elem ===  elem.owner Document.b ody ) {
  8916                             return  jQuery.of fset.bodyO ffset( ele m );
  8917                    }
  8918  
  8919                    try  {
  8920                             box =  elem.getBo undingClie ntRect();
  8921                    } ca tch(e) {}
  8922  
  8923                    var  doc = elem .ownerDocu ment,
  8924                             docEle m = doc.do cumentElem ent;
  8925  
  8926                    // M ake sure w e're not d ealing wit h a discon nected DOM  node
  8927                    if (  !box || ! jQuery.con tains( doc Elem, elem  ) ) {
  8928                             return  box ? { t op: box.to p, left: b ox.left }  : { top: 0 , left: 0  };
  8929                    }
  8930  
  8931                    var  body = doc .body,
  8932                             win =  getWindow( doc),
  8933                             client Top  = doc Elem.clien tTop  || b ody.client Top  || 0,
  8934                             client Left = doc Elem.clien tLeft || b ody.client Left || 0,
  8935                             scroll Top  = win .pageYOffs et || jQue ry.support .boxModel  && docElem .scrollTop   || body. scrollTop,
  8936                             scroll Left = win .pageXOffs et || jQue ry.support .boxModel  && docElem .scrollLef t || body. scrollLeft ,
  8937                             top  =  box.top   + scrollTo p  - clien tTop,
  8938                             left =  box.left  + scrollLe ft - clien tLeft;
  8939  
  8940                    retu rn { top:  top, left:  left };
  8941           };
  8942  
  8943   } else {
  8944           jQ uery.fn.of fset = fun ction( opt ions ) {
  8945                    var  elem = thi s[0];
  8946  
  8947                    if (  options )  {
  8948                             return  this.each (function(  i ) {
  8949                                      jQuery.o ffset.setO ffset( thi s, options , i );
  8950                             });
  8951                    }
  8952  
  8953                    if (  !elem ||  !elem.owne rDocument  ) {
  8954                             return  null;
  8955                    }
  8956  
  8957                    if (  elem ===  elem.owner Document.b ody ) {
  8958                             return  jQuery.of fset.bodyO ffset( ele m );
  8959                    }
  8960  
  8961                    var  computedSt yle,
  8962                             offset Parent = e lem.offset Parent,
  8963                             prevOf fsetParent  = elem,
  8964                             doc =  elem.owner Document,
  8965                             docEle m = doc.do cumentElem ent,
  8966                             body =  doc.body,
  8967                             defaul tView = do c.defaultV iew,
  8968                             prevCo mputedStyl e = defaul tView ? de faultView. getCompute dStyle( el em, null )  : elem.cu rrentStyle ,
  8969                             top =  elem.offse tTop,
  8970                             left =  elem.offs etLeft;
  8971  
  8972                    whil e ( (elem  = elem.par entNode) & & elem !==  body && e lem !== do cElem ) {
  8973                             if ( j Query.supp ort.fixedP osition &&  prevCompu tedStyle.p osition == = "fixed"  ) {
  8974                                      break;
  8975                             }
  8976  
  8977                             comput edStyle =  defaultVie w ? defaul tView.getC omputedSty le(elem, n ull) : ele m.currentS tyle;
  8978                             top  - = elem.scr ollTop;
  8979                             left - = elem.scr ollLeft;
  8980  
  8981                             if ( e lem === of fsetParent  ) {
  8982                                      top  +=  elem.offse tTop;
  8983                                      left +=  elem.offse tLeft;
  8984  
  8985                                      if ( jQu ery.suppor t.doesNotA ddBorder & & !(jQuery .support.d oesAddBord erForTable AndCells & & rtable.t est(elem.n odeName))  ) {
  8986                                               top  += pa rseFloat(  computedSt yle.border TopWidth   ) || 0;
  8987                                               left += pa rseFloat(  computedSt yle.border LeftWidth  ) || 0;
  8988                                      }
  8989  
  8990                                      prevOffs etParent =  offsetPar ent;
  8991                                      offsetPa rent = ele m.offsetPa rent;
  8992                             }
  8993  
  8994                             if ( j Query.supp ort.subtra ctsBorderF orOverflow NotVisible  && comput edStyle.ov erflow !==  "visible"  ) {
  8995                                      top  +=  parseFloat ( computed Style.bord erTopWidth   ) || 0;
  8996                                      left +=  parseFloat ( computed Style.bord erLeftWidt h ) || 0;
  8997                             }
  8998  
  8999                             prevCo mputedStyl e = comput edStyle;
  9000                    }
  9001  
  9002                    if (  prevCompu tedStyle.p osition == = "relativ e" || prev ComputedSt yle.positi on === "st atic" ) {
  9003                             top  + = body.off setTop;
  9004                             left + = body.off setLeft;
  9005                    }
  9006  
  9007                    if (  jQuery.su pport.fixe dPosition  && prevCom putedStyle .position  === "fixed " ) {
  9008                             top  + = Math.max ( docElem. scrollTop,  body.scro llTop );
  9009                             left + = Math.max ( docElem. scrollLeft , body.scr ollLeft );
  9010                    }
  9011  
  9012                    retu rn { top:  top, left:  left };
  9013           };
  9014   }
  9015  
  9016   jQuery.off set = {
  9017  
  9018           bo dyOffset:  function(  body ) {
  9019                    var  top = body .offsetTop ,
  9020                             left =  body.offs etLeft;
  9021  
  9022                    if (  jQuery.su pport.does NotInclude MarginInBo dyOffset )  {
  9023                             top  + = parseFlo at( jQuery .css(body,  "marginTo p") ) || 0 ;
  9024                             left + = parseFlo at( jQuery .css(body,  "marginLe ft") ) ||  0;
  9025                    }
  9026  
  9027                    retu rn { top:  top, left:  left };
  9028           },
  9029  
  9030           se tOffset: f unction( e lem, optio ns, i ) {
  9031                    var  position =  jQuery.cs s( elem, " position"  );
  9032  
  9033                    // s et positio n first, i n-case top /left are  set even o n static e lem
  9034                    if (  position  === "stati c" ) {
  9035                             elem.s tyle.posit ion = "rel ative";
  9036                    }
  9037  
  9038                    var  curElem =  jQuery( el em ),
  9039                             curOff set = curE lem.offset (),
  9040                             curCSS Top = jQue ry.css( el em, "top"  ),
  9041                             curCSS Left = jQu ery.css( e lem, "left " ),
  9042                             calcul atePositio n = ( posi tion === " absolute"  || positio n === "fix ed" ) && j Query.inAr ray("auto" , [curCSST op, curCSS Left]) > - 1,
  9043                             props  = {}, curP osition =  {}, curTop , curLeft;
  9044  
  9045                    // n eed to be  able to ca lculate po sition if  either top  or left i s auto and  position  is either  absolute o r fixed
  9046                    if (  calculate Position )  {
  9047                             curPos ition = cu rElem.posi tion();
  9048                             curTop  = curPosi tion.top;
  9049                             curLef t = curPos ition.left ;
  9050                    } el se {
  9051                             curTop  = parseFl oat( curCS STop ) ||  0;
  9052                             curLef t = parseF loat( curC SSLeft ) | | 0;
  9053                    }
  9054  
  9055                    if (  jQuery.is Function(  options )  ) {
  9056                             option s = option s.call( el em, i, cur Offset );
  9057                    }
  9058  
  9059                    if (  options.t op != null  ) {
  9060                             props. top = ( op tions.top  - curOffse t.top ) +  curTop;
  9061                    }
  9062                    if (  options.l eft != nul l ) {
  9063                             props. left = ( o ptions.lef t - curOff set.left )  + curLeft ;
  9064                    }
  9065  
  9066                    if (  "using" i n options  ) {
  9067                             option s.using.ca ll( elem,  props );
  9068                    } el se {
  9069                             curEle m.css( pro ps );
  9070                    }
  9071           }
  9072   };
  9073  
  9074  
  9075   jQuery.fn. extend({
  9076  
  9077           po sition: fu nction() {
  9078                    if (  !this[0]  ) {
  9079                             return  null;
  9080                    }
  9081  
  9082                    var  elem = thi s[0],
  9083  
  9084                    // G et *real*  offsetPare nt
  9085                    offs etParent =  this.offs etParent() ,
  9086  
  9087                    // G et correct  offsets
  9088                    offs et       =  this.offs et(),
  9089                    pare ntOffset =  rroot.tes t(offsetPa rent[0].no deName) ?  { top: 0,  left: 0 }  : offsetPa rent.offse t();
  9090  
  9091                    // S ubtract el ement marg ins
  9092                    // n ote: when  an element  has margi n: auto th e offsetLe ft and mar ginLeft
  9093                    // a re the sam e in Safar i causing  offset.lef t to incor rectly be  0
  9094                    offs et.top  -=  parseFloa t( jQuery. css(elem,  "marginTop ") ) || 0;
  9095                    offs et.left -=  parseFloa t( jQuery. css(elem,  "marginLef t") ) || 0 ;
  9096  
  9097                    // A dd offsetP arent bord ers
  9098                    pare ntOffset.t op  += par seFloat( j Query.css( offsetPare nt[0], "bo rderTopWid th") ) ||  0;
  9099                    pare ntOffset.l eft += par seFloat( j Query.css( offsetPare nt[0], "bo rderLeftWi dth") ) ||  0;
  9100  
  9101                    // S ubtract th e two offs ets
  9102                    retu rn {
  9103                             top:   offset.top   - parent Offset.top ,
  9104                             left:  offset.lef t - parent Offset.lef t
  9105                    };
  9106           },
  9107  
  9108           of fsetParent : function () {
  9109                    retu rn this.ma p(function () {
  9110                             var of fsetParent  = this.of fsetParent  || docume nt.body;
  9111                             while  ( offsetPa rent && (! rroot.test (offsetPar ent.nodeNa me) && jQu ery.css(of fsetParent , "positio n") === "s tatic") )  {
  9112                                      offsetPa rent = off setParent. offsetPare nt;
  9113                             }
  9114                             return  offsetPar ent;
  9115                    });
  9116           }
  9117   });
  9118  
  9119  
  9120   // Create  scrollLeft  and scrol lTop metho ds
  9121   jQuery.eac h( ["Left" , "Top"],  function(  i, name )  {
  9122           va r method =  "scroll"  + name;
  9123  
  9124           jQ uery.fn[ m ethod ] =  function(  val ) {
  9125                    var  elem, win;
  9126  
  9127                    if (  val === u ndefined )  {
  9128                             elem =  this[ 0 ] ;
  9129  
  9130                             if ( ! elem ) {
  9131                                      return n ull;
  9132                             }
  9133  
  9134                             win =  getWindow(  elem );
  9135  
  9136                             // Ret urn the sc roll offse t
  9137                             return  win ? ("p ageXOffset " in win)  ? win[ i ?  "pageYOff set" : "pa geXOffset"  ] :
  9138                                      jQuery.s upport.box Model && w in.documen t.document Element[ m ethod ] ||
  9139                                               win.docume nt.body[ m ethod ] :
  9140                                      elem[ me thod ];
  9141                    }
  9142  
  9143                    // S et the scr oll offset
  9144                    retu rn this.ea ch(functio n() {
  9145                             win =  getWindow(  this );
  9146  
  9147                             if ( w in ) {
  9148                                      win.scro llTo(
  9149                                               !i ? val :  jQuery( w in ).scrol lLeft(),
  9150                                                i ? val :  jQuery( w in ).scrol lTop()
  9151                                      );
  9152  
  9153                             } else  {
  9154                                      this[ me thod ] = v al;
  9155                             }
  9156                    });
  9157           };
  9158   });
  9159  
  9160   function g etWindow(  elem ) {
  9161           re turn jQuer y.isWindow ( elem ) ?
  9162                    elem  :
  9163                    elem .nodeType  === 9 ?
  9164                             elem.d efaultView  || elem.p arentWindo w :
  9165                             false;
  9166   }
  9167  
  9168  
  9169  
  9170  
  9171   // Create  width, hei ght, inner Height, in nerWidth,  outerHeigh t and oute rWidth met hods
  9172   jQuery.eac h([ "Heigh t", "Width " ], funct ion( i, na me ) {
  9173  
  9174           va r type = n ame.toLowe rCase();
  9175  
  9176           //  innerHeig ht and inn erWidth
  9177           jQ uery.fn[ " inner" + n ame ] = fu nction() {
  9178                    var  elem = thi s[0];
  9179                    retu rn elem ?
  9180                             elem.s tyle ?
  9181                             parseF loat( jQue ry.css( el em, type,  "padding"  ) ) :
  9182                             this[  type ]() :
  9183                             null;
  9184           };
  9185  
  9186           //  outerHeig ht and out erWidth
  9187           jQ uery.fn[ " outer" + n ame ] = fu nction( ma rgin ) {
  9188                    var  elem = thi s[0];
  9189                    retu rn elem ?
  9190                             elem.s tyle ?
  9191                             parseF loat( jQue ry.css( el em, type,  margin ? " margin" :  "border" )  ) :
  9192                             this[  type ]() :
  9193                             null;
  9194           };
  9195  
  9196           jQ uery.fn[ t ype ] = fu nction( si ze ) {
  9197                    // G et window  width or h eight
  9198                    var  elem = thi s[0];
  9199                    if (  !elem ) {
  9200                             return  size == n ull ? null  : this;
  9201                    }
  9202  
  9203                    if (  jQuery.is Function(  size ) ) {
  9204                             return  this.each (function(  i ) {
  9205                                      var self  = jQuery(  this );
  9206                                      self[ ty pe ]( size .call( thi s, i, self [ type ]()  ) );
  9207                             });
  9208                    }
  9209  
  9210                    if (  jQuery.is Window( el em ) ) {
  9211                             // Eve ryone else  use docum ent.docume ntElement  or documen t.body dep ending on  Quirks vs  Standards  mode
  9212                             // 3rd  condition  allows No kia suppor t, as it s upports th e docElem  prop but n ot CSS1Com pat
  9213                             var do cElemProp  = elem.doc ument.docu mentElemen t[ "client " + name ] ,
  9214                                      body = e lem.docume nt.body;
  9215                             return  elem.docu ment.compa tMode ===  "CSS1Compa t" && docE lemProp ||
  9216                                      body &&  body[ "cli ent" + nam e ] || doc ElemProp;
  9217  
  9218                    // G et documen t width or  height
  9219                    } el se if ( el em.nodeTyp e === 9 )  {
  9220                             // Eit her scroll [Width/Hei ght] or of fset[Width /Height],  whichever  is greater
  9221                             return  Math.max(
  9222                                      elem.doc umentEleme nt["client " + name],
  9223                                      elem.bod y["scroll"  + name],  elem.docum entElement ["scroll"  + name],
  9224                                      elem.bod y["offset"  + name],  elem.docum entElement ["offset"  + name]
  9225                             );
  9226  
  9227                    // G et or set  width or h eight on t he element
  9228                    } el se if ( si ze === und efined ) {
  9229                             var or ig = jQuer y.css( ele m, type ),
  9230                                      ret = pa rseFloat(  orig );
  9231  
  9232                             return  jQuery.is Numeric( r et ) ? ret  : orig;
  9233  
  9234                    // S et the wid th or heig ht on the  element (d efault to  pixels if  value is u nitless)
  9235                    } el se {
  9236                             return  this.css(  type, typ eof size = == "string " ? size :  size + "p x" );
  9237                    }
  9238           };
  9239  
  9240   });
  9241  
  9242  
  9243  
  9244  
  9245   // Expose  jQuery to  the global  object
  9246   window.jQu ery = wind ow.$ = jQu ery;
  9247  
  9248   // Expose  jQuery as  an AMD mod ule, but o nly for AM D loaders  that
  9249   // underst and the is sues with  loading mu ltiple ver sions of j Query
  9250   // in a pa ge that al l might ca ll define( ). The loa der will i ndicate
  9251   // they ha ve special  allowance s for mult iple jQuer y versions  by
  9252   // specify ing define .amd.jQuer y = true.  Register a s a named  module,
  9253   // since j Query can  be concate nated with  other fil es that ma y use defi ne,
  9254   // but not  use a pro per concat enation sc ript that  understand s anonymou s
  9255   // AMD mod ules. A na med AMD is  safest an d most rob ust way to  register.
  9256   // Lowerca se jquery  is used be cause AMD  module nam es are der ived from
  9257   // file na mes, and j Query is n ormally de livered in  a lowerca se file na me.
  9258   // Do this  after cre ating the  global so  that if an  AMD modul e wants to  call
  9259   // noConfl ict to hid e this ver sion of jQ uery, it w ill work.
  9260   if ( typeo f define = == "functi on" && def ine.amd &&  define.am d.jQuery )  {
  9261           de fine( "jqu ery", [],  function ( ) { return  jQuery; }  );
  9262   }
  9263  
  9264  
  9265  
  9266   })( window  );
  9267   if (!this. JSON) { th is.JSON =  {}; } (fun ction () {  function  f(n) { ret urn n < 10  ? '0' + n  : n; } if  (typeof D ate.protot ype.toJSON  !== 'func tion') { D ate.protot ype.toJSON  = functio n (key) {  return isF inite(this .valueOf() ) ? this.g etUTCFullY ear() + '- ' + f(this .getUTCMon th() + 1)  + '-' + f( this.getUT CDate()) +  'T' + f(t his.getUTC Hours()) +  ':' + f(t his.getUTC Minutes())  + ':' + f (this.getU TCSeconds( )) + 'Z' :  null; };  String.pro totype.toJ SON = Numb er.prototy pe.toJSON  = Boolean. prototype. toJSON = f unction (k ey) { retu rn this.va lueOf(); } ; } var cx  = /[\u000 0\u00ad\u0 600-\u0604 \u070f\u17 b4\u17b5\u 200c-\u200 f\u2028-\u 202f\u2060 -\u206f\uf eff\ufff0- \uffff]/g,  escapable  = /[\\\"\ x00-\x1f\x 7f-\x9f\u0 0ad\u0600- \u0604\u07 0f\u17b4\u 17b5\u200c -\u200f\u2 028-\u202f \u2060-\u2 06f\ufeff\ ufff0-\uff ff]/g, gap , indent,  meta = { ' \b': '\\b' , '\t': '\ \t', '\n':  '\\n', '\ f': '\\f',  '\r': '\\ r', '"': ' \\"', '\\' : '\\\\' } , rep; fun ction quot e(string)  { escapabl e.lastInde x = 0; ret urn escapa ble.test(s tring) ? ' "' + strin g.replace( escapable,  function  (a) { var  c = meta[a ]; return  typeof c = == 'string ' ? c : '\ \u' + ('00 00' + a.ch arCodeAt(0 ).toString (16)).slic e(-4); })  + '"' : '" ' + string  + '"'; }  function s tr(key, ho lder) { va r i, k, v,  length, m ind = gap,  partial,  value = ho lder[key];  if (value  && typeof  value ===  'object'  && typeof  value.toJS ON === 'fu nction') {  value = v alue.toJSO N(key); }  if (typeof  rep === ' function')  { value =  rep.call( holder, ke y, value);  } switch  (typeof va lue) { cas e 'string' : return q uote(value ); case 'n umber': re turn isFin ite(value)  ? String( value) : ' null'; cas e 'boolean ': case 'n ull': retu rn String( value); ca se 'object ': if (!va lue) { ret urn 'null' ; } gap +=  indent; p artial = [ ]; if (Obj ect.protot ype.toStri ng.apply(v alue) ===  '[object A rray]') {  length = v alue.lengt h; for (i  = 0; i < l ength; i + = 1) { par tial[i] =  str(i, val ue) || 'nu ll'; } v =  partial.l ength ===  0 ? '[]' :  gap ? '[\ n' + gap +  partial.j oin(',\n'  + gap) + ' \n' + mind  + ']' : ' [' + parti al.join(', ') + ']';  gap = mind ; return v ; } if (re p && typeo f rep ===  'object')  { length =  rep.lengt h; for (i  = 0; i < l ength; i + = 1) { k =  rep[i]; i f (typeof  k === 'str ing') { v  = str(k, v alue); if  (v) { part ial.push(q uote(k) +  (gap ? ':  ' : ':') +  v); } } }  } else {  for (k in  value) { i f (Object. hasOwnProp erty.call( value, k))  { v = str (k, value) ; if (v) {  partial.p ush(quote( k) + (gap  ? ': ' : ' :') + v);  } } } } v  = partial. length ===  0 ? '{}'  : gap ? '{ \n' + gap  + partial. join(',\n'  + gap) +  '\n' + min d + '}' :  '{' + part ial.join(' ,') + '}';  gap = min d; return  v; } } if  (typeof JS ON.stringi fy !== 'fu nction') {  JSON.stri ngify = fu nction (va lue, repla cer, space ) { var i;  gap = '';  indent =  ''; if (ty peof space  === 'numb er') { for  (i = 0; i  < space;  i += 1) {  indent +=  ' '; } } e lse if (ty peof space  === 'stri ng') { ind ent = spac e; } rep =  replacer;  if (repla cer && typ eof replac er !== 'fu nction' &&  (typeof r eplacer != = 'object'  || typeof  replacer. length !==  'number') ) { throw  new Error( 'JSON.stri ngify'); }  return st r('', { '' : value }) ; }; } if  (typeof JS ON.parse ! == 'functi on') { JSO N.parse =  function ( text, revi ver) { var  j; functi on walk(ho lder, key)  { var k,  v, value =  holder[ke y]; if (va lue && typ eof value  === 'objec t') { for  (k in valu e) { if (O bject.hasO wnProperty .call(valu e, k)) { v  = walk(va lue, k); i f (v !== u ndefined)  { value[k]  = v; } el se { delet e value[k] ; } } } }  return rev iver.call( holder, ke y, value);  } text =  String(tex t); cx.las tIndex = 0 ; if (cx.t est(text))  { text =  text.repla ce(cx, fun ction (a)  { return ' \\u' + ('0 000' + a.c harCodeAt( 0).toStrin g(16)).sli ce(-4); }) ; } if (/^ [\],:{}\s] *$/.test(t ext.replac e(/\\(?:[" \\\/bfnrt] |u[0-9a-fA -F]{4})/g,  '@').repl ace(/"[^"\ \\n\r]*"|t rue|false| null|-?\d+ (?:\.\d*)? (?:[eE][+\ -]?\d+)?/g , ']').rep lace(/(?:^ |:|,)(?:\s *\[)+/g, ' '))) { j =  eval('('  + text + ' )'); retur n typeof r eviver ===  'function ' ? walk({  '': j },  '') : j; }  throw new  SyntaxErr or('JSON.p arse'); };  } }());
  9268   /*globales  Xrm, $ */
  9269  
  9270   ///
  9271   /// AlfaPe ople CRM 2 011 CrmRes tKit
  9272   ///
  9273   /// Based  on 'MSCRM4  Web Servi ce Toolkit  for JavaS cript v2.1 ' (http:// crmtoolkit .codeplex. com/releas es/view/48 329)
  9274   /// and Xr mSvcTookit  'http://x rmsvctoolk it.codeple x.com/
  9275   ///
  9276  
  9277   /// Credit s:
  9278   ///     Da niel Cai ( getClientU rl, associ ate, disas sociate)
  9279   ///     Ma tt (https: //www.code plex.com/s ite/users/ view/MattM att)
  9280   ///
  9281   /// @autho r:
  9282   ///     Da niel Rene  Thul, drt@ alfapeople .com
  9283   ///
  9284   /// @versi on:
  9285   ///     2. 6.1
  9286   ///
  9287   /// requir es (jquery .1.7.2.js,  JSON2.js)
  9288   ///
  9289   var CrmRes tKit = (fu nction (wi ndow, docu ment, unde fined) {
  9290       'use s trict';
  9291  
  9292       ///
  9293       /// Pr ivate memb ers
  9294       ///
  9295       var OD ATA_ENDPOI NT = "/XRM Services/2 011/Organi zationData .svc",
  9296           ve rsion = '2 .6.0';
  9297  
  9298       ///
  9299       /// Pr ivate func tion to th e context  object.
  9300       ///
  9301       functi on getCont ext() {
  9302  
  9303           if  (typeof G etGlobalCo ntext !==  "undefined ") {
  9304                /*ignore  jslint st art*/
  9305                return G etGlobalCo ntext();
  9306                /*ignore  jslint en d*/
  9307  
  9308           }
  9309           el se {
  9310  
  9311                if (type of Xrm !==  "undefine d") {
  9312                    retu rn Xrm.Pag e.context;
  9313                }
  9314                else {
  9315  
  9316                    thro w new Erro r("Context  is not av ailable.") ;
  9317                }
  9318           }
  9319       }
  9320  
  9321       ///
  9322       /// Pr ivate func tion to re turn the s erver URL  from the c ontext
  9323       ///
  9324       functi on getClie ntUrl() {
  9325  
  9326           va r url = nu ll,
  9327                localSer verUrl = w indow.loca tion.proto col + "//"  + window. location.h ost,
  9328                context  = getConte xt();
  9329  
  9330  
  9331           if  (Xrm.Page .context.g etClientUr l !== unde fined) {
  9332                // since  version S DK 5.0.13 
  9333                // http: //www.magn etismsolut ions.com/b log/gayan- pereras-bl og/2013/01 /07/crm-20 11-polaris -new-xrm.p age-method
  9334  
  9335                url = Xr m.Page.con text.getCl ientUrl();
  9336           }
  9337           el se if (con text.isOut lookClient () && !con text.isOut lookOnline ()) {
  9338                url = lo calServerU rl;
  9339           }
  9340           el se {
  9341                url = co ntext.getC lientUrl() ;
  9342                url = ur l.replace( /^(http|ht tps):\/\/( [_a-zA-Z0- 9\-\.]+)(: ([0-9]{1,5 }))?/, loc alServerUr l);
  9343                url = ur l.replace( /\/$/, "") ;
  9344           }
  9345           re turn url;
  9346       }
  9347  
  9348       ///
  9349       /// Pr ivate func tion to re turn the p ath to the  REST endp oint.
  9350       ///
  9351       functi on getODat aPath() {
  9352  
  9353           re turn getCl ientUrl()  + ODATA_EN DPOINT;
  9354       }
  9355  
  9356       ///
  9357       /// Re turns an o bject that  reprensts  a entity- reference 
  9358       ///
  9359       functi on entityR eferenceFa ctory(id,  opt_logica lName) {
  9360  
  9361           va r referenc e = null;
  9362  
  9363           if  (id !== u ndefined & & id !== n ull) {
  9364  
  9365                referenc e = {
  9366                    __me tadata: {  type: "Mic rosoft.Crm .Sdk.Data. Services.E ntityRefer ence" },
  9367                    Id:  id
  9368                };
  9369  
  9370                if (opt_ logicalNam e !== unde fined && o pt_logical Name !== n ull) {
  9371  
  9372                    refe rence.Logi calName =  opt_logica lName;
  9373                }
  9374           }
  9375  
  9376           re turn refer ence;
  9377       }
  9378  
  9379       ///
  9380       /// Re turns an o bject that  reprensts  a option- set-value 
  9381       ///
  9382       functi on optionS etValueFac tory(optio n_value) {
  9383  
  9384           re turn {
  9385                __metada ta: { type : 'Microso ft.Crm.Sdk .Data.Serv ices.Optio nSetValue'  },
  9386                Value: o ption_valu e
  9387           };
  9388       }
  9389  
  9390       ///
  9391       /// Re turns an o bject that  represent s an money  value
  9392       ///
  9393       functi on moneyVa lueFactory (value) {
  9394  
  9395           re turn {
  9396                __metada ta: { type : 'Microso ft.Crm.Sdk .Data.Serv ices.Money ' },
  9397                Value: v alue
  9398           };
  9399       }
  9400  
  9401       ///
  9402       /// Pa rses the O DATA date- string int o a date-o bject
  9403       /// Al l queries  return a d ate in the  format "/ Date(13686 88809000)/ "
  9404       /// 
  9405       functi on parseOD ataDate(va lue) {
  9406  
  9407           re turn new D ate(parseI nt(value.r eplace('/D ate(', '') .replace(' )/', ''),  10));
  9408       }
  9409  
  9410       ///
  9411       /// Ge nerics aja x-call fun citon. Ret urns a pro mise objec t
  9412       ///
  9413       functi on doReque st(options , asyn) {
  9414  
  9415           //  default v alues for  the ajax q ueries
  9416           va r ajaxDefa ults = {
  9417                type: "G ET",
  9418                async: t rue,
  9419                contentT ype: "appl ication/js on; charse t=utf-8",
  9420                datatype : "json",
  9421                beforeSe nd: functi on (reques t) {
  9422  
  9423                    requ est.setReq uestHeader ("Accept",  "applicat ion/json") ;
  9424                }
  9425           };
  9426  
  9427           //  merge the  default-s ettings wi th the opt ions-objec t
  9428           op tions = $. extend(aja xDefaults,  options);
  9429  
  9430           //  request c ould be ex ecuted in  sync or as yn mode
  9431           op tions.asyn c = (asyn  === undefi ned) ? tru e : asyn;
  9432  
  9433           re turn $.aja x(options) ;
  9434       }
  9435  
  9436       ///
  9437       /// Cr eates a li nk between  records 
  9438       ///
  9439       functi on associa te(entity1 Id, entity 1Name, ent ity2Id, en tity2Name,  relations hipName, o pt_asyn) {
  9440  
  9441           //  default i s 'true'
  9442           va r asyn = ( opt_asyn = == undefin ed) ? true  : opt_asy n,
  9443                odatapat h = getODa taPath(),
  9444                request  = {
  9445                    url:  odatapath  + "/" + e ntity1Name  + "Set(gu id'" + ent ity1Id + " ')/$links/ " + relati onshipName ,
  9446                    type : "POST",
  9447                    data : window.J SON.string ify({
  9448                         uri: odata path + "/"  + entity2 Name + "Se t(guid'" +  entity2Id  + "')"
  9449                    })
  9450                };
  9451  
  9452           re turn doReq uest(reque st, asyn);
  9453       }
  9454  
  9455       ///
  9456       /// Re moves a li nk between  records 
  9457       ///
  9458       functi on disasso ciate(enti ty1Id, ent ity1Name,  entity2Id,  relations hipName, o pt_asyn) {
  9459  
  9460           va r asyn = ( opt_asyn = == undefin ed) ? true  : opt_asy n,
  9461                odatapat h = getODa taPath(),
  9462                request  = {
  9463                    url:  odatapath  + "/" + e ntity1Name  + "Set(gu id'" + ent ity1Id + " ')/$links/ " + relati onshipName  + "(guid' " + entity 2Id + "')" ,
  9464                    type : "POST",
  9465                    // m ethod: "DE LETE",
  9466                    befo reSend: fu nction (re quest) {
  9467                         request.se tRequestHe ader('Acce pt', 'appl ication/js on');
  9468                         request.se tRequestHe ader('X-HT TP-Method' , 'DELETE' );
  9469                    }
  9470                };
  9471  
  9472           re turn doReq uest(reque st, asyn);
  9473       }
  9474  
  9475       ///
  9476       /// Re trieves a  single rec ord 
  9477       ///
  9478       functi on retriev e(entityNa me, id, co lumns, opt _asyn) {
  9479  
  9480           //  default i s 'true'
  9481           va r asyn = ( opt_asyn = == undefin ed) ? true  : opt_asy n,
  9482                setName  = entityNa me + 'Set' ,
  9483                query =  getODataPa th() + "/"  + setName  + "(guid' " + id + " ')" + "?$s elect=" +  columns.jo in(',');
  9484  
  9485           //  returns a  promise i nstance
  9486           re turn doReq uest({ url : query },  asyn);
  9487       }
  9488  
  9489       ///
  9490       /// Us ed in the  context of  lazy-load ing (more  than 50 re cords foun d in the r etrieveMul tiple requ est)
  9491       /// Qu ery (url)  needs to d efine the  entity, co lumns and  filter
  9492       ///
  9493       functi on byQuery Url(queryU rl, opt_as yn) {
  9494  
  9495           re turn doReq uest({ url : queryUrl  }, opt_as yn);
  9496       }
  9497  
  9498       ///
  9499       /// Us ed for joi ns
  9500       ///
  9501       functi on byExpan dQuery(ent ityName, c olumns, ex pand, filt er, opt_as yn) {
  9502  
  9503           //  default i s 'true'
  9504           va r asyn = ( opt_asyn = == undefin ed) ? true  : opt_asy n;
  9505  
  9506           //  in case f ilter is e mpty 
  9507           fi lter = (fi lter) ? "& $filter="  + encodeUR IComponent (filter) :  '';
  9508  
  9509           //  create de fered obje ct
  9510           va r setName  = entityNa me + 'Set' ,
  9511                query =  getODataPa th() + "/"  + setName  + "?$sele ct=" + col umns.join( ',') + '&$ expand=' +  expand +  filter;
  9512  
  9513           re turn doReq uest({ url : query },  asyn);
  9514       }
  9515  
  9516       ///
  9517       /// Re trievs mul tiuple rec ords based  on filter
  9518       /// Th e max numb er of reco rds return ed by Odat a is limit ed to 50,  the result  object co ntains the  property 
  9519       /// 'n ext' and t he fn load Next that  could be u sed to loa d the addi onal recor ds 
  9520       ///
  9521       functi on byQuery (entityNam e, columns , filter,  opt_asyn)  {
  9522  
  9523           //  default i s 'true'
  9524           va r asyn = ( opt_asyn = == undefin ed) ? true  : opt_asy n;
  9525  
  9526           //  in case f ilter is e mpty 
  9527           fi lter = (fi lter) ? "& $filter="  + encodeUR IComponent (filter) :  '';
  9528  
  9529           //  create de fered obje ct
  9530           va r setName  = entityNa me + 'Set' ,
  9531                query =  getODataPa th() + "/"  + setName  + "?$sele ct=" + col umns.join( ',') + fil ter;
  9532  
  9533           re turn doReq uest({ url : query },  asyn);
  9534       }
  9535  
  9536       ///
  9537       /// Pe r default  a REST que ry returns  only 50 r ecord. Thi s function  will load  all recor ds
  9538       ///
  9539       functi on byQuery All(entity Name, colu mns, filte r, opt_asy n) {
  9540  
  9541           va r dfdAll =  new $.Def erred(),
  9542                allRecor ds = [];
  9543  
  9544           by Query(enti tyName, co lumns, fil ter, opt_a syn).then( function b yQueryAllS uccess(res ult) {
  9545  
  9546                // add t he element s to the c ollection
  9547                allRecor ds = allRe cords.conc at(result. d.results) ;
  9548  
  9549                if (resu lt.d.__nex t) {
  9550  
  9551                    // t he success -handler w ill be thi s function
  9552                    byQu eryUrl(res ult.d.__ne xt, opt_as yn).then(b yQueryAllS uccess, df dAll.rejec t);
  9553  
  9554                    // c all the pr ogressCall backs of t he promise
  9555                    dfdA ll.notify( result);
  9556                }
  9557                else {
  9558                    dfdA ll.resolve (allRecord s);
  9559                }
  9560  
  9561           },  dfdAll.re ject);
  9562  
  9563           re turn dfdAl l.promise( );
  9564       }
  9565  
  9566       ///
  9567       /// Cr eate a sin gle reocrd
  9568       ///
  9569       functi on created (entityNam e, entityO bject, opt _asyn) {
  9570  
  9571           //  default i s 'true'
  9572           va r asyn = ( opt_asyn = == undefin ed) ? true  : opt_asy n,
  9573                setName  = entityNa me + 'Set' ,
  9574                json = w indow.JSON .stringify (entityObj ect),
  9575                query =  getODataPa th() + "/"  + setName ;
  9576  
  9577           //  returns a  promise o bject
  9578           re turn doReq uest({ typ e: "POST",  url: quer y, data: j son }, asy n);
  9579       }
  9580  
  9581       ///
  9582       /// Up dates the  record wit h the stat ed intance .
  9583       /// ME RGE method e does not  return da ta
  9584       ///
  9585       /// Sa mple:
  9586       ///      CrmRestK it.Update( 'Account',  id, { 'Ad dress1_Cit y': 'sampl e', 'Name' : 'sample'  }).done(. ..).fail(. .)
  9587       ///
  9588       functi on update( entityName , id, enti tyObject,  opt_asyn)  {
  9589  
  9590           //  default i s 'true'
  9591           va r asyn = ( opt_asyn = == undefin ed) ? true  : opt_asy n,
  9592                setName  = entityNa me + 'Set' ,
  9593                json = w indow.JSON .stringify (entityObj ect),
  9594                query =  getODataPa th() + "/"  + setName  + "(guid' " + id + " ')",
  9595                // ajax- call-optio ns
  9596                options  = {
  9597                    type : "POST",
  9598                    url:  query,
  9599                    data : json,
  9600                    befo reSend: fu nction (re quest) {
  9601                         request.se tRequestHe ader("Acce pt", "appl ication/js on");
  9602                         request.se tRequestHe ader("X-HT TP-Method" , "MERGE") ;
  9603                    }
  9604                };
  9605  
  9606           //  MERGE met hode does  not return  data
  9607           re turn doReq uest(optio ns, asyn);
  9608       }
  9609  
  9610       ///
  9611       /// De letes as s ingle reco rd identif ied by the  id
  9612       /// Sa mple:
  9613       ///          CrmR estKit.Del ete('Accou nt', id).d one(...).f ail(..);
  9614       ///
  9615       functi on deleteR ecord(enti tyName, id , opt_asyn ) {
  9616  
  9617           //  default i s 'true'
  9618           va r asyn = ( opt_asyn = == undefin ed) ? true  : opt_asy n,
  9619                setName  = entityNa me + 'Set' ,
  9620                query =  getODataPa th() + '/'  + setName  + "(guid' " + id + " ')",
  9621                options  = {
  9622                    type : "POST",
  9623                    url:  query,
  9624                    befo reSend: fu nction (re quest) {
  9625                         request.se tRequestHe ader('Acce pt', 'appl ication/js on');
  9626                         request.se tRequestHe ader('X-HT TP-Method' , 'DELETE' );
  9627                    }
  9628                };
  9629  
  9630           re turn doReq uest(optio ns, asyn);
  9631       }
  9632  
  9633       ///
  9634       /// Pu blic API
  9635       ///
  9636       return  {
  9637           Ve rsion: ver sion,
  9638           /*  Read /ret rieve meth ods*/
  9639           Re trieve: re trieve,
  9640           By Query: byQ uery,
  9641           By QueryUrl:  byQueryUrl ,
  9642           By ExpandQuer y: byExpan dQuery,
  9643           By QueryAll:  byQueryAll ,
  9644           /*  C U D */
  9645           Cr eate: crea ted,
  9646           Up date: upda te,
  9647           De lete: dele teRecord,
  9648           /*  N:M relat ionship op erations * /
  9649           As sociate: a ssociate,
  9650           Di sassociate : disassoc iate,
  9651           /*  Factory m ethods */
  9652           En tityRefere nceFactory : entityRe ferenceFac tory,
  9653           Op tionSetVal ueFactory:  optionSet ValueFacto ry,
  9654           Mo neyValueFa ctory: mon eyValueFac tory,
  9655           /*  util meth ods */
  9656           Pa rseODataDa te: parseO DataDate
  9657       };
  9658   }(window,  document)) ;
  9659   //Library  Name: cvt_ CommonFunc tions.js
  9660   //If the S DK namespa ce object  is not def ined, crea te it.
  9661   if (typeof  (MCS) ==  "undefined ")
  9662   { MCS = {} ; }
  9663   // Create  Namespace  container  for functi ons in thi s library;
  9664   MCS.cvt_Co mmon = {};
  9665   //Form Typ es
  9666   MCS.cvt_Co mmon.FORM_ TYPE_CREAT E = 1;
  9667   MCS.cvt_Co mmon.FORM_ TYPE_UPDAT E = 2;
  9668   MCS.cvt_Co mmon.FORM_ TYPE_READ_ ONLY = 3;
  9669   MCS.cvt_Co mmon.FORM_ TYPE_DISAB LED = 4;
  9670   MCS.cvt_Co mmon.FORM_ TYPE_QUICK CREATE = 5 ;
  9671   MCS.cvt_Co mmon.FORM_ TYPE_BULKE DIT = 6;
  9672  
  9673   MCS.cvt_Co mmon.Blank GUID = "00 000000-000 0-0000-000 0-00000000 0000";
  9674  
  9675   MCS.cvt_Co mmon.Appoi ntmentOccu rsInPast =  function  () {
  9676       if (Xr m.Page.ui. getFormTyp e() == MCS .cvt_Commo n.FORM_TYP E_CREATE)
  9677           re turn false ;
  9678       var st artTimeObj  = Xrm.Pag e.getAttri bute("sche duledstart ");
  9679       if (st artTimeObj  == null)
  9680           re turn false ;
  9681       var st artTime =  startTimeO bj.getValu e();
  9682       if (st artTime ==  null)
  9683           re turn false ;
  9684       var no w = new Da te();
  9685       if (no w > startT ime)
  9686           re turn true;
  9687       else
  9688           re turn false ;
  9689   }
  9690  
  9691   //Get Serv er URL
  9692   MCS.cvt_Co mmon.Build Relationsh ipServerUr l = functi on () {
  9693       var se rver = Xrm .Page.cont ext.getCli entUrl();
  9694       if (se rver.match (/\/$/)) {
  9695           se rver = ser ver.substr ing(0, ser ver.length  - 1);
  9696       }
  9697       return  server;
  9698   };
  9699  
  9700   //Check if  Obj is nu ll else ge t Value
  9701   MCS.cvt_Co mmon.check Null = fun ction (fie ldname) {
  9702       var fi eldObj = X rm.Page.ge tAttribute (fieldname );
  9703  
  9704       if (fi eldObj !=  null)
  9705           re turn field Obj.getVal ue();
  9706  
  9707       return  null;
  9708   };
  9709  
  9710   //Close wi ndow
  9711   MCS.cvt_Co mmon.close Window = f unction (m sg) {
  9712       if (ms g != null)
  9713           al ert(msg);
  9714       //Clea r all fiel ds so ther e are no d irty field s
  9715       var at tributes =  Xrm.Page. data.entit y.attribut es.get();
  9716       for (v ar i in at tributes)  {
  9717           at tributes[i ].setSubmi tMode("nev er");
  9718       }
  9719       //Clos e record          
  9720       Xrm.Pa ge.ui.clos e();
  9721   };
  9722  
  9723   //collapse  a tab
  9724   MCS.cvt_Co mmon.colla pseTab = f unction (t ab, field)  {
  9725       /***** ********** ********** ********** ********** ********** ********** ****
  9726       USAGE:  collapses /expands a  tab based  upon whet her a cont rol is emp ty.
  9727       Pass i n the sche ma name of  the tab a nd the nam e of the f ield to ch eck
  9728  
  9729       Exampl e:
  9730       //tab  name: "tab _9"  <--sc hema name  is what we  want pass ed in
  9731       //mcs_ relatedtsa   <--pass  in the fie ld name to  check
  9732  
  9733       ****** ********** ********** ********** ********** ********** ********** ****/
  9734  
  9735       var ct lControl =  Xrm.Page. getControl (field);
  9736       var at rControl =  ctlContro l.getAttri bute();
  9737       var va lControl =  atrContro l.getValue ();
  9738  
  9739       var ta bObj = Xrm .Page.ui.t abs.get(ta b);
  9740  
  9741       if ((v alControl  != "") &&  (valContro l != null) ) {
  9742           ta bObj.setDi splayState ("expanded ");
  9743       }
  9744       else {
  9745           ta bObj.setDi splayState ("collapse d");
  9746       }
  9747   }
  9748   //Check if  GUIDS are  the same
  9749   MCS.cvt_Co mmon.compa reGUIDS =  function ( guid1, gui d2) {
  9750       if (gu id1 == nul l && guid2  == null)
  9751           re turn true;
  9752  
  9753       if ((g uid1 == nu ll) || (gu id2 == nul l))
  9754           re turn false ;
  9755  
  9756       var gu id1Cleaned  = guid1.r eplace(/\W /g, '');
  9757       guid1C leaned = g uid1Cleane d.toString ().toUpper Case();
  9758  
  9759       var gu id2Cleaned  = guid2.r eplace(/\W /g, '');
  9760       guid2C leaned = g uid2Cleane d.toString ().toUpper Case();
  9761  
  9762       if (gu id1Cleaned  == guid2C leaned)
  9763           re turn true;
  9764       else
  9765           re turn false ;   
  9766   };
  9767  
  9768   //Create F etch
  9769   MCS.cvt_Co mmon.Creat eFetch = f unction (e ntityName,  columns,  conditions , order) {
  9770       var fo rmattedCol umns = '';
  9771       var fo rmattedCon ditions =  '';
  9772       var fo rmattedOrd er = '';
  9773  
  9774       //colu mns is an  array, so  that we ca n build th at string  with the x ml tags
  9775       if ((c olumns !=  null) && ( columns.le ngth > 0))  {
  9776           fo r (column  in columns ) {
  9777                formatte dColumns + = '<attrib ute name=" ' + column s[column]  + '" />';
  9778           }
  9779       }
  9780       //pref ix filter  type and a dd conditi ons
  9781       if ((c onditions  != null) & & (conditi ons.length  > 0)) {
  9782           fo rmattedCon ditions =  "<filter t ype='and'> ";
  9783           fo r (conditi on in cond itions) {
  9784                formatte dCondition s += condi tions[cond ition];
  9785           }
  9786       }
  9787       //form at order
  9788       if ((o rder != nu ll) && (or der.length  == 2))
  9789           fo rmattedOrd er = '<ord er attribu te="' + or der[0] + ' " descendi ng="' + or der[1] + ' " />';
  9790  
  9791       var fe tchXml = " <fetch ver sion='1.0'  output-fo rmat='xml- platform'  mapping='l ogical' di stinct='tr ue' aggreg ate='false '>";
  9792       fetchX ml += "<en tity name= '" + entit yName + "' >";
  9793       fetchX ml += form attedColum ns;
  9794       fetchX ml += form attedOrder ;
  9795       fetchX ml += form attedCondi tions;
  9796       fetchX ml += "</f ilter>";
  9797       fetchX ml += "</e ntity>";
  9798       fetchX ml += "</f etch>";
  9799  
  9800       return  fetchXml;
  9801   };
  9802  
  9803   MCS.cvt_Co mmon.DateT ime = func tion (attr ibuteName,  hour, min ute) {
  9804       var at tribute =  Xrm.Page.g etAttribut e(attribut eName);
  9805       if (at tribute.ge tValue() = = null) {
  9806           at tribute.se tValue(new  Date());
  9807       }
  9808       attrib ute.setVal ue(attribu te.getValu e().setHou rs(hour, m inute, 0)) ;
  9809   };
  9810  
  9811   //Used for  Specialty  Subtype b ased off o f Subtype
  9812   MCS.cvt_Co mmon.Enabl eDependent Lookup = f unction (p rimaryLU,  secondaryL U) {
  9813  
  9814       var pr imaryLUatt ribute = X rm.Page.ge tAttribute (primaryLU );
  9815       var pr imaryLUval ue = (prim aryLUattri bute != nu ll) ? prim aryLUattri bute.getVa lue() : nu ll;
  9816       var pr imaryLUval ueproperty  = (primar yLUvalue ! = null) ?  primaryLUv alue[0].na me : null;
  9817  
  9818       if (pr imaryLUval ueproperty  != null)  {
  9819           Xr m.Page.get Control(se condaryLU) .setVisibl e(true);
  9820           Xr m.Page.get Control(se condaryLU) .setFocus( );
  9821       }
  9822       else {
  9823           Xr m.Page.get Control(se condaryLU) .setVisibl e(false);
  9824           Xr m.Page.get Attribute( secondaryL U).setValu e(null);
  9825       }
  9826   };
  9827  
  9828   MCS.cvt_Co mmon.Enabl eOtherDeta ils = func tion (sour ce, target , value) {
  9829       var ta rgetFieldC ontrol = X rm.Page.ui .controls. get(target );
  9830       var ta rgetFieldO bject = Xr m.Page.get Attribute( target);
  9831       var so urceValue  = Xrm.Page .getAttrib ute(source ).getValue ();
  9832       if (so urceValue  != null &&  sourceVal ue.toStrin g() == val ue) {
  9833           ta rgetFieldC ontrol.set Disabled(f alse);
  9834           ta rgetFieldC ontrol.set Visible(tr ue);
  9835           ta rgetFieldO bject.setR equiredLev el("requir ed");
  9836           ta rgetFieldO bject.setS ubmitMode( "dirty");
  9837       }
  9838       else {
  9839           if  (targetFi eldObject. getValue()  != "") {
  9840                targetFi eldObject. setValue(" ");
  9841                targetFi eldObject. setSubmitM ode("alway s");
  9842           }
  9843           ta rgetFieldC ontrol.set Disabled(t rue);
  9844           ta rgetFieldC ontrol.set Visible(fa lse);
  9845           ta rgetFieldO bject.setR equiredLev el("none") ;
  9846       }
  9847   };
  9848  
  9849   //XML Fix  - replace  & with &am p;
  9850   MCS.cvt_Co mmon.forma tXML = fun ction (str ) {
  9851       if (st r) {
  9852           st r = str.re place(/&/g , "&amp;") ;
  9853           re turn str;
  9854       }
  9855   };
  9856  
  9857   //Gets the  EntityTyp eCode / Ob jectTypeCo de of a en tity
  9858   MCS.cvt_Co mmon.getOb jectTypeCo de = funct ion (entit yName) {
  9859       var lo okupServic e = new pa rent.Remot eCommand(" LookupServ ice", "Ret rieveTypeC ode");
  9860       lookup Service.Se tParameter ("entityNa me", entit yName);
  9861       var re sult = loo kupService .Execute() ;
  9862       if (re sult.Succe ss && type of result. ReturnValu e == "numb er") {
  9863           re turn resul t.ReturnVa lue;
  9864       } else  {
  9865           re turn null;
  9866       }
  9867   };
  9868  
  9869   //MCS.cvt_ Common.JSD ebugAlert  = function  (msg) {
  9870   //    Set  showAlerts  to false  to stop sh owing Aler ts
  9871   //    var  showAlerts  = false;
  9872  
  9873   //    if ( showAlerts  == true)  {
  9874   //         if (msg !=  null) {
  9875   //             alert( "JS Debug  Message: \ n\n" + msg );
  9876   //         }
  9877   //    }
  9878   //};
  9879  
  9880   MCS.cvt_Co mmon.MVICo nfig = fun ction () {
  9881       var ro les = "";
  9882       var MV IConfig =  false;
  9883       var fi lter = "mc s_name eq  'Active Se ttings'";
  9884       calls  = CrmRestK it.ByQuery ("mcs_sett ing", ['cv t_UseMVI',  'cvt_MVIR oles'], fi lter, fals e);
  9885       calls. fail(funct ion (err)  {
  9886           re turn MVICo nfig;
  9887       }).don e(function  (data) {
  9888           if  (data &&  data.d &&  data.d.res ults != nu ll && data .d.results .length !=  0) {
  9889                MVIConfi g = data.d .results[0 ].cvt_UseM VI != null  ? data.d. results[0] .cvt_UseMV I : false;
  9890                roles =  data.d.res ults[0].cv t_MVIRoles ;
  9891           }
  9892       });
  9893       var ro leCheck =  MCS.cvt_Co mmon.userH asRoleInLi st(roles);
  9894       return  MVIConfig  && roleCh eck;
  9895   };
  9896  
  9897   //UNSUPPOR TED: Add M essage to  Notificati ons area
  9898   MCS.cvt_Co mmon.Notif ications =  function  (action, i con, messa ge) {
  9899       var no tification sList = Sy s.Applicat ion.findCo mponent('c rmNotifica tions');
  9900  
  9901       switch  (action)  {
  9902           ca se "Add":
  9903                if ((not ifications List) && ( icon) && ( message))
  9904                    noti ficationsL ist.AddNot ification( 'noteId1',  icon, 'na mespace',  message);            
  9905                break;
  9906           ca se "Hide":
  9907                notifica tionsList. SetVisible (false);
  9908                break;
  9909       }
  9910   };
  9911  
  9912   MCS.cvt_Co mmon.openD ialogOnCur rentRecord  = functio n (dialogI d) {
  9913       Entity Name = Xrm .Page.data .entity.ge tEntityNam e();
  9914       object Id = Xrm.P age.data.e ntity.getI d();
  9915       return  MCS.cvt_C ommon.open DialogProc ess(dialog Id, Entity Name, obje ctId);
  9916   }
  9917  
  9918  
  9919   MCS.cvt_Co mmon.openD ialogProce ss = funct ion (dialo gId, Entit yName, obj ectId) {
  9920       if (En tityName = = null ||  EntityName  == "")
  9921           En tityName =  Xrm.Page. data.entit y.getEntit yName();
  9922       if (ob jectId ==  null || ob jectId ==  "")
  9923           ob jectId = X rm.Page.da ta.entity. getId();
  9924       var ur l = Xrm.Pa ge.context .getClient Url() +
  9925         "/cs /dialog/ru ndialog.as px?DialogI d=" +
  9926         dial ogId + "&E ntityName= " +
  9927         Enti tyName + " &ObjectId= " +
  9928         obje ctId;
  9929       var wi dth = 400;
  9930       var he ight = 400 ;
  9931       var le ft = (scre en.width -  width) /  2;
  9932       var to p = (scree n.height -  height) /  2;
  9933       return  window.op en(url, '' , 'locatio n=0,menuba r=1,resiza ble=1,widt h=' + widt h + ',heig ht=' + hei ght + ',to p=' + top  + ',left='  + left +  '');
  9934   };
  9935  
  9936   MCS.cvt_Co mmon.RestE rror = fun ction (err ) {
  9937       return  JSON.pars e(err.resp onseText). error.mess age.value;
  9938   };
  9939  
  9940   //From the  Site, Set  Facility
  9941   MCS.cvt_Co mmon.SetFa cilityFrom Site = fun ction (sit eFieldName , facility FieldName)  {
  9942       var si teField =  Xrm.Page.g etAttribut e(siteFiel dName);
  9943       var fa cilityFiel d = Xrm.Pa ge.getAttr ibute(faci lityFieldN ame);
  9944       var pr iorFacilit yValue = ( facilityFi eld.getVal ue() != nu ll) ? faci lityField. getValue() [0].id : n ull;
  9945       var si teValue =  (siteField .getValue( ) != null)  ? siteFie ld.getValu e()[0].id  : null;
  9946  
  9947       if (si teValue !=  null) {
  9948           // Get Parent  Facility  of Site
  9949           va r calls =  CrmRestKit .Retrieve( "mcs_site" , siteValu e, ['mcs_F acilityId' ], false);
  9950           ca lls.fail(
  9951                    func tion (erro r) {
  9952                    }).d one(functi on (data)  {
  9953                         if (data & & data.d & & data.d.m cs_Facilit yId) {
  9954                             //Chec k and Set  Facility
  9955                             var va lue = new  Array();
  9956                             value[ 0] = new O bject();
  9957                             value[ 0].id = '{ ' + data.d .mcs_Facil ityId.Id +  '}';
  9958                             value[ 0].name =  data.d.mcs _FacilityI d.Name;
  9959                             value[ 0].entityT ype = "mcs _facility" ;
  9960  
  9961                             //Set  Facility f ield
  9962                             facili tyField.se tValue(val ue);
  9963                         }
  9964                    });
  9965       }
  9966       else {
  9967           // Clear Faci lity field
  9968           fa cilityFiel d.setValue (null);
  9969       }
  9970       if (MC S.cvt_Comm on.compare GUIDS(prio rFacilityV alue, ((fa cilityFiel d.getValue () != null ) ? facili tyField.ge tValue()[0 ].id : nul l)) != tru e)
  9971           fa cilityFiel d.setSubmi tMode("alw ays");         
  9972   };
  9973  
  9974   MCS.cvt_Co mmon.TrimB ookendBrac kets = fun ction (str ingVar) {
  9975       if (st ringVar !=  null && s tringVar.l ength > 0)
  9976           re turn strin gVar.charA t(0) == '{ ' ? string Var.slice( 1, stringV ar.length  - 1) : str ingVar;
  9977       else
  9978           re turn "";
  9979   };
  9980  
  9981   //Check if  the passe d in User  has a part icular rol e
  9982   MCS.cvt_Co mmon.userH asRoleInLi st = funct ion (roles ) {
  9983       var us erRoles =  Xrm.Page.c ontext.get UserRoles( );
  9984       var ha sRole = fa lse;
  9985       for (v ar i = 0;  i < userRo les.length  ; i++) {
  9986           if  (hasRole)  {
  9987                return t rue;
  9988           }
  9989           Cr mRestKit.R etrieve('R ole', user Roles[i],  ['Name'],  false).fai l(
  9990                function  (err) {
  9991                    retu rn;
  9992                }).done(
  9993                function  (data) {
  9994                    if ( data != nu ll && data .d != null ) {
  9995                         var roleNa me = data. d.Name.tri m().toLowe rCase();
  9996                         if (roles. toLowerCas e().indexO f(roleName ) != -1) {
  9997                             hasRol e = true;
  9998                             return ;
  9999                         }
  10000                    }
  10001                });
  10002  
  10003       }
  10004       return  hasRole;
  10005   }
  10006  
  10007  
  10008   /********* ********** ********** ********** ********** ********** ********** **
  10009   /** 
  10010   /** MCSGlb al Functio ns.js
  10011   /** Descri ption: Glo bal rules  called by  form level  jscripts 
  10012   /** 
  10013   ********** ********** ********** ********** ********** ********** ********** */
  10014   //If the M CS namespa ce object  is not def ined, crea te it.
  10015   if (typeof  (MCS) ==  "undefined ")
  10016   { MCS = {  __namespac e: true };  }
  10017   MCS.Global Functions  = {
  10018       GetReq uestObject : function  () {
  10019           if  (window.X MLHttpRequ est) {
  10020                return n ew window. XMLHttpReq uest;
  10021           }
  10022           el se {
  10023                try {
  10024                    retu rn new Act iveXObject ("MSXML2.X MLHTTP.3.0 ");
  10025                }
  10026                catch (e x) {
  10027                    retu rn null;
  10028                }
  10029           }
  10030       },
  10031       GuidsA reEqual: f unction (g uid1, guid 2) {
  10032           va r isEqual  = false;
  10033  
  10034           if  (guid1 ==  null || g uid2 == nu ll) {
  10035                isEqual  = false;
  10036           }
  10037           el se {
  10038                isEqual  = guid1.re place(/[{} ]/g, "").t oLowerCase () == guid 2.replace( /[{}]/g, " ").toLower Case();
  10039           }
  10040  
  10041           re turn isEqu al;
  10042       },
  10043  
  10044       getODa taUTCDateF ilter: fun ction (dat e) {
  10045  
  10046           va r monthStr ing;
  10047           va r rawMonth  = (date.g etUTCMonth () + 1).to String();
  10048           if  (rawMonth .length ==  1) {
  10049                monthStr ing = "0"  + rawMonth ;
  10050           }
  10051           el se { month String = r awMonth; }
  10052  
  10053           va r dateStri ng;
  10054           va r rawDate  = date.get UTCDate(). toString() ;
  10055           if  (rawDate. length ==  1) {
  10056                dateStri ng = "0" +  rawDate;
  10057           }
  10058           el se { dateS tring = ra wDate; }
  10059  
  10060  
  10061           va r DateFilt er = "date time\'";
  10062           Da teFilter + = date.get UTCFullYea r() + "-";
  10063           Da teFilter + = monthStr ing + "-";
  10064           // DateFilter  += "07-";
  10065           Da teFilter + = dateStri ng;
  10066           Da teFilter + = "T";
  10067           va r temp = d ate.getUTC Hours();
  10068           if  (temp.toS tring().le ngth == 1)  {
  10069                temp = " 0" + temp;
  10070           }
  10071           Da teFilter + = temp + " :";
  10072  
  10073           te mp = date. getUTCMinu tes();
  10074           if  (temp.toS tring().le ngth == 1)  {
  10075                temp = " 0" + temp;
  10076           }
  10077           Da teFilter + = temp + " :";
  10078  
  10079           te mp = date. getUTCSeco nds();
  10080           if  (temp.toS tring().le ngth == 1)  {
  10081                temp = " 0" + temp;
  10082           }
  10083           Da teFilter + = temp + " \'";
  10084  
  10085           //
  10086           //          D ateFilter  += date.ge tUTCSecond s() + ":";
  10087           //          D ateFilter  += date.ge tUTCMillis econds();
  10088           //          D ateFilter  += "Z\'";
  10089           re turn DateF ilter;
  10090       },
  10091       getAut henticatio nHeader: f unction ()  {
  10092           va r authenti cationHead er = Xrm.P age.contex t.getAuthe nticationH eader();
  10093  
  10094       },
  10095       _getCl ientUrl: f unction (u rlType) {
  10096  
  10097           va r orgServi cePath = " /xrmservic es/2011/or ganization .svc/web";
  10098  
  10099           if  (urlType  == "ODATA" ) {
  10100                orgServi cePath = " /xrmservic es/2011/or ganization data.svc";
  10101           }
  10102           va r serverUr l = "";
  10103           if  (typeof G etGlobalCo ntext == " function")  {
  10104                var cont ext = GetG lobalConte xt();
  10105                serverUr l = contex t.getClien tUrl();
  10106           }
  10107           el se {
  10108                if (type of Xrm.Pag e.context  == "object ") {
  10109                    serv erUrl = Xr m.Page.con text.getCl ientUrl();
  10110                }
  10111                else { t hrow new E rror("Unab le to acce ss the ser ver URL");  }
  10112           }
  10113           if  (serverUr l.match(/\ /$/)) {
  10114                serverUr l = server Url.substr ing(0, ser verUrl.len gth - 1);
  10115           }
  10116           re turn serve rUrl + org ServicePat h;
  10117       },
  10118  
  10119       runWor kflow: fun ction (obj ectId, wor kflowId, r unResponse ) {
  10120           va r request  = "<Execut e xmlns=\" http://sch emas.micro soft.com/x rm/2011/Co ntracts/Se rvices\" x mlns:i=\"h ttp://www. w3.org/200 1/XMLSchem a-instance \">";
  10121           re quest += " <request i :type=\"b: ExecuteWor kflowReque st\" xmlns :a=\"http: //schemas. microsoft. com/xrm/20 11/Contrac ts\" xmlns :b=\"http: //schemas. microsoft. com/crm/20 11/Contrac ts\">";
  10122           re quest += " <a:Paramet ers xmlns: c=\"http:/ /schemas.d atacontrac t.org/2004 /07/System .Collectio ns.Generic \">";
  10123           re quest += " <a:KeyValu ePairOfstr inganyType >";
  10124           re quest += " <c:key>Ent ityId</c:k ey>";
  10125           re quest += " <c:value i :type=\"d: guid\" xml ns:d=\"htt p://schema s.microsof t.com/2003 /10/Serial ization/\" >" + objec tId + "</c :value>";
  10126           re quest += " </a:KeyVal uePairOfst ringanyTyp e>";
  10127           re quest += " <a:KeyValu ePairOfstr inganyType >";
  10128           re quest += " <c:key>Wor kflowId</c :key>";
  10129           re quest += " <c:value i :type=\"d: guid\" xml ns:d=\"htt p://schema s.microsof t.com/2003 /10/Serial ization/\" >" + workf lowId + "< /c:value>" ;
  10130           re quest += " </a:KeyVal uePairOfst ringanyTyp e>";
  10131           re quest += " </a:Parame ters>";
  10132           re quest += " <a:Request Id i:nil=\ "true\" /> ";
  10133           re quest += " <a:Request Name>Execu teWorkflow </a:Reques tName>";
  10134           re quest += " </request> ";
  10135           re quest += " </Execute> ";
  10136           re quest = th is._getSOA PWrapper(r equest);
  10137  
  10138           va r req = ne w XMLHttpR equest();
  10139           re q.open("PO ST", this. _getClient Url("SOAP" ), true);
  10140           re q.setReque stHeader(" Accept", " applicatio n/xml, tex t/xml, */* ");
  10141           re q.setReque stHeader(" Content-Ty pe", "text /xml; char set=utf-8" );
  10142           re q.setReque stHeader(" SOAPAction ", this._A ction.RunW orkflow);
  10143           re q.onreadys tatechange  = functio n () { run Response(r eq); };
  10144           re q.send(req uest);
  10145  
  10146       },
  10147       runWor kflowRespo nse: funct ion () {
  10148           re turn new M CS.GlobalF unctions._ response(2 00, functi on (respon seXML) {
  10149                return " OK";
  10150           }) ;
  10151       },
  10152       create SOAPReques t: functio n (type, a ttributes,  createRes ponse) {
  10153           va r request  = "<Create  xmlns=\"h ttp://sche mas.micros oft.com/xr m/2011/Con tracts/Ser vices\">";
  10154           re quest += " <entity xm lns:b=\"ht tp://schem as.microso ft.com/xrm /2011/Cont racts\"";
  10155           re quest += "  xmlns:i=\ "http://ww w.w3.org/2 001/XMLSch ema-instan ce\">";
  10156           re quest += t his._getAt tributeWra pper(attri butes);
  10157           re quest += " <b:EntityS tate i:nil =\"true\"/ >";
  10158           re quest += " <b:Formatt edValues x mlns:c=\"h ttp://sche mas.dataco ntract.org /2004/07/S ystem.Coll ections.Ge neric\"/>" ;
  10159           re quest += " <b:Id>0000 0000-0000- 0000-0000- 0000000000 00</b:Id>" ;
  10160           re quest += " <b:Logical Name>" + t ype + "</b :LogicalNa me>";
  10161           re quest += " <b:Related Entities x mlns:c=\"h ttp://sche mas.dataco ntract.org /2004/07/S ystem.Coll ections.Ge neric\"/>" ;
  10162           re quest += " </entity>" ;
  10163           re quest += " </Create>" ;
  10164           re quest = th is._getSOA PWrapper(r equest);
  10165  
  10166           va r req = ne w XMLHttpR equest();
  10167           re q.open("PO ST", this. _getClient Url("SOAP" ), true);
  10168           re q.setReque stHeader(" Accept", " applicatio n/xml, tex t/xml, */* ");
  10169           re q.setReque stHeader(" Content-Ty pe", "text /xml; char set=utf-8" );
  10170           re q.setReque stHeader(" SOAPAction ", this._A ction.Crea te);
  10171           re q.onreadys tatechange  = functio n () { cre ateRespons e.parseRes ponse(req) ; };
  10172           re q.send(req uest);
  10173  
  10174       }, cre ateRespons e: functio n () {
  10175           re turn new M CS.GlobalF unctions._ response(2 00, functi on (respon seXML) {
  10176                return r esponseXML .selectSin gleNode("/ /CreateRes ult").text ;
  10177           }) ;
  10178       },
  10179       retrie veRequest:  function  (type, id,  columnSet , retrieve Response)  {
  10180  
  10181           va r request  = "<Retrie ve xmlns=\ "http://sc hemas.micr osoft.com/ xrm/2011/C ontracts/S ervices\"> ";
  10182           re quest += " <entityNam e>" + type  + "</enti tyName>";
  10183           re quest += " <id>" + id  + "</id>" ;
  10184           re quest += M CS.GlobalF unctions._ getColumnS et(columnS et);
  10185           re quest += " </Retrieve >";
  10186           re quest = th is._getSOA PWrapper(r equest);
  10187  
  10188           va r req = ne w XMLHttpR equest();
  10189           re q.open("PO ST", this. _getClient Url("SOAP" ) + "/web" , true);
  10190           re q.setReque stHeader(" Accept", " applicatio n/xml, tex t/xml, */* ");
  10191           re q.setReque stHeader(" Content-Ty pe", "text /xml; char set=utf-8" );
  10192           re q.setReque stHeader(" SOAPAction ", this._A ction.Retr ieve);
  10193           re q.onreadys tatechange  = functio n () { ret rieveRespo nse._parse Response(r eq); };
  10194           re q.send(req uest);
  10195  
  10196       },
  10197       retrie veResponse : function  () {
  10198           re turn new M CS.GlobalF unctions._ response(2 00, functi on (respon seXML) {
  10199                var attr ibutesData  = respons eXML.selec tNodes("// a:KeyValue PairOfstri nganyType" )
  10200                var enti tyInstance  = {};
  10201                for (var  i = 0; i  < attribut esData.len gth; i++)  {
  10202  
  10203                    var  attributeN ame = attr ibutesData [i].select SingleNode ("b:key"). text;
  10204                    var  attributeT ype = attr ibutesData [i].select SingleNode ("b:value" ).attribut es.getName dItem("i:t ype").text ;
  10205                    var  attributeV alue = att ributesDat a[i].selec tSingleNod e("b:value ");
  10206                    swit ch (attrib uteType) {
  10207                         case "c:gu id":
  10208                         case "c:st ring":
  10209                             entity Instance[a ttributeNa me] = attr ibuteValue .text;
  10210                             break;
  10211                         case "a:En tityRefere nce":
  10212                             var va lue = {};
  10213                             value. Id = attri buteValue. selectSing leNode("a: Id").text;
  10214                             value. LogicalNam e = attrib uteValue.s electSingl eNode("a:L ogicalName ").text;
  10215                             value. Name = att ributeValu e.selectSi ngleNode(" a:Name").t ext;
  10216                             entity Instance[a ttributeNa me] = valu e;
  10217                             break;
  10218                         default:
  10219                             throw  new Error( "Parsing "  + attribu teType + "  attribute s not Impl emented.") ;
  10220                             break;
  10221                    }
  10222  
  10223                }
  10224  
  10225                return e ntityInsta nce;
  10226  
  10227  
  10228           }) ;
  10229       },
  10230       update Request: f unction ()
  10231       { },
  10232       update Response:  function ( )
  10233       { },
  10234       delete Request: f unction ()
  10235       { },
  10236       delete Response:  function ( )
  10237       { },
  10238       _getSO APWrapper:  function  (request)  {
  10239           va r SOAP = " <s:Envelop e xmlns:s= \"http://s chemas.xml soap.org/s oap/envelo pe/\"><s:B ody>";
  10240           SO AP += requ est;
  10241           SO AP += "</s :Body></s: Envelope>" ;
  10242           re turn SOAP;
  10243       },
  10244       _getAt tributeWra pper: func tion (attr ibutes) {
  10245           va r attribut esString =  "<b:Attri butes xmln s:c=\"http ://schemas .datacontr act.org/20 04/07/Syst em.Collect ions.Gener ic\">";
  10246  
  10247           fo r (var i =  0; i < at tributes.l ength; i++ ) {
  10248  
  10249                var attr ibute = "< b:KeyValue PairOfstri nganyType> ";
  10250                attribut e += "<c:k ey>" + att ributes[i] .name + "< /c:key>";
  10251  
  10252                switch ( attributes [i].type)  {
  10253  
  10254                    case  "string":
  10255                         attribute  += "<c:val ue i:type= \"d:" + at tributes[i ].type + " \" ";
  10256                         attribute  += " xmlns :d=\"http: //www.w3.o rg/2001/XM LSchema\"> " + attrib utes[i].va lue + "</c :value>";
  10257                         break;
  10258                    case  "EntityRe ference":
  10259                         attribute  += "<c:val ue i:type= \"b:Entity Reference\ ">";
  10260                         attribute  += "<b:Id> " + attrib utes[i].va lue.Id + " </b:Id>";
  10261                         attribute  += "<b:Log icalName>"  + attribu tes[i].val ue.Logical Name + "</ b:LogicalN ame>";
  10262                         if (attrib utes[i].va lue.Name = = null)
  10263                         { attribut e += "<b:N ame i:nil= \"true\"/> "; }
  10264                         else
  10265                         { attribut e += "<b:N ame>" + at tributes[i ].value.Na me + "</b: Name>"; }
  10266                         attribute  += "</c:va lue>";
  10267                         break;
  10268                }
  10269  
  10270  
  10271  
  10272  
  10273                attribut e += "</b: KeyValuePa irOfstring anyType>"
  10274                attribut esString + = attribut e;
  10275  
  10276           }
  10277           at tributesSt ring += "< /b:Attribu tes>";
  10278  
  10279           re turn attri butesStrin g;
  10280  
  10281       },
  10282       column Set: funct ion (colum ns) {
  10283           if  (columns  == null) {
  10284                return {  allColumn s: false,  columns: [ ] };
  10285           }
  10286           el se {
  10287                var erro rMessage =  "The colu mns parame ter must b e a comma  separated  list of st rings or a n array of  strings." ;
  10288                var arrC olumns = [ ];
  10289                switch ( typeof col umns) {
  10290                    case  "string":
  10291                         arrColumns  = columns .split("," );
  10292                         break;
  10293                    case  "object":
  10294                         if (column s instance of Array)  {
  10295                             var st ringArray  = true;
  10296                             for (v ar i = 0;  i < column s.length;  i++) {
  10297                                 if  (typeof c olumns[i]  != "string ") {
  10298                                      stringAr ray = fals e;
  10299                                      break;
  10300                                 }
  10301                             }
  10302                             if (st ringArray)
  10303                             { arrC olumns = c olumns; }
  10304                             else
  10305                             { thro w new Erro r(errorMes sage); }
  10306                         }
  10307                         else { thr ow new Err or(errorMe ssage); }
  10308                         break;
  10309                    defa ult:
  10310                         throw new  Error(erro rMessage);
  10311                         break;
  10312                }
  10313                return {  allColumn s: false,  columns: a rrColumns  };
  10314           }
  10315       },
  10316       _getCo lumnSet: f unction (c olumnSet)  {
  10317  
  10318           va r col = "< columnSet  xmlns:b=\" http://sch emas.micro soft.com/x rm/2011/Co ntracts\"" ;
  10319           co l += " xml ns:i=\"htt p://www.w3 .org/2001/ XMLSchema- instance\" >";
  10320           if  (columnSe t.allColum ns == true )
  10321           {  col += "<b :AllColumn s>true</b: AllColumns >"; }
  10322           el se {
  10323                col += " <b:AllColu mns>false< /b:AllColu mns>";
  10324                col += " <b:Columns  xmlns:c=\ "http://sc hemas.micr osoft.com/ 2003/10/Se rializatio n/Arrays\" >";
  10325                for (var  i = 0; i  < columnSe t.columns. length; i+ +) {
  10326                    col  += "<c:str ing>" + co lumnSet.co lumns[i] +  "</c:stri ng>";
  10327                }
  10328                col += " </b:Column s>";
  10329           }
  10330  
  10331           co l += "</co lumnSet>";
  10332  
  10333           re turn col;
  10334  
  10335       },
  10336       _Actio n: {
  10337           Ex ecute: "ht tp://schem as.microso ft.com/xrm /2011/Cont racts/Serv ices/IOrga nizationSe rvice/Exec ute",
  10338           Cr eate: "htt p://schema s.microsof t.com/xrm/ 2011/Contr acts/Servi ces/IOrgan izationSer vice/Creat e",
  10339           Re trieve: "h ttp://sche mas.micros oft.com/xr m/2011/Con tracts/Ser vices/IOrg anizationS ervice/Ret rieve",
  10340           Up date: "htt p://schema s.microsof t.com/xrm/ 2011/Contr acts/Servi ces/IOrgan izationSer vice/Updat e",
  10341           De lete: "htt p://schema s.microsof t.com/xrm/ 2011/Contr acts/Servi ces/IOrgan izationSer vice/Delet e",
  10342           Ru nWorkflow:  "http://s chemas.mic rosoft.com /xrm/2011/ Contracts/ Services/I Organizati onService/ Execute"
  10343       },
  10344       _getEr ror: funct ion (fault Xml) {
  10345           va r errorMes sage = "Un known Erro r (Unable  to parse t he fault)" ;
  10346           if  (typeof f aultXml ==  "object")  {
  10347                try {
  10348                    var  bodyNode =  faultXml. firstChild .firstChil d;
  10349                    //Re trieve the  fault nod e
  10350                    for  (var i = 0 ; i < body Node.child Nodes.leng th; i++) {
  10351                         var node =  bodyNode. childNodes [i];
  10352  
  10353                         //NOTE: Th is compari son does n ot handle  the case w here the X ML namespa ce changes
  10354                         if ("s:Fau lt" == nod e.nodeName ) {
  10355                             for (v ar j = 0;  j < node.c hildNodes. length; j+ +) {
  10356                                 va r faultStr ingNode =  node.child Nodes[j];
  10357                                 if  ("faultst ring" == f aultString Node.nodeN ame) {
  10358                                      errorMes sage = fau ltStringNo de.text;
  10359                                      break;
  10360                                 }
  10361                             }
  10362                             break;
  10363                         }
  10364                    }
  10365                }
  10366                catch (e ) { };
  10367           }
  10368  
  10369           re turn new E rror(error Message);
  10370  
  10371       },
  10372       _respo nse: funct ion (succe ssStatus,  parseData)  {
  10373           re turn {
  10374                _state:  "sent",
  10375                _data: n ull,
  10376                _error:  null,
  10377                _parseDa ta: parseD ata,
  10378                onComple te: null,
  10379                _parseRe sponse: fu nction (re q) {
  10380  
  10381                    if ( req.readyS tate == 4)  {
  10382                         this._stat e = "recie ved";
  10383                         if (req.st atus == su ccessStatu s) {
  10384                             this._ data = par seData(req .responseX ML);
  10385                             this._ state = "c omplete";
  10386                             if (th is.onCompl ete != nul l) {
  10387                                 th is.onCompl ete();
  10388                             }
  10389                         }
  10390                         else {
  10391                             this._ state = "e rror";
  10392                             this._ error = ne w MCS.Glob alFunction s._getErro r(req.resp onseXML);
  10393                             if (th is.onCompl ete != nul l) {
  10394                                 th is.onCompl ete();
  10395                             }
  10396                         }
  10397                    }
  10398  
  10399                },
  10400                getError : function  () {
  10401                    if ( this._erro r != null)
  10402                    { re turn this. _error; }
  10403                    else
  10404                    { th row new Er ror("No er ror exists ."); }
  10405                },
  10406                getState : function  ()
  10407                { return  this._sta te; },
  10408                getData:  function  () {
  10409                    if ( this._stat e == "comp lete") {
  10410                         return thi s._data;
  10411                    }
  10412                    else  { throw n ew Error(" Data is no t ready ye t."); }
  10413                }
  10414           };
  10415       },
  10416  
  10417       create RestRecord : function  (recordTo Create, ca llback, re cordType)  {
  10418           va r jsonReco rd = windo w.JSON.str ingify(rec ordToCreat e);
  10419  
  10420           va r createRe q = new XM LHttpReque st();
  10421           cr eateReq.op en("POST",  this._get ClientUrl( "ODATA") +  "/" + rec ordType, t rue);
  10422           cr eateReq.se tRequestHe ader("Acce pt", "appl ication/js on");
  10423           cr eateReq.se tRequestHe ader("Cont ent-Type",  "applicat ion/json;  charset=ut f-8");
  10424           cr eateReq.on readystate change = f unction ()  {
  10425                MCS.Glob alFunction s.createRe stReqCallB ack(this,  callback);
  10426           };
  10427           cr eateReq.se nd(jsonRec ord);
  10428  
  10429       },
  10430       create RestReqCal lBack: fun ction (cre ateReq, ca llback) {
  10431           if  (createRe q.readySta te == 4 /*  complete  */) {
  10432                if (crea teReq.stat us == 201)  {
  10433                    //Su ccess
  10434                    var  newRecord  = JSON.par se(createR eq.respons eText).d;
  10435                    call back(newRe cord);
  10436                }
  10437                else {
  10438                    //Fa ilure
  10439                    MCS. GlobalFunc tions.erro rHandler(c reateReq);
  10440                }
  10441           }
  10442       },
  10443  
  10444  
  10445       Retrie veRecords:  function  (filter, c allback) {
  10446           // / <summary >
  10447           // / Initiate s an async hronous re quest to r etrieve re cords.
  10448           // / If there  are addit ional page s of recor ds the SDK .RestEndpo intPaging. RetrieveRe cordsCallB ack functi on will
  10449           // / call thi s function .
  10450           // / </summar y>
  10451           va r retrieve RecordsReq  = new XML HttpReques t();
  10452           re trieveReco rdsReq.ope n("GET", t his._getCl ientUrl("O DATA") + f ilter, tru e);
  10453           re trieveReco rdsReq.set RequestHea der("Accep t", "appli cation/jso n");
  10454           re trieveReco rdsReq.set RequestHea der("Conte nt-Type",  "applicati on/json; c harset=utf -8");
  10455           re trieveReco rdsReq.onr eadystatec hange = fu nction ()  {
  10456                /// <sum mary>
  10457                /// This  event han dler passe s the call back throu gh
  10458                /// </su mmary>
  10459                MCS.Glob alFunction s.Retrieve RecordsCal lBack(this , callback );
  10460           };
  10461           re trieveReco rdsReq.sen d();
  10462  
  10463       },
  10464       dateRe viver: fun ction (key , value) {
  10465           va r a;
  10466           if  (typeof v alue === ' string') {
  10467                a = /^(\ d{4})-(\d{ 2})-(\d{2} )T(\d{2}): (\d{2}):(\ d{2}(?:\.\ d*)?)Z$/.e xec(value) ;
  10468                if (a) {
  10469                    retu rn new Dat e(Date.UTC (+a[1], +a [2] - 1, + a[3], +a[4 ], +a[5],  +a[6]));
  10470                }
  10471           }
  10472           re turn value ;
  10473       },
  10474       Retrie veRecordsC allBack: f unction (r etrieveRec ordsReq, c allback) {
  10475           // / <summary >
  10476           // / Handles  the onread ystatechan ge event t o process  the record s returned .
  10477           // / If more  pages are  available  this funct ion will c all the SD K.RestEndp ointPaging .RetrieveR ecords 
  10478           // / function  to get th e rest.
  10479           // / </summar y>
  10480           if  (retrieve RecordsReq .readyStat e == 4 /*  complete * /) {
  10481                if (retr ieveRecord sReq.statu s == 200)  {
  10482                    //Su ccess
  10483                    var  retrievedR ecords = J SON.parse( retrieveRe cordsReq.r esponseTex t, MCS.Glo balFunctio ns.dateRev iver).d;
  10484                    ///  The callba ck is call ed with th e results.
  10485                    call back(retri evedRecord s.results) ;
  10486  
  10487                    if ( null != re trievedRec ords.__nex t) {
  10488                         // The exi stance of  the '__nex t' propert y indicate s that mor e records  are availa ble
  10489                         // So the  originatin g function  is called  again usi ng the fil ter value  returned
  10490                         var filter  = retriev edRecords. __next.rep lace(MCS.G lobalFunct ions.GetOD ataPath(),  "");
  10491                         MCS.Global Functions. RetrieveRe cords(filt er, callba ck);
  10492                    }
  10493  
  10494  
  10495                }
  10496                else {
  10497                    //Fa ilure
  10498                    MCS. GlobalFunc tions.erro rHandler(r etrieveRec ordsReq);
  10499  
  10500                }
  10501           }
  10502       },
  10503       //Func tion to ha ndle any h ttp errors
  10504       errorH andler: fu nction (Xm lHttpReque st) {
  10505           // / <summary >
  10506           // / Simply d isplays an  alert mes sage with  details ab out any er rors.
  10507           // / </summar y>
  10508           if  (XmlHttpR equest) {
  10509                if (XmlH ttpRequest .status !=  null) {
  10510                    if ( XMLHttpReq uest.statu sText != n ull) {
  10511                         alert("Err or : " +
  10512                                 Xm lHttpReque st.status  + ": " +
  10513                         XmlHttpReq uest.statu sText + ":  " +
  10514                                 JS ON.parse(X mlHttpRequ est.respon seText).er ror.messag e.value);
  10515                    }
  10516                    else  {
  10517                         alert(XMLH ttpRequest );
  10518                    }
  10519                }
  10520                else {
  10521                    aler t(XMLHttpR equest);
  10522                }
  10523           }
  10524           el se {
  10525                alert("U nknown err or occurre d");
  10526           }
  10527       },
  10528  
  10529       __name space: tru e
  10530   };
  10531   var XrmSvc Toolkit =  (function  (window, u ndefined)  {
  10532       /**
  10533       * XrmS vcToolkit  v0.2, a sm all JavaSc ript libra ry that he lps access  
  10534       * Micr osoft Dyna mics CRM 2 011 web se rvice inte rfaces (SO AP and RES T)
  10535       *
  10536       * @cop yright     Copyright  (c) 2011 -  2013, Kin gswaySoft  (http://ww w.kingsway soft.com)
  10537       * @lic ense       Microsoft  Public Lic ense (Ms-P L)
  10538       * @dev eloper     Daniel Cai  (http://d anielcai.b logspot.co m)
  10539  
  10540       * @con tributors  George Dou binski, Mi tch Milam,  Carsten G roth
  10541       *
  10542       * THIS  SOFTWARE  IS PROVIDE D BY Kings waySoft '' AS IS'' AN D ANY
  10543       * EXPR ESS OR IMP LIED WARRA NTIES, INC LUDING, BU T NOT LIMI TED TO, TH E IMPLIED
  10544       * WARR ANTIES OF  MERCHANTAB ILITY AND  FITNESS FO R A PARTIC ULAR PURPO SE ARE
  10545       * DISC LAIMED. IN  NO EVENT  SHALL King swaySoft B E LIABLE F OR ANY
  10546       * DIRE CT, INDIRE CT, INCIDE NTAL, SPEC IAL, EXEMP LARY, OR C ONSEQUENTI AL DAMAGES
  10547       * (INC LUDING, BU T NOT LIMI TED TO, PR OCUREMENT  OF SUBSTIT UTE GOODS  OR SERVICE S;
  10548       * LOSS  OF USE, D ATA, OR PR OFITS; OR  BUSINESS I NTERRUPTIO N) HOWEVER  CAUSED AN D
  10549       * ON A NY THEORY  OF LIABILI TY, WHETHE R IN CONTR ACT, STRIC T LIABILIT Y, OR TORT
  10550       * (INC LUDING NEG LIGENCE OR  OTHERWISE ) ARISING  IN ANY WAY  OUT OF TH E USE OF T HIS
  10551       * SOFT WARE, EVEN  IF ADVISE D OF THE P OSSIBILITY  OF SUCH D AMAGE.
  10552       *
  10553       */
  10554  
  10555       var od ataEndpoin t = "/XRMS ervices/20 11/Organiz ationData. svc",
  10556           so apEndpoint  = "/XRMSe rvices/201 1/Organiza tion.svc/w eb";
  10557  
  10558       // Typ e snifferi ng
  10559       var to String = O bject.prot otype.toSt ring,
  10560           is Function =  function  (o) {
  10561                return t oString.ca ll(o) ===  "[object F unction]";
  10562           },
  10563           is Integer =  function ( o) {
  10564                return ! isNaN(pars eInt(o));
  10565           },
  10566           is String = f unction (o ) {
  10567                return t oString.ca ll(o) ===  "[object S tring]";
  10568           },
  10569           is Array = fu nction (o)  {
  10570                return t oString.ca ll(o) ===  "[object A rray]";
  10571           },
  10572           is NonEmptySt ring = fun ction (o)  {
  10573                if (!isS tring(o) | | o.length  === 0) {
  10574                    retu rn false;
  10575                }
  10576  
  10577                // check s for a no n-white sp ace charac ter 
  10578                return / [^\s]+/.te st(o);
  10579           };
  10580  
  10581       var is oDateExpr  = /^(\d{4} )-(\d{2})- (\d{2})T(\ d{2}):(\d{ 2}):(\d{2} )\.?(\d*)? (Z|[+-]\d{ 2}?(:\d{2} )?)?$/,
  10582           js onDateExpr  = /^\/Dat e\(([-+]?\ d+)\)\/$/;
  10583  
  10584       var co ntext = (f unction ()  {
  10585           if  (isFuncti on(window. GetGlobalC ontext)) {
  10586                return G etGlobalCo ntext();
  10587           }  else if (X rm != unde fined) {
  10588                return X rm.Page.co ntext;
  10589           }  else {
  10590                throw ne w Error("C RM context  is not av ailable.") ;
  10591           }
  10592       })();
  10593  
  10594       var cl ientUrl =  (function  () {
  10595           if  (context. getClientU rl !== und efined) {
  10596                return c ontext.get ClientUrl( );
  10597           }
  10598  
  10599           va r localSer verUrl = w indow.loca tion.proto col + "//"  + window. location.h ost;
  10600           if  (context. isOutlookC lient() &&  !context. isOutlookO nline()) {
  10601                return l ocalServer Url;
  10602           }  else {
  10603                var crmS erverUrl =  context.g etClientUr l();
  10604                crmServe rUrl = crm ServerUrl. replace(/^ (http|http s):\/\/([_ a-zA-Z0-9\ -\.]+)(:([ 0-9]{1,5}) )?/, local ServerUrl) ;
  10605                crmServe rUrl = crm ServerUrl. replace(/\ /$/, "");
  10606           }
  10607  
  10608           re turn crmSe rverUrl;
  10609       })();
  10610  
  10611       var re stErrorHan dler = fun ction (req ) {
  10612           va r errorMes sage;
  10613  
  10614           tr y {
  10615                errorMes sage = JSO N.parse(re q.response Text).erro r.message. value;
  10616           }  catch (err ) {
  10617                // Ignor e any erro r when par sing the e rror messa ge. 
  10618                errorMes sage = req .responseT ext;
  10619           }
  10620  
  10621           er rorMessage  = errorMe ssage.leng th > 0
  10622                ? "Error : " + req. status + " : " + req. statusText  + ": " +  errorMessa ge
  10623                : "Error : " + req. status + " : " + req. statusText ;
  10624  
  10625           re turn new E rror(error Message);
  10626       };
  10627  
  10628       var so apErrorHan dler = fun ction (req ) {
  10629           va r errorMes sage = req .responseT ext.length  > 0
  10630                ? "Error : " + req. status + " : " + req. statusText  + ": " +  req.respon seText
  10631                : "Error : " + req. status + " : " + req. statusText ;
  10632  
  10633           re turn new E rror(error Message);
  10634       };
  10635  
  10636       var da teReviver  = function  (key, val ue) {
  10637           if  (typeof v alue === ' string') {
  10638                if (valu e.match(js onDateExpr )) {
  10639                    var  dateValue  = value.re place(json DateExpr,  "$1");
  10640                    retu rn new Dat e(parseInt (dateValue , 10));
  10641                }
  10642           }
  10643           re turn value ;
  10644       };
  10645  
  10646       var xm lEncode =  function ( input) {
  10647           if  (input ==  null) {
  10648                return n ull;
  10649           }
  10650  
  10651           if  (input ==  '') {
  10652                return ' ';
  10653           }
  10654  
  10655           va r c;
  10656           va r result =  '';
  10657  
  10658           fo r (var pos  = 0; pos  < input.le ngth; pos+ +) {
  10659                c = inpu t.charCode At(pos);
  10660  
  10661                if ((c >  96 && c <  123) ||
  10662                    (c >  64 && c <  91) ||
  10663                    (c >  47 && c <  58) ||
  10664                    (c = = 32) ||
  10665                    (c = = 44) ||
  10666                    (c = = 46) ||
  10667                    (c = = 45) ||
  10668                    (c = = 95)) {
  10669                    resu lt = resul t + String .fromCharC ode(c);
  10670                } else {
  10671                    resu lt = resul t + '&#' +  c + ';';
  10672                }
  10673           }
  10674  
  10675           re turn resul t;
  10676       };
  10677  
  10678       var pa rseIsoDate  = functio n (s) {
  10679           if  (s == nul l || !s.ma tch(isoDat eExpr))
  10680                return n ull;
  10681  
  10682           va r datePart s = isoDat eExpr.exec (s);
  10683           re turn new D ate(Date.U TC(parseIn t(datePart s[1], 10),
  10684                parseInt (dateParts [2], 10) -  1,
  10685                parseInt (dateParts [3], 10),
  10686                parseInt (dateParts [4], 10) -  (datePart s[8] == ""  || datePa rts[8] ==  "Z" ? 0 :  parseInt(d ateParts[8 ])),
  10687                parseInt (dateParts [5], 10),
  10688                parseInt (dateParts [6], 10))) ;
  10689       };
  10690  
  10691       var ge tAttribute  = functio n (xmlNode , attrName ) {
  10692           fo r (var i =  0; i < xm lNode.attr ibutes.len gth; i++)  {
  10693                var attr  = xmlNode .attribute s[i];
  10694                if (attr .name == a ttrName) {
  10695                    retu rn attr.va lue;
  10696                }
  10697           }
  10698       };
  10699  
  10700       var ge tNodeText  = function  (node) {
  10701           re turn node. text !== u ndefined
  10702                ? node.t ext
  10703                : node.t extContent ;
  10704       }
  10705  
  10706       var ge tTypedValu e = functi on (fieldT ype, value Node) {
  10707           sw itch (fiel dType) {
  10708                case "c: string":
  10709                case "c: guid":
  10710                    retu rn getNode Text(value Node);
  10711                case "c: boolean":
  10712                    retu rn getNode Text(value Node) ===  "true";
  10713                case "c: int":
  10714                    retu rn parseIn t(getNodeT ext(valueN ode));
  10715                case "c: decimal":
  10716                case "c: double":
  10717                    retu rn parseFl oat(getNod eText(valu eNode));
  10718                case "c: dateTime":
  10719                    retu rn parseIs oDate(getN odeText(va lueNode));
  10720                case "a: OptionSetV alue":
  10721                    valu eNode = ge tChildNode (valueNode , "a:Value ");
  10722                    retu rn {
  10723                         Value: par seInt(getN odeText(va lueNode))
  10724                    };
  10725                case "a: Money":
  10726                    valu eNode = ge tChildNode (valueNode , "a:Value ");
  10727                    retu rn {
  10728                         Value: get NodeText(v alueNode)
  10729                    };
  10730                case "a: EntityRefe rence":
  10731                    retu rn getEnti tyReferenc e(valueNod e);
  10732                case "a: EntityColl ection":
  10733                    retu rn getEnti tyCollecti on(valueNo de);
  10734                case "a: AliasedVal ue":
  10735                    valu eNode = ge tChildNode (valueNode , "a:Value ");
  10736                    fiel dType = ge tAttribute (valueNode , "i:type" );
  10737                    retu rn getType dValue(fie ldType, va lueNode);
  10738  
  10739                default:
  10740                    thro w new Erro r("Unhandl ed field t ype: \"" +  fieldType  + "\", pl ease repor t the prob lem to the  developer . ");
  10741           }
  10742       };
  10743  
  10744       var co ncatOdataF ields = fu nction (fi elds, para meterName)  {
  10745           if  (isArray( fields) &&  fields.le ngth > 0)  {
  10746                return f ields.join (',');
  10747           }  else if (i sString(fi elds)) {
  10748                return f ields;
  10749           }
  10750           el se if (par ameterName  != undefi ned) {
  10751                throw ne w Error(pa rameterNam e + " para meter must  be either  a delimit ed string  or an arra y. ");
  10752           }
  10753           el se {
  10754                return " ";
  10755           }
  10756       };
  10757  
  10758       // Get  a list of  entities  from an En tityCollec tion XML n ode.
  10759       var ge tEntityCol lection =  function ( entityColl ectionNode ) {
  10760           va r entityNa me, moreRe cords, pag ingCookie,  totalReco rdCount, e ntitiesNod e;
  10761  
  10762           //  Try to ge t all chil d nodes in  one pass
  10763           fo r (var m =  0; m < en tityCollec tionNode.c hildNodes. length; m+ +) {
  10764                var coll ectionChil dNode = en tityCollec tionNode.c hildNodes[ m];
  10765                switch ( collection ChildNode. nodeName)  {
  10766                    case  "a:Entity Name":
  10767                         entityName  = getNode Text(colle ctionChild Node);
  10768                         break;
  10769                    case  "a:MoreRe cords":
  10770                         moreRecord s = getNod eText(coll ectionChil dNode) ===  "true";
  10771                         break;
  10772                    case  "a:Paging Cookie":
  10773                         pagingCook ie = getNo deText(col lectionChi ldNode);
  10774                         break;
  10775                    case  "a:TotalR ecordCount ":
  10776                         totalRecor dCount = p arseInt(ge tNodeText( collection ChildNode) );
  10777                         break;
  10778                    case  "a:Entiti es":
  10779                         entitiesNo de = colle ctionChild Node;
  10780                         break;
  10781                }
  10782           }
  10783  
  10784           va r result =  {
  10785                entityNa me: entity Name,
  10786                moreReco rds: moreR ecords,
  10787                pagingCo okie: pagi ngCookie,
  10788                totalRec ordCount:  totalRecor dCount,
  10789                entities : []
  10790           };
  10791  
  10792           fo r (var i =  0; i < en titiesNode .childNode s.length;  i++) {
  10793                var enti ty = { for mattedValu es: [] };
  10794                var enti tyNode = e ntitiesNod e.childNod es[i];
  10795                var attr ibutes = g etChildNod e(entityNo de, "a:Att ributes");
  10796                for (var  j = 0; j  < attribut es.childNo des.length ; j++) {
  10797                    var  attr = att ributes.ch ildNodes[j ];
  10798  
  10799                    var  fieldName  = getNodeT ext(getChi ldNode(att r, "b:key" ));
  10800                    var  valueNode  = getChild Node(attr,  "b:value" );
  10801                    var  fieldType  = getAttri bute(value Node, "i:t ype");
  10802  
  10803                    enti ty[fieldNa me] = getT ypedValue( fieldType,  valueNode );
  10804                }
  10805  
  10806                var form attedValue s = getChi ldNode(ent ityNode, " a:Formatte dValues");
  10807  
  10808                for (var  k = 0; k  < formatte dValues.ch ildNodes.l ength; k++ ) {
  10809                    var  valuePair  = formatte dValues.ch ildNodes[k ];
  10810                    enti ty.formatt edValues[g etNodeText (getChildN ode(valueP air, "b:ke y"))] = ge tNodeText( getChildNo de(valuePa ir, "b:val ue"));
  10811                }
  10812  
  10813                result.e ntities.pu sh(entity) ;
  10814           }
  10815  
  10816           re turn resul t;
  10817       };
  10818  
  10819       // Get  an Entity Reference  from an XM L node. Fo r performa nce reason , we try t o
  10820       // get  the entit y referenc e in one p ass, inste ad of mult iple.
  10821       var ge tEntityRef erence = f unction (x mlNode) {
  10822           va r id, logi calName, n ame;
  10823           fo r (var i =  0; i < xm lNode.chil dNodes.len gth; i++)  {
  10824                var chil dNode = xm lNode.chil dNodes[i];
  10825  
  10826                switch ( childNode. nodeName)  {
  10827                    case  "a:Id":
  10828                         id = getNo deText(chi ldNode);
  10829                         break;
  10830                    case  "a:Logica lName":
  10831                         logicalNam e = getNod eText(chil dNode);
  10832                         break;
  10833                    case  "a:Name":
  10834                         name = get NodeText(c hildNode);
  10835                         break;
  10836                }
  10837           }
  10838  
  10839           re turn {
  10840                Id: id,
  10841                LogicalN ame: logic alName,
  10842                Name: na me
  10843           };
  10844       }
  10845  
  10846       // Get  a single  child node  that matc hes the sp ecified na me.
  10847       var ge tChildNode  = functio n (xmlNode , nodeName ) {
  10848           fo r (var i =  0; i < xm lNode.chil dNodes.len gth; i++)  {
  10849                var chil dNode = xm lNode.chil dNodes[i];
  10850  
  10851                if (chil dNode.node Name == no deName) {
  10852                    retu rn childNo de;
  10853                }
  10854           }
  10855       }
  10856  
  10857       var ge tSoapError  = functio n (soapXml ) {
  10858           tr y {
  10859                var body Node = soa pXml.first Child.firs tChild;
  10860                var faul tNode = ge tChildNode (bodyNode,  "s:Fault" );
  10861                var faul tStringNod e = getChi ldNode(fau ltNode, "f aultstring ");
  10862                return n ew Error(g etNodeText (faultStri ngNode));
  10863           }
  10864           ca tch (e) {
  10865                return n ew Error(" An error o ccurred wh en parsing  the error  returned  from CRM s erver: " +  e.message );
  10866           }
  10867       }
  10868  
  10869       var pr ocessSoapR esponse =  function ( responseXm l, success Callback,  errorCallb ack) {
  10870           tr y {
  10871                var exec uteResult  = response Xml.firstC hild.first Child.firs tChild.fir stChild; / / "s:Envel ope/s:Body /ExecuteRe sponse/Exe cuteResult "
  10872           }  catch (err ) {
  10873                errorCal lback(err) ;
  10874                return;
  10875           }
  10876  
  10877           re turn succe ssCallback (executeRe sult);
  10878       };
  10879  
  10880       var ge tFetchResu lts = func tion (resu ltXml) {
  10881           //  For simpl icity reas on, we are  assuming  the return ed SOAP me ssage uses  the follo wing three  namespace  aliases
  10882           //    xmlns:a ="http://s chemas.mic rosoft.com /xrm/2011/ Contracts"
  10883           //    xmlns:i ="http://w ww.w3.org/ 2001/XMLSc hema-insta nce"
  10884           //    xmlns:b ="http://s chemas.dat acontract. org/2004/0 7/System.C ollections .Generic"
  10885           //  however i t is possi ble that t he namespa ce aliases  returned  from CRM s erver coul d be diffe rent, in w hich
  10886           //  case, the  fetch fun ction will  not work  properly
  10887           //  For futur e referenc e, XPath t o the enti ty collect ion node:
  10888           //  a:Results /a:KeyValu ePairOfstr inganyType /b:value[@ i:type='a: EntityColl ection']
  10889           va r resultsN ode = getC hildNode(r esultXml,  "a:Results "); // a:R esults
  10890           va r entityCo llectionNo de = getCh ildNode(re sultsNode. firstChild , "b:value "); // b:v alue
  10891           re turn getEn tityCollec tion(entit yCollectio nNode);
  10892       };
  10893  
  10894       var pr ocessRestR esult = fu nction (re q, success Callback,  errorCallb ack) {
  10895           if  ((req.sta tus >= 200  && req.st atus < 300 ) || req.s tatus ===  304 || req .status == = 1223) {
  10896                try {
  10897                    var  result = ( !!req.resp onseText)
  10898                                                                ? JS ON.parse(r eq.respons eText, dat eReviver). d
  10899                                                                : nu ll;
  10900                } catch  (err) {
  10901                    erro rCallback( err);
  10902                    retu rn;
  10903                }
  10904  
  10905                return s uccessCall back(resul t);
  10906  
  10907           }  else {
  10908                errorCal lback(rest ErrorHandl er(req));
  10909           }
  10910       };
  10911  
  10912       var do RestReques t = functi on (restRe q, success Callback,  errorCallb ack) {
  10913           va r req = ne w XMLHttpR equest();
  10914           re q.open(res tReq.type,  restReq.u rl, restRe q.async);
  10915           re q.setReque stHeader(" Accept", " applicatio n/json");
  10916           re q.setReque stHeader(" Content-Ty pe", "appl ication/js on; charse t=utf-8");
  10917           if  (!!restRe q.method)  {
  10918                req.setR equestHead er("X-HTTP -Method",  restReq.me thod);
  10919           }
  10920  
  10921           va r erred =  false;
  10922  
  10923           if  (restReq. async) {
  10924                req.onre adystatech ange = fun ction () {
  10925                    if ( req.readyS tate == 4  /* complet e */) {
  10926                         processRes tResult(re q, success Callback,  errorCallb ack);
  10927                    }
  10928                };
  10929  
  10930                if (!!re stReq.data ) {
  10931                    req. send(restR eq.data);
  10932                } else {
  10933                    req. send();
  10934                }
  10935           }  else {
  10936                try {
  10937                    //sy nchronous:  send requ est, then  call the c allback fu nctions
  10938                    if ( !!restReq. data) {
  10939                         req.send(r estReq.dat a);
  10940                    } el se {
  10941                         req.send() ;
  10942                    }
  10943  
  10944                    retu rn process RestResult (req, succ essCallbac k, errorCa llback);
  10945  
  10946                } catch  (err) {
  10947                    erro rCallback( err);
  10948                }
  10949           }
  10950       };
  10951  
  10952       var do SoapReques t = functi on (soapBo dy, async,  successCa llback, er rorCallbac k) {
  10953           va r req = ne w XMLHttpR equest();
  10954  
  10955           re q.open("PO ST", clien tUrl + soa pEndpoint,  async);
  10956           re q.setReque stHeader(" Accept", " applicatio n/xml, tex t/xml, */* ");
  10957           re q.setReque stHeader(" Content-Ty pe", "text /xml; char set=utf-8" );
  10958           re q.setReque stHeader(" SOAPAction ", "http:/ /schemas.m icrosoft.c om/xrm/201 1/Contract s/Services /IOrganiza tionServic e/Execute" );
  10959  
  10960           va r soapXml  = [
  10961   '<s:Envelo pe xmlns:s ="http://s chemas.xml soap.org/s oap/envelo pe/"><s:Bo dy>',
  10962       soapBo dy,
  10963   '</s:Body> </s:Envelo pe>'].join ('');
  10964  
  10965           if  (async) {
  10966                req.onre adystatech ange = fun ction () {
  10967                    if ( req.readyS tate == 4)  { // "com plete"
  10968                         if (req.st atus == 20 0) { // "O K"
  10969                             proces sSoapRespo nse(req.re sponseXML,  successCa llback, er rorCallbac k);
  10970                         } else {
  10971                             errorC allback(so apErrorHan dler(req)) ;
  10972                         }
  10973                    }
  10974                };
  10975  
  10976                req.send (soapXml);
  10977           }  else {
  10978                var sync Result;
  10979                try {
  10980                    //sy nchronous:  send requ est, then  call the c allback fu nction dir ectly
  10981                    req. send(soapX ml);
  10982                    if ( req.status  == 200) {
  10983                         return pro cessSoapRe sponse(req .responseX ML, succes sCallback,  errorCall back);
  10984                    }
  10985                    else  {
  10986                         var syncEr r = getSoa pError(req .responseX ML);
  10987                         errorCallb ack(syncEr r);
  10988                         return;
  10989                    }
  10990                } catch  (err) {
  10991                    erro rCallback( err);
  10992                    retu rn;
  10993                }
  10994  
  10995                successC allback(sy ncResult);
  10996           }
  10997       };
  10998  
  10999       var ex ecute = fu nction (op ts) {
  11000  
  11001           if  (!isNonEm ptyString( opts.execu teXml)) {
  11002                throw ne w Error("e xecuteXml  parameter  was not pr ovided. ") ;
  11003           }
  11004  
  11005           va r async =  !!opts.asy nc;
  11006  
  11007           re turn doSoa pRequest(o pts.execut eXml, asyn c, functio n (result)  {
  11008                if (isFu nction(opt s.successC allback))  {
  11009                    opts .successCa llback(res ult);
  11010                }
  11011  
  11012                if (!asy nc) {
  11013                    retu rn result;
  11014                }
  11015           },  function  (err) {
  11016                if (isFu nction(opt s.errorCal lback)) {
  11017                    opts .errorCall back(err);
  11018                }
  11019                else {
  11020                    thro w err;
  11021                }
  11022           }) ;
  11023       };
  11024  
  11025       var se tState = f unction (o pts) {
  11026  
  11027           if  (!isNonEm ptyString( opts.id))  {
  11028                throw ne w Error("i d paramete r was not  provided.  ");
  11029           }
  11030  
  11031           if  (!isNonEm ptyString( opts.entit yName)) {
  11032                throw ne w Error("e ntityName  parameter  was not pr ovided. ") ;
  11033           }
  11034  
  11035           if  (!isInteg er(opts.st ateCode))  {
  11036                throw ne w Error("s tateCode p arameter m ust be an  integer. " );
  11037           }
  11038  
  11039           if  (opts.sta tusCode ==  null) {
  11040                opts.sta tusCode =  -1;
  11041           }
  11042  
  11043           va r request  = [
  11044   '<Execute  xmlns="htt p://schema s.microsof t.com/xrm/ 2011/Contr acts/Servi ces">',
  11045       '<requ est i:type ="b:SetSta teRequest" ',
  11046                ' xmlns: a="http:// schemas.mi crosoft.co m/xrm/2011 /Contracts " ',
  11047                ' xmlns: b="http:// schemas.mi crosoft.co m/crm/2011 /Contracts " ',
  11048                ' xmlns: c="http:// schemas.da tacontract .org/2004/ 07/System. Collection s.Generic"  ',
  11049                ' xmlns: i="http:// www.w3.org /2001/XMLS chema-inst ance">',
  11050           '< a:Paramete rs>',
  11051                '<a:KeyV aluePairOf stringanyT ype>',
  11052                    '<c: key>Entity Moniker</c :key>',
  11053                    '<c: value i:ty pe="a:Enti tyReferenc e">',
  11054                         '<a:Id>',  opts.id, ' </a:Id>',
  11055                         '<a:Logica lName>', o pts.entity Name, '</a :LogicalNa me>',
  11056                         '<a:Name i :nil="true " />',
  11057                    '</c :value>',
  11058                '</a:Key ValuePairO fstringany Type>',
  11059                '<a:KeyV aluePairOf stringanyT ype>',
  11060                    '<c: key>State< /c:key>',
  11061                    '<c: value i:ty pe="a:Opti onSetValue ">',
  11062                         '<a:Value> ', opts.st ateCode, ' </a:Value> ',
  11063                    '</c :value>',
  11064                '</a:Key ValuePairO fstringany Type>',
  11065                '<a:KeyV aluePairOf stringanyT ype>',
  11066                    '<c: key>Status </c:key>',
  11067                    '<c: value i:ty pe="a:Opti onSetValue ">',
  11068                         '<a:Value> ', opts.st atusCode,  '</a:Value >',
  11069                    '</c :value>',
  11070                '</a:Key ValuePairO fstringany Type>',
  11071           '< /a:Paramet ers>',
  11072           '< a:RequestI d i:nil="t rue"/>',
  11073           '< a:RequestN ame>SetSta te</a:Requ estName>',
  11074       '</req uest>',
  11075   '</Execute >'].join(" ");
  11076  
  11077           va r async =  !!opts.asy nc;
  11078  
  11079           re turn doSoa pRequest(r equest, as ync, funct ion (resul t) {
  11080                if (isFu nction(opt s.successC allback))  {
  11081                    opts .successCa llback(res ult);
  11082                }
  11083  
  11084                if (!asy nc) {
  11085                    retu rn result;
  11086                }
  11087           },  function  (err) {
  11088                if (isFu nction(opt s.errorCal lback)) {
  11089                    opts .errorCall back(err);
  11090                }
  11091                else {
  11092                    thro w err;
  11093                }
  11094           }) ;
  11095       };
  11096  
  11097       var fe tch = func tion (opts ) {
  11098           if  (!isNonEm ptyString( opts.fetch Xml)) {
  11099                throw ne w Error("f etchXml pa rameter wa s not prov ided. ");
  11100           }
  11101  
  11102           va r request  = [
  11103   '<Execute  xmlns="htt p://schema s.microsof t.com/xrm/ 2011/Contr acts/Servi ces">',
  11104       '<requ est i:type ="a:Retrie veMultiple Request"',
  11105                ' xmlns: a="http:// schemas.mi crosoft.co m/xrm/2011 /Contracts " ',
  11106                ' xmlns: i="http:// www.w3.org /2001/XMLS chema-inst ance">',
  11107           '< a:Paramete rs xmlns:c ="http://s chemas.dat acontract. org/2004/0 7/System.C ollections .Generic"> ',
  11108                '<a:KeyV aluePairOf stringanyT ype>',
  11109                    '<c: key>Query< /c:key>',
  11110                    '<c: value i:ty pe="a:Fetc hExpressio n">',
  11111                         '<a:Query> ', xmlEnco de(opts.fe tchXml), ' </a:Query> ',
  11112                    '</c :value>',
  11113                '</a:Key ValuePairO fstringany Type>',
  11114           '< /a:Paramet ers>',
  11115           '< a:RequestI d i:nil="t rue"/>',
  11116           '< a:RequestN ame>Retrie veMultiple </a:Reques tName>',
  11117       '</req uest>',
  11118   '</Execute >'].join(" ");
  11119  
  11120           va r async =  !!opts.asy nc;
  11121  
  11122           re turn doSoa pRequest(r equest, as ync, funct ion (resul t) {
  11123                var fetc hResults =  getFetchR esults(res ult);
  11124  
  11125                if (isFu nction(opt s.successC allback))  {
  11126                    opts .successCa llback(fet chResults) ;
  11127                }
  11128  
  11129                if (!asy nc) {
  11130                    retu rn fetchRe sults;
  11131                }
  11132           },  function  (err) {
  11133                if (isFu nction(opt s.errorCal lback)) {
  11134                    opts .errorCall back(err);
  11135                }
  11136                else {
  11137                    thro w err;
  11138                }
  11139           }) ;
  11140       };
  11141  
  11142       var re trieve = f unction (o pts) {
  11143           if  (!isNonEm ptyString( opts.entit yName)) {
  11144                throw ne w Error("e ntityName  parameter  was not pr ovided. ") ;
  11145           }
  11146  
  11147           if  (!isNonEm ptyString( opts.id))  {
  11148                throw ne w Error("i d paramete r was not  provided.  ");
  11149           }
  11150  
  11151           va r select =  opts.sele ct == null
  11152                ? ""
  11153                : concat OdataField s(opts.sel ect, "sele ct");
  11154  
  11155           va r expand =  opts.expa nd == null
  11156                ? ""
  11157                : concat OdataField s(opts.exp and, "expa nd");
  11158  
  11159           va r odataQue ry = "";
  11160  
  11161           if  (select.l ength > 0  || expand. length > 0 ) {
  11162                odataQue ry = "?";
  11163                if (sele ct.length  > 0) {
  11164                    odat aQuery +=  "$select="  + select;
  11165  
  11166                    if ( expand.len gth > 0) {
  11167                         odataQuery  += "&";
  11168                    }
  11169                }
  11170  
  11171                if (expa nd.length  > 0) {
  11172                    odat aQuery +=  "$expand="  + expand;
  11173                }
  11174           }
  11175  
  11176           va r restReq  = {
  11177                url: cli entUrl + o dataEndpoi nt + "/" +  opts.enti tyName + " Set(guid'"  + opts.id  + "')" +  odataQuery ,
  11178                type: "G ET",
  11179                async: ! !opts.asyn c
  11180           };
  11181  
  11182           re turn doRes tRequest(r estReq, fu nction (re sult) {
  11183                if (isFu nction(opt s.successC allback))  {
  11184                    opts .successCa llback(res ult);
  11185                }
  11186  
  11187                if (!opt s.async) {
  11188                    retu rn result;
  11189                }
  11190           },  function  (err) {
  11191                if (isFu nction(opt s.errorCal lback)) {
  11192                    opts .errorCall back(err);
  11193                } else {
  11194                    thro w err;
  11195                }
  11196           }) ;
  11197       };
  11198  
  11199       var re trieveMult iple = fun ction (opt s) {
  11200           if  (!isNonEm ptyString( opts.entit yName)) {
  11201                throw ne w Error("e ntityName  parameter  was not pr ovided. ") ;
  11202           }
  11203  
  11204           va r odataQue ry = "";
  11205           if  (opts.oda taQuery !=  null) {
  11206                if (!isS tring(opts .odataQuer y)) {
  11207                    thro w new Erro r("odataQu ery parame ter must b e a string . ");
  11208                }
  11209  
  11210                if (opts .odataQuer y.charAt(0 ) != "?")  {
  11211                    odat aQuery = " ?" + opts. odataQuery ;
  11212                } else {
  11213                    odat aQuery = o pts.odataQ uery;
  11214                }
  11215           }
  11216  
  11217           va r restReq  = {
  11218                url: cli entUrl + o dataEndpoi nt + "/" +  opts.enti tyName + " Set" + oda taQuery,
  11219                type: "G ET",
  11220                async: ! !opts.asyn c
  11221           };
  11222  
  11223           re turn doRes tRequest(r estReq, fu nction (re sult) {
  11224                if (isFu nction(opt s.successC allback))  {
  11225                    opts .successCa llback(res ult.result s);
  11226                }
  11227  
  11228                if (!opt s.async) {
  11229                    retu rn result. results;
  11230                }
  11231  
  11232                if (resu lt.__next  != null) {
  11233                    opts .odataQuer y = result .__next.su bstring((c lientUrl +  odataEndp oint + "/"  + opts.en tityName +  "Set").le ngth);
  11234                    retr ieveMultip le(opts);
  11235                } else {
  11236                    if ( isFunction (opts.comp letionCall back)) {
  11237                         opts.compl etionCallb ack();
  11238                    }
  11239                }
  11240           },  function  (err) {
  11241                if (isFu nction(opt s.errorCal lback)) {
  11242                    opts .errorCall back(err);
  11243                } else {
  11244                    thro w err;
  11245                }
  11246           }) ;
  11247       };
  11248  
  11249       var cr eateRecord  = functio n (opts) {
  11250           if  (!isNonEm ptyString( opts.entit yName)) {
  11251                throw ne w Error("e ntityName  parameter  was not pr ovided. ") ;
  11252           }
  11253  
  11254           if  (opts.ent ity === nu ll || opts .entity == = undefine d) {
  11255                throw ne w Error("e ntity para meter was  not provid ed. ");
  11256           }
  11257  
  11258           va r restReq  = {
  11259                url: cli entUrl + o dataEndpoi nt + "/" +  opts.enti tyName + ' Set',
  11260                type: "P OST",
  11261                data: wi ndow.JSON. stringify( opts.entit y),
  11262                async: ! !opts.asyn c
  11263           };
  11264  
  11265           re turn doRes tRequest(r estReq, fu nction (re sult) {
  11266                if (isFu nction(opt s.successC allback))  {
  11267                    opts .successCa llback(res ult);
  11268                }
  11269  
  11270                if (!opt s.async) {
  11271                    retu rn result;
  11272                }
  11273           },  function  (err) {
  11274                if (isFu nction(opt s.errorCal lback)) {
  11275                    opts .errorCall back(err);
  11276                } else {
  11277                    thro w err;
  11278                }
  11279           }) ;
  11280       };
  11281  
  11282       var up dateRecord  = functio n (opts) {
  11283           if  (!isNonEm ptyString( opts.entit yName)) {
  11284                throw ne w Error("e ntityName  parameter  was not pr ovided. ") ;
  11285           }
  11286  
  11287           if  (!isNonEm ptyString( opts.id))  {
  11288                throw ne w Error("i d paramete r was not  provided.  ");
  11289           }
  11290  
  11291           if  (opts.ent ity === nu ll || opts .entity == = undefine d) {
  11292                throw ne w Error("e ntity para meter was  not provid ed. ");
  11293           }
  11294  
  11295           va r restReq  = {
  11296                url: cli entUrl + o dataEndpoi nt + "/" +  opts.enti tyName + " Set(guid'"  + opts.id  + "')",
  11297                type: "P OST",
  11298                method:  "MERGE",
  11299                data: wi ndow.JSON. stringify( opts.entit y),
  11300                async: ! !opts.asyn c
  11301           };
  11302  
  11303           re turn doRes tRequest(r estReq, fu nction (re sult) {
  11304                if (isFu nction(opt s.successC allback))  {
  11305                    opts .successCa llback(res ult);
  11306                }
  11307  
  11308                if (!opt s.async) {
  11309                    retu rn result;
  11310                }
  11311           },  function  (err) {
  11312                if (isFu nction(opt s.errorCal lback)) {
  11313                    opts .errorCall back(err);
  11314                } else {
  11315                    thro w err;
  11316                }
  11317           }) ;
  11318       };
  11319  
  11320       var de leteRecord  = functio n (opts) {
  11321  
  11322           if  (!isNonEm ptyString( opts.entit yName)) {
  11323                throw ne w Error("e ntityName  parameter  was not pr ovided. ") ;
  11324           }
  11325  
  11326           if  (!isNonEm ptyString( opts.id))  {
  11327                throw ne w Error("i d paramete r was not  provided.  ");
  11328           }
  11329  
  11330           va r restReq  = {
  11331                url: cli entUrl + o dataEndpoi nt + "/" +  opts.enti tyName + " Set(guid'"  + opts.id  + "')",
  11332                type: "P OST",
  11333                method:  "DELETE",
  11334                async: ! !opts.asyn c
  11335           };
  11336  
  11337           re turn doRes tRequest(r estReq, fu nction (re sult) {
  11338                if (isFu nction(opt s.successC allback))  {
  11339                    opts .successCa llback(res ult);
  11340                }
  11341  
  11342                if (!opt s.async) {
  11343                    retu rn result;
  11344                }
  11345           },  function  (err) {
  11346                if (isFu nction(opt s.errorCal lback)) {
  11347                    opts .errorCall back(err);
  11348                }
  11349                else {
  11350                    thro w err;
  11351                }
  11352           }) ;
  11353       };
  11354  
  11355       var as sociate =  function ( opts) {
  11356  
  11357           if  (!isNonEm ptyString( opts.entit y1Id)) {
  11358                throw ne w Error("e ntity1Id p arameter w as not pro vided. ");
  11359           }
  11360  
  11361           if  (!isNonEm ptyString( opts.entit y1Name)) {
  11362                throw ne w Error("e ntity1Name  parameter  was not p rovided. " );
  11363           }
  11364  
  11365           if  (!isNonEm ptyString( opts.entit y2Id)) {
  11366                throw ne w Error("e ntity2Id p arameter w as not pro vided. ");
  11367           }
  11368  
  11369           if  (!isNonEm ptyString( opts.entit y2Name)) {
  11370                throw ne w Error("e ntity2Name  parameter  was not p rovided. " );
  11371           }
  11372  
  11373           if  (!isNonEm ptyString( opts.relat ionshipNam e)) {
  11374                throw ne w Error("r elationshi pName para meter was  not provid ed. ");
  11375           }
  11376  
  11377           va r entity2U ri = {
  11378                uri: cli entUrl + o dataEndpoi nt + "/" +  opts.enti ty2Name +  "Set(guid' " + opts.e ntity2Id +  "')"
  11379           };
  11380  
  11381           va r restReq  = {
  11382                url: cli entUrl + o dataEndpoi nt + "/" +  opts.enti ty1Name +  "Set(guid' " + opts.e ntity1Id +  "')/$link s/" + opts .relations hipName,
  11383                type: "P OST",
  11384                data: wi ndow.JSON. stringify( entity2Uri ),
  11385                async: ! !opts.asyn c
  11386           };
  11387  
  11388           re turn doRes tRequest(r estReq, fu nction (re sult) {
  11389                if (isFu nction(opt s.successC allback))  {
  11390                    opts .successCa llback(res ult);
  11391                }
  11392  
  11393                if (!opt s.async) {
  11394                    retu rn result;
  11395                }
  11396           },  function  (err) {
  11397                if (isFu nction(opt s.errorCal lback)) {
  11398                    opts .errorCall back(err);
  11399                } else {
  11400                    thro w err;
  11401                }
  11402           }) ;
  11403       };
  11404  
  11405       var di sassociate  = functio n (opts) {
  11406  
  11407           if  (!isNonEm ptyString( opts.entit y1Id)) {
  11408                throw ne w Error("e ntity1Id p arameter w as not pro vided. ");
  11409           }
  11410  
  11411           if  (!isNonEm ptyString( opts.entit y1Name)) {
  11412                throw ne w Error("e ntity1Name  parameter  was not p rovided. " );
  11413           }
  11414  
  11415           if  (!isNonEm ptyString( opts.entit y2Id)) {
  11416                throw ne w Error("e ntity2Id p arameter w as not pro vided. ");
  11417           }
  11418  
  11419           if  (!isNonEm ptyString( opts.relat ionshipNam e)) {
  11420                throw ne w Error("r elationshi pName para meter was  not provid ed. ");
  11421           }
  11422  
  11423           va r restReq  = {
  11424                url: cli entUrl + o dataEndpoi nt + "/" +  opts.enti ty1Name +  "Set(guid' " + opts.e ntity1Id +  "')/$link s/" + opts .relations hipName +  "(guid'" +  opts.enti ty2Id + "' )",
  11425                type: "P OST",
  11426                method:  "DELETE",
  11427                async: ! !opts.asyn c
  11428           };
  11429  
  11430           re turn doRes tRequest(r estReq, fu nction (re sult) {
  11431                if (isFu nction(opt s.successC allback))  {
  11432                    opts .successCa llback(res ult);
  11433                }
  11434  
  11435                if (!opt s.async) {
  11436                    retu rn result;
  11437                }
  11438           },  function  (err) {
  11439                if (isFu nction(opt s.errorCal lback)) {
  11440                    opts .errorCall back(err);
  11441                } else {
  11442                    thro w err;
  11443                }
  11444           }) ;
  11445       };
  11446  
  11447       // Too lkit's pub lic member s
  11448       return  {
  11449           co ntext: con text,
  11450           se rverUrl: c lientUrl,
  11451           re trieve: re trieve,
  11452           re trieveMult iple: retr ieveMultip le,
  11453           cr eateRecord : createRe cord,
  11454           up dateRecord : updateRe cord,
  11455           de leteRecord : deleteRe cord,
  11456           as sociate: a ssociate,
  11457           di sassociate : disassoc iate,
  11458           se tState: se tState,
  11459           ex ecute: exe cute,
  11460           fe tch: fetch
  11461       };
  11462   })(window) ;
  11463  
  11464   /********* ***** udo_ process.js  ********* ********** ********** ********** ***/
  11465   var MCS =  MCS || {};
  11466   MCS.Script s = MCS.Sc ripts || { };
  11467  
  11468   MCS.Script s.Process  = function () {
  11469          var  serverUrl  = null;
  11470          
  11471          var  DataTypes  = {
  11472                  Bool:  "boolean",
  11473                  Int: " int",
  11474                  String : "string" ,
  11475                  DateTi me: "dateT ime",
  11476                  Entity Reference:  "EntityRe ference",
  11477                  Option Set: "Opti onSetValue ",
  11478                  Money:  "Money",
  11479                  Guid:  "guid"
  11480          };
  11481          
  11482          var  soapParam s = functi on (paramA rray, gene ricNSPrefi x, schemaN SPrefix) {
  11483  
  11484               var xmlEn code = fun ction (inp ut) {
  11485                   var b etween = f unction (i , a, b) {  return (i  > a && i <  b); };
  11486                   if (t ypeof inpu t === "und efined" ||  input ===  null || i nput == '' ) return ' ';
  11487  
  11488                   var o utput = '' ;
  11489                   for ( var i = 0;  i < input .length; i ++) {
  11490                       v ar c = inp ut.charCod eAt(i);
  11491                       i f (between (c, 96, 12 3) || betw een(c, 64,  91) || be tween(c, 4 7, 58) ||  between(c,  43, 47) | | c == 95  || c == 32 ) {
  11492                            output  += String. fromCharCo de(c);
  11493                       }  else {
  11494                            output  += "&#" +  c + ";";
  11495                       }
  11496                   }
  11497                   retur n output;
  11498               };
  11499  
  11500               var param s = "";
  11501               var value  = "";
  11502  
  11503               if (param Array) {
  11504                   // Ad d each inp ut param
  11505                   for ( var i = 0;  i < param Array.leng th; i++) {
  11506                       v ar param =  paramArra y[i];
  11507                       v ar include NS = false ;
  11508                       v ar type =  ":" + para m.Type;
  11509                       v ar typeNS  = "http:// www.w3.org /2001/XMLS chema";
  11510  
  11511                       s witch (par am.Type) {
  11512                            case "d ateTime":
  11513                                val ue = param .Value.toI SOString() ;
  11514                                typ e = schema NSPrefix +  type;
  11515                                inc ludeNS = t rue;
  11516                                bre ak;
  11517                            case "E ntityRefer ence":
  11518                                typ e = "a" +  type;
  11519                                val ue = "<a:I d>" + para m.Value.id  + "</a:Id ><a:Logica lName>" +  param.Valu e.entityTy pe + "</a: LogicalNam e><a:Name  i:nil='tru e' />";
  11520                                bre ak;
  11521                            case "O ptionSetVa lue":
  11522                            case "M oney":
  11523                                typ e = "a" +  type;
  11524                                val ue = "<a:V alue>" + p aram.Value  + "</a:Va lue>";
  11525                                bre ak;
  11526                            case "g uid":
  11527                                typ e = schema NSPrefix +  type;
  11528                                val ue = param .Value;
  11529                                inc ludNS = tr ue;
  11530                                typ eNS = "htt p://schema s.microsof t.com/2003 /10/Serial ization/";
  11531                                bre ak;
  11532                            case "s tring":
  11533                                typ e = schema NSPrefix +  type;
  11534                                val ue = xmlEn code(param .Value);
  11535                                inc ludeNS = t rue;
  11536                                bre ak;
  11537                            default :
  11538                                typ e = schema NSPrefix +  type;
  11539                                val ue = param .Value;
  11540                                inc ludeNS = t rue;
  11541                                bre ak;
  11542                       }
  11543  
  11544                       p arams += " <a:KeyValu ePairOfstr inganyType >" +
  11545                            "<" + g enericNSPr efix + ":k ey>" + par am.Key + " </" + gene ricNSPrefi x + ":key> " +
  11546                            "<" + g enericNSPr efix + ":v alue i:typ e='" + typ e + "'";
  11547                       i f (include NS) params  += " xmln s:" + sche maNSPrefix  + "='" +  typeNS + " '";
  11548                       p arams += " >" + value  + "</" +  genericNSP refix + ": value>" +
  11549                            "</a:Ke yValuePair Ofstringan yType>";
  11550                   }
  11551               }
  11552  
  11553               return "< a:Paramete rs xmlns:"  + generic NSPrefix +  "='http:/ /schemas.d atacontrac t.org/2004 /07/System .Collectio ns.Generic '>" +
  11554                   param s + "</a:P arameters> ";
  11555          };
  11556          
  11557          var  soapExecu te = funct ion(reques tXml) {
  11558                  return  "<Execute  xmlns='ht tp://schem as.microso ft.com/xrm /2011/Cont racts/Serv ices' xmln s:i='http: //www.w3.o rg/2001/XM LSchema-in stance'>"  +
  11559                             reques tXml + "</ Execute>";
  11560          };
  11561          
  11562          var  soapEnvel ope = func tion(messa ge)
  11563          {
  11564                  return  "<s:Envel ope xmlns: s='http:// schemas.xm lsoap.org/ soap/envel ope/'>" +
  11565                             "<s:Bo dy>" + mes sage + "</ s:Body>" +
  11566                             "</s:E nvelope>";
  11567          };
  11568          
  11569          var  soapActio nRequest =  function( action, in putParams)
  11570          {
  11571                  return  "<request  xmlns:a=' http://sch emas.micro soft.com/x rm/2011/Co ntracts'>"  +
  11572                             soapPa rams(input Params, 'b ', 'c') + 
  11573                             "<a:Re questId i: nil='true'  />" +
  11574                             "<a:Re questName> " + action  + "</a:Re questName> " +
  11575                             "</req uest>";
  11576          };
  11577          
  11578          var  soapExecu teWorkflow Request =  function(w orkflowId,  recordId)
  11579          {
  11580                  return  "<request  i:type='b :ExecuteWo rkflowRequ est' xmlns :a='http:/ /schemas.m icrosoft.c om/xrm/201 1/Contract s' xmlns:b ='http://s chemas.mic rosoft.com /crm/2011/ Contracts' >" +
  11581                                soa pParams([{ Key:"Entit yId",   Ty pe:DataTyp es.Guid,   Value:reco rdId}, 
  11582                                                       {K ey:"Workfl owId", Typ e:DataType s.Guid,  V alue:workf lowId}], ' c', 'd') +
  11583                                "<a :RequestId  i:nil='tr ue' />" +
  11584                                "<a :RequestNa me>Execute Workflow</ a:RequestN ame>" +
  11585                                "</ request>";
  11586          };
  11587          
  11588          var  execCrmSo apRequest  = function (soapMessa ge)
  11589          {
  11590                  if (se rverUrl ==  null) {
  11591                          serverUrl  = Xrm.Pag e.context. getClientU rl();
  11592                          serverUrl  += "/XRMS ervices/20 11/Organiz ation.svc/ web";
  11593                          serverUrl  = serverU rl.replace ("//XRMSer vices", "/ XRMService s");
  11594                  }
  11595                  
  11596                  var op tions = {
  11597                          url: serv erUrl,
  11598                          type: "PO ST",
  11599                          dataType:  "xml",
  11600                          data: soa pMessage,
  11601                          processDa ta: false,
  11602                          global: f alse,
  11603                          beforeSen d: functio n(xhr){
  11604                                xhr .setReques tHeader('S OAPAction' , 'http:// schemas.mi crosoft.co m/xrm/2011 /Contracts /Services/ IOrganizat ionService /Execute') ;
  11605                                xhr .setReques tHeader("A ccept", "a pplication /xml, text /xml */*") ;
  11606                                xhr .setReques tHeader("C ontent-Typ e", "text/ xml; chars et=utf-8") ;
  11607                          }
  11608                  };
  11609                  
  11610                  return  $.ajax(op tions);
  11611                  return  result;
  11612          };
  11613          
  11614          var  callActio n = functi on (action , inputPar ams) {
  11615                  var df d = $.Defe rred();
  11616                  
  11617                  execCr mSoapReque st(soapEnv elope(soap Execute(so apActionRe quest(acti on, inputP arams))))
  11618                  .done( function(a ,b,xhr) {
  11619                          var resul t = getVal ues(xhr.re sponseXML) ;
  11620                          dfd.resol ve(result, b,xhr);
  11621                  })
  11622                  .fail( function(e rr) {
  11623                          dfd.rejec t(err);
  11624                  });
  11625                  
  11626                  return  dfd.promi se();
  11627          };
  11628          
  11629          var  getValues  = functio n (xmlData ) {
  11630               var XmlTo Entity = f unction (n ode) {
  11631                   try {
  11632                       / /ToDo: Thi s code nee ds to be v alidated
  11633                       v ar entity  = {
  11634                            logical Name: node .getElemen tsByTagNam e("a:Logic alName")[0 ].text(),
  11635                            id: nod e.getEleme ntsByTagNa me("a:Id") [0].text() ,
  11636                            attribu tes: getVa lues(node. getElement sByTagName ("a:Attrib utes")[0])
  11637                       } ;
  11638                   } cat ch (err) {
  11639                       r eturn null ;
  11640                   }
  11641                   try {
  11642                       v ar formatt edValuesNo de = node. getElement sByTagName ("a:Format tedValues" );
  11643                       i f (formatt edValuesNo de != null  && format tedValuesN ode.length  > 0) {
  11644                            entity. formattedV alues = ge tValues(fo rmattedVal uesNode);
  11645                       }
  11646                   } cat ch (err) {  }
  11647                   retur n entity;
  11648               };
  11649  
  11650               var XmlTo Entities =  function  (node) {
  11651                   var x mlEntities  = node.ge tElementsB yTagName(" a:Entity") ;
  11652                   var e ntities =  [];
  11653                   for ( var i = 0;  i < xmlEn tities.len gth; i++)  {
  11654                       e ntities[i]  = XmlToEn tity(xmlEn tities[i]) ;
  11655                   }
  11656                   retur n entities ;
  11657               };
  11658  
  11659               var kvps  = xmlData. getElement sByTagName ("a:KeyVal uePairOfst ringanyTyp e");
  11660               if (typeo f kvps ===  "undefine d" || kvps  === null  || kvps.le ngth == 0)  {
  11661                   kvps  = xmlData. getElement sByTagName ("KeyValue PairOfstri nganyType" );
  11662               }
  11663               if (typeo f kvps ===  "undefine d" || kvps  === null  || kvps.le ngth == 0)  {
  11664                   kvps  = [];
  11665               } else {
  11666                   kvps  = kvps[0]. parentNode .childNode s;
  11667               }
  11668  
  11669               var resul t = {};
  11670               for (var  i = 0; i <  kvps.leng th; i++) {
  11671                   var k ey = $(kvp s[i].child Nodes[0]). text();
  11672                   var v alueObj =  $(kvps[i]. childNodes [1]);
  11673                   var t ypeNode =  valueObj.a ttr("i:typ e");
  11674                   // co ntinue if  no type (l ike null v alues)
  11675                   if (t ypeof type Node == "u ndefined"  || typeNod e == null)  continue;
  11676                   // ge t the type  from the  node
  11677                   var t ype = valu eObj.attr( "i:type"). toLowerCas e();
  11678                   type  = type.sub string(typ e.indexOf( ":") + 1);
  11679  
  11680                   // se tup value  variable.
  11681                   var v alue = "";
  11682                   if (t ype == "al iasedvalue ") {
  11683                       f or (var j  = 0; j < v alueObj[0] .childNode s.length;  j++) {
  11684                            if (val ueObj[0].c hildNodes[ j].tagName  == "a:Val ue") {
  11685                                val ueObj = $( valueObj.c hildNodes[ j]);
  11686                                bre ak;
  11687                            }
  11688                       }
  11689                       / / reset ty pe using t he aliased value resu lt
  11690                       t ype = valu eObj.attr( "i:type"). toLowerCas e();
  11691                       t ype = type .substring (type.inde xOf(":") +  1);
  11692                   }
  11693                   switc h (type) {
  11694                       c ase "entit y":
  11695                            value =  XmltoEnti ty(valueOb j);
  11696                            break;
  11697                       c ase "entit ycollectio n":
  11698                            value =  XmlToEnti ties(value Obj[0]);
  11699                            break;
  11700                       c ase "entit yreference ":
  11701                            value =  {
  11702                                id:  $(valueOb j[0].child Nodes[0]). text(),
  11703                                ent ityType: $ (valueObj[ 0].childNo des[1]).te xt()
  11704                            };
  11705                            if (val ueObj[0].c hildNodes[ 2]) value. name = $(v alueObj[0] .childNode s[2]).text ();
  11706                            break;
  11707                       c ase "datet ime":
  11708                            value =  new Date( valueObj.t ext());
  11709                            break;
  11710                       c ase "decim al":
  11711                       c ase "doubl e":
  11712                       c ase "int":
  11713                       c ase "money ":
  11714                       c ase "optio nsetvalue" :
  11715                            value =  Number(va lueObj.tex t());
  11716                            break;
  11717                       c ase "boole an":
  11718                            value =  valueObj. text().toL owerCase()  == "true" ;
  11719                            break;
  11720                       d efault: // string
  11721                            value =  valueObj. text();
  11722                            break;
  11723                   }
  11724  
  11725                   resul t[key] = v alue;
  11726               }
  11727               return re sult;
  11728          };
  11729          
  11730          var  callWorkf low = func tion (work flowId, re cordId) {
  11731                  return  execCrmSo apRequest( soapEnvelo pe(soapExe cute(soapE xecuteWork flowReques t(workflow Id, record Id))));
  11732          };
  11733                  
  11734          ret urn {
  11735                  DataTy pe: DataTy pes,
  11736                  Execut eAction: c allAction,
  11737                  Execut eWorkflow:  callWorkf low
  11738          };
  11739   }();
  11740  
  11741   /*
  11742   var Initia lize = fun ction () {
  11743  
  11744       var re questName  = "Your_ac tionname",
  11745  
  11746       var re questParam s =
  11747           [{
  11748                Key: "Pa rentEntity Reference" ,
  11749                Type: Va .Udo.Crm.S cripts.Pro cess.DataT ype.Entity Reference,
  11750                Value: {  id: entit yId, entit yType: ent ityName }
  11751           }]
  11752  
  11753       MCS.Sc ripts.Proc ess.Execut eAction(re questName,  requestPa rams)
  11754           .d one(functi on (respon se) { onRe sponse(res ponse, req uestName)  })
  11755           .f ail(functi on (err) {
  11756                $('#load ingGifDiv' ).hide();
  11757                if (Debu g == false )
  11758                    $('# notFoundDi v').text(" An error o ccurred wh ile attemp ting to pr ocess this  request.  Please ref resh the p age and tr y again. I f this err or persist s, please  contact th e applicat ion suppor t team.");
  11759                else
  11760                    $('# notFoundDi v').text(e rr.respons eText);
  11761  
  11762                $('#notF oundDiv'). show();
  11763           }) ;
  11764   };
  11765  
  11766   function o nResponse( responseOb ject, requ estName) {
  11767       $('#lo adingGifDi v').hide() ;
  11768       if (re sponseObje ct.DataIss ue != fals e || respo nseObject. Timeout !=  false ||  responseOb ject.Excep tion != fa lse) {
  11769           $( '#notFound Div').text (responseO bject.Resp onseMessag e);
  11770           $( '#notFound Div').show ();
  11771       } else  {
  11772           // Do whateve r
  11773       }
  11774   }
  11775   */
  11776   //If the S DK namespa ce object  is not def ined, crea te it.
  11777   if (typeof  (MCS) ==  "undefined ")
  11778   { MCS = {} ; }
  11779   // Create  Namespace  container  for functi ons in thi s library;
  11780   MCS.mcs_Se rvice_Acti vity_OnSav e = {};
  11781  
  11782   MCS.mcs_Se rvice_Acti vity_OnSav e.SetSched uled = fun ction () {
  11783       var re sources =  Xrm.Page.g etAttribut e("resourc es").getVa lue();
  11784       if (re sources !=  null)
  11785           Xr m.Page.get Attribute( "cvt_sched uled").set Value(1);
  11786   };
  11787  
  11788   //If the S DK namespa ce object  is not def ined, crea te it.
  11789   if (typeof  (MCS) ==  "undefined ")
  11790   { MCS = {} ; }
  11791   // Create  Namespace  container  for functi ons in thi s library;
  11792   MCS.mcs_Se rvice_Acti vity_OnLoa d = {};
  11793  
  11794   //Global V ariables
  11795   var totalP atients =  new Array( );
  11796   var totalG roupPatien ts = new A rray();
  11797   MCS.Patien ts = [];
  11798  
  11799   //This onL oad functi on is the  master fun ction that  coordinat es the act ual script s that run
  11800   MCS.mcs_Se rvice_Acti vity_OnLoa d.OnLoad =  function  () {
  11801       //Add  Scripting  events to  fields for  when fiel ds change
  11802       Xrm.Pa ge.getAttr ibute("cvt _type").ad dOnChange( MCS.mcs_Se rvice_Acti vity.CVTto Home);
  11803       Xrm.Pa ge.getAttr ibute("mcs _groupappo intment"). addOnChang e(MCS.mcs_ Service_Ac tivity.Gro upAppt);
  11804       Xrm.Pa ge.getAttr ibute("mcs _groupappo intment"). addOnChang e(MCS.mcs_ Service_Ac tivity.Ena bleTSA);
  11805       Xrm.Pa ge.getAttr ibute("mcs _groupappo intment"). addOnChang e(MCS.mcs_ Service_Ac tivity.Han dleOnChang eTSALookup );
  11806       Xrm.Pa ge.getAttr ibute("mcs _groupappo intment"). addOnChang e(MCS.mcs_ Service_Ac tivity.Cre ateName);
  11807       Xrm.Pa ge.getAttr ibute("cvt _telehealt hmodality" ).addOnCha nge(MCS.mc s_Service_ Activity.H andleOnCha ngeTSALook up);
  11808       Xrm.Pa ge.getAttr ibute("mcs _relatedsi te").addOn Change(MCS .mcs_Servi ce_Activit y.EnableTS A);
  11809       Xrm.Pa ge.getAttr ibute("mcs _relatedsi te").addOn Change(MCS .mcs_Servi ce_Activit y.HandleOn ChangeTSAL ookup);
  11810       Xrm.Pa ge.getAttr ibute("mcs _relatedpr ovidersite ").addOnCh ange(MCS.m cs_Service _Activity. EnableTSA) ;
  11811       Xrm.Pa ge.getAttr ibute("mcs _relatedpr ovidersite ").addOnCh ange(MCS.m cs_Service _Activity. HandleOnCh angeTSALoo kup);
  11812       Xrm.Pa ge.getAttr ibute("mcs _servicety pe").addOn Change(MCS .mcs_Servi ce_Activit y.EnableSe rviceSubTy pe);
  11813       Xrm.Pa ge.getAttr ibute("mcs _servicety pe").addOn Change(MCS .mcs_Servi ce_Activit y.HandleOn ChangeTSAL ookup);
  11814       Xrm.Pa ge.getAttr ibute("mcs _servicety pe").addOn Change(MCS .mcs_Servi ce_Activit y.CreateNa me);
  11815       Xrm.Pa ge.getAttr ibute("mcs _servicesu btype").ad dOnChange( MCS.mcs_Se rvice_Acti vity.Enabl eTSA);
  11816       Xrm.Pa ge.getAttr ibute("mcs _servicesu btype").ad dOnChange( MCS.mcs_Se rvice_Acti vity.Handl eOnChangeT SALookup);
  11817       Xrm.Pa ge.getAttr ibute("mcs _servicesu btype").ad dOnChange( MCS.mcs_Se rvice_Acti vity.Creat eName);
  11818       Xrm.Pa ge.getAttr ibute("cvt _relatedpr oviderid") .addOnChan ge(MCS.mcs _Service_A ctivity.Ha ndleOnChan geTSALooku p);
  11819       Xrm.Pa ge.getAttr ibute("mcs _relatedts a").addOnC hange(MCS. mcs_Servic e_Activity .GetTSADat a);
  11820       Xrm.Pa ge.getAttr ibute("mcs _relatedts a").addOnC hange(MCS. mcs_Servic e_Activity .HandleOnC hangeTSALo okup);
  11821       Xrm.Pa ge.getAttr ibute("mcs _relatedts a").addOnC hange(MCS. mcs_Servic e_Activity .ClearReso urces);
  11822       Xrm.Pa ge.getAttr ibute("mcs _relatedts a").addOnC hange(MCS. mcs_Servic e_Activity .filterSub Grid);
  11823       Xrm.Pa ge.getAttr ibute("mcs _relatedts a").addOnC hange(MCS. VIALogin.S aml);
  11824       Xrm.Pa ge.getAttr ibute("cvt _samltoken ").addOnCh ange(MCS.V IALogin.Lo gin);
  11825  
  11826       //Xrm. Page.getAt tribute("c ustomers") .addOnChan ge(MCS.mcs _Service_A ctivity.Ca lculateRem ainingCapa city);
  11827       //Xrm. Page.getAt tribute("c ustomers") .addOnChan ge(MCS.mcs _Service_A ctivity.Cr eateName);
  11828       //Xrm. Page.getAt tribute("r esources") .addOnChan ge(MCS.mcs _Service_A ctivity.Sc hedulingIn fo);
  11829       Xrm.Pa ge.getAttr ibute("cus tomers").a ddOnChange (MCS.mcs_S ervice_Act ivity.Bloc kAddPatien t)
  11830  
  11831       //Run  the follow ing functi ons when t he form lo ads
  11832       MCS.mc s_Service_ Activity.E nableServi ceSubType( );
  11833       MCS.mc s_Service_ Activity.E nableTSA() ;
  11834       MCS.mc s_Service_ Activity.G roupAppt() ;
  11835       MCS.mc s_Service_ Activity_O nLoad.SetD efaultDate Time();
  11836       MCS.mc s_Service_ Activity.G etTSAData( );
  11837       MCS.mc s_Service_ Activity.H andleOnCha ngeTSALook up();
  11838       MCS.mc s_Service_ Activity.C VTtoHome() ;
  11839       MCS.mc s_Service_ Activity_O nLoad.Remo veNotifica tion();
  11840       MCS.mc s_Service_ Activity_O nLoad.Show MVI();
  11841       MCS.mc s_Service_ Activity_O nLoad.Load Patients() ;
  11842       MCS.mc s_Service_ Activity_O nLoad.Rese tPatients( );
  11843       //MCS. VIALogin.S aml();
  11844       //MCS. VIALogin.L ogin();
  11845  
  11846       Xrm.Pa ge.getAttr ibute("cvt _patuserdu z").setVal ue(null);
  11847       Xrm.Pa ge.getAttr ibute("cvt _prouserdu z").setVal ue(null);
  11848   };
  11849  
  11850  
  11851   //If the S ervice is  not loaded , default  the start  and end ti me to 8:30 -9:30
  11852   MCS.mcs_Se rvice_Acti vity_OnLoa d.SetDefau ltDateTime  = functio n () {
  11853       //Set  Default Da tetime if  the TSA Se rvice has  not been l oaded yet.  
  11854       if (Xr m.Page.get Attribute( "serviceid ").getValu e() == nul l) {
  11855           MC S.cvt_Comm on.DateTim e('schedul edstart',  8, 30);
  11856           MC S.cvt_Comm on.DateTim e('schedul edend', 9,  30);
  11857           Xr m.Page.get Attribute( "scheduled durationmi nutes").se tValue(60) ;
  11858       }
  11859   };
  11860  
  11861   //unsuppor ted modifi cation to  clear out  the incorr ect notifi cation tha t the reso urces do n ot match t he service  rules lis ted (they  are in the  appointme nts per de sign)
  11862   MCS.mcs_Se rvice_Acti vity_OnLoa d.RemoveNo tification  = functio n () {
  11863       //Grou p and Upda te Form
  11864       if ((X rm.Page.ge tAttribute ("mcs_grou pappointme nt").getVa lue() == t rue) && (X rm.Page.ui .getFormTy pe() != 1) ) {
  11865           va r notifica tionsList  = Sys.Appl ication.fi ndComponen t('crmNoti fications' );
  11866           if  (notifica tionsList)  {
  11867                //Hide m essage
  11868                notifica tionsList. SetVisible (false);
  11869           }
  11870       }
  11871   };
  11872  
  11873   //Read the  configura tion value  from Acti ve Setting s to deter mine wheth er or not  to display  the Patie nt Search  (MVI) iFra me as well  as the pa tients fie ld
  11874   MCS.mcs_Se rvice_Acti vity_OnLoa d.ShowMVI  = function  () {
  11875       var pa tObj = Xrm .Page.getA ttribute(" customers" );
  11876       var pa tientExist s = patObj .getValue( ) != null;
  11877       var mv iTab = Xrm .Page.ui.t abs.get("t ab_7");
  11878       var sh owMVI = MC S.cvt_Comm on.MVIConf ig();
  11879       showMV I = showMV I && !MCS. cvt_Common .Appointme ntOccursIn Past();
  11880       mviTab .setVisibl e(showMVI) ;
  11881       Xrm.Pa ge.getCont rol("custo mers").set Disabled(! showMVI);
  11882       if (sh owMVI && ! patientExi sts)
  11883           mv iTab.setFo cus();
  11884       else
  11885           Xr m.Page.get Control("c vt_type"). setFocus() ;
  11886  
  11887       if (pa tientExist s) {
  11888           mv iTab.setDi splayState ("collapse d");
  11889       }
  11890   };
  11891  
  11892   MCS.mcs_Se rvice_Acti vity_OnLoa d.LoadPati ents = fun ction () {
  11893       var pa tientObj =  Xrm.Page. getAttribu te("custom ers");
  11894       var pa tients = p atientObj  != null ?  patientObj .getValue( ) : [];
  11895       MCS.Pa tients = p atients;
  11896   }
  11897  
  11898   //This fun ction is r equired in  order to  ensure the  "Patients " Activity  Party Lis t does not  show empt y/duplicat e APs - ex isting CRM  bug
  11899   MCS.mcs_Se rvice_Acti vity_OnLoa d.ResetPat ients = fu nction ()  {
  11900       var cu st = Xrm.P age.getAtt ribute("cu stomers"). getValue() ;
  11901       Xrm.Pa ge.getAttr ibute("cus tomers").s etValue(cu st);
  11902   }
  11903   ///<summar y>Helper f unction: O pens a win dow for a  new Recurr ing Appoin tment reco rd using t he Informa tion form. </summary>
  11904   ///<param  name="subj ect" optio nal="false " type="St ring">
  11905   ///Subject  associate d with the  recurring  appointme nt series.
  11906   ///</param >
  11907   ///<param  name="cvt_ serviceact ivityid" o ptional="f alse" type ="String">
  11908   ///Unique  identifier  for Servi ce Activit y associat ed with Re curring Ap pointment.  Expected  value is a  String th at matches  the patte rn for a G UID '/^{?[ A-Z0-9]{8} -[A-Z0-9]{ 4}-[A-Z0-9 ]{4}-[A-Z0 -9]{4}-[A- Z0-9]{12}} ?$/i'.
  11909   ///</param >
  11910   ///<param  name="cvt_ serviceact ivityidnam e" optiona l="false"  type="Stri ng">
  11911   ///The tex t to displ ay for the  record re presented  by the cvt _serviceac tivityid p arameter.
  11912   ///</param >
  11913   //MCS.VIAL ogin.Getti ngNewUserD uz = false ;
  11914  
  11915   function o penNewRecu rringAppoi ntmentMast er(subject , serviceA ctivityID,  serviceAc tivityName ) {
  11916       if ((t ypeof Xrm  != "undefi ned") && ( typeof Xrm .Utility ! = "undefin ed")) {
  11917           va r p = {};
  11918           p. formid = " 4a8cda55-0 24e-419c-b be1-9540e0 b8e297"
  11919           p. subject =  subject;
  11920           p. cvt_servic eactivityi d = servic eActivityI D;
  11921           p. cvt_servic eactivityi dname = se rviceActiv ityName;
  11922           Xr m.Utility. openEntity Form("recu rringappoi ntmentmast er", null,  p);
  11923       }
  11924       else {
  11925           va r features  = "locati on=no,menu bar=no,sta tus=no,too lbar=no,re sizable=ye s";
  11926           va r extraqs  = ["formid =4a8cda55- 024e-419c- bbe1-9540e 0b8e297",
  11927           "s ubject=" +  subject,
  11928           "c vt_service activityid =" + servi ceActivity ID,
  11929           "c vt_service activityid name=" + s erviceActi vityName]
  11930           va r url = Xr m.Page.con text.getSe rverUrl();
  11931           if  (url.matc h(/\/$/))  {
  11932                url = ur l.substrin g(0, url.l ength - 1) ;
  11933           }
  11934           if  (typeof X rm.Page.co ntext.getC lientUrl ! = "undefin ed") {
  11935                url = Xr m.Page.con text.getCl ientUrl();
  11936           }
  11937           wi ndow.open( url + "/ma in.aspx?et n=recurrin gappointme ntmaster&p agetype=en tityrecord &extraqs="  + encodeU RIComponen t(extraqs. join("&")) , "_blank" , features , false);
  11938       }
  11939   }
  11940  
  11941   //Function s Called b y Ribbon B uttons
  11942   //Example:
  11943   //Calls op enNewRecur ringAppoin tmentMaste r - called  by Ribbon  Button "R ecurring S ervice Act ivity"
  11944   function C reateRecur ringServic eActivity( ) {
  11945       var se rviceActiv ityName =  "Recurring  " + Xrm.P age.getAtt ribute("su bject").ge tValue();
  11946       openNe wRecurring Appointmen tMaster(se rviceActiv ityName, X rm.Page.da ta.entity. getId(), s erviceActi vityName)
  11947   }
  11948  
  11949   //Open Rec urring App ointment M aster Reco rd - calle d by Ribbo n Button " Edit Serie s"
  11950   EditServic eActivityS eries = fu nction ()  {
  11951       var re latedMaste r = Xrm.Pa ge.getAttr ibute("cvt _recurring appointmen tsmaster") .getValue( );
  11952       if (re latedMaste r != null)
  11953           Xr m.Utility. openEntity Form("recu rringappoi ntmentmast er", relat edMaster[0 ].id)
  11954   }
  11955  
  11956   ReOpenServ iceActivit y = functi on () {
  11957       var is DataAdmin  = MCS.cvt_ Common.use rHasRoleIn List("TSS  Data Admin istrator|S ystem Admi nistrator| TSS Applic ation Admi nistrator" );
  11958       if (is DataAdmin  || Xrm.Pag e.getAttri bute("owne rid").getV alue()[0]. id == Xrm. Page.conte xt.getUser Id())
  11959           Ms crm.Comman dBarAction s.activate (Xrm.Page. data.entit y.getId(),  Xrm.Page. data.entit y.getEntit yName());
  11960       else 
  11961           MC S.cvt_Comm on.openDia logOnCurre ntRecord(" 00520409-9 8FB-4A1E-B 67C-D3D678 3ACB84");     
  11962   }
  11963  
  11964   CancelServ iceActivit y = functi on () {
  11965       var ru nVista = M CS.VIALogi n.CheckVis taSwitches ();
  11966       var di alogId = " ";
  11967       if (!r unVista) {
  11968           // or here
  11969           di alogId = " 789CD165-5 CAD-49B3-A CF3-42C3D5 B31584";
  11970       }
  11971       else {
  11972           va r validDuz  = MCS.VIA Login.IsVa lidUserDuz ();
  11973           if  (!validDu z) {
  11974                var vali dToken = M CS.VIALogi n.IsValidS amlToken() ;
  11975                if (vali dToken) {
  11976                    MCS. VIALogin.L ogin();
  11977                    aler t("Unable  to cancel  appointmen t in Vista  until you  have logg ed into Vi sta.");
  11978                }
  11979                else {
  11980                    MCS. VIALogin.S aml();
  11981                    aler t("Unable  to cancel  appointmen t in Vista  until you  have logg ed into Vi sta.");
  11982                }
  11983           }
  11984           el se
  11985                dialogId  = "B8A805 D8-01B1-49 22-80CA-D4 E46F2EC836 ";
  11986       }
  11987       openRe cords = Ch eckGroupCh ildRecords ();
  11988       if (op enRecords  > 0) {
  11989           di alogId = " ";
  11990           al ert("For ( clinic bas ed) Group  Appointmen ts, you mu st cancel  all Vista  Appointmen ts from th e Block Re sources be fore cance ling the w hole apppo intment.   Found: " +  openRecor ds + " Boo ked Vista  Appointmen ts");
  11991       }
  11992       if (di alogId !=  "") {
  11993           // Save the d uz to the  record
  11994           va r updatePa ram = {};
  11995           va r patDuz =  Xrm.Page. getAttribu te("cvt_pa tuserduz") .getValue( );
  11996           va r proDuz =  Xrm.Page. getAttribu te("cvt_pr ouserduz") .getValue( );
  11997  
  11998           if  (patDuz ! = null ||  patDuz !=  "")
  11999                updatePa ram.cvt_Pa tUserDuz =  patDuz;
  12000  
  12001           if  (proDuz ! = null ||  proDuz !=  "")
  12002                updatePa ram.cvt_Pr oUserDuz =  proDuz;
  12003  
  12004           Cr mRestKit.U pdate('Ser viceAppoin tment', Xr m.Page.dat a.entity.g etId(), up dateParam,  false)
  12005                .fail(
  12006                function  (err) {
  12007                    aler t(MCS.cvt_ Common.Res tError(err ));
  12008                })
  12009                .done(fu nction (da ta) {
  12010                    MCS. cvt_Common .openDialo gOnCurrent Record(dia logId);
  12011                });
  12012       }
  12013   }
  12014  
  12015  
  12016   CompleteSe rviceActiv ity = func tion () {
  12017       var re questName  = "cvt_Com pleteAppoi ntment";
  12018       var re questParam s =
  12019           [{
  12020                Key: "Ta rget",
  12021                Type: MC S.Scripts. Process.Da taType.Ent ityReferen ce,
  12022                Value: {  id: Xrm.P age.data.e ntity.getI d(), entit yType: 'se rviceappoi ntment' }
  12023           }] ;
  12024  
  12025       MCS.Sc ripts.Proc ess.Execut eAction(re questName,  requestPa rams)
  12026           .d one(functi on (respon se) {
  12027                Xrm.Page .ui.close( );
  12028           })
  12029           .f ail(functi on (err) {
  12030                alert("F ailed to C omplete th is appoint ment.  Det ails: " +  err.Respon seText);
  12031           }) ;
  12032       
  12033   }
  12034  
  12035   CheckGroup ChildRecor ds = funct ion () {
  12036       var op enChildRec ordsCount;
  12037       var is Group = Xr m.Page.get Attribute( "mcs_group appointmen t").getVal ue();
  12038       var is HomeMobile  = Xrm.Pag e.getAttri bute("cvt_ type").get Value();
  12039       if (is Group && ! isHomeMobi le) {
  12040           va r filter =  "cvt_Vist AStatus eq  'BOOKED'  and cvt_Se rviceActiv ity/Id eq  (Guid'" +  Xrm.Page.d ata.entity .getId() +  "')";
  12041           Cr mRestKit.B yQuery('cv t_vistaint egrationre sult', ['c vt_name'],  filter, f alse).fail (
  12042                function  (err) {
  12043                    aler t("unable  to retriev e group: "  + MCS.cvt _Common.Re stError(er r));
  12044                    open ChildRecor dsCount =  0;
  12045                    retu rn;
  12046                }).done(
  12047                function  (data) {
  12048                    if ( data && da ta.d && da ta.d.resul ts != null ) {
  12049                         openChildR ecordsCoun t = data.d .results.l ength;
  12050                    }
  12051                });
  12052       }
  12053       return  openChild RecordsCou nt;
  12054   }
  12055  
  12056   OnDialogCl ose = func tion(dialo g, timer)  {
  12057       if (!d ialog || d ialog.clos ed) {
  12058           cl earInterva l(timer);  //stop the  timer
  12059           Cr mRestKit.R etrieve('S erviceAppo intment',  Xrm.Page.d ata.entity .getId(),  ['StateCod e'], false )
  12060                .fail(fu nction(err ) {
  12061                    wind ow.locatio n.reload(t rue);
  12062                }).done( function(s erviceActi vity) {
  12063                    saRe cord = ser viceActivi ty.d;
  12064  
  12065                    //Re fresh the  form when  the state  code has c hanged fro m Active t o Closed/C ancelled f rom the di alog
  12066                    if ( saRecord.S tateCode ! = null &&  (saRecord. StateCode. Value == 1  || saReco rd.StateCo de.Value = = 2)) {
  12067                         window.loc ation.relo ad(true);
  12068                    }
  12069                });
  12070       }
  12071   }
  12072  
  12073   SaveSA = f unction ()  {
  12074       SaveRe cord(null) ;
  12075   };
  12076  
  12077   SaveAndClo seSA = fun ction(){
  12078       SaveRe cord("save andclose") ;
  12079   };
  12080  
  12081   SaveAndNew SA = funct ion(){
  12082       SaveRe cord("save andnew");
  12083   }
  12084  
  12085   SaveRecord  = functio n (saveOpt ion) {
  12086       //if ( MCS.VIALog in.Getting NewUserDuz ) {
  12087       //     alert("Log ging into  Vista, ple ase keep t his page o pen while  the appoin tment is b eing saved ");
  12088       //     return;
  12089       //}
  12090       var va lidUserDuz  = MCS.VIA Login.IsVa lidUserDuz ();
  12091       if (!v alidUserDu z) {
  12092           // MCS.VIALog in.Getting NewUserDuz  = true;
  12093           al ert("Vista  login has  expired,  attempting  to get ne w login");
  12094           MC S.VIALogin .Saml();
  12095           re turn;
  12096       }
  12097       //else
  12098       //     MCS.VIALog in.Getting NewUserDuz  = false;
  12099  
  12100       var is Group = Xr m.Page.get Attribute( "mcs_group appointmen t").getVal ue();
  12101       var is HomeMobile  = Xrm.Pag e.getAttri bute("cvt_ type").get Value();
  12102       var us ingVMR = f alse;
  12103       if (is Group && ! isHomeMobi le) {
  12104           Xr m.Page.dat a.entity.s ave(saveOp tion);
  12105           re turn;
  12106       }
  12107       var pa tientObj =  Xrm.Page. getAttribu te('custom ers');
  12108       var pa tients = p atientObj  != null ?  patientObj .getValue( ) != null  ? patientO bj.getValu e() : null  : null;
  12109       if (pa tients ==  null || pa tients.len gth == 0)
  12110       {
  12111           al ert("You m ust add a  patient to  all indiv idual or H ome/Mobile  Group app ointments" );
  12112           re turn;
  12113       }
  12114       var pa tRecord;
  12115       var al lowSave =  false;
  12116       var cu rrentVeter anIndex =  0;
  12117       for(va r i = 0; i  < patient s.length;  i++)
  12118       {
  12119           al lowSave =  false;
  12120           Cr mRestKit.R etrieve('C ontact', p atients[i] .id, ['Con tactId', ' EMailAddre ss1', 'DoN otEMail',  'cvt_BLTab let'], fal se)
  12121               .fail(fun ction (err ) {
  12122                   alert ("Patient  could not  be found:  " + patien ts[i].id);
  12123                   retur n;
  12124               }).done(f unction(co ntact){
  12125                   patRe cord = con tact.d;
  12126                   var d oNotEMail  = patRecor d.DoNotEMa il != null  ? patReco rd.DoNotEM ail : fals e;
  12127  
  12128                   if (p atRecord.c vt_BLTable t == null  || patReco rd.cvt_BLT ablet == " ")
  12129                       u singVMR =  isHomeMobi le;
  12130                   if (p atRecord.E MailAddres s1 != null  && patRec ord.EMailA ddress1 !=  "")
  12131                       a llowSave =  true;
  12132                   if (d oNotEMail  && !usingV MR)
  12133                       a llowSave =  true;
  12134               });
  12135           if  (!allowSa ve)
  12136           {
  12137                currentV eteranInde x = i;
  12138                break;
  12139           }
  12140       }
  12141       if (al lowSave)
  12142           Xr m.Page.dat a.entity.s ave(saveOp tion);
  12143       else
  12144           En terEmail(p atients[cu rrentVeter anIndex].i d, usingVM R);
  12145   };
  12146  
  12147   EnterEmail  = functio n (patient Id, usingV MR) {
  12148       if (us ingVMR)
  12149       {
  12150           al ert("All v eterans us ing VMRs m ust have e mail addre sses befor e they can  be booked .  Enter p atient's e mail and t ry to save  again or  else infor m the vete ran that h e/she will  need to f ind anothe r video vi sit option .");
  12151           MC S.cvt_Comm on.openDia logProcess ("52e2a47a -becc-449f -821a-0b95 916e1cb1",  "contact" , patientI d);
  12152       }
  12153       else
  12154       {
  12155           al ert("Pleas e Enter th e patient' s email ad dress or e lse opt th em out of  emails and  then try  to save ag ain.");
  12156           MC S.cvt_Comm on.openDia logProcess ("AB9FF42A -ADAC-4C01 -ADE7-01C1 A1F7E320",  "contact" , patientI d);
  12157       }
  12158   }
  12159   //If the S DK namespa ce object  is not def ined, crea te it.
  12160   if (typeof  (MCS) ==  "undefined ")
  12161   { MCS = {} ; }
  12162  
  12163  
  12164   // Create  Namespace  container  for functi ons in thi s library;
  12165   if (typeof  (MCS.mcs_ Service_Ac tivity) ==  "undefine d")
  12166   MCS.mcs_Se rvice_Acti vity = {};
  12167  
  12168   MCS.mcs_Se rvice_Acti vity.FORM_ TYPE_CREAT E = 1;
  12169   MCS.mcs_Se rvice_Acti vity.FORM_ TYPE_UPDAT E = 2;
  12170   MCS.mcs_Se rvice_Acti vity.FORM_ TYPE_READ_ ONLY = 3;
  12171   MCS.mcs_Se rvice_Acti vity.FORM_ TYPE_DISAB LED = 4;
  12172  
  12173   //Gets the  TSA Data  - populate s fields o n Service  Activity
  12174   MCS.mcs_Se rvice_Acti vity.GetTS AData = fu nction ()  {
  12175       var re latedtsa =  Xrm.Page. getAttribu te("mcs_re latedtsa") .getValue( );
  12176  
  12177       if (re latedtsa ! = null) {
  12178           MC S.mcs_Serv ice_Activi ty.getmcs_ relatedtsa LookupData (relatedts a[0].id);
  12179           MC S.mcs_Serv ice_Activi ty.GroupPa t();
  12180       }
  12181       else {         
  12182           Xr m.Page.get Attribute( "serviceid ").setValu e(null);
  12183           Xr m.Page.get Attribute( "mcs_servi cetype").s etValue(nu ll);
  12184           Xr m.Page.get Attribute( "mcs_servi cesubtype" ).setValue (null);
  12185       }
  12186   };
  12187  
  12188   //re-writt en piece l everaging  the Crm Re st Kit Lib rary - pul ls in valu es from th e TSA and  sets appro priate fie lds on Ser vice Activ ity
  12189   MCS.mcs_Se rvice_Acti vity.getmc s_relatedt saLookupDa ta = funct ion (mcs_r elatedtsa)  {
  12190       CrmRes tKit.Retri eve('mcs_s ervices',  mcs_relate dtsa, ['cv t_services ubtype', ' cvt_servic etype', 'm cs_Related ServiceId' , 'cvt_Typ e',
  12191           'c vt_Availab leTeleheal thModaliti es', 'cvt_ relatedpat ientsiteid ','cvt_rel atedprovid ersiteid',  'cvt_grou pappointme nt', 'cvt_ Scheduling Instructio ns'], true ).fail(
  12192           fu nction (er r) {
  12193                alert("P lease veri fy that th is TSA is  in Product ion, and i f so, cont act your s ystem admi nistrator" );
  12194                return;
  12195           }) .done(
  12196           fu nction (da ta) {
  12197                MCS.mcs_ Service_Ac tivity.Set Lookup(dat a.d.mcs_Re latedServi ceId, Xrm. Page.getAt tribute("s erviceid") );
  12198                MCS.mcs_ Service_Ac tivity.Set Lookup(dat a.d.cvt_se rvicetype,  Xrm.Page. getAttribu te("mcs_se rvicetype" ));
  12199                MCS.mcs_ Service_Ac tivity.Set Lookup(dat a.d.cvt_se rvicesubty pe, Xrm.Pa ge.getAttr ibute("mcs _servicesu btype"));
  12200                MCS.mcs_ Service_Ac tivity.Set Lookup(dat a.d.cvt_re latedpatie ntsiteid,  Xrm.Page.g etAttribut e("mcs_rel atedsite") );
  12201                MCS.mcs_ Service_Ac tivity.Set Lookup(dat a.d.cvt_re latedprovi dersiteid,  Xrm.Page. getAttribu te("mcs_re latedprovi dersite")) ;
  12202  
  12203                //Fire O nChange so  that SubT ype shows
  12204                Xrm.Page .getAttrib ute("mcs_s ervicetype ").fireOnC hange();
  12205  
  12206                if (data .d.cvt_Typ e != null)
  12207                    Xrm. Page.getAt tribute("c vt_type"). setValue(d ata.d.cvt_ Type);
  12208                if (data .d.cvt_gro upappointm ent != nul l)
  12209                    Xrm. Page.getAt tribute("m cs_groupap pointment" ).setValue (data.d.cv t_groupapp ointment);
  12210                Xrm.Page .getAttrib ute("cvt_t elehealthm odality"). setValue(( data.d.cvt _Available Telehealth Modalities .Value ==  917290001) )
  12211                if (data .d.cvt_Sch edulingIns tructions  != null)
  12212                    Xrm. Page.getAt tribute("c vt_schedul inginstruc tions").se tValue(dat a.d.cvt_Sc hedulingIn structions );
  12213  
  12214           }) ;
  12215   };
  12216  
  12217   //Pass in  OData Enti tyReferenc es and set  a lookup  with the E ntityRefer ence Value
  12218   MCS.mcs_Se rvice_Acti vity.SetLo okup = fun ction (col umn, targe tField) {
  12219       if (ta rgetField  != null) {
  12220           va r obj = {  id: column .Id, entit yType: col umn.Logica lName, nam e: column. Name }
  12221           if  (obj.name  == null)
  12222                targetFi eld.setVal ue(null);
  12223           el se 
  12224                targetFi eld.setVal ue([obj]);
  12225       }
  12226   }
  12227  
  12228   //Show TSA  lookup fi eld once s ite has be en selecte d
  12229   MCS.mcs_Se rvice_Acti vity.Enabl eTSA = fun ction () {
  12230       var re latedSite  = null;
  12231       var re latedSiteS LU = null;
  12232       var re latedProvi derSite =  null;
  12233       var re latedProvi derSiteSLU  = null;
  12234  
  12235       var re latedSiteA ttribute =  Xrm.Page. getAttribu te("mcs_re latedsite" );
  12236       if (re latedSiteA ttribute ! = null)
  12237           re latedSite  = relatedS iteAttribu te.getValu e();
  12238       if (re latedSite  != null)
  12239           re latedSiteS LU = relat edSite[0]. name;
  12240  
  12241       var re latedProvi derSiteAtt ribute = X rm.Page.ge tAttribute ("mcs_rela tedprovide rsite");
  12242       if (re latedProvi derSiteAtt ribute !=  null)
  12243           re latedProvi derSite =  relatedPro viderSiteA ttribute.g etValue();
  12244       if (re latedProvi derSite !=  null)
  12245           re latedProvi derSiteSLU  = related ProviderSi te[0].name ;
  12246    
  12247       if (re latedSiteS LU != null  || relate dProviderS iteSLU !=  null) {
  12248           Xr m.Page.ui. controls.g et("mcs_re latedtsa") .setVisibl e(true);
  12249           Xr m.Page.ui. controls.g et("mcs_re latedtsa") .setFocus( );
  12250       }
  12251       else {
  12252           Xr m.Page.ui. controls.g et("mcs_re latedtsa") .setVisibl e(false);
  12253           Xr m.Page.get Attribute( "mcs_relat edtsa").se tValue(nul l);
  12254       }
  12255   };
  12256  
  12257   //Show Spe cialty Sub type field  once Spec ialty has  been selec ted
  12258   MCS.mcs_Se rvice_Acti vity.Enabl eServiceSu bType = fu nction ()  {
  12259       var se rviceType  = null;
  12260       var se rviceTypeS LU = null;
  12261  
  12262       if (Xr m.Page.get Attribute( "mcs_servi cetype") ! = null)
  12263           se rviceType  = Xrm.Page .getAttrib ute("mcs_s ervicetype ").getValu e();
  12264       if (se rviceType  != null)
  12265           se rviceTypeS LU = servi ceType[0]. name;
  12266  
  12267       if (se rviceTypeS LU != null ) {
  12268           Xr m.Page.get Control("m cs_service subtype"). setVisible (true);
  12269           // Xrm.Page.g etControl( "mcs_servi cesubtype" ).setFocus ();
  12270       }
  12271       else {
  12272           Xr m.Page.get Control("m cs_service subtype"). setVisible (false);
  12273           Xr m.Page.get Attribute( "mcs_servi cesubtype" ).setValue (null);
  12274       }
  12275   };
  12276  
  12277       /* Add s Custom F iltered lo okup view  for TSA ba sed on sel ections
  12278       /* for  Specialty , Service  Sub-Type,  and Site(P atient Sit e). */
  12279   MCS.mcs_Se rvice_Acti vity.Handl eOnChangeT SALookup =  function  () {
  12280       var ts aControl =  Xrm.Page. ui.control s.get("mcs _relatedts a");
  12281       if (ts aControl.g etVisible( )) {
  12282           va r siteObj,  site, sit esearch;
  12283           va r serviceT ype = new  Array();
  12284           va r serviceS ubType = n ew Array() ;
  12285           se rviceType  = Xrm.Page .getAttrib ute("mcs_s ervicetype ").getValu e();
  12286           se rviceSubTy pe = Xrm.P age.getAtt ribute("mc s_services ubtype").g etValue();
  12287           va r TSAtype  = Xrm.Page .getAttrib ute("cvt_t ype").getV alue();
  12288  
  12289           va r groupApp t = Xrm.Pa ge.getAttr ibute("mcs _groupappo intment")  == null ?  0 : Xrm.Pa ge.getAttr ibute("mcs _groupappo intment"). getValue() ;
  12290           va r provider s = Xrm.Pa ge.getAttr ibute("cvt _relatedpr oviderid") .getValue( );
  12291  
  12292           if  (groupApp t == 0) {
  12293                if (TSAt ype == tru e) { //CVT  to Home -  Provider
  12294                    site Obj = Xrm. Page.getAt tribute("m cs_related providersi te");
  12295                    site search = " cvt_relate dproviders iteid";
  12296                }
  12297                else { / /(I) - Pat ient
  12298                    site Obj = Xrm. Page.getAt tribute("m cs_related site");
  12299                    site search = " cvt_relate dpatientsi teid";
  12300                }
  12301           }
  12302           el se { //(G)  - Provide r
  12303                siteObj  = Xrm.Page .getAttrib ute("mcs_r elatedprov idersite") ;
  12304                sitesear ch = "cvt_ relatedpro vidersitei d";
  12305           }
  12306           if  (siteObj  != null)
  12307                site = s iteObj.get Value();
  12308           if  (site ==  null)
  12309                return;
  12310  
  12311           va r viewDisp layName =  "Filtered  by Site";
  12312           va r siteID =  site[0].i d;
  12313           va r fetchBas e = '<fetc h version= "1.0" outp ut-format= "xml-platf orm" mappi ng="logica l" distinc t="false"> <entity na me="mcs_se rvices"><a ttribute n ame="mcs_s ervicesid" /><attribu te name="m cs_name"/> <attribute  name="cre atedon"/>< order attr ibute="mcs _name" des cending="f alse"/><fi lter type= "and"><con dition att ribute="st atecode" o perator="e q" value=" 0"/><condi tion attri bute="' +  sitesearch  + '" oper ator="eq"  uiname="'  + MCS.cvt_ Common.for matXML(sit e[0].name)  + '" uity pe="mcs_si te" value= "' + siteI D + '"/>';
  12314           if  (provider s != null)  {
  12315                viewDisp layName +=  " & Provi der";
  12316                fetchBas e += '<con dition att ribute="cv t_provider s" value=" ' + '%' +  MCS.cvt_Co mmon.forma tXML(provi ders[0].na me) + '%'  + '" opera tor="like" />';
  12317           }
  12318           if  (serviceT ype != nul l) {
  12319                viewDisp layName +=  " & Speci alty";
  12320                var serv iceTypeID  = serviceT ype[0].id;
  12321                fetchBas e += '<con dition att ribute="cv t_servicet ype" opera tor="eq" u iname="' +  MCS.cvt_C ommon.form atXML(serv iceType[0] .name) + ' " uitype=" mcs_servic etype" val ue="' + se rviceTypeI D + '"/>';
  12322                if (serv iceSubType  != null)  {
  12323                    view DisplayNam e += " & S ervice Sub -Type";
  12324                    var  serviceSub TypeID = s erviceSubT ype[0].id;
  12325                    fetc hBase += ' <condition  attribute ="cvt_serv icesubtype " operator ="eq" uina me="' + MC S.cvt_Comm on.formatX ML(service SubType[0] .name) + ' " uitype=" mcs_servic esubtype"  value="' +  serviceSu bTypeID +  '"/>';
  12326                }
  12327           }
  12328           if  (TSAtype  == true) {
  12329                viewDisp layName +=  " & Home/ Mobile";
  12330                fetchBas e += '<con dition att ribute="cv t_type" va lue="true"  operator= "eq"/>';
  12331           }
  12332           el se {
  12333                viewDisp layName +=  " & Clini c Based";
  12334                fetchBas e += '<fil ter type=" or"><condi tion attri bute="cvt_ type" valu e="false"  operator=" eq"/><cond ition attr ibute="cvt _type" ope rator="nul l"/></filt er>';
  12335           }
  12336  
  12337           if  (Xrm.Page .getAttrib ute("cvt_t elehealthm odality"). getValue()  == true)  {
  12338                viewDisp layName +=  " & SFT";
  12339                fetchBas e += '<con dition att ribute="cv t_availabl etelehealt hmodalitie s" value=" 917290001"  operator= "eq"/>';
  12340           }
  12341           el se {
  12342                viewDisp layName +=  " & CVT";
  12343                fetchBas e += '<fil ter type=" or"><condi tion attri bute="cvt_ availablet elehealthm odalities"  value="91 7290000" o perator="e q"/><condi tion attri bute="cvt_ availablet elehealthm odalities"  operator= "null"/></ filter>';
  12344           }
  12345           fe tchBase +=  '<conditi on attribu te="status code" valu e="2519200 00" operat or="eq"/>< condition  attribute= "cvt_group appointmen t" value=" ' + groupA ppt + '" o perator="e q"/></filt er></entit y></fetch> ';
  12346  
  12347           va r Tsalayou tXml = '<g rid name=" resultset"  object="1 0010" jump ="mcs_name " select=" 1" icon="0 " preview= "0"><row n ame="resul t" id="mcs _servicesi d"><cell n ame="cvt_p rovsitevis taclinics"  width="30 0"/><cell  name="cvt_ patsitevis taclinics"  width="30 0"/><cell  name="cvt_ providers"  width="30 0"/><cell  name="mcs_ name" widt h="300"/>< cell name= "cvt_group appointmen t" width=" 125"/><cel l name="cv t_patients ites" widt h="300"/>< cell name= "cvt_servi cetype" wi dth="100"/ ><cell nam e="cvt_ser vicesubtyp e" width=" 100"/><cel l name="cr eatedon" w idth="125" /></row></ grid>';
  12348           ts aControl.a ddCustomVi ew(siteID,  "mcs_serv ices", vie wDisplayNa me, fetchB ase, Tsala youtXml, t rue);
  12349       }
  12350   };
  12351  
  12352   //Descript ion: Creat eName for  Service Ac tivity Sub ject
  12353   MCS.mcs_Se rvice_Acti vity.Creat eName = fu nction ()  {
  12354       var se rviceType  = Xrm.Page .getAttrib ute("mcs_s ervicetype ").getValu e();
  12355       var se rviceSubTy pe = Xrm.P age.getAtt ribute("mc s_services ubtype").g etValue();
  12356       var gr oupApptOpt ion = Xrm. Page.getAt tribute("m cs_groupap pointment" ).getValue ();
  12357       var de rivedResul tField = " ";       
  12358       if (se rviceType  != null)
  12359           de rivedResul tField +=  serviceTyp e[0].name  + " ";
  12360       if (se rviceSubTy pe != null )
  12361           de rivedResul tField +=  " : " + se rviceSubTy pe[0].name  + " ";
  12362       if (gr oupApptOpt ion == 1)
  12363           de rivedResul tField +=  "Group App ointment";
  12364  
  12365       Xrm.Pa ge.getAttr ibute("sub ject").set Value(deri vedResultF ield);
  12366   };
  12367  
  12368   //If group  appointme nt, show p ro site an d patient  rooms,
  12369   MCS.mcs_Se rvice_Acti vity.Group Appt = fun ction () {
  12370  
  12371       var gr oupAppt =  Xrm.Page.g etAttribut e("mcs_gro upappointm ent").getV alue();
  12372       var pa tSite = Xr m.Page.ui. controls.g et("mcs_re latedsite" );
  12373       var pr oSite = Xr m.Page.ui. controls.g et("mcs_re latedprovi dersite");
  12374  
  12375       var pa tRoomsTab  = Xrm.Page .ui.tabs.g et("tab_gr oupschedul ing");
  12376   //    var  grouppatie ntsTab = X rm.Page.ui .tabs.get( "tab_group patients") ;
  12377  
  12378       var te leModala =  Xrm.Page. getAttribu te("cvt_te lehealthmo dality");
  12379       var te leModalc =  Xrm.Page. getControl ("cvt_tele healthmoda lity");
  12380       var is HomeMobile  = Xrm.Pag e.getAttri bute("cvt_ type").get Value();
  12381  
  12382       if (gr oupAppt ==  true) {
  12383           pr oSite.setV isible(tru e);
  12384           pa tSite.setV isible(fal se);
  12385           pa tRoomsTab. setVisible (!isHomeMo bile);
  12386           Xr m.Page.get Control("c ustomers") .setDisabl ed(!isHome Mobile);
  12387           
  12388           Xr m.Page.get Attribute( "mcs_relat edsite").s etValue(nu ll);
  12389           Xr m.Page.get Attribute( "mcs_relat edprovider site").set RequiredLe vel("requi red");
  12390           Xr m.Page.get Attribute( "mcs_relat edsite").s etRequired Level("non e");
  12391  
  12392           te leModala.s etValue(fa lse);
  12393           te leModala.f ireOnChang e();
  12394           te leModalc.s etVisible( false);
  12395  
  12396       }
  12397       else {
  12398           pr oSite.setV isible(fal se);
  12399           pa tSite.setV isible(tru e);
  12400           pa tRoomsTab. setVisible (false);
  12401           Xr m.Page.get Attribute( "mcs_relat edprovider site").set RequiredLe vel("none" );
  12402           Xr m.Page.get Attribute( "mcs_relat edsite").s etRequired Level("req uired");
  12403           if  (Xrm.Page .getAttrib ute("cvt_t ype").getV alue() !=  true) {
  12404                Xrm.Page .getAttrib ute("mcs_r elatedprov idersite") .setValue( null);
  12405           }
  12406           te leModalc.s etVisible( true);
  12407           te leModala.f ireOnChang e();
  12408       }
  12409   };
  12410  
  12411   //Group SA  - add Pat Side AR Re sSpec to R esources f ield
  12412   MCS.mcs_Se rvice_Acti vity.Group Pat = func tion () {
  12413       if (Xr m.Page.get Attribute( "mcs_group appointmen t").getVal ue() == tr ue && Xrm. Page.ui.ge tFormType( ) == 1) {
  12414           va r TSAid =  "";
  12415           if  (Xrm.Page .getAttrib ute("mcs_r elatedtsa" ).getValue () != null ) {
  12416                TSAid =  Xrm.Page.g etAttribut e("mcs_rel atedtsa"). getValue() [0].id;
  12417           }
  12418           // Retrieve t he info fr om the TSA
  12419           Cr mRestKit.R etrieve('m cs_service s', TSAid,  ['cvt_gro uppatientb ranch'], t rue).fail(
  12420                function  (err) {
  12421                    //
  12422                }).done(
  12423                function  (data) {
  12424                    if ( data.d.cvt _grouppati entbranch  != null) {
  12425                         //break re sult into  an array
  12426                         var result Array = da ta.d.cvt_g rouppatien tbranch.sp lit("|");
  12427                         if (result Array.leng th == 3) {
  12428                             //Turn  it into a n object
  12429                             var gr oupActivit yParty = [ ];
  12430                             groupA ctivityPar ty[0] = {
  12431                                 id : resultAr ray[0],
  12432                                 re souceSpecI d: resultA rray[2],
  12433                                 ty peName: re sultArray[ 1],
  12434                                 en tityType:  resultArra y[1],
  12435                                 na me: "Searc h for All  Resources"
  12436                             };
  12437  
  12438                             //Set  the object  to the Re souce fiel d
  12439                             Xrm.Pa ge.getAttr ibute("res ources").s etValue(gr oupActivit yParty);
  12440                         }
  12441                    }
  12442  
  12443                });
  12444       }
  12445   };
  12446   MCS.mcs_Se rvice_Acti vity.Clear Resources  = function  () {
  12447       var ts a = Xrm.Pa ge.getAttr ibute("mcs _relatedts a").getVal ue(); 
  12448       if (ts a == null)  {
  12449           Xr m.Page.get Attribute( "resources ").setValu e(null);
  12450           Xr m.Page.get Attribute( "resources ").setSubm itMode();
  12451       }
  12452   };
  12453  
  12454   //If resou rces are o n Service  Activity,  display th e scheduli ng tab, ot herwise hi de it
  12455   MCS.mcs_Se rvice_Acti vity.Sched ulingInfo  = function  () {
  12456       var re sources =  Xrm.Page.g etAttribut e("resourc es").getVa lue();
  12457       var sc hedulingTa b = Xrm.Pa ge.ui.tabs .get("tab_ scheduling ").setVisi ble(resour ces.length  > 0);
  12458   };
  12459  
  12460   //TO DO: e xplore why  this is r unning onS ave - prob ably need  to remove  this
  12461   MCS.mcs_Se rvice_Acti vity.filte rSubGrid =  function( ) {
  12462       var Pa tRoomsGrid  = documen t.getEleme ntById("Pa tientRooms "); //grid  to filter  
  12463       if (Pa tRoomsGrid  == null)  { //make s ure the gr id has loa ded 
  12464           se tTimeout(f unction ()  { MCS.mcs _Service_A ctivity.fi lterSubGri d(); }, 50 0); //if t he grid ha sn’t loa ded run th is again w hen it has  
  12465           re turn;
  12466       }
  12467  
  12468       var TS AValue = X rm.Page.ge tAttribute ("mcs_rela tedtsa").g etValue();  //field t o filter b
  12469  
  12470       var TS AId = "000 00000-0000 -0000-0000 -000000000 000"; //if  filter fi eld is nul l display  nothing 
  12471       if (TS AValue !=  null) {
  12472           va r TSAId =  TSAValue[0 ].id;
  12473       }
  12474  
  12475       //fetc h xml code  which wil l retrieve  all Pat S ites Relat ed to this  Service A ctivity.  
  12476       var fe tchXml =
  12477           
  12478           "< ?xml versi on='1.0'?> " +
  12479           "< fetch dist inct='fals e' mapping ='logical'  output-fo rmat='xml- platform'  version='1 .0'>" +
  12480           "< entity nam e='cvt_pat ientresour cegroup'>"  +
  12481           "< attribute  name='cvt_ roomcapaci ty'/>" +
  12482           "< attribute  name='cvt_ type'/>" +
  12483           "< attribute  name='cvt_ name'/>" +
  12484           "< attribute  name='cvt_ patientres ourcegroup id'/>" +
  12485           "< order desc ending='fa lse' attri bute='cvt_ name'/>" +
  12486           "< filter typ e='and'>"  +
  12487           "< condition  attribute= 'cvt_type'  value='25 1920001' o perator='e q'/>" +
  12488           "< condition  attribute= 'cvt_relat edtsaid' v alue='" +  TSAId + "'  operator= 'eq'/>" +
  12489           "< condition  attribute= 'statecode ' value='0 ' operator ='eq'/>" +
  12490           "< /filter>"  +
  12491           "< /entity>"  +
  12492           "< /fetch>"
  12493  
  12494       PatRoo msGrid.con trol.SetPa rameter("f etchXml",  fetchXml);  //set the  fetch xml  to the su b grid   
  12495       PatRoo msGrid.con trol.Refre sh(); //re fresh the  sub grid u sing the n ew fetch x ml 
  12496   };
  12497  
  12498   MCS.mcs_Se rvice_Acti vity.Enfor ceChanges  = function  () {
  12499     
  12500       Xrm.Pa ge.getAttr ibute("res ources").s etSubmitMo de("always ");
  12501       Xrm.Pa ge.getAttr ibute("ser viceid").s etSubmitMo de("always ");
  12502       Xrm.Pa ge.getAttr ibute("sch eduledstar t").setSub mitMode("a lways");
  12503       Xrm.Pa ge.getAttr ibute("sch eduledend" ).setSubmi tMode("alw ays");
  12504       Xrm.Pa ge.getAttr ibute("sch eduleddura tionminute s").setSub mitMode("a lways");
  12505   };
  12506  
  12507   MCS.mcs_Se rvice_Acti vity.CVTto Home = fun ction () {
  12508       var ty pe = Xrm.P age.getAtt ribute("cv t_type").g etValue();
  12509       var ty pec = Xrm. Page.getCo ntrol("cvt _type");
  12510       if (Xr m.Page.ui. getFormTyp e() == MCS .mcs_Servi ce_Activit y.FORM_TYP E_CREATE)  {
  12511           ty pec.setDis abled(fals e);
  12512       }
  12513       var gr oupAppta =  Xrm.Page. getAttribu te("mcs_gr oupappoint ment");
  12514       var gr oupApptc =  Xrm.Page. getControl ("mcs_grou pappointme nt");
  12515  
  12516       var pa tSitea = X rm.Page.ge tAttribute ("mcs_rela tedsite");
  12517       var pa tSitec = X rm.Page.ge tControl(" mcs_relate dsite");
  12518  
  12519       var pr oSitea = X rm.Page.ge tAttribute ("mcs_rela tedprovide rsite");
  12520       var pr oSitec = X rm.Page.ge tControl(" mcs_relate dproviders ite");
  12521  
  12522       var pa tients = X rm.Page.ge tControl(" customers" );
  12523       var pa tRoomsTab  = Xrm.Page .ui.tabs.g et("tab_gr oupschedul ing");
  12524       var gr ouppatient sTab = Xrm .Page.ui.t abs.get("t ab_grouppa tients");
  12525  
  12526       var te leModala =  Xrm.Page. getAttribu te("cvt_te lehealthmo dality");
  12527       var te leModalc =  Xrm.Page. getControl ("cvt_tele healthmoda lity");
  12528  
  12529       if (ty pe == true ) { //Cvt  to home
  12530           // groupAppta .setValue( true);
  12531           // groupAppta .fireOnCha nge();
  12532           gr oupApptc.s etVisible( true);
  12533           if  (groupApp ta.getValu e())
  12534                Xrm.Page .getContro l("custome rs").setDi sabled(fal se);
  12535  
  12536           te leModala.s etValue(fa lse);
  12537           te leModala.f ireOnChang e();
  12538           te leModalc.s etVisible( false);
  12539  
  12540           pr oSitec.set Visible(tr ue);
  12541           pr oSitea.set RequiredLe vel("requi red");
  12542  
  12543           pa tSitea.set Value(null );
  12544           pa tSitea.set RequiredLe vel("none" );
  12545           pa tSitec.set Visible(fa lse);
  12546  
  12547           pa tRoomsTab. setVisible (false);
  12548       }
  12549       else {  //Clinic  based
  12550           if  (groupApp ta.getValu e() != tru e)
  12551                proSitea .setValue( null);
  12552  
  12553           pr oSitec.set Visible(fa lse);
  12554           pr oSitea.set RequiredLe vel("none" );
  12555           
  12556           pa tSitec.set Visible(tr ue);
  12557           pa tSitea.set RequiredLe vel("requi red");
  12558  
  12559           gr oupApptc.s etVisible( true);
  12560           gr oupAppta.f ireOnChang e();
  12561  
  12562           te leModalc.s etVisible( true);
  12563           te leModala.f ireOnChang e();
  12564       }
  12565   };
  12566  
  12567   MCS.mcs_Se rvice_Acti vity.Block AddPatient  = functio n () {
  12568       var pa tientObj =  Xrm.Page. getAttribu te("custom ers");
  12569       var pa tients = p atientObj  != null ?  patientObj .getValue( ) : [];
  12570       var ne wPatsAdded  = MCS.mcs _Service_A ctivity.co mpareArray s(MCS.Pati ents, pati ents);
  12571       if (ne wPatsAdded .length ==  0) {
  12572           // Determine  if we want  to re-bui ld the cac hed patien ts list af ter removi ng a veter an - 
  12573           // scenario:  if you rem ove a vete ran - clic k away - a nd then tr y to add a  new one,  should the  one that  got remove d get adde d back or  not?  
  12574           //     MCS.Pa tients = X rm.Page.ge tAttribute ("optional attendees" ).getValue ();
  12575           re turn;
  12576       }
  12577       else {
  12578           al ert("You c an only ad d patients  through t he Patient  Search.   Not adding : " + newP atsAdded);
  12579           pa tientObj.s etValue(MC S.Patients );
  12580       }
  12581   }
  12582  
  12583   MCS.mcs_Se rvice_Acti vity.compa reArrays =  function  (cachedPat ients, new Patients)  {
  12584       var ne wPats = [] ;
  12585       var ne wPatString  = "";
  12586       if (ne wPatients  == null)
  12587           re turn "";
  12588       for (v ar i in ne wPatients)  {
  12589           va r alreadyE xists = fa lse;
  12590           va r newPatId Obj = newP atients[i] ;
  12591           if  (newPatId Obj != nul l) {
  12592                var newP atId = MCS .cvt_Commo n.TrimBook endBracket s(newPatId Obj.id.toL owerCase() );
  12593                for (var  j in cach edPatients ) {
  12594                    var  cachedPati entObj = c achedPatie nts[j];
  12595                    var  cachedPati entObjId =  MCS.cvt_C ommon.Trim BookendBra ckets(cach edPatientO bj.id.toLo werCase()) ;
  12596                    if ( cachedPati entObj !=  null && ne wPatId ==  cachedPati entObjId)  {
  12597                         alreadyExi sts = true ;
  12598                         break;
  12599                    }
  12600                }
  12601           }
  12602           if  (!already Exists) {
  12603                newPats. push(newPa tIdObj.nam e);
  12604           }
  12605       }
  12606       if (ne wPats.leng th > 0) {
  12607  
  12608           fo r (var pat  in newPat s) {
  12609                newPatSt ring += ne wPats[pat]  + "; ";
  12610           }
  12611           ne wPatString  = newPatS tring.subs tr(0, newP atString.l ength - 2)
  12612       }
  12613       return  newPatStr ing;
  12614   }
  12615   if (typeof  (MCS) ==  "undefined ")
  12616       MCS =  {};
  12617  
  12618   if (typeof  (MCS.VIAL ogin == "u ndefined") )
  12619       MCS.VI ALogin = { }
  12620  
  12621   MCS.VIALog in.KeepAli veWindowNa me = "crms soi";
  12622   MCS.VIALog in.Refresh es = 0;
  12623   //MCS.VIAL ogin.Getti ngNewUserD uz;
  12624  
  12625   // ******* ********** ********** ********** *********P age Specif ic Functio ns
  12626   MCS.VIALog in.LoginBu tton = fun ction () {
  12627       var va lidSamlTok en = MCS.V IALogin.Is ValidSamlT oken();
  12628       if (va lidSamlTok en) {
  12629           MC S.VIALogin .Login();
  12630       }
  12631       else {
  12632           MC S.VIALogin .Saml();
  12633       }
  12634   }
  12635  
  12636   MCS.VIALog in.IsValid SamlToken  = function  () {
  12637       if (!M CS.VIALogi n.RunVista Integratio n())
  12638           re turn true;
  12639       //To D o - add in  possible  check to e nsure the  user who g ot the tok en origina lly is the  same pers on that is  now takin g action
  12640       var sa mlToken =  Xrm.Page.g etAttribut e("cvt_sam ltoken") ! = null ? X rm.Page.ge tAttribute ("cvt_saml token").ge tValue() :  null;
  12641       if (sa mlToken ==  null) //N o token
  12642           re turn false ;
  12643  
  12644       var er rorTag = s amlToken.i ndexOf("<w st:Reason> ");
  12645       if (er rorTag !=  -1) //Erro red Token
  12646           re turn false ;
  12647  
  12648       var en dTimeIndex  = samlTok en.indexOf ("NotOnOrA fter");
  12649       if (en dTimeIndex  != -1) {
  12650           va r endTimeS tring = sa mlToken.su bstring(en dTimeIndex  + "NotOnO rAfter".le ngth + 2,  endTimeInd ex + "NotO nOrAfter". length + 2 +20);
  12651           va r end = ne w Date(end TimeString ).getTime( );
  12652  
  12653           // Note: VA c omputer cl ocks are c ontrolled  by IT, so  it should  be safe to  assume th at clocks  are close  enough to  accurate t hat this i s a safe w ay to chec k
  12654           if  (new Date ().getTime () + 1000  * 30 > end ) //Inacti ve token,  or token w ill be ina ctive in 3 0 seconds,  so consid er it expi red
  12655                return f alse;
  12656           el se //Valid  token tha t doesnt e xpire for  at least 3 0 seconds  from now
  12657                return t rue;
  12658       }
  12659       else / /Invalid T oken - all  valid tok ens must c ontain the  NotOnOrAf ter token
  12660           re turn false ;
  12661   };
  12662  
  12663   MCS.VIALog in.IsValid UserDuz =  function ( ) {
  12664       if (!M CS.VIALogi n.RunVista Integratio n())
  12665           re turn true;
  12666  
  12667       //To D o - Check  for the du z field(s)
  12668       var si de = MCS.V IALogin.Du zSide();
  12669       var du zMissing =  false;
  12670       if (si de == "bot h" || side  == "pat")  {
  12671           du zMissing =  Xrm.Page. getAttribu te("cvt_pa tuserduz") .getValue( ) == null;
  12672       }
  12673       if (si de == "bot h" || side  == "pro")  {
  12674           du zMissing =  duzMissin g ? true :  Xrm.Page. getAttribu te("cvt_pr ouserduz") .getValue( ) == null;
  12675       }
  12676  
  12677       return  !duzMissi ng;
  12678  
  12679       //if ( duzMissing )
  12680       //     return fal se;
  12681  
  12682       ////To  Do - add  in possibl e check to  ensure th e user who  got the t oken origi nally is t he same pe rson that  is now tak ing action
  12683       //var  samlToken  = Xrm.Page .getAttrib ute("cvt_s amltoken")  != null ?  Xrm.Page. getAttribu te("cvt_sa mltoken"). getValue()  : null;
  12684       //if ( samlToken  == null) / /No token
  12685       //     return fal se;
  12686  
  12687       //var  errorTag =  samlToken .indexOf(" <wst:Reaso n>");
  12688       //if ( errorTag ! = -1) //Er rored Toke n
  12689       //     return fal se;
  12690  
  12691       //var  notBeforeT imeIndex =  samlToken .indexOf(" NotBefore" );
  12692       //if ( notBeforeT imeIndex ! = -1) {
  12693       //     var notBef oreString  = samlToke n.substrin g(notBefor eTimeIndex  + "NotBef ore".lengt h + 2, not BeforeTime Index + "N otBefore". length + 2  + 20);
  12694       //     var notBef ore = new  Date(notBe foreString ).getTime( );
  12695  
  12696       //     //Note: VA  computer  clocks are  controlle d by IT, s o it shoul d be safe  to assume  that clock s are clos e enough t o accurate  that this  is a safe  way to ch eck
  12697       //     if (new Da te().getTi me() + 100 0 * 30 > n otBefore +  1000 * 60  * 60 * 4)  //Inactiv e Duz, or  Duz (which  lasts 4 h ours from  issue inst ant, aka n otBefore)  will be in active in  30 seconds , so consi der it exp ired
  12698       //         return  false;
  12699       //     else {
  12700       //         var em ailAddress  = "";
  12701       //         CrmRes tKit.Retri eve('Syste mUser', Xr m.Page.con text.getUs erId(), [' DomainName ','Interna lEMailAddr ess'], fal se)
  12702       //         .fail( function ( err) {
  12703       //             al ert("Inval id Vista L ogin (User  Duz) - tr y logging  in again.   Details:  " + MCS.cv t_Common.R estError(e rr));
  12704       //         }).don e(function  (data) {
  12705       //             if  (data !=  null && da ta.d != nu ll) {
  12706       //                  emailAdd ress = dat a.d.Domain Name;
  12707       //                  if (emai lAddress.i ndexOf("@v a.gov") ==  -1)
  12708       //                      emai lAddress =  data.d.In ternalEMai lAddress;
  12709       //             }
  12710       //         });
  12711       //         if (em ailAddress  != "" &&  samlToken. toLowerCas e().indexO f(emailAdd ress.toLow erCase())  != -1) //V alid token  that is a ssigned to  you and i s good for  at least  30 seconds  from now
  12712       //             re turn true;
  12713       //         else
  12714       //             re turn false ; //this i s not your  token
  12715       //     }
  12716       //}
  12717       //else  //Invalid  Token - a ll valid t okens must  contain t he NotOnOr After toke n
  12718       //     return fal se;
  12719   };
  12720  
  12721   MCS.VIALog in.Saml =  function ( ) {
  12722       //MCS. VIALogin.I sValidSaml Token();
  12723       var ru nVista = M CS.VIALogi n.RunVista Integratio n();
  12724       if (ru nVista)
  12725           MC S.VIALogin .GetSamlTo ken();
  12726   };
  12727  
  12728   MCS.VIALog in.DuzSide  = functio n () {
  12729       var ty peCode = X rm.Page.co ntext.getQ ueryString Parameters ().etc;
  12730  
  12731       var ru nProSide =  true;
  12732       var ru nPatSide =  true;
  12733       if (ty peCode ==  4214) {
  12734           ru nPatSide =  Xrm.Page. getAttribu te("cvt_ty pe").getVa lue() == f alse;
  12735           ru nProSide =  Xrm.Page. getAttribu te("cvt_te lehealthmo dality").g etValue()  == false;
  12736       }
  12737       if (ru nPatSide & & runProSi de)
  12738           re turn "both ";
  12739       else i f (runPatS ide)
  12740           re turn "pat" ;
  12741       else i f (runProS ide)
  12742           re turn "pro" ;
  12743       else
  12744           re turn null;
  12745   }
  12746  
  12747   MCS.VIALog in.Login =  function  () {
  12748       var ru nVista = M CS.VIALogi n.RunVista Integratio n();
  12749       if (!r unVista)
  12750           re turn;
  12751       Xrm.Pa ge.ui.tabs .get('serv ice').sect ions.get(' VistaLogin ').setVisi ble(true);
  12752       if (Xr m.Page.get Attribute( "cvt_samlt oken").get Value() ==  null) {
  12753           re turn;
  12754       }
  12755       var si de = MCS.V IALogin.Du zSide();
  12756  
  12757       if (MC S.VIALogin .GetSettin g("VIA Log in Endpoin t") != "")
  12758           MC S.VIALogin .LoginToVi aBah(side) ;
  12759       else 
  12760           MC S.VIALogin .ViaLoginV imt(side);
  12761   };
  12762  
  12763   MCS.VIALog in.RunVist aIntegrati on = funct ion () {
  12764       var ty peCode = X rm.Page.co ntext.getQ ueryString Parameters ().etc;
  12765       //if b lock resou rce and th eres no re lated appo intment
  12766       if (ty peCode ==  4201 && Xr m.Page.get Attribute( "cvt_servi ceactivity id").getVa lue() == n ull)
  12767           re turn false ;
  12768       //if a ppointment  and no ts a is set
  12769       if (ty peCode ==  4214 && (X rm.Page.ge tAttribute ("mcs_rela tedtsa") = = null ||  Xrm.Page.g etAttribut e("mcs_rel atedtsa"). getValue()  == null))
  12770           re turn false ;
  12771       //if a ppt and cl inic based  Group
  12772       if (ty peCode ==  4214 && (! Xrm.Page.g etAttribut e("cvt_typ e").getVal ue() && Xr m.Page.get Attribute( "mcs_group appointmen t").getVal ue()))
  12773           re turn false ;
  12774       var st ateCode =  Xrm.Page.g etAttribut e('stateco de').getVa lue();
  12775       //if n ot active
  12776       if (st ateCode !=  3 && Xrm. Page.ui.ge tFormType( ) != 1)
  12777           re turn false ;
  12778       //If v ista integ ration swi tch is tur ned off
  12779       if (!M CS.VIALogi n.CheckVis taSwitches ())
  12780           re turn false ;
  12781       return  true;
  12782   };
  12783  
  12784   // ******* ********** ********** ********** ********** *STS Retri eval Funct ions****** ********** ********** ********** ********** ******
  12785   //Retrieve s the SSOi  SAML Toke n either t hrough Kee p Alive or  through D irect IAM  STS depend ing on whi ch URLs ar e availabl e
  12786   MCS.VIALog in.GetSaml Token = fu nction ()  {
  12787       var re freshUrl =  MCS.VIALo gin.GetKee pAliveUrl( );
  12788       var ke epAliveLog inUrl = MC S.VIALogin .GetKeepAl iveLoginUr l();
  12789       var di rectIamUrl  = MCS.VIA Login.GetS tsUrl();
  12790  
  12791       if (re freshUrl ! = "" && ke epAliveLog inUrl != " ")
  12792           MC S.VIALogin .RefreshTo ken();
  12793       else i f (directI amUrl != " ")
  12794           MC S.VIALogin .CallIamSt s(directIa mUrl);
  12795       else {
  12796           al ert("No PI V Authenti cation has  been set  up");
  12797           va r fake = ' <?xml vers ion="1.0"  encoding=" UTF- 8"?><  soapenv:E nvelope xm lns: wsa =  "http://w ww.w3.org/ 2005/08/ad dressing"  xmlns: xsi  = "http:/ /www.w3.or g/2001/XML Schema-ins tance" xml ns: xsd =  "http://ww w.w3.org/2 001/XMLSch ema" xmlns : Soapenv  = "http:// schemas.xm lsoap.org/ soap/envel ope/" xmln s: wst = " http://sch emas.xmlso ap.org/ws/ 2005/02/tr ust" > <so apenv:Head er><ns1:Se curity soa penv:mustU nderstand= "0" xmlns: ns1="http: //docs.oas is-open.or g/wss/2004 /01/oasis- 200401-wss -wssecurit y-secext-1 .0.xsd"><n s2:Timesta mp xmlns:n s2="http:/ /docs.oasi s-open.org /wss/2004/ 01/oasis-2 00401-wss- wssecurity -utility-1 .0.xsd"><n s2:Created >2017-11-2 7T19:37:26 Z</ns2:Cre ated ></ns 2: Timesta mp ></ns1:  Security  ></soapenv : Header >  <soapenv: Body><wst: RequestSec urityToken Response>< wst:Reques tType>http ://schemas .xmlsoap.o rg/ws/2005 /02/trust/ Issue</wst :RequestTy pe > <wst: TokenType> http://doc s.oasis-op en.org/wss /oasis-wss -saml-toke n-profile- 1.1#SAMLV2 .0</wst:To kenType >  <wst:Statu s><wst:Cod e>http://d ocs.oasis- open.org/w s-sx/ws-tr ust/200512 /status/In valid</wst :Code > <w st:Reason> BACK_END_C ONNECTION_ FAILED: Ba ck End Aut h Provider  Connectio n Failed.< /wst:Reaso n ></wst:  Status ></ wst: Reque stSecurity TokenRespo nse ></soa penv: Body  ></soapen v: Envelop e >';
  12798           Xr m.Page.get Attribute( "cvt_samlt oken").set Value(fake );
  12799           Xr m.Page.get Attribute( "cvt_samlt oken").fir eOnChange( );
  12800       }
  12801   };
  12802  
  12803   //Retrieve s the Toke n from IAM  directly
  12804   MCS.VIALog in.CallIam Sts = func tion (iamU rl) {
  12805       var po ststring =  "<soapenv :Envelope  xmlns:soap env=\"http ://schemas .xmlsoap.o rg/soap/en velope/\"  xmlns:ns=\ "http://do cs.oasis-o pen.org/ws -sx/ws-tru st/200512\ ">"
  12806           +  "<soapenv: Header/>"
  12807           +  "<soapenv: Body>"
  12808           +  "<ns:Reque stSecurity Token>"
  12809           +  "<ns:Base> "
  12810           +  "<wss:TLS  xmlns:wss= \"http://d ocs.oasis- open.org/w ss/2004/01 /oasis-200 401-wss-ws security-s ecext-1.0. xsd\"/>"
  12811           +  "</ns:Base >"
  12812           +  "<wsp:Appl iesTo xmln s:wsp=\"ht tp://schem as.xmlsoap .org/ws/20 04/09/poli cy\">"
  12813           +  "<wsa:Endp ointRefere nce xmlns: wsa=\"http ://schemas .xmlsoap.o rg/ws/2004 /08/addres sing\">"
  12814             + "<wsa:Ad dress>http s:// DNS          .crm15.xrm .va.gov/TM P</wsa:Add ress>"
  12815           +  "</wsa:End pointRefer ence>"
  12816           +  "</wsp:App liesTo>"
  12817           +  "<ns:Issue r>"
  12818             + "<wsa:Ad dress xmln s:wsa=\"ht tp://schem as.xmlsoap .org/ws/20 04/08/addr essing\">h ttps:// DNS               /Issuer/sm token/SAML 2</wsa:Add ress>"
  12819           +  "</ns:Issu er>"
  12820           +  "<ns:Reque stType>htt p://schema s.xmlsoap. org/ws/200 5/02/trust /Validate< /ns:Reques tType>"
  12821           +  "</ns:Requ estSecurit yToken>"
  12822           +  "</soapenv :Body>"
  12823           +  "</soapenv :Envelope> "
  12824           ;
  12825       url =  iamUrl ==  null ? MCS .VIALogin. GetStsUrl( ) : iamUrl ;
  12826       //$.su pport.cors  = true;
  12827       $.get( url).done( function ( ) {
  12828           $. ajax({
  12829                url: url ,
  12830                type: 'P OST',
  12831                crossDom ain: true,
  12832                data: po ststring,
  12833                contentT ype: 'text /plain',
  12834                dataType : 'text',
  12835                success:  function  (result) {
  12836                    Xrm. Page.getAt tribute("c vt_samltok en").setVa lue(result );
  12837                    Xrm. Page.getAt tribute("c vt_samltok en").fireO nChange();
  12838                },
  12839                error: f unction (j qXHR, tran Status, er rorThrown)  {
  12840                    aler t("Unable  to Get SAM L token to  log into  Vista\n" +
  12841                         'Status: '  + jqXHR.s tatus + '  ' + jqXHR. statusText  + '. ' +
  12842                         'Response:  ' + jqXHR .responseT ext
  12843                    );
  12844                }
  12845           }) ;
  12846       }).fai l(function  (err) {
  12847           al ert("Failu re to Get  SAML token  to log in to Vista\n " +
  12848                'Status:  ' + err.s tatus + '  ' + err.st atusText +  '. ' +
  12849                'Respons e: ' + err .responseT ext
  12850           );
  12851       });
  12852           
  12853   };
  12854  
  12855   //Function  calls the  refresh e ndpoint an d sets the  resulting  SAML toke n onto the  form if t he call is  successfu l, otherwi se keeps c alling its elf every  5 seconds
  12856   MCS.VIALog in.Refresh Token = fu nction ()  {
  12857       MCS.VI ALogin.Ref reshes++;
  12858       var ur l = MCS.VI ALogin.Get KeepAliveU rl();
  12859       var to ken = "";
  12860       $.ajax ({
  12861           ur l: url,
  12862           su ccess: fun ction (res ult) {
  12863                if (resu lt != null )
  12864                    toke n = result .SAMLToken ;
  12865                if (toke n != null  && token ! = "") {
  12866                    Xrm. Page.getAt tribute("c vt_samltok en").setVa lue(token) ;
  12867                    Xrm. Page.getAt tribute("c vt_samltok en").fireO nChange();
  12868                }
  12869                else if  (MCS.VIALo gin.Refres hes == 1)
  12870                    aler t("Please  login with  your PIN  in the new  window to  sign into  Vista.");
  12871           },
  12872           er ror: funct ion (reque st, status , error) {
  12873                alert("T oken Refre sh call fa iled: " +  request.re sponseText  + "; info : " + requ est.status Text);
  12874           },
  12875           co mplete: fu nction ()  {
  12876                if (Xrm. Page.getAt tribute("c vt_samltok en").getVa lue() == n ull && MCS .VIALogin. Refreshes  < 4) {
  12877                    setT imeout(MCS .VIALogin. RefreshTok en, 15000) ;
  12878                    MCS. VIALogin.K eepSession Alive();
  12879                }
  12880           }
  12881           
  12882       });
  12883   };
  12884  
  12885   //Funtion  to open th e Keep Ali ve page (i f its alre ady open,  then it wi ll just fo rce focus  to it)
  12886   MCS.VIALog in.KeepSes sionAlive  = function  () {
  12887       var ur l = MCS.VI ALogin.Get KeepAliveL oginUrl();
  12888       ssoiWi ndow = win dow.open(u rl,
  12889           MC S.VIALogin .KeepAlive WindowName ,
  12890           'h eight=500,  width=865 , location =yes, resi zable=yes,  scrollbar s=yes, sta tus=yes, t itlebar=ye s, top=100 , left=100 ',
  12891           tr ue
  12892       );
  12893       ssoiWi ndow.focus ();
  12894       return ;
  12895   };
  12896  
  12897   // ******* ********** ********** ********** *****VIA L ogin Funct ions****** ********** ********** ********** ********** *
  12898   ////////// ////////// ///iHub Vi aLogin
  12899   //main met hod to log  into VIA  using BAH' s VIA Logi n Web Part  (iHub)
  12900   MCS.VIALog in.LoginTo ViaBah = f unction (s ide) {
  12901       var ur l = MCS.VI ALogin.Via LoginUrl() ;
  12902       var to ken = Xrm. Page.getAt tribute("c vt_samltok en").getVa lue();
  12903       if (to ken == nul l || token  == "") {
  12904           al ert("No VI A Login co mpleted be cause SAML  token not  found.  " );
  12905           re turn;
  12906       }
  12907  
  12908       if (si de == "bot h") {
  12909           va r patFacil ityNumber  = MCS.VIAL ogin.GetFa cilityNumb er("pat");
  12910           va r proFacil ityNumber  = MCS.VIAL ogin.GetFa cilityNumb er("pro");
  12911           va r patMessa ge = MCS.V IALogin.Se tupViaMess age(patFac ilityNumbe r, token);
  12912           va r patDuz =  MCS.VIALo gin.CallBa hLogin(pat Message);
  12913           Xr m.Page.get Attribute( "cvt_patus erduz").se tValue(pat Duz);
  12914  
  12915           if  (patFacil ityNumber  != proFaci lityNumber ) {
  12916                var proM essage = M CS.VIALogi n.SetupVia Message(pr oFacilityN umber, tok en);
  12917                var proD uz = MCS.V IALogin.Ca llBahLogin (proMessag e);
  12918                if (proD uz != "")  {
  12919                    Xrm. Page.getAt tribute("c vt_prouser duz").setV alue(proDu z);
  12920                    MCS. VIALogin.T riggerGetC onsults();
  12921                }
  12922                else
  12923                    aler t("No VIA  Login comp leted for  pro side") ;
  12924           }
  12925           el se {
  12926                if (patD uz != "")  {
  12927                    //Bo th sides a re the sam e, so use  the same l ogin (duz)  for pat a nd pro sid e
  12928                    Xrm. Page.getAt tribute("c vt_prouser duz").setV alue(patDu z);
  12929                    MCS. VIALogin.T riggerGetC onsults();
  12930                }
  12931                else
  12932                    aler t("No VIA  Login comp leted for  pat side") ;
  12933           }
  12934       }
  12935       else {
  12936           va r facility  = MCS.VIA Login.GetF acilityNum ber(side);
  12937           va r message  = MCS.VIAL ogin.Setup ViaMessage (facility,  token);
  12938           va r duz = MC S.VIALogin .CallBahLo gin(messag e);
  12939           if  (duz != " ") {
  12940                Xrm.Page .getAttrib ute("cvt_"  + side +  "userduz") .setValue( duz);
  12941                MCS.VIAL ogin.Trigg erGetConsu lts();
  12942           }
  12943           el se
  12944                alert("N o VIA Logi n complete d for " +  side + "si de");
  12945       }
  12946   };
  12947  
  12948   MCS.VIALog in.Trigger GetConsult s = functi on () {
  12949       var ty pecode = X rm.Page.co ntext.getQ ueryString Parameters ().etc;
  12950       if (ty pecode ==  4214)
  12951           Xr m.Page.get Attribute( "cvt_runge tconsults" ).fireOnCh ange();
  12952   };
  12953  
  12954   //Helper m ethod tp P repare the  VIA Login  Message
  12955   MCS.VIALog in.SetupVi aMessage =  function  (facilityN umber, tok en) {
  12956       var vi aMessage =  {};
  12957       viaMes sage.Acces sCode = "d onotuse";
  12958       viaMes sage.Verif yCode = "d onotuse";
  12959       viaMes sage.SiteI d = facili tyNumber;
  12960       viaMes sage.SamlT oken = tok en;
  12961       return  viaMessag e;
  12962   };
  12963  
  12964   //Helper m ethod call ed by VIA  Login whic h performs  the ajax  call and r eturns the  resulting  Duz (if e xists)
  12965   MCS.VIALog in.CallBah Login = fu nction (me ssage, url ) {
  12966       var du z = "";
  12967       $.ajax ({
  12968           as ync: false ,
  12969           ty pe: 'POST' ,
  12970           ur l: url,
  12971           be foreSend:  function ( request) {
  12972                request. setRequest Header("CR MSSOiSessi onSaml", w indow.btoa (message.S amlToken))
  12973           },
  12974           da taType: 'j son',
  12975           co ntentType:  'applicat ion/json',
  12976           da ta: JSON.s tringify(m essage),
  12977           su ccess: fun ction (dat a, textSta tus, jqXHR ) {
  12978                if (data  == null | | data.Dat a == null  || data.Da ta[0] == n ull || dat a.Data[0]. Duz == nul l) {
  12979                    if ( data == nu ll)
  12980                         alert("No  data retur ned");
  12981                    else  if (data. Data == nu ll || data .Data[0] = = null)
  12982                         alert("Emp ty Data" +  data.Erro rMessage);
  12983                    else  if (data. Data[0].Fa ult != nul l)
  12984                         alert("Fai led to log in: " + da ta.Data[0] .Fault.Mes sage)
  12985                }
  12986                else {
  12987                    if ( data.Data[ 0].Duz !=  null)
  12988                         duz = data .Data[0].D uz;
  12989                }
  12990  
  12991           },
  12992           er ror: funct ion (jqXHR , textStat us, errorT hrown) {
  12993                alert(te xtStatus +  ".  Error : " + erro rThrown);
  12994                return " ";
  12995           }
  12996       });
  12997       return  duz;
  12998   };
  12999  
  13000   ////////// ////////// /EC ViaLog in
  13001   //main met hod to log  into VIA  using VIMT  EC (throu gh Actions /CWF/LOB)
  13002   MCS.VIALog in.ViaLogi nVimt = fu nction (si de, access , verify)  {
  13003       var sa mlToken =  Xrm.Page.g etAttribut e("cvt_sam ltoken").g etValue();
  13004       if (si de == "bot h") {
  13005           va r patStati onNumber =  MCS.VIALo gin.GetFac ilityNumbe r("pat");
  13006           va r proStati onNumber =  MCS.VIALo gin.GetFac ilityNumbe r("pro");
  13007           if  (patStati onNumber ! = proStati onNumber)  {
  13008                MCS.VIAL ogin.Login WithAction (samlToken , patStati onNumber,  "pat", acc ess, verif y);
  13009                MCS.VIAL ogin.Login WithAction (samlToken , proStati onNumber,  "pro", acc ess, verif y);
  13010           }
  13011           el se {
  13012                MCS.VIAL ogin.Login WithAction (samlToken , proStati onNumber,  side, acce ss, verify );
  13013           }
  13014       }
  13015       else {
  13016           va r stationN umber = MC S.VIALogin .GetFacili tyNumber(s ide);
  13017           MC S.VIALogin .LoginWith Action(sam lToken, st ationNumbe r, side, a ccess, ver ify);
  13018       }
  13019   };
  13020  
  13021   //Calls th e action a nd sets th e resultin g DUZ onto  the page  or else ca lls the Lo gin throug h Access-V erify code s
  13022   MCS.VIALog in.LoginWi thAction =  function  (samlToken , stationN umber, sid e, access,  verify) {
  13023       var re questName  = "cvt_Via LoginActio n";
  13024  
  13025       var re questParam s =
  13026           [{
  13027                Key: "St ationNumbe r",
  13028                Type: MC S.Scripts. Process.Da taType.Str ing,
  13029                Value: s tationNumb er
  13030           },
  13031           {
  13032                Key: "Sa mlToken",
  13033                Type: MC S.Scripts. Process.Da taType.Str ing,
  13034                Value: s amlToken
  13035           },
  13036           {
  13037                Key: "Ac cessCode",
  13038                Type: MC S.Scripts. Process.Da taType.Str ing,
  13039                Value: t ypeof(acce ss) === "u ndefined"  ? "" : acc ess
  13040           },
  13041           {
  13042                Key: "Ve rifyCode",
  13043                Type: MC S.Scripts. Process.Da taType.Str ing,
  13044                Value: t ypeof(veri fy) === "u ndefined"  ? "" : ver ify
  13045           }] ;
  13046  
  13047       MCS.Sc ripts.Proc ess.Execut eAction(re questName,  requestPa rams)
  13048           .d one(functi on (respon se) {
  13049                // Succe ss
  13050                var user Duz = resp onse.UserD uz;
  13051                var succ ess = resp onse.Succe ssfulLogin ;
  13052                var erro rMessage =  response. ErrorMessa ge;
  13053                //alert( "Duz: " +  userDuz +  "\nError:  " + errorM essage);
  13054  
  13055                if (succ ess) {
  13056                    if ( side == "b oth") {
  13057                         Xrm.Page.g etAttribut e("cvt_pro userduz"). setValue(u serDuz);
  13058                         Xrm.Page.g etAttribut e("cvt_pat userduz"). setValue(u serDuz);
  13059                    }
  13060                    else
  13061                         Xrm.Page.g etAttribut e("cvt_" +  side + "u serduz").s etValue(us erDuz);
  13062                    //if  (MCS.VIAL ogin.Getti ngNewUserD uz)
  13063                    //// {
  13064                    //     MCS.VIAL ogin.Getti ngNewUserD uz = false ;
  13065                    //     //SaveSA ();
  13066                    //// }
  13067                    //el se
  13068                         MCS.VIALog in.Trigger GetConsult s();
  13069                }
  13070                else {
  13071                    var  useAVCodes  = confirm ("Failed t o log in w ith PIV, a ttempting  Access Ver ify Codes  for " + si de + " sid e.  Error  Details: "  + errorMe ssage);
  13072                    if ( useAVCodes )
  13073                         MCS.VIALog in.LoginWi thAccessVe rify(side,  samlToken , stationN umber);
  13074                    //el se {
  13075                    //     if (MCS. VIALogin.G ettingNewU serDuz) {
  13076                    //         MCS. VIALogin.G ettingNewU serDuz = f alse;
  13077                    //         aler t("Canceli ng Save");
  13078                    //     }
  13079                    //}
  13080                }
  13081           })
  13082           .f ail(functi on (err) {
  13083                alert("L ogin Actio n Failed:  " + err.re sponseText );
  13084                //if (MC S.VIALogin .GettingNe wUserDuz)
  13085                //    MC S.VIALogin .GettingNe wUserDuz =  false;
  13086           }) ;
  13087   };
  13088  
  13089   //Helper t o re-call  LoginVIMT  using acce ssVerify e ntered by  user promp t - user c an leave b lank or hi t cancel t o end loop
  13090   MCS.VIALog in.LoginWi thAccessVe rify = fun ction (sid e, samlTok en, statio nNumber) {
  13091       //var  cancelLogi n = false;
  13092       var fa cilityStri ng = side  == "both"  ? "the" :  "the " + s ide;
  13093       var ac cessCode =  prompt("P lease ente r your acc ess code f or " + fac ilityStrin g + " faci lity (" +  stationNum ber + ")." , "");
  13094       var ve rifyCode;
  13095       if (ac cessCode ! = null &&  accessCode  != "") {
  13096           ve rifyCode =  prompt("P lease ente r your ver ify code f or " + fac ilityStrin g + " faci lity (" +  stationNum ber + ")." , "");
  13097           if  (verifyCo de != null  && verify Code != "" )
  13098                MCS.VIAL ogin.Login WithAction (samlToken , stationN umber, sid e, accessC ode, verif yCode);
  13099           // else
  13100           //     cancel Login = tr ue;
  13101       }
  13102       //else
  13103       //     cancelLogi n = true;
  13104       //if ( cancelLogi n)
  13105       //     MCS.VIALog in.Getting NewUserDuz  = true;
  13106   };
  13107  
  13108   // ******* ********** *******Hel per method s to retri eve Integr ation Sett ings (URLS ) ******** ********** ********** *********
  13109   //Helper M ethod to g et SAML To ken URL
  13110   MCS.VIALog in.GetStsU rl = funct ion () {
  13111       var de faultUrl =  "";// "ht tps://dev. services.e auth.va.go v:9301/STS /RequestSe curityToke n";
  13112       var ur l = MCS.VI ALogin.Get Setting("I AM SAML To ken Endpoi nt");
  13113       return  url != ""  ? url : d efaultUrl;
  13114   };
  13115  
  13116   //Helper m ethod to g et the Kee p Alive Lo gin Page
  13117   MCS.VIALog in.GetKeep AliveLogin Url = func tion () {
  13118       var de faultUrl =  "";//"htt ps://qacrm dac.np.crm .vrm.vba.v a.gov/CRMS SOi/qa/def ault.aspx" ;
  13119       var ur l = MCS.VI ALogin.Get Setting("K eep Alive  Login Endp oint");
  13120       return  url != ""  ? url : d efaultUrl;
  13121   };
  13122  
  13123   //Helper M ethod to g et the url  to refres h your tok en (assumi ng you hav e already  called the  login pag e)
  13124   MCS.VIALog in.GetKeep AliveUrl =  function  () {
  13125       var de faultUrl =  "";// "ht tps://qacr mdac.np.cr m.vrm.vba. va.gov/CRM SSOi/qa/re freshtoken session.as px";
  13126       var ur l = MCS.VI ALogin.Get Setting("R efresh SAM L Token En dpoint");
  13127       return  url != ""  ? url : d efaultUrl;
  13128   };
  13129  
  13130   //Helper M ethod to g et BAH VIA  Login iHu b Endpoint  URL
  13131   MCS.VIALog in.ViaLogi nUrl = fun ction () {
  13132       var ur l = MCS.VI ALogin.Get Setting("V IA Login E ndpoint");
  13133       var de faultUrl =  "";//"htt ps://qacrm dac.np.crm .vrm.vba.v a.gov/WebP arts/DEV/a pi/VIA/Log inVIA/2.1/ json";
  13134       return  url != ""  ? url : d efaultUrl;
  13135   };
  13136  
  13137   //Helper m ethod to g et any int egration s etting wit h the pass ed in name
  13138   MCS.VIALog in.GetSett ing = func tion (name ) {
  13139       var va lue = "";
  13140       var fi lter = "mc s_name eq  '" + name  + "'";
  13141       calls  = CrmRestK it.ByQuery ("mcs_inte grationset ting", ['m cs_value'] , filter,  false);
  13142       calls. fail(funct ion (err)  {
  13143           re turn value ;
  13144       }).don e(function  (data) {
  13145           if  (data &&  data.d &&  data.d.res ults != nu ll && data .d.results .length !=  0) {
  13146                value =  data.d.res ults[0].mc s_value
  13147           }
  13148           }) ;
  13149       return  value;
  13150   };
  13151  
  13152   //Helper m ethod to g et the TSA  id whethe r the curr ent record  is an app t or a blo ck resourc e
  13153   MCS.VIALog in.GetTsaI d = functi on () {
  13154       var ts aObj = Xrm .Page.getA ttribute(" mcs_relate dtsa");
  13155       if (ts aObj != nu ll)
  13156           re turn tsaOb j.getValue ()[0].id;
  13157       var ts aId;
  13158       var sa  = Xrm.Pag e.getAttri bute("cvt_ serviceact ivityid"). getValue() [0].id;
  13159       CrmRes tKit.Retri eve('Servi ceAppointm ent', sa,  ['mcs_rela tedtsa'],  false)
  13160           .f ail(functi on (err) {
  13161                alert("f ailed TSA  check, Una ble to per form VIA l ogin: " +  MCS.cvt_Co mmon.RestE rror(err)) ;
  13162           })
  13163           .d one(functi on (data)  {
  13164                if (data  != null & & data.d ! = null) {
  13165                    tsaI d = data.d .mcs_relat edtsa.Id;
  13166                }
  13167           }) ;
  13168       return  tsaId;
  13169   };
  13170  
  13171   //Helper m ethod to g et the sta tion numbe r of the f acility
  13172   MCS.VIALog in.GetFaci lityNumber  = functio n (side) {
  13173       var ts aId = MCS. VIALogin.G etTsaId();
  13174       var pa tFacId = n ull;
  13175       var pr oFacId = n ull;
  13176       var is InterFacil ity = fals e;
  13177       CrmRes tKit.Retri eve('mcs_s ervices',  tsaId, ['c vt_Patient Facility',  'cvt_Prov iderFacili ty', 'cvt_ ServiceSco pe'], fals e)
  13178           .f ail(functi on (err) {
  13179                alert("f ailed TSA  check, Una ble to per form VIA l ogin: " +  MCS.cvt_Co mmon.RestE rror(err)) ;
  13180           })
  13181           .d one(functi on (data)  {
  13182                if (data  != null & & data.d ! = null) {
  13183                    if ( data.d.cvt _PatientFa cility !=  null)
  13184                         patFacId =  data.d.cv t_PatientF acility.Id ;
  13185                    if ( data.d.cvt _ProviderF acility !=  null)
  13186                         proFacId =  data.d.cv t_Provider Facility.I d;
  13187                    if ( data.d.cvt _ServiceSc ope != nul l)
  13188                         isInterFac ility = da ta.d.cvt_S erviceScop e.Value ==  917290000 ;
  13189                }
  13190           }) ;
  13191       var id  = side ==  "pat" ? p atFacId :  proFacId;
  13192       var fa cilityNumb er;
  13193       CrmRes tKit.Retri eve('mcs_f acility',  id, ['mcs_ StationNum ber'], fal se)
  13194           .f ail(functi on (err) {
  13195                alert("F ailed to g et TSA, Un able to Pe rform VIA  Login: " +  MCS.cvt_C ommon.Rest Error(err) );
  13196           }) .done(func tion (data ) {
  13197                if (data  != null & & data.d ! = null)
  13198                    faci lityNumber  = data.d. mcs_Statio nNumber;
  13199                else
  13200                    aler t("Failed  to get TSA  station n umber, Una ble to Per form VIA L ogin");
  13201           }) ;
  13202       return  facilityN umber;
  13203   };
  13204  
  13205   MCS.VIALog in.CheckVi staSwitche s = functi on () {
  13206       var Vi staSwitche sConfig =  true;
  13207       var ba seSwitchCo nfig = tru e;
  13208       var hm Config = t rue;
  13209       var if cConfig =  true;
  13210       var si ngleNonHmC onfig = tr ue;
  13211       var fi lter = "mc s_name eq  'Active Se ttings'";
  13212       calls  = CrmRestK it.ByQuery ("mcs_sett ing", ['cv t_UseVista Integratio n', 'cvt_U seVVSHomeM obile', 'c vt_UseVVSI nterfacili ty', 'cvt_ UseVVSSing leEncounte rNonHomeMo bile'], fi lter, fals e);
  13213       calls. fail(funct ion (err)  {
  13214           re turn Vista SwitchesCo nfig;
  13215       }).don e(function  (data) {
  13216           if  (data &&  data.d &&  data.d.res ults != nu ll && data .d.results .length !=  0) {
  13217                var reco rd = data. d.results[ 0];
  13218                baseSwit chConfig =  record.cv t_UseVista Integratio n != null  ? record.c vt_UseVist aIntegrati on : true;
  13219                hmConfig  = record. cvt_UseVVS HomeMobile  != null ?  record.cv t_UseVVSHo meMobile :  true;
  13220                ifcConfi g = record .cvt_UseVV SInterfaci lity != nu ll ? recor d.cvt_UseV VSInterfac ility : tr ue;
  13221                singleNo nHmConfig  = record.c vt_UseVVSS ingleEncou nterNonHom eMobile !=  null ? re cord.cvt_U seVVSSingl eEncounter NonHomeMob ile : true ;
  13222           }
  13223       });
  13224       //Note  that this  is a trip le equal,  not a doub le, so a n ull value  is conside red accept able to co ntinue, on ly a false  will mean  "don't sh ow Get Con sults"
  13225       if (ba seSwitchCo nfig === f alse)
  13226           re turn false ;
  13227       var ap ptTypeChec k = MCS.VI ALogin.App ointmentTy peSwitchCh eck(hmConf ig, ifcCon fig, singl eNonHmConf ig);
  13228       return  apptTypeC heck;
  13229   };
  13230  
  13231   MCS.VIALog in.Appoint mentTypeSw itchCheck  = function  (hmConfig , ifcConfi g, singleN onHmConfig ) {
  13232       var Xr m = parent .Xrm;
  13233       var ts aId = MCS. VIALogin.G etTsaId();
  13234       var pa tFacId = n ull;
  13235       var pr oFacId = n ull;
  13236       var su bSpecialty  = null;
  13237       var sp ecialty =  null;
  13238       var is InterFacil ity = fals e;
  13239       CrmRes tKit.Retri eve('mcs_s ervices',  tsaId, ['c vt_Patient Facility',  'cvt_Prov iderFacili ty', 'cvt_ ServiceSco pe', 'cvt_ servicetyp e', 'cvt_s ervicesubt ype', 'cvt _relatedpr ovidersite id', 'cvt_ relatedpat ientsiteid '], false)
  13240           .f ail(functi on (err) {
  13241                alert("f ailed TSA  check, def aulting to  display C onsults" +  MCS.cvt_C ommon.Rest Error(err) );
  13242           })
  13243           .d one(functi on (data)  {
  13244                if (data  != null & & data.d ! = null) {
  13245                    if ( data.d.cvt _PatientFa cility !=  null)
  13246                         patFacId =  data.d.cv t_PatientF acility.Id ;
  13247                    if ( data.d.cvt _ProviderF acility !=  null)
  13248                         proFacId =  data.d.cv t_Provider Facility.I d;
  13249                    if ( data.d.cvt _ServiceSc ope != nul l)
  13250                         isInterFac ility = da ta.d.cvt_S erviceScop e.Value ==  917290000 ;
  13251                    if ( data.d.cvt _servicety pe != null )
  13252                         specialty  = data.d.c vt_service type.Id;
  13253                    if ( data.d.cvt _servicesu btype != n ull)
  13254                         subSpecial ty = data. d.cvt_serv icesubtype .Id;
  13255                    if ( data.d.cvt _relatedpr ovidersite id != null )
  13256                         TsaProvide rSiteId =  data.d.cvt _relatedpr ovidersite id.Id; //T his is key  to run ea ch time TS A is set b ecause the  Provider  Site does  not come t hrough unt il after T SA js has  run, but t his functi on runs be fore TSA j s is compl ete, so pu lling in T SAProvider SiteId wil l set prov iderSiteId  when its  not otherw ise popula ted
  13257                    if ( data.d.cvt _relatedpr ovidersite id != null )
  13258                         TsaPatient SiteId = d ata.d.cvt_ relatedpat ientsiteid .Id;
  13259                }
  13260           }) ;
  13261  
  13262       var ts aObj = Xrm .Page.getA ttribute(" mcs_relate dtsa");
  13263       if (ts aObj != nu ll) {
  13264  
  13265           va r isHomeMo bile = Xrm .Page.getA ttribute(" cvt_type") .getValue( );
  13266           if  (isHomeMo bile)
  13267                return h mConfig;
  13268           va r isSingle NonHm = Xr m.Page.get Attribute( "cvt_teleh ealthmodal ity").getV alue();
  13269           if  (isSingle NonHm)
  13270                return s ingleNonHm Config;
  13271       }
  13272  
  13273       var su bSpecialty Switch = n ull;
  13274       if (su bSpecialty  != null)  {
  13275           // Check SubS pecialty S witch
  13276           Cr mRestKit.R etrieve('m cs_service subtype',  subSpecial ty, ['cvt_ UseVVS'],  false)
  13277                .fail(fu nction (er r) {
  13278                    aler t("failed  sub-specia lty type c heck, look ing for sp ecialty sw itch: " +  MCS.cvt_Co mmon.RestE rror(err)) ;
  13279                }).done( function ( data) {
  13280                    subS pecialtySw itch = dat a.d.cvt_Us eVVS;
  13281                });
  13282       }
  13283       //vari ous "==="  is so that  if the va lue is nul l, then we  evaluate  the next c ondition i nstead of  considerin g it false
  13284       if (su bSpecialty Switch ===  false)
  13285           re turn false ;
  13286       var sp ecialtySwi tch = true ;
  13287       if (su bSpecialty Switch ==  null) {
  13288           Cr mRestKit.R etrieve('m cs_service type', spe cialty, [' cvt_UseVVS '], false)
  13289                .fail(fu nction (er r) {
  13290                    aler t("failed  specialty  type check , defaulti ng to disp lay Consul ts" + MCS. cvt_Common .RestError (err));
  13291                })
  13292                .done(fu nction (da ta) {
  13293                    spec ialtySwitc h = data.d .cvt_UseVV S;
  13294                });
  13295       }
  13296       if (sp ecialtySwi tch === fa lse)
  13297           re turn false ;
  13298  
  13299       if (is InterFacil ity)
  13300           re turn ifcCo nfig;
  13301  
  13302       var fa cilitySwit ch = true;
  13303  
  13304       if (pa tFacId !=  null && pr oFacId !=  null && pa tFacId ==  proFacId)  {
  13305           Cr mRestKit.R etrieve('m cs_facilit y', patFac Id, ['cvt_ UseVistaIn trafacilit y'], false )
  13306                .fail(fu nction (er r) {
  13307                    aler t("failed  Intrafacil ity check,  defaultin g to displ ay Consult s" + MCS.c vt_Common. RestError( err));
  13308                })
  13309                .done(fu nction (da ta) {
  13310                    if ( data != nu ll && data .d != null )
  13311                         facilitySw itch = dat a.d.cvt_Us eVistaIntr afacility  != null ?  data.d.cvt _UseVistaI ntrafacili ty : true;
  13312                });
  13313       }
  13314       return  facilityS witch ===  false ? fa lse : true ;
  13315   };