diff --git a/lib/Value/Matrix.pm b/lib/Value/Matrix.pm index 130067fa3d..f28cbefb4e 100644 --- a/lib/Value/Matrix.pm +++ b/lib/Value/Matrix.pm @@ -186,7 +186,7 @@ sub numberMatrix { #internal my @M = (); my $isFormula = 0; foreach my $x (@_) { $x = Value::makeValue($x,context=>$context); - Value::Error("Matrix row entries must be numbers") unless _isNumber($x); + Value::Error("Matrix row entries must be numbers: $x ") unless _isNumber($x); push(@M,$x); $isFormula = 1 if Value::isFormula($x); } return $self->formula([@M]) if $isFormula; @@ -249,7 +249,7 @@ sub isRow { } # -# See if the matrix is an Indenity matrix +# See if the matrix is an Identity matrix # sub isOne { my $self = shift; diff --git a/lib/VectorField.pm b/lib/VectorField.pm index c49c4ae756..d761da4b74 100644 --- a/lib/VectorField.pm +++ b/lib/VectorField.pm @@ -8,11 +8,11 @@ use Carp; use GD; use WWPlot; - use Fun; - $fn = new Fun( rule_reference); - $fn = new Fun( rule_reference , graph_reference); - $fn = new Fun ( x_rule_ref, y_rule_ref ); - $fn = new Fun ( x_rule_ref, y_rule_ref, graph_ref ); + use VectorField; + $vf = new VectorField( dy_rule_ref); + $vf = new VectorField( dy_rule_ref , graph_reference); + $vf = new VectorField( x_rule_ref, y_rule_ref ); + $vf = new VectorField( x_rule_ref, y_rule_ref, graph_ref ); =head1 DESCRIPTION @@ -25,19 +25,14 @@ The following functions are provided: =over 4 -=item $fn = new VectorField( dy_rule_ref); +=item $vf = new VectorField( dy_rule_ref); rule_reference is a reference to a subroutine which accepts a pair of numerical values and returns a numerical value. -The Fun object will draw the direction field associated with this subroutine. - -The new method returns a reference to the vector field object. - -=item $fn = new Fun( rule_reference , graph_reference); - The vector field is also placed into the printing queue of the graph object pointed to by graph_reference and the domain of the vector field object is set to the domain of the graph. +The graph_ref must come last. =back @@ -45,22 +40,22 @@ domain of the vector field object is set to the domain of the graph. =over 4 -=item $fn = new VectorField ( dx_rule_ref, dy_rule_ref ); +=item $vf = new VectorField ( dx_rule_ref, dy_rule_ref ); A vector field object is created where the subroutines refered to by dx_rule_ref and dy_rule_ref define the x and y components of the vector field at (x,y). Both subroutines must be functions of two variables. -=item $fn = new VectorField ( x_rule_ref, y_rule_ref, graph_ref ); +=item $vf = new VectorField ( x_rule_ref, y_rule_ref, graph_ref ); This variant inserts the vector field object into the graph object referred to by graph_ref. The domain -of the vector field object is set to the domain of the graph. +of the vector field object is set to the domain of the graph. The graph_ref must come last. =back =head2 Properites - All of the properties are set using the construction $new_value = $fn->property($new_value) - and read using $current_value = $fn->property() + All of the properties are set using the construction $new_value = $vf->property($new_value) + and read using $current_value = $vf->property() =over 4 @@ -105,12 +100,12 @@ The width in pixels of the pen used to draw the arrow (respectively the dot). =item domain -$array_ref = $fn->domain(-1,-2,1,2) sets xmin to -1, ymin to -2, xmax to 1, and ymax to 2. +$array_ref = $vf->domain(-1,-2,1,2) sets xmin to -1, ymin to -2, xmax to 1, and ymax to 2. =item draw -$fn->draw($graph_ref) draws the vector field in the graph object pointed to by $graph_ref. +$vf->draw($graph_ref) draws the vector field in the graph object pointed to by $graph_ref. The graph object must respond to the methods below. The draw call is mainly for internal diff --git a/lib/WeBWorK/PG/IO.pm b/lib/WeBWorK/PG/IO.pm index 0990606be6..ad0fa29f4b 100644 --- a/lib/WeBWorK/PG/IO.pm +++ b/lib/WeBWorK/PG/IO.pm @@ -33,7 +33,7 @@ BEGIN { directoryFromPath createFile createDirectory - path_is_course_subdir + path_is_course_subdir ); our @SHARED_FUNCTIONS = qw( @@ -260,8 +260,12 @@ sub path_is_course_subdir { # sub query_sage_server { my ($python, $url, $accepted_tos, $setSeed, $webworkfunc, $debug, $curlCommand)=@_; - my $sagecall = qq{$curlCommand -i -k -sS -L --data-urlencode "accepted_tos=${accepted_tos}"}. +# my $sagecall = qq{$curlCommand -i -k -sS -L --http1.1 --data-urlencode "accepted_tos=${accepted_tos}"}. +# qq{ --data-urlencode 'user_expressions={"WEBWORK":"_webwork_safe_json(WEBWORK)"}' --data-urlencode "code=${setSeed}${webworkfunc}$python" $url}; + my $sagecall = qq{$curlCommand -i -k -sS -L --data-urlencode "accepted_tos=${accepted_tos}"}. qq{ --data-urlencode 'user_expressions={"WEBWORK":"_webwork_safe_json(WEBWORK)"}' --data-urlencode "code=${setSeed}${webworkfunc}$python" $url}; + + my $output =`$sagecall`; if ($debug) { warn "debug is turned on in IO.pm. "; @@ -279,13 +283,44 @@ sub query_sage_server { # Access-Control-Allow-Origin: * # Content-Type: application/json; charset=UTF-8 # $content: Either error message about terms of service or output from sage - my ($continue, $header, @content) = split("\r\n\r\n",$output); - my $content = join("\r\n\r\n",@content); # handle case where there were blank lines in the content - # warn "output list is ", join("|||\n|||",($continue, $header, @content)); - # warn "header is $header =" , $header =~/200 OK\r\n/; + # find the header + # expecting something like + # HTTP/1.1 100 Continue + + # HTTP/1.1 200 OK + # Date: Wed, 20 Sep 2017 14:54:03 GMT + # ...... + # two blank lines + # content + + # or (notice that here there is no continue response) + # HTTP/2 200 + # date: Wed, 20 Sep 2017 16:06:03 GMT + # ...... + # two blank lines + # content + + my ($continue, $header, @content) = split("\r\n\r\n",$output); + #my $content = join("\r\n\r\n",@content); # handle case where there were blank lines in the content + my @lines = split("\r\n\r\n", $output); + $continue=0; + my $header_ok =0; + while (@lines) { + my $header_block = shift(@lines); + warn "checking for header: $header_block" if $debug; + next unless $header_block=~/\S/; #skip empty lines; + next if $header_block=~/HTTP/ and $header_block=~/100/; # skip continue line + if ($header_block=~/200/) { # 200 return is ok + $header_ok=1; + last; + } + } + my $content = join("|||\n|||",@lines) ; #headers have been removed. + #warn "output list is ", $content; # join("|||\n|||",($continue, $header, $content)); + #warn "header_ok is $header_ok"; my $result; - if ($header =~/200 OK\r\n/) { #success - $result = $content; + if ($header_ok) { #success put any extraneous splits back together + $result = join("\r\n\r\n",@lines); } else { warn "ERROR in contacting sage server. Did you accept the terms of service by setting {accepted_tos=>'true'} in the askSage options?\n $content\n"; @@ -343,7 +378,9 @@ END # has something been returned? not_null($output) or die "Unable to make a sage call to $url."; warn "IO::askSage: We have some kind of value |$output| returned from sage" if $output and $debug; - + if ($output =~ /"success":\s*true/ and $debug){ + warn '"success": true is present in the output'; + } my $decoded = decode_json($output); not_null($decoded) or die "Unable to decode sage output"; if ($debug and defined $decoded ) { @@ -351,16 +388,19 @@ END foreach my $key (keys %$decoded) {$warning_string .= "$key=".$decoded->{$key}.", ";} $warning_string .= ' end decoded contents'; #warn "\n$warning_string" if $debug; - warn " decoded contents \n", PGUtil::pretty_print($decoded, 'text'), "end decoded contents"; + warn " decoded contents \n", PGUtil::pretty_print($decoded, 'text'), "end decoded contents" if $debug; } # was there a Sage/python syntax Error # is the returned something text from stdout (deprecated) # have objects been returned in a WEBWORK variable? - my $success = $decoded->{success} if defined $decoded; + my $success = 0; + $success = $decoded->{success} if defined $decoded and $decoded->{success}; warn "success is $success" if $debug; # the decoding process seems to change the string "true" to "1" sometimes -- we could enforce this $success = 1 if defined $success and $success eq 'true'; - if ($decoded->{success}==1) { + $success = 1 if $decoded->{execute_reply}->{status} eq 'ok'; + warn "now success is $success because status was ok" if $debug; + if ($success) { my $WEBWORK_variable_non_empty=0; my $sage_WEBWORK_data = $decoded->{execute_reply}{user_expressions}{WEBWORK}{data}{'text/plain'}; warn "sage_WEBWORK_data $sage_WEBWORK_data" if $debug; @@ -387,7 +427,7 @@ END } else { die "Error receiving JSON output from sage: \n$output\n "; } - } elsif ($decoded->{success} == 0 ) { # this might be a syntax error + } elsif ($success == 0 ) { # this might be a syntax error $ret->{error_message} = $decoded->{execute_reply}; # this is a hash. # need a better pretty print method warn ( "IO.pm: Perhaps there was syntax error.", join(" ",%{ $decoded->{execute_reply}})); } else { diff --git a/lib/WeBWorK/PG/Translator.pm b/lib/WeBWorK/PG/Translator.pm index 1779bdc20c..33f99e1221 100644 --- a/lib/WeBWorK/PG/Translator.pm +++ b/lib/WeBWorK/PG/Translator.pm @@ -1334,7 +1334,7 @@ sub process_answers{ if defined($new_rh_ans_evaluation_result) && ref($new_rh_ans_evaluation_result) && defined($new_rh_ans_evaluation_result->error_flag()); } else { - $PG->warning_message(" The evaluated answer is not an answer hash $new_rh_ans_evaluation_result: |".ref($new_rh_ans_evaluation_result)."|."); + $PG->warning_message(" The evaluated answer is not an answer hash ".($new_rh_ans_evaluation_result//'').': |'.ref($new_rh_ans_evaluation_result)."|."); } # $PG->debug_message( $self->{envir}->{'probFileName'} ." new_temp_ans and temp_ans don't agree: ". # ref($new_temp_ans)." $new_temp_ans ". ref($temp_ans). " $temp_ans".length($new_temp_ans).length($temp_ans)) diff --git a/macros/LinearProgramming.pl b/macros/LinearProgramming.pl index d2e2fa2c38..fbe81409b2 100644 --- a/macros/LinearProgramming.pl +++ b/macros/LinearProgramming.pl @@ -290,7 +290,7 @@ sub lp_current_value { if (defined &Fraction) { return Fraction(0); # MathObjects version } else { - return new Fraction(0); # old style Function module version + return Fraction->new(0); # old style Function module version } } else { return 0; diff --git a/macros/LiveGraphics3D.pl b/macros/LiveGraphics3D.pl index 442bef806d..942fd26da4 100644 --- a/macros/LiveGraphics3D.pl +++ b/macros/LiveGraphics3D.pl @@ -87,7 +87,7 @@ sub LiveGraphics3D { size => [250,250], jar => "live.jar", # "${htmlURL}live.jar", codebase => findAppletCodebase("live.jar"), - # codebase => "http://hosted2.webwork.rochester.edu/webwork2_files/applets/", # used for testing + # codebase => "http://demo.webwork.rochester.edu/webwork2_files/applets/", # used for testing background => "#FFFFFF", scale => 1., tex_size => 500, diff --git a/macros/PGmatrixmacros.pl b/macros/PGmatrixmacros.pl index 7982aa7eaa..bf49b7d985 100644 --- a/macros/PGmatrixmacros.pl +++ b/macros/PGmatrixmacros.pl @@ -178,16 +178,18 @@ sub display_matrix { # column labels for linear programming $out .= dm_special_tops(%opts, 'alignList'=>$alignList) if ($opts{'top_labels'}); $out .= dm_mat_left($numRows, %opts); - my $cnt = 1; # we count rows in in case an element is boxed + my $cnt = 1; # we count rows in in case an element is boxed # vertical lines put in with first row $j = shift @myRows; - $out .= dm_mat_row($j, $alignList, %opts, 'isfirst'=>$numRows, - 'cnt' => $cnt); - $cnt++ unless ($j eq 'hline'); + my $tag = $opts{side_labels}->[$cnt-1]; + $out .= dm_mat_row($j, $alignList, %opts, 'isfirst'=>$numRows, + 'cnt' => $cnt, 'tag'=>$tag); + $cnt++ unless ($j eq 'hline'); $out .= dm_mat_right($numRows, %opts); for $j (@myRows) { + $tag = $opts{side_labels}->[$cnt-1]; $out .= dm_mat_row($j, $alignList, %opts, 'isfirst'=>0, - 'cnt' => $cnt); + 'cnt' => $cnt,'tag'=>$tag); $cnt++ unless ($j eq 'hline'); } $out .= dm_end_matrix(%opts); @@ -488,7 +490,11 @@ sub dm_mat_row { $out .= '}' if ($colcount == $opts{'box'}->[1] and $opts{'cnt'} == $opts{'box'}->[0]); $out .= " &"; } - chop($out); # remove last & + if ($opts{tag}) { + $out.= $opts{tag}; + } else { + chop($out); # remove last & + } $out .= "\\cr \n"; # carriage returns must be added manually for tex } elsif ( $main::displayMode eq 'HTML_MathJax' @@ -762,7 +768,7 @@ =head2 convert_to_array_ref { sub convert_to_array_ref { my $input = shift; - if (Value::isParser($input) and Value::classMatch($input,"Matrix")) { + if (Value::classMatch($input,"Matrix")) { $input = [$input->value]; } elsif (ref($input) eq 'Matrix' ) { $input = $input->array_ref; diff --git a/macros/contextCongruence.pl b/macros/contextCongruence.pl new file mode 100644 index 0000000000..cc7a8489dd --- /dev/null +++ b/macros/contextCongruence.pl @@ -0,0 +1,302 @@ +################################################################################ +# WeBWorK Online Homework Delivery System +# Copyright © 2000-2017 The WeBWorK Project, http://openwebwork.sf.net/ +# $CVSHeader:$ +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of either: (a) the GNU General Public License as published by the +# Free Software Foundation; either version 2, or (at your option) any later +# version, or (b) the "Artistic License" which comes with this package. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the +# Artistic License for more details. +################################################################################ + + +=head1 NAME + + +C - Provides contexts that allow the +entry of congruence solutions + +=head1 DESCRIPTION + +These contexts allow you to enter congruence solutions. +Either the general solution or all possible solutions can be accepted +based on settings. + +There are three contexts included here: C, which +allows both types of solutions, C, which +requires the general solution, and C, which +requires all solutions to be entered. + +Congruences must be created with three paramters (a, b, m) from ax ≡ b (mod m). + +=head1 USAGE + + + loadMacros("contextCongruence.pl"); + + Context("Congruence"); + + ax ≡ b (mod m) + can initialize with Congruence(a, b, m); + + #ex: 15x ≡ 10 (mod 25) + $C1 = Congruence(15, 10, 25); + $general_answer = Compute("4+5k"); + $all_answers = Compute("4+25k,9+25k,14+25k,19+25k,24+25k"); + $all_answers_diff_order = Compute("9+25k,4+25k,14+25k,19+25k,24+25k"); + + $C1->compare($general_answer); # is true + $C1->compare($all_answers); # is true + $C1->compare($all_answers_diff_order); # is true + + Can an force general solution only with + + Context()->flags->set(requireGeneralSolution => 1); + $C1->compare($general_answer); # is true + $C1->compare($all_answers); # is false + + + Can an force all solutions only with + + Context()->flags->set(requireAllSolutions => 1); + $C1->compare($general_answer); # is false + $C1->compare($all_answers); # is true + + Students can enter 'none' when there is no solution + #ex: 15x ≡ 10 (mod 24) + $C2 = Congruence(15, 10, 24); + $none = Compute("None"); + $n = Compute("n"); + + $C2->compare($none); # is true + $C2->compare($n); # is true + $C1->compare($none); # is false + +=cut + +loadMacros('MathObjects.pl', 'contextInteger.pl'); + +sub _contextCongruence_init {context::Congruence::Init()}; + +########################################################################### + +package context::Congruence; +our @ISA = ('Value::Formula'); + +# +# Initialize the contexts and make the creator function. +# +sub Init { + my $context = $main::context{Congruence} = Parser::Context->getCopy("Numeric"); + $context->{name} = "Congruence"; + Parser::Number::NoDecimals($context); + + $context->variables->clear(); + $context->variables->add(k => 'Real'); + + $context->strings->add( + None=>{caseSensitive=>0}, + N=>{caseSensitive=>0, alias=>"None"} + ); + + $context->flags->set( + requireGeneralSolution => 0, # require general solution as answer? + requireAllSolutions => 0, # require all solution as answer? + outputAllSolutions => 0 # default display only general solution. switch to 1 to display all possible solutions + ); + + # + # Only allow general solution for answer and output + # + $context = $main::context{"Congruence-General-Solution"} = $context->copy; + $context->{name} = "Congruence-General-Solution"; + $context->flags->set( + requireGeneralSolution => 1, + requireAllSolutions => 0, + outputAllSolutions => 0 + ); + + # + # Only allow all solutions for answer and output + # + $context = $main::context{"Congruence-All-Solutions"} = $context->copy; + $context->{name} = "Congruence-All-Solutions"; + $context->flags->set( + requireGeneralSolution => 0, + requireAllSolutions => 1, + outputAllSolutions => 1 + ); + + + main::PG_restricted_eval("sub Congruence {context::Congruence->new(\@_)}"); +} + +sub new { + my $self = shift; my $class = ref($self) || $self; + my $context = (Value::isContext($_[0]) ? shift : $self->context); + + # validation is handled in _getCongruenceData + my ($g, $residue, $divisor) = context::Congruence::Function::Numeric3::_getCongruenceData(@_); + my $formula = main::Formula->new($context, "k"); + $formula->{g} = $g; + $formula->{residue} = $residue; + $formula->{divisor} = $divisor; + return bless $formula, $class; +} + +sub compare { + my ($l,$r) = @_; my $self = $l; + my $context = $self->context; + + my $generalSolution = $l->generalSolution; + my $allSolutions = $l->allSolutions; + my $requireGeneralSolution = $self->getFlag("requireGeneralSolution"); + my $requireAllSolutions = $self->getFlag("requireAllSolutions"); + + # allow unorder formula lists + if ($r->classMatch("Formula") && scalar($r->value)) { + my @orderedValues = main::PGsort(sub { + $_[0]->eval(k=>0) < $_[1]->eval(k=>0); + },$r->value); + $r = Value::Formula->new($self->context, join(",", @orderedValues)); + } + + if ($requireGeneralSolution) { + return $generalSolution->compare($r); + } elsif ($requireAllSolutions) { + return $allSolutions->compare($r); + } else { + # check both all solutons and general solution + return 0 if $allSolutions->compare($r) == 0; + return $generalSolution->compare($r); + } +} + +sub generalSolution { + my $self = shift; + + # check no solution + return $self->Package("String")->new($self->context, "None") if ($self->{g} == 0); + + return Value::Formula->new($self->context, $self->{residue} . "+" . $self->{divisor} . "k"); +} + +sub allSolutions { + my $self = shift; + + # check no solution + return $self->Package("String")->new($self->context, "None") if ($self->{g} == 0); + + @solutions = (); + my $divisor = $self->{divisor} * $self->{g}; + for my $index (0..$self->{g}-1) { + my $residue = $self->{residue} + ($index * $self->{g}); + push(@solutions, $residue . "+" . $divisor . "k"); + } + return Value::Formula->new($self->context, join(",", @solutions)); +} + +# +# Produce a string version +# +sub string { + my $self = shift; + my $outputAllSolutions = $self->getFlag("outputAllSolutions"); + + if ($outputAllSolutions) { + return $self->allSolutions->string; + } else { + return $self->generalSolution->string; + } +} + +# +# Produce a TeX version +# +sub TeX { + my $self = shift; + my $outputAllSolutions = $self->getFlag("outputAllSolutions"); + + if ($outputAllSolutions) { + return $self->allSolutions->TeX; + } else { + return $self->generalSolution->TeX; + } +} + + +sub typeMatch { + my $self = shift; my $other = shift; + return $other->classMatch("Formula", "String"); +} + +package context::Congruence::Function::Numeric3; # checks for 3 numeric inputs +our @ISA = qw(Parser::Function); + +# +# Check for two real-valued arguments +# +sub _check { + my $self = shift; + return if ($self->checkArgCount(3)); + if (($self->{params}->[0]->isNumber && $self->{params}->[1]->isNumber && + $self->{params}->[2]->isNumber && + !$self->{params}->[0]->isComplex && !$self->{params}->[1]->isComplex && + !$self->{params}->[2]->isComplex) || + $self->context->flag("allowBadFunctionInputs")) { + $self->{type} = $Value::Type{number}; + } else { + $self->Error("Function '%s' has the wrong type of inputs",$self->{name}); + } +} + +# +# Check that the inputs are OK +# +sub _call { + my $self = shift; my $name = shift; + Value::Error("Function '%s' has too many inputs",$name) if scalar(@_) > 3; + Value::Error("Function '%s' has too few inputs",$name) if scalar(@_) < 3; + Value::Error("Function '%s' has the wrong type of inputs",$name) + unless Value::matchNumber($_[0]) && Value::matchNumber($_[1]); + return $self->$name(@_); +} + +# +# Call the appropriate routine +# +sub _eval { + my $self = shift; my $name = $self->{name}; + $self->$name(@_); +} + +# +# Congruence Class +# ax ≡ b (mod m) +# +# returns gcd, residue, divisor +sub _getCongruenceData { + my $a = shift; my $b = shift; my $m = shift; + my $g = context::Integer::Function::Numeric2::gcd($a, $m); + + # check for no solutions + if ($b % $g != 0) { + return (0, 0, 0); + } + + # (a/g)x ≡ (b/g) (mod (m/g)) reduce multiple solutions + my $a2 = $a / $g; my $b2 = $b / $g; my $m2 = $m / $g; + + # x ≡ $modularInverse * b2 (mod m2) + my $modularInverse = context::Integer::Function::Numeric2::mulularInverse($a2, $m2); + $x = ($modularInverse * $b2) % $m2; + + return ($g, $x, $m2); +} + +1; diff --git a/macros/contextInteger.pl b/macros/contextInteger.pl new file mode 100644 index 0000000000..c523836bb5 --- /dev/null +++ b/macros/contextInteger.pl @@ -0,0 +1,276 @@ +################################################################################ +# WeBWorK Online Homework Delivery System +# Copyright © 2000-2017 The WeBWorK Project, http://openwebwork.sf.net/ +# $CVSHeader:$ +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of either: (a) the GNU General Public License as published by the +# Free Software Foundation; either version 2, or (at your option) any later +# version, or (b) the "Artistic License" which comes with this package. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the +# Artistic License for more details. +################################################################################ + + +=head1 NAME + +contextInteger.pl - adds integer related functions primeFactorization, phi, tau, isPrime, randomPrime, lcm, and gcd. + +=head1 DESCRIPTION + +This is a Parser context that adds integer related functions. +This forces students to only enter integers as their answers. + +=head1 USAGE + + Context("Integer") + + # generates an array of each prime factor + @a = primeFactorization(1000); + ANS(List(@a)->cmp); + + # get the gcd + $b = gcd(5, 2); + ANS($b->cmp); + + # get lcm + $c = lcm(36, 90); + ANS($c->cmp); + + # get phi + $d = phi(365); + ANS($d->cmp); + + # get tau + $e = tau(365); + ANS($e->cmp); + + # check if prime + $f = isPrime(10); #False + $h = isPrime(5); #True + + # get a random prime in a range + $randomPrime = randomPrime(100, 1000); + +=cut + +loadMacros('MathObjects.pl'); + +sub _contextInteger_init {context::Integer::Init()}; + +########################################################################### + +package context::Integer; + +# +# Initialize the contexts and make the creator function. +# +sub Init { + my $context = $main::context{Integer} = Parser::Context->getCopy("Numeric"); + $context->{name} = "Integer"; + Parser::Number::NoDecimals($context); + $context->{pattern}{number} = '(?:\d+)'; + $context->{pattern}{signedNumber} = '[-+]?(?:\d+)'; + + $context->{parser}{Number} = "Parser::Legacy::LimitedNumeric::Number"; + $context->operators->undefine( + 'U', '.', '><', 'u+', '_', + ); + + $context->functions->add( + primeFactorization => {class => 'context::Integer::Function::Numeric'}, + phi => {class => 'context::Integer::Function::Numeric'}, + tau => {class => 'context::Integer::Function::Numeric'}, + isPrime => {class => 'context::Integer::Function::Numeric'}, + randomPrime => {class => 'context::Integer::Function::Numeric'}, + lcm => {class => 'context::Integer::Function::Numeric2'}, + gcd => {class => 'context::Integer::Function::Numeric2'}, + ); + + $context->{error}{msg}{"You are not allowed to type decimal numbers in this problem"} = + "You are only allowed to enter integers, not decimal numbers"; + + main::PG_restricted_eval('sub Integer {Value->Package("Integer()")->new(@_)};'); + main::PG_restricted_eval("sub primeFactorization {context::Integer::Function::Numeric::primeFactorization(\@_)}"); + main::PG_restricted_eval("sub phi {context::Integer::Function::Numeric::phi(\@_)}"); + main::PG_restricted_eval("sub tau {context::Integer::Function::Numeric::tau(\@_)}"); + main::PG_restricted_eval("sub isPrime {context::Integer::Function::Numeric::isPrime(\@_)}"); + main::PG_restricted_eval("sub randomPrime {context::Integer::Function::Numeric::randomPrime(\@_)}"); + main::PG_restricted_eval("sub lcm {context::Integer::Function::Numeric2::lcm(\@_)}"); + main::PG_restricted_eval("sub gcd {context::Integer::Function::Numeric2::gcd(\@_)}"); +} + +# +# divisor function +# +sub _divisor { + my $power = abs(shift); my $a = abs(shift); + $self->Error("Cannot perform divisor function on Zero") if $a == 0; + $result = 1; $sqrt_a = int(sqrt($a)); + for (my $i = 2; $i < $sqrt_a; $i++) { + if ($a % $i == 0) { + # add divisor to result + $result += $i ** $power; + # if both divisors are not the same, add the other divisor + # (ex: 12 / 2 = 6 so add 6 as well) + if ($i != ($a / $i)) { + $result += ($a / $i) ** $power; + } + } + } + # add the final divisor, the number itself unless the number is 1 + $result += ($a ** $power) if $a > 1; + return $result; +} + +sub _getPrimesInRange { + my $index = shift; my $end = shift; + $self->Error("Start of range must be a positive number.") if $index < 0; + $self->Error("End of range must be greater than or equal to 2") if $end < 2; + $self->Error("Start or range must be before end of range") if $index > $end; + @primes = (); + + # consider switching to set upper limit and static array of primes + + push(@primes, 2) if $index <= 2; + # ensure index is odd + $index++ if $index % 2 == 0; + while ($index < $end) { + push(@primes, $index) if context::Integer::Function::Numeric::isPrime($index); + $index += 2; + } + + return @primes; +} + +package context::Integer::Function::Numeric; +our @ISA = qw(Parser::Function::numeric); # checks for 2 numeric inputs + +# +# Prime Factorization +# +sub primeFactorization { + my $a = abs(shift); + $self->Error("Cannot factor Zero into primes.") if $a == 0; + $self->Error("Cannot factor One into primes.") if $a == 1; + + my %factors; my $n = $a; + for (my $i = 2; ($i ** 2) <= $n; $i++) { + while ($n % $i == 0) { + $n /= $i; + $factors{$i}++; + } + } + $factors{$n}++ if $n > 1; + + # store prime factors in array for cmp + my @results = (); + for my $factor (main::num_sort(keys %factors)) { + my $string = $factor; + $string .= "**".$factors{$factor} if $factors{$factor} > 1; + push(@results, $string); + } + return @results; +} + +# +# Euler's totient function phi(n) +# +sub phi { + my $a = abs(shift); + $self->Error("Cannot phi on Zero.") if $a == 0; + $result = $a; $n = $a; + for (my $i = 2; ($i ** 2) < $n; $i++) { + while ($n % $i == 0) { + $n /= $i; + $result -= $result / $i; + } + } + $result -= $result / $n if $n > 1; + return $result; +} + +# +# number of divisors function tau(n) +# +sub tau { + my $a = shift; + return context::Integer::_divisor(0, $a); +} + +sub isPrime { + my $a = abs(shift); + return 1 if $a == 2; + return 0 if $a < 2 || $a % 2 == 0; + for (my $i = 3; $i <= sqrt($a); $i += 2) { + return 0 if $a % $i == 0; + } + return 1; +} + +sub randomPrime { + my ($start,$end) = @_; + my @primes = context::Integer::_getPrimesInRange($start, $end); + $self->Error("Could not find any prime numbers in range.") if $#primes == 0; + my $primeIndex = $main::PG_random_generator->random(0,($#primes - 1), 1); + return $primes[$primeIndex]; +} + +package context::Integer::Function::Numeric2; +our @ISA = qw(Parser::Function::numeric2); # checks for 2 numeric inputs + +# +# Greatest Common Divisor +# +sub gcd { + my $a = abs(shift); my $b = abs(shift); + return $a if $b == 0; + return $b if $a == 0; + ($a,$b) = ($b,$a) if $a > $b; + while ($a) { + ($a, $b) = ($b % $a, $a); + } + return $b; +} + +# +# Extended Greatest Common Divisor +# +# return (g, x, y) a*x + b*y = gcd(x, y) +sub egcd { + my $a = shift; my $b = shift; + if ($a == 0) { + return ($b, 0, 1); + } else { + my ($g, $x, $y) = egcd($b % $a, $a); + my $temp = int($b / $a); $temp-- if $temp > $b / $a; # act as floor() rather than int() + return ($g, $y - $temp * $x, $x); + } +} + +# +# Modular inverse +# +# x = mulinv(b) mod n, (x * b) % n == 1 +sub mulularInverse { + my $b = shift; my $n = shift; + my ($g, $x, $y) = egcd($b, $n); + if ($g == 1) { + return $x % $n; + } else { + Value::Error("Modular inverse: gcd($a, $n) != 1"); + } +} + +# +# Least Common Multiple +# +sub lcm { + my $a = abs(shift); my $b = abs(shift); + return ($a*$b)/gcd($a,$b); +} + +1; \ No newline at end of file diff --git a/macros/contextPermutationUBC.pl b/macros/contextPermutationUBC.pl new file mode 100644 index 0000000000..ae5aebd710 --- /dev/null +++ b/macros/contextPermutationUBC.pl @@ -0,0 +1,728 @@ +################################################################################ +# WeBWorK Online Homework Delivery System +# Copyright © 2000-2014 The WeBWorK Project, http://openwebwork.sf.net/ +# $CVSHeader:$ +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of either: (a) the GNU General Public License as published by the +# Free Software Foundation; either version 2, or (at your option) any later +# version, or (b) the "Artistic License" which comes with this package. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the +# Artistic License for more details. +################################################################################ + + +=head1 NAME + +C - Provides contexts that allow the +entry of cycles and permutations. + + +=head1 DESCRIPTION + +These contexts allow you to enter permutations using cycle notation. +The entries in a cycle are separated by spaces and enclosed in +parentheses. Cycles are multiplied by juxtaposition. A permutation +can be multiplied on the left by a number in order to obtain the +result of that number under the action of the permutation. +Exponentiation is alos allowed (as described below). + +There are three contexts included here: C, which +allows permutations in any form, C, which +only allows permutations that use disjoint cycles, and +C, which only allows permutations that +are written in canonical form (as described below). + + +=head1 USAGE + + loadMacros("contextPermutationUBC.pl"); + + Context("Permutation"); + + $P1 = Compute("(1 4 2)(3 5)"); + $P2 = Permutation([1,4,2],[3,5]); # same as $P1 + $C1 = Cycle(1,4,2); + $P3 = Cycle(1,4,2)*Cycle(3,5); # same as $P1 + + $n = 3 * $P1; # sets $n to 5 + $m = Compute("3 (2 4 3 1)"); # sets $m to 1 + + $P4 = Compute("(1 2 3)^2"); # square a cycle + $P5 = Compute("((1 2)(3 4))^2"); # square a permutation + $I = Comptue("(1 2 3)^-1"); # inverse + + $L = Compute("(1 2),(1 3 2)"); # list of permutations + + $P = $P1->inverse; # inverse + $P = $P1->canonical; # canonical representation + + $P1 = Compute("(1 2 3)(4 5)"); + $P2 = Compute("(5 4)(3 1 2)"); + $P1 == $P2; # is true + +Cycles and permutations can be multiplied to obtain the permutation +that consists of one followed by the other, or multiplied on the left +by a number to obtain the image of the number under the permutation. +A permutation raised to a positive integer is the permutation +multiplied by itself that many times. A power of -1 is the inverse of +the permutation, while a larger negative number is the inverse +multiplied by itself that many times (the absolute value of the +power). + +There are times when you might not want to allow inverses to be +computed automatically. In this case, set + + Context()->flags->set(noInverses => 1); + +This will cause an error message if a student enters a negative power +for a cycle or permutation. + +If you don't want to allow any powers at all, then set + + Context()->flags->set(noPowers => 1); + +Similarly, if you don't want to allow grouping of cycles via +parentheses (e.g., "((1 2)(3 4))^2 (5 6)"), then use + + Context()->flags->set(noGroups => 1); + +The comparison between permutations is done by comparing the +canonical forms, so even if they are entered in different orders or +with the cycles rotated, two equivalent permutations will be counted +as equal. If you want to perform more sophisticated checks, then a +custom error checker could be used. + +You can require that permutations be entered using disjoint cycles by +setting + + Context()->flags->set(requireDisjoint => 1); + +When this is set, Compute("(1 2) (1 3)") will produce an error +indicating that the permutation doesn't have disjoint cycles. + +You can also require that students enter permutations in a canonical +form. The canonical form has each cycle listed with its lowest entry +first, and with the cycles ordered by their initial entries. So the +canonical form for + + (5 4 6) (3 1 2) + +is + + (1 2 3) (4 6 5) + +To require that permutations be entered in canonical form, use + + Context()->flags->set(requireCanonical => 1); + +The C context has C, C, C, and +C all set to 1, while the C has +C, C, C, and C all set to 1. +The C context has all the flags set to 0, so any permutation +is allowed. All three contexts allow lists of permutations to be +entered. + +=cut + +########################################################### +# +# Create the contexts and add the constructor functions +# + +sub _contextPermutation_init { + my $context = $main::context{Permutation} = Parser::Context->getCopy("Numeric"); + $context->{name} = "Permutation"; + Parser::Number::NoDecimals($context); + $context->variables->clear(); + $context->operators->clear(); + $context->constants->clear(); + $context->strings->clear(); + $context->functions->disable("All"); + + $context->{pattern}{number} = '(?:(?:^|(?<=[( ^*]))-)?(?:\d+(?:\.\d*)?|\.\d+)(?:E[-+]?\d+)?', + + $context->operators->add( + ',' => {precedence => 0, associativity => 'left', type => 'bin', string => ',', + class => 'Parser::BOP::comma', isComma => 1}, + + 'fn'=> {precedence => 7.5, associativity => 'left', type => 'unary', string => '', + parenPrecedence => 5, hidden => 1}, + + ' ' => {precedence => 3, associativity => 'right', type => 'bin', string => ' ', + class => 'context::Permutation::BOP::space', hidden => 1, isComma => 1}, + + '^' => {precedence => 7, associativity => 'right', type => 'bin', string => '^', perl => '**', + class => 'context::Permutation::BOP::power'}, + + '**'=> {precedence => 7, associativity => 'right', type => 'bin', string => '^', perl => '**', + class => 'context::Permutation::BOP::power'}, + ); + + $context->{value}{Cycle} = "context::Permutation::Cycle"; + $context->{value}{Permutation} = "context::Permutation::Permutation"; + $context->{precedence}{Cycle} = $context->{precedence}{special}; + $context->{precedence}{Permutation} = $context->{precedence}{special}+1; + $context->lists->add( + "Cycle" => {class => "context::Permutation::List::Cycle", open => "(", close => ")", separator => " "}, + "PermutationOneLineNotation" => {class => "context::Permutation::List::PermutationOneLineNotation", + open => "[", close => "]", separator => " "}, + "Permutation" => {open => "", close => "", separator => " "}, # used for output only + ); + $context->parens->set( + '(' => {close => ')', type => 'Cycle', formList => 0, removable => 0, emptyOK => 0, function => 1}, + '[' => {close => ']', type => 'PermutationOneLineNotation', formList => 0, removable => 0, emptyOK => 0, function => 1}, + ); + $context->flags->set(reduceConstants => 0); + + $context->flags->set( + displayOneLineNotation => 0, # output in one line notation + displayTwoLineNotation => 0, # output in two line notation + requireDisjoint => 0, # require disjoint cycles as answers? + requireCanonical => 0, # require canonical form? + noPowers => 0, # allow powers of cycles and permutations? + noInverses => 0, # allow negative powers to mean inverse? + noGroups => 0, # allow parens for grouping (for powers)? + ); + + $context->{error}{msg}{"Entries in a Cycle must be of the same type"} = + "Entries in a Cycle must be positive integers"; + + # + # A context in which permutations must be entered as + # products of disjoint cycles. + # + $context = $main::context{"Permutation-Strict"} = $context->copy; + $context->{name} = "Permutation-Strict"; + $context->flags->set( + requireDisjoint => 1, + noPowers => 1, + noInverses => 1, + noGroups => 1, + ); + + # + # A context in which permutation must be entered + # in canonical form. + # + $context = $main::context{"Permutation-Canonical"} = $context->copy; + $context->{name} = "Permutation-Canonical"; + $context->flags->set( + requireCanonical => 1, + requireDisjoint => 0, # requireCanonical already covers that + ); + + + PG_restricted_eval("sub Cycle {context::Permutation::Cycle->new(\@_)}"); + PG_restricted_eval("sub Permutation {context::Permutation::Permutation->new(\@_)}"); + +} + +########################################################### +# +# Methods common to cycles and permutations +# + +package context::Permutation; +our @ISA = ("Value"); + +# +# Use the usual make(), and then add the permutation data +# +sub make { + my $self = shift; + $self = $self->SUPER::make(@_); + $self->makeP; + return $self; +} + +# +# Permform multiplication of a number by a cycle or permutation, +# or a product of two cycles or permutations. +# +sub mult { + my ($self,$l,$r,$other) = Value::checkOpOrderWithPromote(@_); + if ($l->isReal) { + $l = $l->value; + Value->Error("Can't multiply %s by a non-integer value",$self->showType) unless $l == int($l); + Value->Error("Can't multiply %s by a negative value",$self->showType) if $l < 0; + my $n = $self->{P}{$l}; $n = $l unless defined $n; + return $self->Package("Real")->make($n); + } else { + Value->Error("Can't multiply %s by %s",$l->showType,$r->showType) + unless $r->classMatch("Cycle","Permutation"); + + my @lKeys = %{$l->{P}} ? keys %{$l->{P}} : (); + my @rKeys = %{$r->{P}} ? keys %{$r->{P}} : (); + + my %unique = (); + foreach my $item (@lKeys, @rKeys) { + $unique{$item}++; + } + my @keys = main::num_sort(keys %unique); + my @cycles = (); + while(my $key = shift(@keys)) { + my @cycle = ($key); + + # complete the cycle + my $currentKey = $key; + while(@keys) { + # set to right side value if present + if ($r->{P}{$currentKey}) { + $currentKey = $r->{P}{$currentKey}; + } # else set to identity which doesn't need assignment + + # set to left side value if present + if ($l->{P}{$currentKey}) { + $currentKey = $l->{P}{$currentKey}; + } # else set to identity which doesn't need assignment + + # if cycle complete + if ($key == $currentKey) { + last; + } else { + # add $currentKey to the cycle + push(@cycle, $currentKey); + foreach my $index (reverse 0 .. $#keys) { + splice(@keys, $index, 1) if $keys[$index] == $currentKey; + } + } + } + push(@cycles, $self->Package("Cycle")->new(@cycle)); + } + # return a Cycle if there is only one cycle as the result + return @cycles[0] if scalar(@cycles) == 1; + # else return a Permutation if there are more than 1 cycles + return $self->Package("Permutation")->new(@cycles); + } +} + +# +# Perform powers by repeated multiplication; +# Negative powers are inverses. +# +sub power { + my ($self,$l,$r,$other) = Value::checkOpOrderWithPromote(@_); + Value->Error("Can't raise %s to %s",$l->showType,$r->showType) unless $r->isNumber; + Value->Error("Powers are not allowed") if $self->getFlag("noPowers"); + if ($r < 0) { + Value->Error("Inverses are not allowed",$l->showType) if $self->getFlag("noInverses"); + $r = -$r; $l = $l->inverse; + } + $self->Package("Permutation")->make(map {$l} (1..$r))->canonical; +} + +# +# Compare canonical representations +# +sub compare { + my ($self,$l,$r,$other) = Value::checkOpOrderWithPromote(@_); + Value->Error("Can't compare %s and %s",$self->showType,$other->showType) + unless $other->classMatch("Cycle","Permutation"); + return $l->canonical cmp $r->canonical; +} + +# +# True if the permutation is in canonical form +# +sub isCanonical { + my $self = shift; + return $self eq $self->canonical; +} + +# +# Promote a number to a Real (since we can take a number times a +# permutation, or a permutation to a power), and anything else to a +# Cycle or Permutation. +# +sub promote { + my $self = shift; my $other = shift; + return Value::makeValue($other,context => $self->{context}) if Value::matchNumber($other); + return $self->SUPER::promote($other); +} + +# +# Produce a canonical representation as a collection of +# cycles that have their lowest entry first, sorted +# by initial entry. +# +sub canonical { + my $self = shift; + my @P = (); my @C; + my %N = (map {$_ => 1} (keys %{$self->{P}})); + while (scalar(keys %N)) { + $i = (main::num_sort(keys %N))[0]; @C = (); + do { + push(@C,$self->Package("Real")->new($i)); delete $N{$i}; + $i = $self->{P}{$i} if defined $self->{P}{$i}; + } while ($i != $C[0]); + push(@P,$self->Package("Cycle")->make($self->{context},@C)); + } + return $P[0] if scalar(@P) == 1; + return $self->Package("Permutation")->make($self->{context},@P); +} + +# +# Produce the inverse of a permutation or cycle. +# +sub inverse { + my $self = shift; + my $P = {map {$self->{P}{$_} => $_} (keys %{$self->{P}})}; + return $self->with(P => $P)->canonical; +} + +# +# Produce a string version (use "(1)" as the identity). +# +sub string { + my $self = shift; + my $displayOneLineNotation = $self->getFlag("displayOneLineNotation"); + my $displayTwoLineNotation = $self->getFlag("displayTwoLineNotation"); + if ($displayOneLineNotation || $displayTwoLineNotation) { + my @keys = main::num_sort(keys %{$self->{P}}); + my $string = ""; + if (@keys) { + $string .= join(' ',@{$self->{P}}{@keys}); + } else { + $string .= "1"; + } + return "(".$string.")"; + } else { + my $string = $self->SUPER::string(@_); + $string = "(1)" unless length($string); + return $string; + } +} + +# +# Produce a TeX version (uses \; for spaces) +# +sub TeX { + my $self = shift; + my $displayTwoLineNotation = $self->getFlag("displayTwoLineNotation"); + if ($displayTwoLineNotation) { + my $tex = "\\bigl(\\begin{smallmatrix} "; + my @keys = main::num_sort(keys %{$self->{P}}); + if (@keys) { + $tex .= join(' & ',@keys) . " \\\\ " . join(' & ',@{$self->{P}}{@keys}); + } else { + $tex .= "1 \\\\ 1"; + } + $tex .= "\\end{smallmatrix}\\bigr)"; + return $tex; + } else { + my $tex = $self->string; + $tex =~ s/\) \(/)\\,(/g; + $tex =~ s/ /\\;/g; + return $tex; + } +} + +########################################################### +# +# A single cycle +# + +package context::Permutation::Cycle; +our @ISA = ("context::Permutation"); + +sub new { + my $self = shift; my $class = ref($self) || $self; + my $context = (Value::isContext($_[0]) ? shift : $self->context); + my $p = [@_]; $p = $p->[0] if scalar(@$p) == 1 && ref($p->[0]) eq "ARRAY"; + return $p->[0] if scalar(@$p) == 1 && Value::classMatch($p->[0],"Cycle","Permutation"); + my %N; + foreach my $x (@{$p}) { + $x = Value::makeValue($x,context => $context); + Value->Error("An entry of a Cycle can't be %s",$x->showType) + unless $x->isNumber && !$x->isFormula; + my $i = $x->value; + Value->Error("An entry of a Cycle can't be negative") if $i < 0; + Value->Error("Cycles can't contain repeated values") if $N{$i}; $N{$i} = 1; + } + my $cycle = bless {data => $p, context => $context}, $class; + $cycle->makeP; + return $cycle; +} + +# +# Find the internal representation of the permutation +# (a hash representing where each element goes) +# +sub makeP { + my $self = shift; + my $p = $self->{data}; my $P = {}; + my $displayOneLineNotation = $self->getFlag("displayOneLineNotation"); + my $displayTwoLineNotation = $self->getFlag("displayTwoLineNotation"); + if (@$p) { + my $i = $p->[scalar(@$p)-1]->value; + foreach my $x (@{$p}) { + my $j = $x->value; + $P->{$i} = $j if $i != $j || $displayOneLineNotation || $displayTwoLineNotation; + $i = $j; + } + } + $self->{P} = $P; +} + +########################################################### +# +# A combination of cycles +# + +package context::Permutation::Permutation; +our @ISA = ("context::Permutation"); + +sub new { + my $self = shift; my $class = ref($self) || $self; + my $context = (Value::isContext($_[0]) ? shift : $self->context); + my $disjoint = $self->getFlag("requireDisjoint"); + my $p = [@_]; my %N; + foreach my $x (@$p) { + $x = Value::makeValue($x,context=>$context) unless ref($x); + $x = Value->Package("Cycle")->new($context,$x) if ref($x) eq "ARRAY"; + Value->Error("An entry of a Permutation can't be %s",Value::showClass($x)) + unless Value::classMatch($x,"Cycle","Permutation"); + if ($disjoint) { + foreach my $i (keys %{$x->{P}}) { + Value->Error("Your Permutation does not have disjoint Cycles") if $N{$i}; + $N{$i} = 1; + } + } + } + my $perm = bless {data => $p, context => $context}, $class; + $perm->makeP; + Value->Error("Your Permutation is not in canonical form") + if $perm->getFlag("requireCanonical") && $perm ne $perm->canonical; + return $perm; +} + +# +# Find the internal representation of the permutation +# (a hash representing where each element goes) +# +sub makeP { + my $self = shift; my $p = $self->{data}; + my $P = {}; my %N; + my $displayOneLineNotation = $self->getFlag("displayOneLineNotation"); + my $displayTwoLineNotation = $self->getFlag("displayTwoLineNotation"); + foreach my $x (@$p) {map {$N{$_} = 1} (keys %{$x->{P}})} # get all elements used + foreach my $i (keys %N) { + my $j = $i; + map {$j = $_->{P}{$j} if defined $_->{P}{$j}} @$p; # apply all cycles/permutations + $P->{$i} = $j if $i != $j || $displayOneLineNotation || $displayTwoLineNotation; + } + $self->{P} = $P; +} + +########################################################### +# +# Space between numbers forms a cycle. +# Space between cycles forms a permutation. +# Space between a number and a cycle or +# permutation evaluates the permutation +# on the number. +# +package context::Permutation::BOP::space; +our @ISA = ("Parser::BOP"); + +# +# Check that the operands are appropriate, and return +# the proper type reference, or give an error. +# +sub _check { + my $self = shift; my $type; + my ($ltype,$rtype) = ($self->{lop}->typeRef,$self->{rop}->typeRef); + if ($ltype->{name} eq "Number") { + if ($rtype->{name} eq "Number") { + $type = Value::Type("Comma",2,$Value::Type{number}); + } elsif ($rtype->{name} eq "Comma") { + $type = Value::Type("Comma",$rtype->{length}+1,$Value::Type{number}); + } elsif ($rtype->{name} eq "Cycle" || $rtype->{name} eq "Permutation") { + $type = $Value::Type{number}; + } + } elsif ($ltype->{name} eq "Cycle") { + if ($rtype->{name} eq "Cycle") { + $type = Value::Type("Permutation",2,$ltype); + } elsif ($rtype->{name} eq "Permutation") { + $type = Value::Type("Permutation",$rtype->{length}+1,$ltype); + } + } + if (!$type) { + $ltype = $ltype->{name}; $rtype = $rtype->{name}; + $ltype = (($ltype =~ m/^[aeiou]/i)? "An ": "A ") . $ltype; + $rtype = (($rtype =~ m/^[aeiou]/i)? "an ": "a ") . $rtype; + $self->{equation}->Error(["%s can not be multiplied by %s",$ltype,$rtype]); + } + $self->{type} = $type; +} + +# +# Evaluate by forming a list if this is acting as a comma, +# othewise take a product (Value object will take care of things). +# +sub _eval { + my $self = shift; + my ($a,$b) = @_; + return ($a,$b) if $self->type eq "Comma"; + return $a * $b; +} + +# +# If the operator is not a comma, return the item itself. +# Otherwise, make a list out of the lists that are the left +# and right operands. +# +sub makeList { + my $self = shift; my $prec = shift; + return $self unless $self->{def}{isComma} && $self->type eq 'Comma'; + return ($self->{lop}->makeList,$self->{rop}->makeList); +} + +# +# Produce the TeX form +# +sub TeX { + my $self = shift; + return $self->{lop}->TeX."\\,".$self->{rop}->TeX; +} + + +########################################################### +# +# Powers of cycles form permutations +# +package context::Permutation::BOP::power; +our @ISA = ("Parser::BOP::power"); + +# +# Check that the operands are appropriate, +# and return the proper type reference +# +sub _check { + my $self = shift; my $equation = $self->{equation}; + $equation->Error(["Powers are not allowed"]) if $equation->{context}->flag("noPowers"); + $equation->Error(["You can only take powers of Cycles or Permutations"]) + unless $self->{lop}->type eq "Cycle"; + $self->{rop} = $self->{rop}{coords}[0] if $self->{rop}->type eq "Cycle" && $self->{rop}->length == 1; + $equation->Error(["Powers of Cycles and Permutations must be Numbers"]) + unless $self->{rop}->type eq "Number"; + $self->{type} = Value::Type("Permutation",1,$self->{lop}->typeRef); +} + + +########################################################### +# +# The List subclass for cycles in the parse tree +# + +package context::Permutation::List::Cycle; +our @ISA = ("Parser::List"); + +# +# Check that the coordinates are numbers. +# If there is one parameter and it is a cycle or permutation +# treat this as plain parentheses, not cycle parentheses +# (so you can take groups of cycles to a power). +# +sub _check { + my $self = shift; + if ($self->length == 1 && !$self->{equation}{context}->flag("noGroups")) { + my $value = $self->{coords}[0]; + return if ($value->type eq "Cycle" || $value->typeRef->{name} eq "Permutation" || + ($value->class eq "Value" && $value->{value}->classMatch("Cycle","Permutation"))); + } + foreach my $x (@{$self->{coords}}) { + unless ($x->isNumber) { + my $type = $x->type; + $type = (($type =~ m/^[aeiou]/i)? "an ": "a ") . $type; + $self->{equation}->Error(["An entry in a Cycle must be a Number not %s",$type]); + } + } +} + +# +# Produce a string version. (Shouldn't be needed, but there is +# a bug in the Value.pm version that neglects the separator value.) +# +sub string { + my $self = shift; my $precedence = shift; my @coords = (); + foreach my $x (@{$self->{coords}}) {push(@coords,$x->string)} + my $comma = $self->{equation}{context}{lists}{$self->{type}{name}}{separator}; + return $self->{open}.join($comma,@coords).$self->{close}; +} + +# +# Produce a TeX version. +# +sub TeX { + my $self = shift; my $precedence = shift; my @coords = (); + foreach my $x (@{$self->{coords}}) {push(@coords,$x->TeX)} + my $comma = $self->{equation}{context}{lists}{$self->{type}{name}}{separator}; + $comma =~ s/ /\\;/g; + return $self->{open}.join($comma,@coords).$self->{close}; +} + +######################################################################### +# +# The List subclass for one line notation permutations in the parse tree +# +package context::Permutation::List::PermutationOneLineNotation; +our @ISA = ("Parser::List"); + +# +# Check that the coordinates are numbers. +# +sub _check { + my $self = shift; + foreach my $x (@{$self->{coords}}) { + unless ($x->isNumber) { + my $type = $x->type; + $type = (($type =~ m/^[aeiou]/i)? "an ": "a ") . $type; + $self->{equation}->Error(["An entry in a Permutation must be a Number not %s",$type]); + } + } +} + +# +# Call the appropriate creation routine from Value.pm +# (Can be over-written by sub-classes) +# +sub _eval { + my $self = shift; + my @elements = @{@_[0]}; + # transform into cycles + my @keys = 1 .. scalar(@elements); + my @cycles = (); + while(my $key = shift(@keys)) { + my @cycle = ($key); + # complete the cycle + my $currentKey = $key; + while(@keys) { + if ($elements[$currentKey-1]) { + $currentKey = $elements[$currentKey-1]; + } + if ($key == $currentKey) { + last; + } else { + push(@cycle, $currentKey); + foreach my $index (reverse 0 .. $#keys) { + splice(@keys, $index, 1) if $keys[$index] == $currentKey; + } + } + } + push(@cycles, $self->Package("Cycle")->new(@cycle)); + } + # return a Cycle if there is only one cycle as the result + return @cycles[0] if scalar(@cycles) == 1; + # else return a Permutation if there are more than 1 cycles + return $self->Package("Permutation")->new(@cycles); +} + +########################################################### + +1; + diff --git a/macros/quickMatrixEntry.pl b/macros/quickMatrixEntry.pl new file mode 100755 index 0000000000..10150f50c9 --- /dev/null +++ b/macros/quickMatrixEntry.pl @@ -0,0 +1,120 @@ +#!/usr/bin/perl -w + +################################### +# quick matrix entry package +################################### + +sub _quickMatrixEntry_init {}; # don't reload this file + +sub INITIALIZE_QUICK_MATRIX_ENTRY { + main::HEADER_TEXT($quick_entry_javascript); + main::TEXT($quick_entry_form); + return ''; +} + +# +sub MATRIX_ENTRY_BUTTON { + my $answer_number = shift; + # warn(" input reference is ". ref($answer_number)); + my ($rows,$columns) = @_; + if (ref($answer_number)=~/Matrix/i) { # (handed a MathObject matrix) + my $matrix = $answer_number; + ($rows,$columns) = $matrix->dimensions(); + $answer_number = $main::PG->{unlabeled_answer_blank_count} +1; + # the +1 assumes that the quick entry button comes before (above) the matrix answer blanks. + } + $rows=$rows//1; + $columns=$columns//5; + my $answer_name = "AnSwEr".sprintf('%04d',$answer_number); + # warn("answer number $answer_name rows $rows columns $columns"); + return qq! + $PAR + + $PAR!; +} + +our $quick_entry_javascript = <<'END_JS'; + +END_JS + +our $quick_entry_form = <<'END_TEXT'; +
+ + +
+END_TEXT + +INITIALIZE_QUICK_MATRIX_ENTRY(); # only need the javascript to be entered once. +1; \ No newline at end of file diff --git a/macros/scaffold.pl b/macros/scaffold.pl index 5e32c20f33..0073f0a449 100644 --- a/macros/scaffold.pl +++ b/macros/scaffold.pl @@ -484,8 +484,8 @@ package Section; # # Shortcuts for Scaffold data # -my $PG_ANSWERS_HASH = $Scaffold::PG_ANSWERS_HASH; -my $PG_OUTPUT = $Scaffold::PG_OUTPUT; +$PG_ANSWERS_HASH = $Scaffold::PG_ANSWERS_HASH; +$PG_OUTPUT = $Scaffold::PG_OUTPUT; # diff --git a/macros/tableau.pl b/macros/tableau.pl new file mode 100755 index 0000000000..5968539c0f --- /dev/null +++ b/macros/tableau.pl @@ -0,0 +1,1608 @@ +#!/usr/bin/perl -w + +# this file needs documentation and unit testing. +# where is it used? + +##### From gage_matrix_ops +# 2014_HKUST_demo/templates/setSequentialWordProblem/bill_and_steve.pg:"gage_matrix_ops.pl", + +=head1 NAME + + macros/tableau.pl + +=head2 TODO + + DONE: change find_next_basis_from_pivot to next_basis_from_pivot + DONE: add phase2 to some match phase1 for some of the pivots -- added as main:: subroutine + DONE: add a generic _solve that solves tableau once it has a filled basis -- needs to be tested + add something that will fill the basis. + + regularize the use of m and n -- should they be the number of + constraints and the number of decision(problem) variables or should + they be the size of the complete tableau. + we probably need both -- need names for everything + + current tableau returns the complete tableau minus the objective function + row. + (do we need a second objective function row? -- think we can skip this for now.) + +=cut + +=head2 DESCRIPTION + + # We're going to have several types + # MathObject Matrices Value::Matrix + # tableaus form John Jones macros + # MathObject tableaus + # Containing an matrix $A coefficients for constraint + # A vertical vector $b for constants for constraints + # A horizontal vector $c for coefficients for objective function + # A vertical vector corresponding to the value $z of the objective function + # dimensions $n problem vectors, $m constraints = $m slack variables + # A basis Value::Set -- positions for columns which are independent and + # whose associated variables can be determined + # uniquely from the parameter variables. + # The non-basis (parameter) variables are set to zero. + # + # state variables (assuming parameter variables are zero or when given parameter variables) + # create the methods for updating the various containers + # create the method for printing the tableau with all its decorations + # possibly with switches to turn the decorations on and off. + + +The structure of the tableau is: + + ----------------------------------------------------------- + | | | | | + | A | S | 0 | b | + | | | | | + ---------------------------------------------- + | -c | 0 | 1 | 0 | + ---------------------------------------------- + Matrix A, the initial constraint matrix is n=num_problem_vars by m=num_slack_vars + Matrix S, the initial slack variables is m by m + Matrix b, the initial constraint constants is n by 1 (Matrix or ColumnVector) + Matrix c, the objective function coefficients matrix is 1 by n + + Matrix which changes with state: + Matrix upper_tableau: m by n+2 (A|S|0|b) + Matrix tableau m+1 by n+2 (A/(-c)) | S/0 | 0/1 |b/z + Matrix current_obj_coeff = 1 by n+m matrix (negative of current coeff for obj_function) + Matrix current_last_row = 1 by n+m+2 matrix tableau is upper_tableau over current_last_row + + The next to the last column holds z or objective value + z(...x^i...) = c_i* x^i (Einstein summation convention) + FIXME: ?? allow c to be a 2 by n matrix so that you can do phase1 calculations easily + + +=cut + + +=head2 Package main + + +=item tableauEquivalence + + ANS( $tableau->cmp(checker=>tableauEquivalence()) ); + + # Note: it is important to include the () at the end of tableauEquivalence + + # tableauEquivalence compares two matrices up to + # reshuffling the rows and multiplying each row by a constant. + # It is equivalent up to multiplying on the left by a permuation matrix + # or a (non-uniformly constant) diagonal matrix. + # It is appropriate for comparing augmented matrices representing a system of equations + # since the order of the equations is unimportant. This applies to tableaus for + # Linear Optimization Problems being solved using the simplex method. + +=cut + + +=item get_tableau_variable_values + (DEPRECATED -- use Tableau->statevars method ) + Parameters: ($MathObjectMatrix_tableau, $MathObjectSet_basis) + Returns: ARRAY or ARRAY_ref + +Returns the solution variables to the tableau assuming +that the parameter (non-basis) variables +have been set to zero. It returns a list in +array context and a reference to +an array in scalar context. + +=item lp_basis_pivot + (DEPRECATED -- preserved for legacy problems. Use Tableau->basis method) + Parameters: ($old_tableau,$old_basis,$pivot) + Returns: ($new_tableau, Set($new_basis),\@statevars) + + +=item linebreak_at_commas + + Parameters: () + Return: + + Useage: + ANS($constraints->cmp()->withPostFilter( + linebreak_at_commas() + )); + +Replaces commas with line breaks in the latex presentations of the answer checker. +Used most often when $constraints is a LinearInequality math object. + + +=cut + + +=head3 References: + +MathObject Matrix methods: L +MathObject Contexts: L +CPAN RealMatrix docs: L + +More references: L + +=cut + +=head2 Package tableau + +=cut + +=item new + + Tableau->new(A=>Matrix, b=>Vector or Matrix, c=>Vector or Matrix) + + A => undef, # original constraint matrix MathObjectMatrix + b => undef, # constraint constants ColumnVector or MathObjectMatrix n by 1 + c => undef, # coefficients for objective function Vector or MathObjectMatrix 1 by n + obj_row => undef, # contains the negative of the coefficients of the objective function. + z => undef, # value for objective function Real + n => undef, # dimension of problem variables (columns in A) + m => undef, # dimension of slack variables (rows in A) + S => undef, # square m by m MathObjectMatrix for slack variables. default is the identity + M => undef, # matrix (m by m+n+1+1) consisting of all original columns and all + rows except for the objective function row. The m+n+1 column and + is the objective_value column. It is all zero with a pivot in the objective row. + The current version of this accessed by Tableau->upper_tableau (A | S |0 | b) + #FIXME + obj_col_num => undef, # have obj_col on the left or on the right? FIXME? obj_column_position + # perhaps not store this column at all and add it when items are printed? + + basis => List | Set, # unordered list describing the current basis columns corresponding + to determined variables. With a basis argument this sets a new state defined by that basis. + current_constraint_matrix=>(m by n matrix), # the current version of [A | S] + current_b=> (1 by m matrix or Column vector) # the current version of the constraint constants b + current_basis_matrix => (m by m invertible matrix) a square invertible matrix + # corresponding to the current basis columns + + # flag indicating the column (1 or n+m+1) for the objective value + constraint_labels => undef, (not sure if this remains relevant after pivots) + problem_var_labels => undef, + slack_var_labels => undef, + + Notes: (1 by m MathObjectMatrix) <= Value::Matrix->new($self->b->transpose->value ) +=cut + + + + + +# ANS( $tableau->cmp(checker=>tableauEquivalence()) ); + +package main; + +sub _tableau_init {}; # don't reload this file + +# loadMacros("tableau_main_subroutines.pl"); +sub tableau_equivalence { # I think this might be better -- matches linebrea_at_commas + # the two should be consistent. + tableauEquivalence(@_); +} + +sub tableauEquivalence { + return sub { + my ($correct, $student, $ansHash) = @_; + #DEBUG_MESSAGE("executing tableau equivalence"); + #DEBUG_MESSAGE("$correct"); + #DEBUG_MESSAGE("$student"); + Value::Error("correct answer is not a matrix") unless ref($correct)=~/Value::Matrix/; + Value::Error("student answer is not a matrix") unless ref($student)=~/Value::Matrix/; + + # convert matrices to arrays of row references + my @rows1 = $correct->extract_rows; + my @rows2 = $student->extract_rows; + # compare the rows as lists with each row being compared as + # a parallel Vector (i.e. up to multiples) + my $score = List(@rows1)->cmp( checker => + sub { + my ($listcorrect,$liststudent,$listansHash,$nth,$value)=@_; + my $listscore = Vector($listcorrect)->cmp(parallel=>1) + ->evaluate(Vector($liststudent))->{score}; + return $listscore; + } + )->evaluate(List(@rows2))->{score}; + return $score; + } + } + + +# $foochecker = $constraints->cmp()->withPostFilter( +# linebreak_at_commas() +# ); + + +sub linebreak_at_commas { + return sub { + my $ans=shift; + my $foo = $ans->{correct_ans_latex_string}; + $foo =~ s/,/,\\\\\\\\/g; + ($ans->{correct_ans_latex_string})=~ s/,/,\\\\\\\\/g; + ($ans->{preview_latex_string})=~ s/,/,\\\\\\\\/g; + #DEBUG_MESSAGE("foo", $foo); + #DEBUG_MESSAGE( "correct", $ans->{correct_ans_latex_string} ); + #DEBUG_MESSAGE( "preview", $ans->{preview_latex_string} ); + #DEBUG_MESSAGE("section4ans1 ", pretty_print($ans, $displayMode)); + $ans; + }; +} + + +# lop_display($tableau, align=>'cccc|cc|c|c', toplevel=>[qw(x1,x2,x3,x4,s1,s2,P,b)]) +# Pretty prints the output of a matrix as a LOP with separating labels and +# variable labels. + + +=item lop_display + + Useage: + + lop_display($tableau, align=>'cccc|cc|c|c', toplevel=>[qw(x1,x2,x3,x4,s1,s2,P,b)]) + +Pretty prints the output of a matrix as a LOP with separating labels and +variable labels. + +=cut +our $max_number_of_steps = 20; + +sub lop_display { + my $tableau = shift; + %options = @_; + #TODO get alignment and toplevel from tableau + #override it with explicit options. + $alignment = ($options{align})? $options{align}: + ($tableau->align)? $tableau->align : "|ccccc|cc|c|c|"; + @toplevel = (); + if (exists( ($options{toplevel})) ) { + @toplevel = @{$options{toplevel}}; + $toplevel[0]=[$toplevel[0],headerrow=>1, midrule=>1]; + } elsif ($tableau->toplevel) { + @toplevel =@{$tableau->toplevel}; + $toplevel[0]=[$toplevel[0],headerrow=>1, midrule=>1]; + } + @matrix = $tableau->current_tableau->value; + $last_row = $#matrix; # last row is objective coefficients + $matrix[$last_row-1]->[0]=[$matrix[$last_row-1]->[0],midrule=>1]; + $matrix[$last_row]->[0]=[$matrix[$last_row]->[0],midrule=>1]; + DataTable([[@toplevel],@matrix],align=>$alignment); +} + +# for main section of tableau.pl + +# make one phase2 pivot on a tableau (works in place) +# returns flag with '', 'optimum' or 'unbounded' + +sub next_tableau { + my $self = shift; + my $max_or_min = shift; + Value::Error("next_tableau requires a 'max' or 'min' argument") + unless $max_or_min=~/max|min/; + my @out = $self->find_next_basis($max_or_min); + my $flag = pop(@out); + if ($flag) { + } else { # update matrix + $self->basis(Set(@out)); + } + return $flag; +} + + +#iteratively phase2 pivots a feasible tableau until the +# flag returns 'optimum' or 'unbounded' +# tableau is returned in a "stopped" state. + +sub phase2_solve { + my $tableau = shift; + my $max_or_min = shift; #FIXME -- this needs a sanity check + Value::Error("phase2_solve requires a 'max' or 'min' argument") + unless $max_or_min=~/max|min/; + # calculate the final state by phase2 pivoting through the tableaus. + my $state_flag = ''; + my $tableau_copy = $tableau->copy; + my $i=0; + while ((not $state_flag) and $i <=$max_number_of_steps ) { + $state_flag = next_tableau($tableau_copy,$max_or_min); + $i++; + } + return($tableau_copy,$state_flag, $i); + # TEXT("Number of iterations is $i $BR"); +} + +# make one phase 1 pivot on a tableau (works in place) +# returns flag with '', 'infeasible_lop' or 'feasible_point' +# perhaps 'feasible_point' should be 'feasible_lop' +sub next_short_cut_tableau { + my $self = shift; + my @out = $self->next_short_cut_basis(); + my $flag = pop(@out); + # TEXT(" short cut tableau flag $flag $BR"); + if ($flag) { + } else { # update matrix + $self->basis(Set(@out)); + } + return $flag; +} +sub phase1_solve { + my $tableau = shift; + my $state_flag = ''; + my $tableau_copy = $tableau->copy; + my $steps = 0; + while (not $state_flag and $steps <= $max_number_of_steps) { + $state_flag = next_short_cut_tableau($tableau_copy); + $steps++; + } + return( $tableau_copy, $state_flag, $steps); +} + +=item primal_basis_to_dual dual_basis_to_primal + + [complementary_basis_set] = $self->primal_basis_to_dual(primal_basis_set) + [complementary_basis_set] = $self->dual_basis_to_primal(dual_basis_set) + +<<<<<<< HEAD +######################## +############## +# get_tableau_variable_values +# + +# Calculates the values of the basis variables of the tableau, +# assuming the parameter variables are 0. +# +# Usage: get_tableau_variable_values($MathObjectMatrix_tableau, $MathObjectSet_basis) +# +# feature request -- for tableau object -- allow specification of non-zero parameter variables +sub get_tableau_variable_values { +======= +=cut + + + +# deprecated for tableaus - use $tableau->statevars instead +sub get_tableau_variable_values { +>>>>>>> Pull updated tableau.pl from fall17mth208/templates/macro/tableau.pl + my $mat = shift; # a MathObject matrix + my $basis =shift; # a MathObject set + # FIXME + # type check ref($mat)='Matrix'; ref($basis)='Set'; + # or check that $mat has dimensions, element methods; and $basis has a contains method + my ($n, $m) = $mat->dimensions; + @var = (); + #DEBUG_MESSAGE( "start new matrix"); + foreach my $j (1..$m-2) { # the last two columns of the tableau are object variable and constants + if (not $basis->contains($j)) { + #DEBUG_MESSAGE( "j= $j not in basis"); + $var[$j-1]=0; next; # non-basis variables (parameters) are set to 0. + + } else { + foreach my $i (1..$n-1) { # the last row is the objective function + # if this is a basis column there should be only one non-zero element(the pivot) + if ( not $mat->element($i,$j) == 0 ) { # should this have ->value????? + $var[$j-1] = ($mat->element($i,$m)/$mat->element($i,$j))->value; + #DEBUG_MESSAGE("i=$i j=$j var = $var[$j-1] "); + next; + } + + } + } + } # element($n, $m-1) is the coefficient of the objective value. + # this last variable is the value of the objective function + push @var , ($mat->element($n,$m)/$mat->element($n,$m-1))->value; + + @var; +} +#### Test -- assume matrix is this +# 1 2 1 0 0 | 0 | 3 +# 4 5 0 1 0 | 0 | 6 +# 7 8 0 0 1 | 0 | 9 +# -1 -2 0 0 0 | 1 | 10 # objective row +# and basis is {3,4,5} (start columns with 1) +# $n= 4; $m = 7 +# $x1=0; $x2=0; $x3=s1=3; $x4=s2=6; $x5=s3=9; w=10=objective value +# +# + +################################################## +package Tableau; +our @ISA = qw(Class::Accessor Value::Matrix Value ); +Tableau->mk_accessors(qw( + A b c obj_row z n m S basis_columns B M current_constraint_matrix + current_objective_coeffs current_b current_basis_matrix current_basis_coeff + obj_col_index toplevel align constraint_labels + problem_var_labels slack_var_labels obj_symbol var_symbol + +)); + +<<<<<<< HEAD + + +sub linebreak_at_commas { + return sub { + my $ans=shift; + my $foo = $ans->{correct_ans_latex_string}; +<<<<<<< HEAD + $foo =~ s/,/,\\\\/g; + ($ans->{correct_ans_latex_string})=~ s/,/,\\\\/g; + ($ans->{preview_latex_string})=~ s/,/,\\\\/g; +======= + $foo =~ s/,/,\\\\\\\\/g; + ($ans->{correct_ans_latex_string})=~ s/,/,\\\\\\\\/g; + ($ans->{preview_latex_string})=~ s/,/,\\\\\\\\/g; +>>>>>>> Add tableau.pl + #DEBUG_MESSAGE("foo", $foo); + #DEBUG_MESSAGE( "correct", $ans->{correct_ans_latex_string} ); + #DEBUG_MESSAGE( "preview", $ans->{preview_latex_string} ); + #DEBUG_MESSAGE("section4ans1 ", pretty_print($ans, $displayMode)); + $ans; + }; +} +# Useage +# $foochecker = $constraints->cmp()->withPostFilter( +# linebreak_at_commas() +# ); + + +# We're going to have several types +# MathObject Matrices Value::Matrix +# tableaus form John Jones macros +# MathObject tableaus +# Containing an matrix $A coefficients for constraint +# A vertical vector $b for constants for constraints +# A horizontal vector $c for coefficients for objective function +# A vertical vector $P for the value of the objective function +# dimensions $n problem vectors, $m constraints = $m slack variables +# A basis Value::Set -- positions for columns which are independent and +# whose associated variables can be determined +# uniquely from the parameter variables. +# The non-basis (parameter) variables are set to zero. +# +# state variables (assuming parameter variables are zero or when given parameter variables) +# create the methods for updating the various containers +# create the method for printing the tableau with all its decorations +# possibly with switches to turn the decorations on and off. +======= +our $tableauZeroLevel = Value::Real->new(1E-10); +# consider entries zero if they are less than $tableauZeroLevel times the current_basis_coeff. +>>>>>>> Pull updated tableau.pl from fall17mth208/templates/macro/tableau.pl + + +sub close_enough_to_zero { + my $self = shift; + my $value = shift; + #main::DEBUG_MESSAGE("value is $value"); + #main::DEBUG_MESSAGE("current_basis is ", $self->current_basis_coeff); + #main::DEBUG_MESSAGE("cutoff is ", $tableauZeroLevel*($self->current_basis_coeff)); + return (abs($value)<= $tableauZeroLevel*($self->current_basis_coeff))? 1: 0; +} + +sub class {"Matrix"}; + + +sub _Matrix { # can we just import this? + Value::Matrix->new(@_); +} + +# tableau constructor Tableau->new(A=>Matrix, b=>Vector or Matrix, c=>Vector or Matrix) + +sub new { + my $self = shift; my $class = ref($self) || $self; + my $context = (Value::isContext($_[0]) ? shift : $self->context); + # these labels are passed only to document what the mutators do + my $tableau = Class::Accessor->new({ + A => undef, # constraint matrix MathObjectMatrix + b => undef, # constraint constants Vector or MathObjectMatrix 1 by n + c => undef, # coefficients for objective function MathObjectMatrix 1 by n or 2 by n matrix + obj_row => undef, # contains the negative of the coefficients of the objective function. + z => undef, # value for objective function + n => undef, # dimension of problem variables (columns in A) + m => undef, # dimension of slack variables (rows in A) + S => undef, # square m by m matrix for slack variables + basis_columns => undef, # list describing the current basis columns corresponding to determined variables. + B => undef, # square invertible matrix corresponding to the current basis columns + M => undef, # matrix of consisting of all columns and all rows except for the objective function row + current_constraint_matrix=>undef, + current_objective_coeffs=>undef, + current_b => undef, + obj_col_index => undef, # an array reference indicating the columns (e.g 1 or n+m+1) for the objective value or values + toplevel => undef, + align => undef, + constraint_labels => undef, + problem_var_labels => undef, + slack_var_labels => undef, + + @_, + }); + bless $tableau, $class; + $tableau->initialize(); + return $tableau; +} + + +sub initialize { + $self= shift; + unless (ref($self->{A}) =~ /Value::Matrix/ && + ref($self->{b}) =~ /Value::Vector|Value::Matrix/ && + ref($self->{c}) =~ /Value::Vector|Value::Matrix/){ + Value::Error ("Error: Required inputs for creating tableau:\n". + "Tableau(A=> Matrix, b=>ColumnVector or Matrix, c=>Vector or Matrix)". + "not the arguments of type ". ref($self->{A}). " |".ref($self->{b})."| |".ref($self->{c}). + "|"); + } + my ($m, $n)=($self->{A}->dimensions); +<<<<<<< HEAD + $self->{n}=$self->{n}//$n; + $self->{m}=$self->{m}//$m; + # main::DEBUG_MESSAGE("m $m, n $n"); + $self->{S} = Value::Matrix->I(4); + $self->{basis} = [($n+1)...($n+$m)] unless ref($self->{basis})=~/ARRAY/; +<<<<<<< HEAD + my @rows = $self->assemble_tableau; +======= + my @rows = $self->assemble_matrix; +>>>>>>> Add tableau.pl + #main::DEBUG_MESSAGE("rows", @rows); + $self->{M} = _Matrix([@rows]); + $self->{B} = $self->{M}->submatrix(rows=>[1..($self->{m})],columns=>$self->{basis}); + $self->{obj_row} = _Matrix($self->objective_row()); + return(); +======= + $self->n( ($self->n) //$n ); + $self->m( ($self->m) //$m ); + my $myAlignString = "c" x $n . "|" . "c" x $m ."|"."c|c"; # usual alignment for tableau. + my $var_symbol = $self->{var_symbol}//'x'; + my $obj_symbol = $self->{obj_symbol}//'z'; + my @myTopLevel = map {$var_symbol.$_} 1..($m+$n); + @myTopLevel = (@myTopLevel,$obj_symbol,'b' ); + $self->{toplevel} = ($self->{toplevel})//[@myTopLevel]; + $self->{align} = ($self->{align})//$myAlignString; + $self->{S} = Value::Matrix->I($m); + $self->{basis_columns} = [($n+1)...($n+$m)] unless ref($self->{basis_columns})=~/ARRAY/; + my @rows = $self->assemble_matrix; + $self->M( _Matrix([@rows]) ); #original matrix + $self->{data}= $self->M->data; + my $new_obj_row = $self->objective_row; + $self->{obj_row} = _Matrix($self->objective_row); + # update everything else: + # current_basis_matrix, current_constraint_matrix,current_b + $self->basis($self->basis->value); + + return(); +>>>>>>> Pull updated tableau.pl from fall17mth208/templates/macro/tableau.pl +} + +<<<<<<< HEAD +sub assemble_tableau { +======= +sub assemble_matrix { +>>>>>>> Add tableau.pl + my $self = shift; + my @rows =(); + my $m = $self->m; + my $n = $self->n; + # sanity check for b; + if (ref($self->{b}) =~/Vector/) { + # replace by n by 1 matrix + $self->{b}=Value::Matrix->new([[$self->{b}->value]])->transpose; + } + my ($constraint_rows, $constraint_cols) = $self->{b}->dimensions; + unless ($constraint_rows== $m and $constraint_cols == 1 ) { + Value::Error("constraint matrix b is $constraint_rows by $constraint_cols but should + be $m by 1 to match the constraint matrix A "); + } + + foreach my $i (1..$m) { + my @current_row=(); + foreach my $j (1..$n) { + push @current_row, $self->{A}->element($i, $j)->value; + } +# foreach my $j (1..$m) { +# push @current_row, $self->{S}->element($i,$j)->value; # slack variables +# } + foreach my $j (1..$m) { #FIXME + # push @current_row, $self->{S}->element($i,$j)->value; # slack variables + # FIXME + # temporary fix because $matrix->I is not defined in master branch + push @current_row, ($i==$j)?1:0; #$self->{S}->element($i,$j)->value; # slack variables + } + + push @current_row, 0, $self->{b}->row($i)->value; # obj column and constant column + push @rows, [@current_row]; + } + + return @rows; # these are the matrices A | S | obj | b + # the final row describing the objective function + # is not in this part of the matrix +} + +=head2 Accessors and mutators + +=item basis_columns + + ARRAY reference = $self->basis_columns() + [3,4] = $self->basis_columns([3,4]) + + Sets or returns the basis_columns as an ARRAY reference + +=cut + + +=item objective_row + + $self->objective_row + Parameters: () + Returns: + +=cut + + + +sub objective_row { + my $self = shift; + # sanity check for objective row + Value::Error("The objective row coefficients (c) should be a 1 by n Matrix or a Vector of length n") + unless $self->n == $self->c->length; + my @last_row=(); + push @last_row, ( -($self->c) )->value; # add the negative coefficients of the obj function + foreach my $i (1..($self->m)) { push @last_row, 0 }; # add 0s for the slack variables + push @last_row, 1, 0; # add the 1 for the objective value and 0 for the initial value + return \@last_row; +} + +=item current_tableau + + $self->current_tableau + Parameters: () or (list) + Returns: A MathObjectMatrix + + Useage: + $MathObjectmatrix = $self->current_tableau + $MathObjectmatrix = $self->current_tableau(3,4) #updates basis to (3,4) + +Returns the current constraint matrix as a MathObjectMatrix, +including the constraint constants, +problem variable coefficients, slack variable coefficients AND the +row containing the objective function coefficients. + ------------- + |A | S |0| b| + ------------- + | -c |z|z*| + ------------- + +If a list of basis columns is passed as an argument then $self->basis() +is called to switch the tableau to the new basis before returning +the tableau. + +=cut + +sub current_tableau { + my $self = shift; + Value::Error( "call current_tableau as a Tableau method") unless ref($self)=~/Tableau/; + my @basis = @_; + if (@basis) { + $self->basis(@basis); + } + return _Matrix( @{$self->current_constraint_matrix->extract_rows}, + $self->current_objective_coeffs ); +} + + +=item statevars + + [x1,.....xn,]= $self->statevars() + + + +=cut + +sub statevars { + my $self = shift; + my $matrix = $self->current_tableau; + my $basis =Value::Set->new($self->basis); # a MathObject set + # FIXME + # type check ref($mat)='Matrix'; ref($basis)='Set'; + # or check that $mat has dimensions, element methods; and $basis has a contains method + my ($m,$n) = $matrix->dimensions; + # m= number of constraints + 1. + # n = number of constraints + number of variables +2 + @var = (); + #print( "start new matrix $m $n \n"); + #print "tableau is ", $matrix, "\n"; + foreach my $j (1..$n-2) { # the last two columns of the tableau are object variable and constants + if (not $basis->contains($j)) { + #DEBUG_MESSAGE( "j= $j not in basis"); + $var[$j-1]=0; next; # non-basis variables (parameters) are set to 0. + + } else { + foreach my $i (1..$m-1) { # the last row is the objective function + # if this is a basis column there should be only one non-zero element(the pivot) + if ( not $matrix->element($i,$j) == 0 ) { # should this have ->value????? + $var[$j-1] = ($matrix->element($i,$n)/$matrix->element($i,$j))->value; + #DEBUG_MESSAGE("i=$i j=$j var = $var[$j-1] "); + next; + } + + } + } + } # element($n, $m-1) is the coefficient of the objective value. + # this last variable is the value of the objective function + push @var , ($matrix->element($m,$n)/$matrix->element($m,$n-1))->value; + + [@var]; +} + +=item basis + + MathObjectList = $self->basis + MathObjectList = $self->basis(3,4) + MathObjectList = $self->basis([3,4]) + MathObjectList = $self->basis(Set(3,4)) + MathObjectList = $self->basis(List(3,4)) + + to obtain ARRAY reference use + [3,4]== $self->basis(Set3,4)->value + +Returns a MathObjectList containing the current basis columns. If basis columns +are provided as arguments it updates all elements of the tableau to present +the view corresponding to the new choice of basis columns. + +=cut + +sub basis { + my $self = shift; #update basis + # basis is stored as an ARRAY reference. + # basis is exported as a list + # FIXME should basis be sorted? + Value::Error( "call basis as a Tableau method") unless ref($self)=~/Tableau/; + my @input = @_; + return Value::List->new($self->{basis_columns}) unless @input; #return basis if no input + my $new_basis; + if (ref( $input[0]) =~/ARRAY/) { + $new_basis=$input[0]; + } elsif (ref( $input[0]) =~/List|Set/){ + $new_basis = [$input[0]->value]; + } else { # input is assumed to be an array + $new_basis = \@input; + } + $self->{basis_columns}= $new_basis; # this should always be an ARRAY + main::WARN_MESSAGE("basis $new_basis was not stored as an array reference") + unless ref($new_basis)=~/ARRAY/; + + # form new basis + my $matrix = $self->M->submatrix(rows=>[1..($self->m)],columns=>$self->basis_columns); + my $basis_det = $matrix->det; + if ($basis_det == 0 ){ + Value::Error("The columns ".main::Set($self->basis_columns)." cannot form a basis"); + } + $self->current_basis_matrix( $matrix ); + $self->current_basis_coeff(abs($basis_det)); + + #my $B = $self->current_basis_matrix; #deprecate B + #$self->{current_basis_matrix}= $B; + #main::DEBUG_MESSAGE("basis: B is $B" ); + + my $Badj = ($self->current_basis_coeff) * ($self->current_basis_matrix->inverse); + my $M = $self->{M}; + my ($row_dim, $col_dim) = $M->dimensions; + my $current_constraint_matrix = $Badj*$M; + my $c_B = $self->{obj_row}->extract_columns($self->basis_columns ); + my $c_B2 = Value::Vector->new([ map {$_->value} @$c_B]); + my $correction_coeff = ($c_B2*($current_constraint_matrix) )->row(1); + my $obj_row_normalized = abs($self->{current_basis_matrix}->det->value)*$self->{obj_row}; + my $current_objective_coeffs = $obj_row_normalized-$correction_coeff ; + # updates + $self->{data} = $current_constraint_matrix->data; + $self->{current_constraint_matrix} = $current_constraint_matrix; + $self->{current_objective_coeffs}= $current_objective_coeffs; + $self->current_b( $current_constraint_matrix->column($col_dim) ); + + # the A | S | obj | b + # main::DEBUG_MESSAGE( "basis: current_constraint_matrix $current_constraint_matrix ". + # ref($self->{current_constraint_matrix}) ); + # main::DEBUG_MESSAGE("basis self ",ref($self), "---", ref($self->{basis_columns})); + + return Value::List->new($self->{basis_columns}); +} + + +=item find_next_basis + + ($col1,$col2,..,$flag) = $self->find_next_basis (max/min, obj_row_number) + +In phase 2 of the simplex method calculates the next basis. +$optimum or $unbounded is set +if the process has found on the optimum value, or the column +$col gives a certificate of unboundedness. + +$flag can be either 'optimum' or 'unbounded' in which case the basis returned is the current basis. +is a list of column numbers. + +FIXME Should we change this so that ($basis,$flag) is returned instead? $basis and $flag +are very different things. $basis could be a set or list type but in that case it can't have undef +as an entry. It probably can have '' (an empty string) + +=cut + + +sub find_next_basis { + my $self = shift;Value::Error( "call find_next_basis as a Tableau method") unless ref($self)=~/Tableau/; + my $max_or_min = shift; + my $obj_row_number = shift//1; + my ( $row_index, $col_index, $optimum, $unbounded)= + $self->find_next_pivot($max_or_min, $obj_row_number); + my $flag = undef; + my $basis; + if ($optimum or $unbounded) { + $basis=$self->basis(); + if ($optimum) { + $flag = 'optimum' + } elsif ($unbounded) { + $flag = 'unbounded'} + } else { + Value::Error("At least part of the pivot index (row,col) is not defined") unless + defined($row_index) and defined($col_index); + $basis =$self->find_next_basis_from_pivot($row_index,$col_index); + } + return( $basis->value, $flag ); +} + +=item find_next_pivot + + ($row, $col,$optimum,$unbounded) = $self->find_next_pivot (max/minm obj_row_number) + +This is used in phase2 so the possible outcomes are only $optimum and $unbounded. +$infeasible is not possible. Use the lowest index strategy to find the next pivot +point. This calls find_pivot_row and find_pivot_column. $row and $col are undefined if +either $optimum or $unbounded is set. + +=cut + +sub find_next_pivot { + my $self = shift; + Value::Error( "call find_next_pivot as a Tableau method") unless ref($self)=~/Tableau/; + my $max_or_min = shift; + my $obj_row_number =shift; + + # sanity check max or min in find pivot column + my ($row_index, $col_index, $value, $optimum, $unbounded) = (undef,undef,undef, 0, 0); + ($col_index, $value, $optimum) = $self->find_pivot_column($max_or_min, $obj_row_number); +# main::DEBUG_MESSAGE("find_next_pivot: col: $col_index, value: $value opt: $optimum "); + return ( $row_index, $col_index, $optimum, $unbounded) if $optimum; + ($row_index, $value, $unbounded) = $self->find_pivot_row($col_index); +# main::DEBUG_MESSAGE("find_next pivot row: $row_index, value: $value unbound: $unbounded"); + return($row_index, $col_index, $optimum, $unbounded); +} + + + +=item find_next_basis_from_pivot + + List(basis) = $self->find_next_basis_from_pivot (pivot_row, pivot_column) + +Calculate the next basis from the current basis +given the pivot position. + +=cut + +sub find_next_basis_from_pivot { + my $self = shift; + Value::Error( "call find_next_basis_from_pivot as a Tableau method") unless ref($self)=~/Tableau/; + my $row_index = shift; + my $col_index =shift; + if (Value::Set->new( $self->basis_columns)->contains(Value::Set->new($col_index))){ + Value::Error(" pivot point should not be in a basis column ($row_index, $col_index) ") + } + # sanity check max or min in find pivot column + my $basis = main::Set($self->{basis_columns}); + my ($leaving_col_index, $value) = $self->find_leaving_column($row_index); + $basis = main::Set( $basis - Value::Set->new($leaving_col_index) + main::Set($col_index)); + # main::DEBUG_MESSAGE( "basis is $basis, leaving index $leaving_col_index + # entering index is $col_index"); + #$basis = [$basis->value, Value::Real->new($col_index)]; + return ($basis); +} + + + +=item find_pivot_column + + ($index, $value, $optimum) = $self->find_pivot_column (max/min, obj_row_number) + +This finds the left most obj function coefficient that is negative (for maximizing) +or positive (for minimizing) and returns the value and the index. Only the +index is really needed for this method. The row number is included because there might +be more than one objective function in the table (for example when using +the Auxiliary method in phase1 of the simplex method.) If there is no coefficient +of the appropriate sign then the $optimum flag is set and $index and $value +are undefined. + +=cut + +sub find_pivot_column { + my $self = shift; + Value::Error( "call find_pivot_column as a Tableau method") unless ref($self)=~/Tableau/; + my $max_or_min = shift; + my $obj_row_index = shift; + # sanity check + unless ($max_or_min =~ /max|min/) { + Value::Error( "The optimization method must be + 'max' or 'min'. |$max_or_min| is not defined."); + } + my $obj_row_matrix = $self->{current_objective_coeffs}; + #FIXME $obj_row_matrix is this a 1 by n or an n dimensional matrix?? + my ($obj_col_dim) = $obj_row_matrix->dimensions; + my $obj_row_dim = 1; + $obj_col_dim=$obj_col_dim-2; + #sanity check row + if (not defined($obj_row_index) ) { + $obj_row_index = 1; + } elsif ($obj_row_index<1 or $obj_row_index >$obj_row_dim){ + Value::Error( "The choice for the objective row $obj_row_index is out of range."); + } + #FIXME -- make sure objective row is always a two dimensional matrix, often with one row. + + + my @obj_row = @{$obj_row_matrix->extract_rows($obj_row_index)}; + my $index = undef; + my $optimum = 1; + my $value = undef; + my $zeroLevelTol = $tableauZeroLevel * ($self->current_basis_coeff); +# main::DEBUG_MESSAGE(" coldim: $obj_col_dim , row: $obj_row_index obj_matrix: $obj_row_matrix ".ref($obj_row_matrix) ); +# main::DEBUG_MESSAGE(" \@obj_row ", join(' ', @obj_row ) ); + for (my $k=1; $k<=$obj_col_dim; $k++) { +# main::DEBUG_MESSAGE("find pivot column: k $k, " .$obj_row_matrix->element($k)->value); + + if ( ($obj_row_matrix->element($k) < -$zeroLevelTol and $max_or_min eq 'max') or + ($obj_row_matrix->element($k) > $zeroLevelTol and $max_or_min eq 'min') ) { + $index = $k; #memorize index + $value = $obj_row_matrix->element($k); + # main::diag("value is $value : is zero:=", (main::Real($value) == main::Real(0))?1:0); + $optimum = 0; + last; # found first coefficient with correct sign + } + } + return ($index, $value, $optimum); +} + +=item find_pivot_row + + ($index, $value, $unbounded) = $self->find_pivot_row(col_number) + +Compares the ratio $b[$j]/a[$j, $col_number] and chooses the smallest +non-negative entry. It assumes that we are in phase2 of simplex methods +so that $b[j]>0; If all entries are negative (or infinity) then +the $unbounded flag is set and returned and the $index and $value +quantities are undefined. + +=cut + +sub find_pivot_row { + my $self = shift; + Value::Error( "call find_pivot_row as a Tableau method") unless ref($self)=~/Tableau/; + my $column_index = shift; + my ($row_dim, $col_dim) = $self->{M}->dimensions; + $col_dim = $col_dim-2; # omit the obj_value and constraint columns + # sanity check column_index + unless (1<=$column_index and $column_index <= $col_dim) { + Value::Error( "Column index must be between 1 and $col_dim" ); + } + # main::DEBUG_MESSAGE("dim = ($row_dim, $col_dim)"); + my $value = undef; + my $index = undef; + my $unbounded = 1; + my $zeroLevelTol = $tableauZeroLevel * ($self->current_basis_coeff); + for (my $k=1; $k<=$row_dim; $k++) { + my $m = $self->{current_constraint_matrix}->element($k,$column_index); + # main::DEBUG_MESSAGE(" m[$k,$column_index] is ", $m->value); + next if $m <=$zeroLevelTol; + my $b = $self->{current_b}->element($k,1); + # main::DEBUG_MESSAGE(" b[$k] is ", $b->value); + # main::DEBUG_MESSAGE("finding pivot row in column $column_index, row: $k ", ($b/$m)->value); + if ( not defined($value) or $b/$m < $value-$zeroLevelTol) { # want first smallest value + $value = $b/$m; + $index = $k; # memorize index + $unbounded = 0; + } + } + return( $index, $value, $unbounded); +} + + + + +=item find_leaving_column + + ($index, $value) = $self->find_leaving_column(obj_row_number) + +Finds the non-basis column with a non-zero entry in the given row. When +called with the pivot row number this index gives the column which will +be removed from the basis while the pivot col number gives the basis +column which will become a parameter column. + +=cut + +sub find_leaving_column { + my $self = shift; + Value::Error( "call find_leaving_column as a Tableau method") unless ref($self)=~/Tableau/; + my $row_index = shift; + my ($row_dim,$col_dim) = $self->{current_constraint_matrix}->dimensions; + $col_dim= $col_dim - 1; # both problem and slack variables are included + # but not the constraint column or the obj_value column(s) (the latter are zero) + + #sanity check row index; + unless (1<=$row_index and $row_index <= $row_dim) { + Value::Error("The row number must be between 1 and $row_dim" ); + } + my $basis = main::Set($self->{basis_columns}); + my $index = 0; + my $value = undef; + foreach my $k (1..$col_dim) { + next unless $basis->contains(main::Set($k)); + $m_ik = $self->{current_constraint_matrix}->element($row_index, $k); + # main::DEBUG_MESSAGE("$m_ik in col $k is close to zero ", $self->close_enough_to_zero($m_ik)); + next if $self->close_enough_to_zero($m_ik); + # main::DEBUG_MESSAGE("leaving column is $k"); + $index = $k; # memorize index + $value = $m_ik; + last; + } + return( $index, $value); +} + +=item next_short_cut_pivot + + ($row, $col, $feasible, $infeasible) = $self->next_short_cut_pivot + + +Following the short-cut algorithm this chooses the next pivot by choosing the row +with the most negative constraint constant entry (top most first in case of tie) and +then the left most negative entry in that row. + +The process stops with either $feasible=1 (state variables give a feasible point for the +constraints) or $infeasible=1 (a row in the tableau shows that the LOP has empty domain.) + +=cut + +sub next_short_cut_pivot { + my $self = shift; + Value::Error( "call next_short_cut_pivot as a Tableau method") unless ref($self)=~/Tableau/; + + my ($col_index, $value, $row_index, $feasible_point, $infeasible_lop) = ('','','',''); + ($row_index, $value, $feasible_point) = $self->find_short_cut_row(); + if ($feasible_point) { + $row_index=undef; $col_index=undef; $infeasible_lop=0; + } else { + ($col_index, $value, $infeasible_lop) = $self->find_short_cut_column($row_index); + if ($infeasible_lop){ + $row_index=undef; $col_index=undef; $feasible_point=0; + } + } + return($row_index, $col_index, $feasible_point, $infeasible_lop); +} + +=item next_short_cut_basis + + ($basis->value, $flag) = $self->next_short_cut_basis() + +In phase 1 of the simplex method calculates the next basis for the short cut method. +$flag is set to 'feasible_point' if the basis and its corresponding tableau is associated with a basic feasible point +(a point on a corner of the domain of the LOP). The tableau is ready for phase 2 processing. +$flag is set to 'infeasible_lop' which means that the tableau has +a row which demonstrates that the LOP constraints are inconsistent and the domain is empty. +In these cases the basis returned is the current basis of the tableau object. + +Otherwise the $basis->value returned is the next basis that should be used in the short_cut method +and $flag contains undef. + + +=cut + + +sub next_short_cut_basis { + my $self = shift; + Value::Error( "call next_short_cut_basis as a Tableau method") unless ref($self)=~/Tableau/; + + my ( $row_index, $col_index, $feasible_point, $infeasible_lop)= + $self->next_short_cut_pivot(); + my $basis; + $flag = undef; + if ($feasible_point or $infeasible_lop) { + $basis=$self->basis(); + if ($feasible_point) { + $flag = 'feasible_point'; #should be feasible_lop ? + } elsif ($infeasible_lop){ + $flag = 'infeasible_lop'; + } + } else { + Value::Error("At least part of the pivot index (row,col) is not defined") unless + defined($row_index) and defined($col_index); + $basis =$self->find_next_basis_from_pivot($row_index,$col_index); + } + return( $basis->value, $flag ); + +} + +=item find_short_cut_row + + ($index, $value, $feasible)=$self->find_short_cut_row + +Find the most negative entry in the constraint column vector $b. If all entries +are positive then the tableau represents a feasible point, $feasible is set to 1 +and $index and $value are undefined. + +=cut + +sub find_short_cut_row { + my $self = shift; + Value::Error( "call find_short_cut_row as a Tableau method") unless ref($self)=~/Tableau/; + my ($row_dim, $col_dim) = $self->{current_b}->dimensions; + my $col_index = 1; # =$col_dim + my $index = undef; + my $value = undef; + my $feasible = 1; + my $zeroLevelTol = $tableauZeroLevel * ($self->current_basis_coeff); + for (my $k=1; $k<=$row_dim; $k++) { + my $b_k1 = $self->current_b->element($k,$col_index); + #main::diag("b[$k] = $b_k1"); + next if $b_k1>=-$zeroLevelTol; #skip positive entries; + if ( not defined($value) or $b_k1 < $value) { + $index =$k; + $value = $b_k1; + $feasible = 0; #found at least one negative entry in the row + } + } + return ( $index, $value, $feasible); +} + +=item find_short_cut_column + + ($index, $value, $infeasible) = $self->find_short_cut_column(row_index) + +Find the left most negative entry in the specified row. If all coefficients are +positive then the tableau represents an infeasible LOP, the $infeasible flag is set, +and the $index and $value are undefined. + +=cut + +sub find_short_cut_column { + my $self = shift; + Value::Error( "call find_short_cut_column as a Tableau method") unless ref($self)=~/Tableau/; + my $row_index = shift; + my ($row_dim,$col_dim) = $self->{M}->dimensions; + $col_dim = $col_dim - 1; # omit constraint column + # FIXME to adjust for additional obj_value columns + #sanity check row index + unless (1<= $row_index and $row_index <= $row_dim) { + Value::Error("The row must be between 1 and $row_dim"); + } + my $index = undef; + my $value = undef; + my $infeasible = 1; + for (my $k = 1; $k<=$col_dim; $k++ ) { + my $m_ik = $self->{current_constraint_matrix}->element($row_index, $k); + # main::DEBUG_MESSAGE( "in M: ($row_index, $k) contains $m_ik"); + next if $m_ik >=0; + $index = $k; + $value = $m_ik; + $infeasible = 0; + last; + } + return( $index, $value, $infeasible); +} + + + + + + +=item row_reduce + +(or tableau pivot???) + + Tableau = $self->row_reduce(3,4) + MathObjectMatrix = $self->row_reduce(3,4)->current_tableau + + +Row reduce matrix so that column 4 is a basis column. Used in +pivoting for simplex method. Returns tableau object. + +=cut +sub row_reduce { + my $self = shift; + Value::Error( "call row_reduce as a Tableau method") unless ref($self)=~/Tableau/; + my ($row_index, $col_index, $basisCoeff); + # FIXME is $basisCoeff needed? isn't it always the same as $self->current_basis_coeff? + my @input = @_; + if (ref( $input[0]) =~/ARRAY/) { + ($row_index, $col_index) = @{$input[0]}; + } elsif (ref( $input[0]) =~/List|Set/){ + ($row_index, $col_index) = @{$input[0]->value}; + } else { # input is assumed to be an array + ($row_index, $col_index)=@input; + } + # calculate new basis + my $new_basis_columns = $self->find_next_basis_from_pivot($row_index,$col_index); + # form new basis + my $basis_matrix = $self->M->submatrix(rows=>[1..($self->m)],columns=>$self->$new_basis_columns); + my $basis_det = $basis_matrix->det; + if ($basis_det == 0 ){ + Value::Error("The columns ", join(",", @$new_basis_columns)." cannot form a basis"); + } + # updates + $self->basis_columns($new_basis_columns); + $self->current_basis_coeff($basis_det); + # this should always be an ARRAY + $basisCoeff=$basisCoeff || $self->{current_basis_coeff} || 1; + #basis_coeff should never be zero. + Value::Error( "need to specify the pivot point for row_reduction") unless $row_index && $col_index; + my $matrix = $self->current_constraint_matrix; + my $pivot_value = $matrix->entry($row_index,$col_index); + Value::Error( "pivot value cannot be zero") if $matrix->entry($row_index,$col_index)==0; + # make pivot value positive + if($pivot_value < 0) { + foreach my $j (1..$self->m) { + $matrix->entry($row_index, $j) *= -1; + } + } + # perform row reduction to clear out column $col_index + foreach my $i (1..$self->m){ + if ($i !=$row_index) { # skip pivot row + my $row_value_in_pivot_col = $matrix->entry($i,$col_index); + foreach my $j (1..$self->n){ + my $new_value = ( + ($pivot_value)*($matrix->entry($i,$j)) + -$row_value_in_pivot_col*($matrix->entry($row_index,$j)) + )/$basisCoeff; + $matrix->change_matrix_entry($i,$j, $new_value); + } + } + + } + $self->{basis_coeff} = $pivot_value; + return $self; +} +# eventually these routines should be included in the Value::Matrix +# module? + + +=item dual_problem + + TableauObject = $self->dual_lop + +Creates the tableau of the LOP which is dual to the linear optimization problem represented by the +current tableau. + +=cut + +sub dual_lop { + my $self = shift; + my $newA = $self->A->transpose; # converts m by n matrix to n by m matrix + my $newb = $self->c; # gives a 1 by n matrix + $newb = $newb->transpose; # converts to an n by 1 matrix + my $newc = $self->b; # gives an m by 1 matrix + $newc = _Matrix( $newc->transpose->value ); # convert to a 1 by m matrix + my $newt = Tableau->new(A=>-$newA, b=>-$newb, c=>$newc); + # rewrites the constraints as negative + # the dual cost function is to be minimized. + $newt; +} + +=pod + +These are specialized routines used in the simplex method + +=cut + + +=item primal2dual + + @array = $self->primal2dual(2,3,4) + +Maps LOP column indices to dual LOP indicies (basis of complementary slack property) + + +=cut + +=item dual2primal + + @array = $self->dual2primal(2,3,4) + +Maps dual LOP column indices to primal LOP indicies (basis of complementary slack property). +Inverse of primal2dual method. + + +=cut + +sub primal2dual { + my $self = shift; + my $n = $self->n; + my $m = $self->m; + $p2d_translate = sub { + my $i = shift; + if ($i<=$n and $i>0) { + return $m +$i; + } elsif ($i > $n and $i<= $n+$m) { + return $i-$n + } else { + Value::Error("index $i is out of range"); + } + }; + my @array = @_; + return (map {&$p2d_translate($_)} @array); #accepts list of numbers +} + + +sub dual2primal { + my $self = shift; + my $n = $self->n; + my $m = $self->m; + $d2p_translate = sub { + my $j = shift; + if ($j<=$m and $j>0) { + return $n+$j; + } elsif ($j>$m and $j<= $n+$m) { + return $j-$m + }else { + Value::Error("index $j is out of range"); + } + }; + my @array = @_; + return (map {&$d2p_translate($_)} @array); #accepts list of numbers +} + + + +=item isOptimal + + $self->isOptimal('min'| 'max') + Returns 1 or 0 + +This checks to see if the state is a local minimum or maximum for the objective function + -- it does not check whether the stateis feasible. + + +=cut + +sub isOptimal { + my $self = shift; + Value::Error( "call isOptimalMin as a Tableau method") unless ref($self)=~/Tableau/; + my $max_or_min = shift; + my ($index, $value, $optimum) = $self->find_pivot_column($max_or_min); + return $optimum; # returns 1 or 0 +} + +=item isFeasible + + +Checks to see if the current state is feasible or whether it requires further phase 1 processing. + +=cut + + + +sub isFeasible { + my $self = shift; + Value::Error( "call isFeasible as a Tableau method") unless ref($self)=~/Tableau/; + my ($index, $value, $feasible)= $self->find_short_cut_row; + return $feasible; # returns 1 or 0 +} + + + +=pod + +These are generic matrix routines. Perhaps some or all of these should +be added to the file Value::Matrix? + +=cut + +package Value::Matrix; + +sub _Matrix { + Value::Matrix->new(@_); +} +<<<<<<< HEAD +<<<<<<< HEAD + +#FIXME -- I think these need default values for slice + +sub extract_rows { # preferable to use row slice +======= +sub extract_rows { +>>>>>>> Add tableau.pl + $self = shift; +======= + +=item row_slice + + $self->row_slice + + Parameter: @slice or \@slice + Return: MathObject matrix + + MathObjectMatrix = $self->row_slice(3,4) + MathObjectMatrix = $self->row_slice([3,4]) + +Similar to $self->extract_rows (or $self->rows) but returns a MathObjectmatrix + +=cut + +sub row_slice { + my $self = shift; + @slice = @_; + return _Matrix( $self->extract_rows(@slice) ); +} + +=item extract_rows + + $self->extract_rows + + Parameter: @slice or \@slice + Return: two dimensional array ref + + ARRAY reference = $self->extract_rows(@slice) + ARRAY reference = $self->extract_rows([@slice]) + +=cut + +sub extract_rows { + my $self = shift; +>>>>>>> Pull updated tableau.pl from fall17mth208/templates/macro/tableau.pl + my @slice = @_; + if (ref($slice[0]) =~ /ARRAY/) { # handle array reference + @slice = @{$slice[0]}; + } elsif (@slice == 0) { # export all rows to List + @slice = ( 1..(($self->dimensions)[0]) ); + } + return [map {$self->row($_)} @slice ]; #prefer to pass references when possible +} + +<<<<<<< HEAD +<<<<<<< HEAD +sub extract_columns { # preferable to use row slice +======= +sub extract_columns { +>>>>>>> Add tableau.pl + $self = shift; +======= +=item column_slice + + $self->column_slice() + + Parameter: @slice or \@slice + Return: two dimensional array ref + + ARRAY reference = $self->extract_rows(@slice) + ARRAY reference = $self->extract_rows([@slice]) + +=cut + +sub column_slice { + my $self = shift; + return _Matrix( $self->extract_columns(@_) )->transpose; # matrix is built as rows then transposed. +} + +=item extract_columns + + $self->extract_columns + + Parameter: @slice or \@slice + Return: two dimensional array ref + + ARRAY reference = $self->extract_columns(@slice) + ARRAY reference = $self->extract_columns([@slice]) + +=cut + +sub extract_columns { + my $self = shift; +>>>>>>> Pull updated tableau.pl from fall17mth208/templates/macro/tableau.pl + my @slice = @_; + if (ref($slice[0]) =~ /ARRAY/) { # handle array reference + @slice = @{$slice[0]}; + } elsif (@slice == 0) { # export all columns to an array + @slice = ( 1..(($self->dimensions)[1] ) ); + } + return [map { $self->transpose->row($_) } @slice] ; + # returns the columns as an array of 1 by n row matrices containing values + # if you pull columns directly you get an array of 1 by n column vectors. + # prefer to pass references when possible +} + +=item extract_rows_to_list + + Parameter: @slice or \@slice + Return: MathObject List of row references + + MathObjectList = $self->extract_rows_to_list(@slice) + MathObjectList = $self->extract_rows_to_list([@slice]) + +=cut + +sub extract_rows_to_list { + my $self = shift; + Value::List->new($self->extract_rows(@_)); +} + +=item extract_columns_to_list + + $self->extract_columns_to_list + + Parameter: @slice or \@slice + Return: MathObject List of Matrix references ? + + ARRAY reference = $self->extract_columns_to_list(@slice) + ARRAY reference = $self->extract_columns_to_list([@slice]) + +=cut + +sub extract_columns_to_list { + my $self = shift; + Value::List->new($self->extract_columns(@_) ); +} + +=item submatrix + + $self->submatrix + + Parameter:(rows=>\@row_slice,columns=>\@column_slice) + Return: MathObject matrix + + MathObjectMatrix = $self->submatrix([[1,2,3],[2,4,5]]) + +Extracts a submatrix from a Matrix and returns it as MathObjectMatrix. + +Indices for MathObjectMatrices start at 1. + +=cut + +sub submatrix { + my $self = shift; + my %options = @_; + my($m,$n) = $self->dimensions; + my $row_slice = ($options{rows})?$options{rows}:[1..$m]; + my $col_slice = ($options{columns})?$options{columns}:[1..$n]; + return $self->row_slice($row_slice)->column_slice($col_slice); +} + + + +=item change_matrix_entry + + $Matrix->change_matrix_entry([i,j,k],$value) + + Taken from MatrixReduce.pl. Written by Davide Cervone. + + perhaps "assign" would be a better name for this? + +=cut + +# This was written by Davide Cervone. +# http://webwork.maa.org/moodle/mod/forum/discuss.php?d=2970 +# taken from MatrixReduce.pl from Paul Pearson + +sub change_matrix_entry { + my $self = shift; my $index = shift; my $x = shift; + my $i = shift(@$index) - 1; + if (scalar(@$index)) {change_matrix_entry($self->{data}[$i],$index,$x);} + else {$self->{data}[$i] = Value::makeValue($x); + } +} + + +1; diff --git a/macros/tableau_main_subroutines.pl b/macros/tableau_main_subroutines.pl new file mode 100644 index 0000000000..5752b2e3de --- /dev/null +++ b/macros/tableau_main_subroutines.pl @@ -0,0 +1,199 @@ +# subroutines included into the main:: package. + +package main; + +sub isMatrix { + my $m = shift; + return ref($m) =~/Value::Matrix/i; +} +sub matrix_column_slice{ + matrix_from_matrix_cols(@_); +} + +sub lp_basis_pivot { + my ($old_tableau,$old_basis,$pivot) = @_; # $pivot is a Value::Point + my $new_tableau= lp_clone($old_tableau); + main::lp_pivot($new_tableau, $pivot->extract(1)-1,$pivot->extract(2)-1); + my $new_matrix = Matrix($new_tableau); + my ($n,$m) = $new_matrix->dimensions; + my $param_size = $m-$n -1; #n=constraints+1, #m = $param_size + $constraints +2 + my $new_basis = ( $old_basis - ($pivot->extract(1)+$param_size) + ($pivot->extract(2)) )->sort; + my @statevars = get_tableau_variable_values($new_matrix, $new_basis); + return ( $new_tableau, Set($new_basis),\@statevars); #FIXME -- force to set (from type Union) to insure that ->data is an array and not a string. +} + +sub matrix_from_matrix_cols { + my $M = shift; # a MathObject matrix_columns + my($n,$m) = $M->dimensions; + my @slice = @_; + if (ref($slice[0]) =~ /ARRAY/) { # handle array reference + @slice = @{$slice[0]}; + } + @slice = @slice?@slice : (1..$m); + my @columns = map {$M->column($_)->transpose->value} @slice; + #create the chosen columns as rows + # then transform to array_refs. + Matrix(@columns)->transpose; #transpose and return an n by m matrix (2 dim) +} +sub matrix_row_slice{ + matrix_from_matrix_rows(@_); +} + +sub matrix_from_matrix_rows { + my $M = shift; # a MathObject matrix_columns + unless (isMatrix($M)){ + WARN_MESSAGE( "matrix_from_matrix_rows: |".ref($M)."| or |$M| is not a MathObject Matrix"); + return undef; + } + + my($n,$m) = $M->dimensions; + my @slice = @_; + if (ref($slice[0]) =~ /ARRAY/) { # handle array reference + @slice = @{$slice[0]}; + } + @slice = @slice? @slice : (1..$n); # the default is the whole matrix. + # DEBUG_MESSAGE("row slice in matrix from rows is @slice"); + my @rows = map {[$M->row($_)->value]} @slice; + #create the chosen columns as rows + # then transform to array_refs. + Matrix([@rows]); # insure that it is still an n by m matrix (2 dim) +} + +sub matrix_extract_submatrix { + matrix_from_submatrix(@_); +} +sub matrix_from_submatrix { + my $M=shift; + unless (isMatrix($M)){ + warn( "matrix_from_submatrix: |".ref($M)."| or |$M| is not a MathObject Matrix"); + return undef; + } + + my %options = @_; + my($n,$m) = $M->dimensions; + my $row_slice = ($options{rows})?$options{rows}:[1..$m]; + my $col_slice = ($options{columns})?$options{columns}:[1..$n]; + # DEBUG_MESSAGE("ROW SLICE", join(" ", @$row_slice)); + # DEBUG_MESSAGE("COL SLICE", join(" ", @$col_slice)); + my $M1 = matrix_from_matrix_rows($M,@$row_slice); + # DEBUG_MESSAGE("M1 - matrix from rows) $M1"); + return matrix_from_matrix_cols($M1, @$col_slice); +} +sub matrix_extract_rows { + my $M =shift; + unless (isMatrix($M)){ + WARN_MESSAGE( "matrix_extract_rows: |".ref($M)."| or |$M| is not a MathObject Matrix"); + return undef; + } + + my @slice = @_; + if (ref($slice[0]) =~ /ARRAY/) { # handle array reference + @slice = @{$slice[0]}; + } elsif (@slice == 0) { # export all rows to List + @slice = ( 1..(($M->dimensions)[0]) ); + } + return map {$M->row($_)} @slice ; +} + +sub matrix_rows_to_list { + List(matrix_extract_rows(@_)); +} +sub matrix_columns_to_list { + List(matrix_extract_columns(@_) ); +} +sub matrix_extract_columns { + my $M =shift; # Add error checking + unless (isMatrix($M)){ + WARN_MESSAGE( "matrix_extract_columns: |".ref($M)."| or |$M| is not a MathObject Matrix"); + return undef; + } + + my @slice = @_; + if (ref($slice[0]) =~ /ARRAY/) { # handle array reference + @slice = @{$slice[0]}; + } elsif (@slice == 0) { # export all columns to an array + @slice = 1..($M->dimensions->[1]); + } + return map {$M->column($_)} @slice; +} + + + +######################## +############## +# get_tableau_variable_values +# +# Calculates the values of the basis variables of the tableau, +# assuming the parameter variables are 0. +# +# Usage: ARRAY = get_tableau_variable_values($MathObjectMatrix_tableau, $MathObjectSet_basis) +# +# feature request -- for tableau object -- allow specification of non-zero parameter variables +sub get_tableau_variable_values { + my $mat = shift; # a MathObject matrix + unless (isMatrix($mat)){ + WARN_MESSAGE( "get_tableau_variable_values: |".ref($mat)."| or |$mat| is not a MathObject Matrix"); + return Matrix([0]); + } + my $basis =shift; # a MathObject set + # FIXME + # type check ref($mat)='Matrix'; ref($basis)='Set'; + # or check that $mat has dimensions, element methods; and $basis has a contains method + my ($n, $m) = $mat->dimensions; + @var = (); + #DEBUG_MESSAGE( "start new matrix"); + foreach my $j (1..$m-2) { # the last two columns of the tableau are object variable and constants + if (not $basis->contains($j)) { + # DEBUG_MESSAGE( "j= $j not in basis"); # set the parameter values to zero + $var[$j-1]=0; next; # non-basis variables (parameters) are set to 0. + + } else { + foreach my $i (1..$n-1) { # the last row is the objective function + # if this is a basis column there should be only one non-zero element(the pivot) + if ( $mat->element($i,$j)->value != 0 ) { # should this have ->value????? + $var[$j-1] = ($mat->element($i,$m)/($mat->element($i,$j))->value); + # DEBUG_MESSAGE("i=$i j=$j var = $var[$j-1] "); # calculate basis variable value + next; + } + + } + } + } # element($n, $m-1) is the coefficient of the objective value. + # this last variable is the value of the objective function + # check for division by zero + if ($mat->element($n,$m-1)->value != 0 ) { + push @var , ($mat->element($n,$m)/$mat->element($n,$m-1))->value; + } else { + push @var , '.666'; + } + return wantarray ? @var : \@var; # return either array or reference to an array +} +#### Test -- assume matrix is this +# 1 2 1 0 0 | 0 | 3 +# 4 5 0 1 0 | 0 | 6 +# 7 8 0 0 1 | 0 | 9 +# -1 -2 0 0 0 | 1 | 10 # objective row +# and basis is {3,4,5} (start columns with 1) +# $n= 4; $m = 7 +# $x1=0; $x2=0; $x3=s1=3; $x4=s2=6; $x5=s3=9; w=10=objective value +# +# + +#################################### +# +# Cover for lp_pivot which allows us to use a set object for the new and old basis + +sub lp_basis_pivot { + my ($old_tableau,$old_basis,$pivot) = @_; # $pivot is a Value::Point + my $new_tableau= lp_clone($old_tableau); + # lp_pivot has 0 based indices + main::lp_pivot($new_tableau, $pivot->extract(1)-1,$pivot->extract(2)-1); + # lp_pivot pivots in place + my $new_matrix = Matrix($new_tableau); + my ($n,$m) = $new_matrix->dimensions; + my $param_size = $m-$n -1; #n=constraints+1, #m = $param_size + $constraints +2 + my $new_basis = ( $old_basis - ($pivot->extract(1)+$param_size) + ($pivot->extract(2)) )->sort; + my @statevars = get_tableau_variable_values($new_matrix, $new_basis); + return ( $new_tableau, Set($new_basis),\@statevars); + # force to set (from type Union) to insure that ->data is an array and not a string. +} diff --git a/t/embedded.html b/t/embedded.html new file mode 100644 index 0000000000..a9229cf777 --- /dev/null +++ b/t/embedded.html @@ -0,0 +1,242 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+

Edit in JSFiddle

+ +
+ +
+
+
+ +
+ + + +
         $(function() {
+            $( "#dialog-1" ).dialog({
+               autoOpen: false,  
+            });
+
+            var name;
+            //= $("#dialog-1").attr("name");
+            
+            $( ".opener" ).click(function() {
+               console.log(this.name );
+               name = this.name
+               //$("#matrix_input").value= "7 5 4 3 2\n 1 2 3 4 5";
+               $("textarea#matrix_input").val("7 5 4 3 2\n 1 2 3 4 5");
+               $( "#dialog-1" ).dialog( "open" );
+               
+            });
+            //console.log("name is " + name );
+            //console.log("rows="+$("#dialog-1").attr("rows")+ " columns= "+$("#dialog-1").attr("columns"));
+            var insert_value = function(name, i,j,entry) {
+            	 var pos = "#MaTrIx_"+name+"_"+i+"_"+j;
+               if (i==0 && j==0 ) {
+               	pos= "#"+name;
+               }  //MaTrIx_AnSwEr0007_0_3
+								 //console.log($(pos).val());
+	     				$(pos).val(entry); //instead of 4000
+  					}
+    
+            $( "#closer" ).click(function() {
+               //var name="AnSwEr0007";
+               var mat=$("textarea#matrix_input").val();
+               var mat2=mat.split(/\n/);
+               var mat3=[];
+               for (i=0; i<mat2.length; i++) {
+               		mat3.push( mat2[i].split(/\s+/) );
+               }
+               for (i=0; i<mat3.length; i++) {
+               	  for(j=0; j<mat3[i].length; j++){
+                  	insert_value(name,i,j,mat3[i][j]);
+                  }		
+               }
+               $( "#dialog-1" ).dialog( "close" );
+            });
+         });
+// dialog is attached to div with id="dialog-1"
+// it is opened when button with id #opener is clicked
+// now to add the entry mechanism
+ + + + + +
 <div id="dialog-1" name="AnSwEr0007" title="Enter 5 by 10 matrix"
+ rows="5" columns="10">
+  <textarea id = "matrix_input" rows="5" columns = "10" value="foobar"> this is supposed to be updated
+  </textarea>
+  <button id="closer">Enter
+  </button>
+ </div>
+<button class="opener" id="007" name="AnSwEr0007">Quick matrix entry</button>
+<div>
+
+<button class="opener" id="008" name="AnSwEr0008">Quick matrix entry</button>
+<div>
+<span class="ans_array" style="display:inline-block;vertical-align:.5ex">
+ <span class="ans_array_open" style="display:inline-block; vertical-align:middle; margin-right:4px"><span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-10-Frame" tabindex="0" data-mathml="<math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;><mrow><mo>[</mo><mpadded width=&quot;0pt&quot; height=&quot;6em&quot; depth=&quot;0pt&quot;><mrow /></mpadded><mo fence=&quot;true&quot; stretchy=&quot;true&quot;></mo></mrow></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-89" role="math" style="width: 0.598em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.479em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(2.027em 1000.48em 15.36em -999.997em); top: -8.926em; left: 0.003em;"><span class="mrow" id="MathJax-Span-90"><span class="mrow" id="MathJax-Span-91"><span class="mo" id="MathJax-Span-92" style="vertical-align: 6.729em;"><span style="display: inline-block; position: relative; width: 0.479em; height: 0px;"><span style="position: absolute; font-family: STIXSizeOneSym; top: -3.33em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; font-family: STIXSizeOneSym; top: 8.693em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: -2.378em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: -1.485em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: -0.533em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 0.36em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 1.313em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 2.265em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 3.158em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 4.11em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 5.003em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 5.955em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 6.848em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 7.801em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span class="mpadded" id="MathJax-Span-93"><span style="display: inline-block; position: relative; width: 0.003em; height: 0px;"><span style="position: absolute; clip: rect(3.812em 1000em 4.17em -999.997em); top: -3.985em; left: 0.003em;"><span class="mrow" id="MathJax-Span-94"><span class="mrow" id="MathJax-Span-95"></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span class="mo" id="MathJax-Span-96"></span></span></span><span style="display: inline-block; width: 0px; height: 8.932em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -7.568em; border-left: 0px solid; width: 0px; height: 15.718em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mrow><mo>[</mo><mpadded width="0pt" height="6em" depth="0pt"><mrow></mrow></mpadded><mo fence="true" stretchy="true"></mo></mrow></math></span></span><script type="math/tex" id="MathJax-Element-10">\left[\Rule{0pt}{6em}{0pt}\right.</script></span><span class="ans_array_table" style="display:inline-table; vertical-align:middle"><span style="display:table-row"><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;">p1</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;">p2</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;">x3</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;">x4</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;">x5</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;">x6</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;">P</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;">b</span></span><span style="display:table-row"><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="text" class="codeshard" size="6" name="AnSwEr0007" id="AnSwEr0007" aria-label="answer 7 row 1 column 1 " value="0">
+<input type="hidden" name="previous_AnSwEr0007" value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_0_1" id="MaTrIx_AnSwEr0007_0_1" class="codeshard" aria-label="answer 7 row 1 column 2 " value="4000">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_0_2" id="MaTrIx_AnSwEr0007_0_2" class="codeshard" aria-label="answer 7 row 1 column 3 " value="1">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_0_3" id="MaTrIx_AnSwEr0007_0_3" class="codeshard" aria-label="answer 7 row 1 column 4 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_0_4" id="MaTrIx_AnSwEr0007_0_4" class="codeshard" aria-label="answer 7 row 1 column 5 " value="-5000">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_0_5" id="MaTrIx_AnSwEr0007_0_5" class="codeshard" aria-label="answer 7 row 1 column 6 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_0_6" id="MaTrIx_AnSwEr0007_0_6" class="codeshard" aria-label="answer 7 row 1 column 7 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_0_7" id="MaTrIx_AnSwEr0007_0_7" class="codeshard" aria-label="answer 7 row 1 column 8 " value="1000">
+</span></span><span style="display:table-row"><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_1_0" id="MaTrIx_AnSwEr0007_1_0" class="codeshard" aria-label="answer 7 row 2 column 1 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_1_1" id="MaTrIx_AnSwEr0007_1_1" class="codeshard" aria-label="answer 7 row 2 column 2 " value="500">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_1_2" id="MaTrIx_AnSwEr0007_1_2" class="codeshard" aria-label="answer 7 row 2 column 3 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_1_3" id="MaTrIx_AnSwEr0007_1_3" class="codeshard" aria-label="answer 7 row 2 column 4 " value="1">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_1_4" id="MaTrIx_AnSwEr0007_1_4" class="codeshard" aria-label="answer 7 row 2 column 5 " value="-400">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_1_5" id="MaTrIx_AnSwEr0007_1_5" class="codeshard" aria-label="answer 7 row 2 column 6 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_1_6" id="MaTrIx_AnSwEr0007_1_6" class="codeshard" aria-label="answer 7 row 2 column 7 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_1_7" id="MaTrIx_AnSwEr0007_1_7" class="codeshard" aria-label="answer 7 row 2 column 8 " value="200">
+</span></span><span style="display:table-row"><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_2_0" id="MaTrIx_AnSwEr0007_2_0" class="codeshard" aria-label="answer 7 row 3 column 1 " value="1">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_2_1" id="MaTrIx_AnSwEr0007_2_1" class="codeshard" aria-label="answer 7 row 3 column 2 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_2_2" id="MaTrIx_AnSwEr0007_2_2" class="codeshard" aria-label="answer 7 row 3 column 3 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_2_3" id="MaTrIx_AnSwEr0007_2_3" class="codeshard" aria-label="answer 7 row 3 column 4 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_2_4" id="MaTrIx_AnSwEr0007_2_4" class="codeshard" aria-label="answer 7 row 3 column 5 " value="1">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_2_5" id="MaTrIx_AnSwEr0007_2_5" class="codeshard" aria-label="answer 7 row 3 column 6 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_2_6" id="MaTrIx_AnSwEr0007_2_6" class="codeshard" aria-label="answer 7 row 3 column 7 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_2_7" id="MaTrIx_AnSwEr0007_2_7" class="codeshard" aria-label="answer 7 row 3 column 8 " value="1">
+</span></span><span style="display:table-row"><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_3_0" id="MaTrIx_AnSwEr0007_3_0" class="codeshard" aria-label="answer 7 row 4 column 1 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_3_1" id="MaTrIx_AnSwEr0007_3_1" class="codeshard" aria-label="answer 7 row 4 column 2 " value="1">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_3_2" id="MaTrIx_AnSwEr0007_3_2" class="codeshard" aria-label="answer 7 row 4 column 3 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_3_3" id="MaTrIx_AnSwEr0007_3_3" class="codeshard" aria-label="answer 7 row 4 column 4 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_3_4" id="MaTrIx_AnSwEr0007_3_4" class="codeshard" aria-label="answer 7 row 4 column 5 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_3_5" id="MaTrIx_AnSwEr0007_3_5" class="codeshard" aria-label="answer 7 row 4 column 6 " value="1">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_3_6" id="MaTrIx_AnSwEr0007_3_6" class="codeshard" aria-label="answer 7 row 4 column 7 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_3_7" id="MaTrIx_AnSwEr0007_3_7" class="codeshard" aria-label="answer 7 row 4 column 8 " value="1">
+</span></span><span style="display:table-row"><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_4_0" id="MaTrIx_AnSwEr0007_4_0" class="codeshard" aria-label="answer 7 row 5 column 1 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_4_1" id="MaTrIx_AnSwEr0007_4_1" class="codeshard" aria-label="answer 7 row 5 column 2 " value="-4500">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_4_2" id="MaTrIx_AnSwEr0007_4_2" class="codeshard" aria-label="answer 7 row 5 column 3 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_4_3" id="MaTrIx_AnSwEr0007_4_3" class="codeshard" aria-label="answer 7 row 5 column 4 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_4_4" id="MaTrIx_AnSwEr0007_4_4" class="codeshard" aria-label="answer 7 row 5 column 5 " value="4500">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_4_5" id="MaTrIx_AnSwEr0007_4_5" class="codeshard" aria-label="answer 7 row 5 column 6 " value="0">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_4_6" id="MaTrIx_AnSwEr0007_4_6" class="codeshard" aria-label="answer 7 row 5 column 7 " value="1">
+</span><span class="ans_array_sep" style="display:table-cell;vertical-align:middle;width:8px"></span><span class="ans_array_cell" style="display:table-cell;vertical-align:middle;padding:4px 0;"><input type="TEXT" size="6" name="MaTrIx_AnSwEr0007_4_7" id="MaTrIx_AnSwEr0007_4_7" class="codeshard" aria-label="answer 7 row 5 column 8 " value="4500">
+</span></span></span><span class="ans_array_close" style="display:inline-block; vertical-align:middle; margin-left:4px"><span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-11-Frame" tabindex="0" data-mathml="<math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;><mrow><mo>]</mo><mpadded width=&quot;0pt&quot; height=&quot;6em&quot; depth=&quot;0pt&quot;><mrow /></mpadded><mo fence=&quot;true&quot; stretchy=&quot;true&quot;></mo></mrow></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-97" role="math" style="width: 0.598em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.479em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(2.027em 1000.48em 15.36em -999.997em); top: -8.926em; left: 0.003em;"><span class="mrow" id="MathJax-Span-98"><span class="mrow" id="MathJax-Span-99"><span class="mo" id="MathJax-Span-100" style="vertical-align: 6.729em;"><span style="display: inline-block; position: relative; width: 0.479em; height: 0px;"><span style="position: absolute; font-family: STIXSizeOneSym; top: -3.33em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; font-family: STIXSizeOneSym; top: 8.693em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: -2.378em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: -1.485em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: -0.533em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 0.36em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 1.313em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 2.265em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 3.158em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 4.11em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 5.003em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 5.955em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 6.848em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: STIXSizeOneSym; position: absolute; top: 7.801em; left: 0.003em;"><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span class="mpadded" id="MathJax-Span-101"><span style="display: inline-block; position: relative; width: 0.003em; height: 0px;"><span style="position: absolute; clip: rect(3.812em 1000em 4.17em -999.997em); top: -3.985em; left: 0.003em;"><span class="mrow" id="MathJax-Span-102"><span class="mrow" id="MathJax-Span-103"></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span class="mo" id="MathJax-Span-104"></span></span></span><span style="display: inline-block; width: 0px; height: 8.932em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -7.568em; border-left: 0px solid; width: 0px; height: 15.718em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mrow><mo>]</mo><mpadded width="0pt" height="6em" depth="0pt"><mrow></mrow></mpadded><mo fence="true" stretchy="true"></mo></mrow></math></span></span><script type="math/tex" id="MathJax-Element-11">\left]\Rule{0pt}{6em}{0pt}\right.</script></span></span>
+
+</div>
+ + + + + +

+              
+            
+          
+            
+ + + +
+ +
+ + + + + + + + + + \ No newline at end of file diff --git a/t/embedded_files/analytics.js b/t/embedded_files/analytics.js new file mode 100644 index 0000000000..92ec834ff2 --- /dev/null +++ b/t/embedded_files/analytics.js @@ -0,0 +1,45 @@ +(function(){var $c=function(a){this.w=a||[]};$c.prototype.set=function(a){this.w[a]=!0};$c.prototype.encode=function(){for(var a=[],b=0;b\x3c/script>')):(c=M.createElement("script"),c.type="text/javascript",c.async=!0,c.src=a,b&&(c.id=b),a=M.getElementsByTagName("script")[0],a.parentNode.insertBefore(c,a)))},Ud=function(){return"https:"==M.location.protocol},E=function(a,b){var c= +a.match("(?:&|#|\\?)"+K(b).replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")+"=([^&#]*)");return c&&2==c.length?c[1]:""},xa=function(){var a=""+M.location.hostname;return 0==a.indexOf("www.")?a.substring(4):a},ya=function(a){var b=M.referrer;if(/^https?:\/\//i.test(b)){if(a)return b;a="//"+M.location.hostname;var c=b.indexOf(a);if(5==c||6==c)if(a=b.charAt(c+a.length),"/"==a||"?"==a||""==a||":"==a)return;return b}},za=function(a,b){if(1==b.length&&null!=b[0]&&"object"===typeof b[0])return b[0];for(var c= +{},d=Math.min(a.length+1,b.length),e=0;e=b.length)wc(a,b,c);else if(8192>=b.length)x(a,b,c)||wd(a,b,c)||wc(a,b,c);else throw ge("len",b.length),new Da(b.length);},wc=function(a,b,c){var d=ta(a+"?"+b);d.onload=d.onerror=function(){d.onload=null;d.onerror=null;c()}},wd=function(a,b,c){var d=O.XMLHttpRequest;if(!d)return!1;var e=new d;if(!("withCredentials"in e))return!1; +e.open("POST",a,!0);e.withCredentials=!0;e.setRequestHeader("Content-Type","text/plain");e.onreadystatechange=function(){4==e.readyState&&(c(),e=null)};e.send(b);return!0},x=function(a,b,c){return O.navigator.sendBeacon?O.navigator.sendBeacon(a,b)?(c(),!0):!1:!1},ge=function(a,b,c){1<=100*Math.random()||G("?")||(a=["t=error","_e="+a,"_v=j47","sr=1"],b&&a.push("_f="+b),c&&a.push("_m="+K(c.substring(0,100))),a.push("aip=1"),a.push("z="+hd()),wc(oc()+"/collect",a.join("&"),ua))};var h=function(a){var b=O.gaData=O.gaData||{};return b[a]=b[a]||{}};var Ha=function(){this.M=[]};Ha.prototype.add=function(a){this.M.push(a)};Ha.prototype.D=function(a){try{for(var b=0;b=100*R(a,Ka))throw"abort";}function Ma(a){if(G(P(a,Na)))throw"abort";}function Oa(){var a=M.location.protocol;if("http:"!=a&&"https:"!=a)throw"abort";} +function Pa(a){try{O.navigator.sendBeacon?J(42):O.XMLHttpRequest&&"withCredentials"in new O.XMLHttpRequest&&J(40)}catch(c){}a.set(ld,Td(a),!0);a.set(Ac,R(a,Ac)+1);var b=[];Qa.map(function(c,d){if(d.F){var e=a.get(c);void 0!=e&&e!=d.defaultValue&&("boolean"==typeof e&&(e*=1),b.push(d.F+"="+K(""+e)))}});b.push("z="+Bd());a.set(Ra,b.join("&"),!0)} +function Sa(a){var b=P(a,gd)||oc()+"/collect",c=P(a,fa);!c&&a.get(Vd)&&(c="beacon");if(c){var d=P(a,Ra),e=a.get(Ia),e=e||ua;"image"==c?wc(b,d,e):"xhr"==c&&wd(b,d,e)||"beacon"==c&&x(b,d,e)||ba(b,d,e)}else ba(b,P(a,Ra),a.get(Ia));b=a.get(Na);b=h(b);c=b.hitcount;b.hitcount=c?c+1:1;b=a.get(Na);delete h(b).pending_experiments;a.set(Ia,ua,!0)} +function Hc(a){(O.gaData=O.gaData||{}).expId&&a.set(Nc,(O.gaData=O.gaData||{}).expId);(O.gaData=O.gaData||{}).expVar&&a.set(Oc,(O.gaData=O.gaData||{}).expVar);var b;var c=a.get(Na);if(c=h(c).pending_experiments){var d=[];for(b in c)c.hasOwnProperty(b)&&c[b]&&d.push(encodeURIComponent(b)+"."+encodeURIComponent(c[b]));b=d.join("!")}else b=void 0;b&&a.set(m,b,!0)}function cd(){if(O.navigator&&"preview"==O.navigator.loadPurpose)throw"abort";} +function yd(a){var b=O.gaDevIds;ka(b)&&0!=b.length&&a.set("&did",b.join(","),!0)}function vb(a){if(!a.get(Na))throw"abort";};var hd=function(){return Math.round(2147483647*Math.random())},Bd=function(){try{var a=new Uint32Array(1);O.crypto.getRandomValues(a);return a[0]&2147483647}catch(b){return hd()}};function Ta(a){var b=R(a,Ua);500<=b&&J(15);var c=P(a,Va);if("transaction"!=c&&"item"!=c){var c=R(a,Wa),d=(new Date).getTime(),e=R(a,Xa);0==e&&a.set(Xa,d);e=Math.round(2*(d-e)/1E3);0=c)throw"abort";a.set(Wa,--c)}a.set(Ua,++b)};var Ya=function(){this.data=new ee},Qa=new ee,Za=[];Ya.prototype.get=function(a){var b=$a(a),c=this.data.get(a);b&&void 0==c&&(c=ea(b.defaultValue)?b.defaultValue():b.defaultValue);return b&&b.Z?b.Z(this,a,c):c};var P=function(a,b){var c=a.get(b);return void 0==c?"":""+c},R=function(a,b){var c=a.get(b);return void 0==c||""===c?0:1*c};Ya.prototype.set=function(a,b,c){if(a)if("object"==typeof a)for(var d in a)a.hasOwnProperty(d)&&ab(this,d,a[d],c);else ab(this,a,b,c)}; +var ab=function(a,b,c,d){if(void 0!=c)switch(b){case Na:wb.test(c)}var e=$a(b);e&&e.o?e.o(a,b,c,d):a.data.set(b,c,d)},bb=function(a,b,c,d,e){this.name=a;this.F=b;this.Z=d;this.o=e;this.defaultValue=c},$a=function(a){var b=Qa.get(a);if(!b)for(var c=0;c=b?!1:!0},gc=function(a){var b={};if(Ec(b)||Fc(b)){var c=b[Eb];void 0==c||Infinity==c||isNaN(c)||(0c)a[b]=void 0},Fd=function(a){return function(b){if("pageview"==b.get(Va)&&!a.I){a.I=!0;var c= +aa(b);b=0=a&&d.push({hash:ca[0],R:e[g],O:ca})}if(0!=d.length)return 1==d.length?d[0]:Zc(b,d)||Zc(c,d)||Zc(null,d)||d[0]}function Zc(a,b){var c,d;null==a?c=d=1:(c=La(a),d=La(D(a,".")?a.substring(1):"."+a));for(var e=0;ed.length)){c=[];for(var e=0;e=ca[0]||0>=ca[1]?"":ca.join("x");a.set(rb,c);a.set(tb,fc());a.set(ob,M.characterSet||M.charset);a.set(sb,b&&"function"=== +typeof b.javaEnabled&&b.javaEnabled()||!1);a.set(nb,(b&&(b.language||b.browserLanguage)||"").toLowerCase());if(d&&a.get(cc)&&(b=M.location.hash)){b=b.split(/[?&#]+/);d=[];for(c=0;carguments.length)){var b,c;"string"===typeof arguments[0]?(b=arguments[0],c=[].slice.call(arguments,1)):(b=arguments[0]&&arguments[0][Va],c=arguments);b&&(c=za(qc[b]||[],c),c[Va]=b,this.b.set(c,void 0,!0),this.filters.D(this.b),this.b.data.m={})}}; +pc.prototype.ma=function(a,b){var c=this;u(a,c,b)||(v(a,function(){u(a,c,b)}),y(String(c.get(V)),a,void 0,b,!0))};var rc=function(a){if("prerender"==M.visibilityState)return!1;a();return!0},z=function(a){if(!rc(a)){J(16);var b=!1,c=function(){if(!b&&rc(a)){b=!0;var d=c,e=M;e.removeEventListener?e.removeEventListener("visibilitychange",d,!1):e.detachEvent&&e.detachEvent("onvisibilitychange",d)}};L(M,"visibilitychange",c)}};var td=/^(?:(\w+)\.)?(?:(\w+):)?(\w+)$/,sc=function(a){if(ea(a[0]))this.u=a[0];else{var b=td.exec(a[0]);null!=b&&4==b.length&&(this.c=b[1]||"t0",this.K=b[2]||"",this.C=b[3],this.a=[].slice.call(a,1),this.K||(this.A="create"==this.C,this.i="require"==this.C,this.g="provide"==this.C,this.ba="remove"==this.C),this.i&&(3<=this.a.length?(this.X=this.a[1],this.W=this.a[2]):this.a[1]&&(qa(this.a[1])?this.X=this.a[1]:this.W=this.a[1])));b=a[1];a=a[2];if(!this.C)throw"abort";if(this.i&&(!qa(b)||""==b))throw"abort"; +if(this.g&&(!qa(b)||""==b||!ea(a)))throw"abort";if(ud(this.c)||ud(this.K))throw"abort";if(this.g&&"t0"!=this.c)throw"abort";}};function ud(a){return 0<=a.indexOf(".")||0<=a.indexOf(":")};var Yd,Zd,$d,A;Yd=new ee;$d=new ee;A=new ee;Zd={ec:45,ecommerce:46,linkid:47}; +var u=function(a,b,c){b==N||b.get(V);var d=Yd.get(a);if(!ea(d))return!1;b.plugins_=b.plugins_||new ee;if(b.plugins_.get(a))return!0;b.plugins_.set(a,new d(b,c||{}));return!0},y=function(a,b,c,d,e){if(!ea(Yd.get(b))&&!$d.get(b)){Zd.hasOwnProperty(b)&&J(Zd[b]);if(p.test(b)){J(52);a=N.j(a);if(!a)return!0;c=d||{};d={id:b,B:c.dataLayer||"dataLayer",ia:!!a.get("anonymizeIp"),na:e,G:!1};a.get(">m")==b&&(d.G=!0);var g=String(a.get("name"));"t0"!=g&&(d.target=g);G(String(a.get("trackingId")))||(d.ja=String(a.get(Q)), +d.ka=Number(a.get(n)),a=c.palindrome?r:q,a=(a=M.cookie.replace(/^|(; +)/g,";").match(a))?a.sort().join("").substring(1):void 0,d.la=a);a=d.B;c=(new Date).getTime();O[a]=O[a]||[];c={"gtm.start":c};e||(c.event="gtm.js");O[a].push(c);c=t(d)}!c&&Zd.hasOwnProperty(b)?(J(39),c=b+".js"):J(43);c&&(c&&0<=c.indexOf("/")||(c=(Ba||Ud()?"https:":"http:")+"//www.google-analytics.com/plugins/ua/"+c),d=ae(c),a=d.protocol,c=M.location.protocol,("https:"==a||a==c||("http:"!=a?0:"http:"==c))&&B(d)&&(wa(d.url,void 0, +e),$d.set(b,!0)))}},v=function(a,b){var c=A.get(a)||[];c.push(b);A.set(a,c)},C=function(a,b){Yd.set(a,b);for(var c=A.get(a)||[],d=0;da.split("/")[0].indexOf(":")&&(a=ca+e[2].substring(0,e[2].lastIndexOf("/"))+"/"+ +a);c.href=a;d=b(c);return{protocol:(c.protocol||"").toLowerCase(),host:d[0],port:d[1],path:d[2],query:c.search||"",url:a||""}};var Z={ga:function(){Z.f=[]}};Z.ga();Z.D=function(a){var b=Z.J.apply(Z,arguments),b=Z.f.concat(b);for(Z.f=[];0c;c++){var d=b[c].src;if(d&&0==d.indexOf("https://www.google-analytics.com/analytics")){J(33); +b=!0;break a}}b=!1}b&&(Ba=!0)}Ud()||Ba||!Ed(new Od(1E4))||(J(36),Ba=!0);(O.gaplugins=O.gaplugins||{}).Linker=Dc;b=Dc.prototype;C("linker",Dc);X("decorate",b,b.ca,20);X("autoLink",b,b.S,25);C("displayfeatures",fd);C("adfeatures",fd);a=a&&a.q;ka(a)?Z.D.apply(N,a):J(50)}};N.da=function(){for(var a=N.getAll(),b=0;b>21:b;return b};})(window); diff --git a/t/embedded_files/css b/t/embedded_files/css new file mode 100644 index 0000000000..a946605790 --- /dev/null +++ b/t/embedded_files/css @@ -0,0 +1,24 @@ +/* vietnamese */ +@font-face { + font-family: 'Inconsolata'; + font-style: normal; + font-weight: 400; + src: local('Inconsolata Regular'), local('Inconsolata-Regular'), url(https://fonts.gstatic.com/s/inconsolata/v15/BjAYBlHtW3CJxDcjzrnZCNDiNsR5a-9Oe_Ivpu8XWlY.woff2) format('woff2'); + unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Inconsolata'; + font-style: normal; + font-weight: 400; + src: local('Inconsolata Regular'), local('Inconsolata-Regular'), url(https://fonts.gstatic.com/s/inconsolata/v15/BjAYBlHtW3CJxDcjzrnZCKE8kM4xWR1_1bYURRojRGc.woff2) format('woff2'); + unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Inconsolata'; + font-style: normal; + font-weight: 400; + src: local('Inconsolata Regular'), local('Inconsolata-Regular'), url(https://fonts.gstatic.com/s/inconsolata/v15/BjAYBlHtW3CJxDcjzrnZCIgp9Q8gbYrhqGlRav_IXfk.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000; +} diff --git a/t/embedded_files/embed-light.css b/t/embedded_files/embed-light.css new file mode 100644 index 0000000000..4b28bdcf94 --- /dev/null +++ b/t/embedded_files/embed-light.css @@ -0,0 +1,259 @@ +@-webkit-keyframes rotate { + from { + -webkit-transform: rotate(0deg); + -moz-transform: rotate(0deg); + -ms-transform: rotate(0deg); + transform: rotate(0deg); } + to { + -webkit-transform: rotate(360deg); + -moz-transform: rotate(360deg); + -ms-transform: rotate(360deg); + transform: rotate(360deg); } } + +*, html, body, button, input, textarea, select { + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; } + +.CodeMirror * { + -moz-osx-font-smoothing: auto; } + +a { + color: #39464E; + text-decoration: none; } + a:hover { + text-decoration: underline; } + +input, textarea, select { + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Fira Sans", "Droid Sans", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; } + +select { + cursor: pointer; } + +body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, fieldset, input, textarea, p, blockquote, th, td { + margin: 0; + padding: 0; } + +table { + border-collapse: collapse; + border-spacing: 0; } + +fieldset, img { + border: 0; } + +address, caption, cite, code, dfn, em, strong, th, var { + font-style: normal; + font-weight: normal; } + +ol, ul { + list-style: none; } + +caption, th { + text-align: left; } + +h1, h2, h3, h4, h5, h6 { + font-size: 100%; + font-weight: normal; } + +abbr, acronym { + border: 0; } + +::-webkit-input-placeholder { + color: #abb9c2; } + +:-moz-placeholder { + /* Firefox 18- */ + color: #abb9c2; } + +::-moz-placeholder { + /* Firefox 19+ */ + color: #abb9c2; } + +:-ms-input-placeholder { + color: #abb9c2; } + +.errorlist { + font-size: .85em; } + .errorlist li { + margin-bottom: 5px; + color: #f36e65; } + +html { + height: 100vh; } + +body { + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Fira Sans", "Droid Sans", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; + overflow: hidden; + padding: 0; + margin: 0; + position: relative; + font-size: 14px; + color: #39464E; } + +a:hover { + text-decoration: none; } + +#wrapper { + position: relative; } + +header { + height: 50px; + box-shadow: 0 0 5px rgba(57, 70, 78, 0.2); + position: relative; + z-index: 100; + position: fixed; + top: 0; + left: 0; + right: 0; } + header h1 { + float: right; + height: 50px; + margin: 0 0 0 10px; } + header h1 a { + display: block; + height: 50px; + line-height: 50px; + color: #7f94a1; + font-size: 12px; + padding-right: 45px; + margin-right: 10px; + background: url(/img/embeddable/logo-dark.png) 100% 50% no-repeat; } + @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2 / 1), only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx) { + header h1 a { + background: transparent url(/img/embeddable/logo-dark@2x.png) no-repeat 100% 50%; + background-size: 37px; } } + header h1 a:hover { + text-decoration: underline; } + +#actions li { + float: left; } + #actions li a { + display: block; + padding: 0 10px; + line-height: 50px; + height: 50px; } + +#actions .hl { + height: 3px; + width: 0; + background: #1C90F3; + position: absolute; + bottom: 0; + left: 0; } + #actions .hl.animated { + -moz-transition: all 0.15s; + /* FF3.6+ */ + -webkit-transition: all 0.15s; + /* Chrome, Safari */ + -o-transition: all 0.15s; + /* Opera */ + -ms-transition: all 0.15s; + /* IE 9 */ + transition: all 0.15s; } + +#tabs { + margin-top: 50px; + overflow: auto; + height: calc(100vh - 50px); } + #tabs .tCont { + padding: 10px; + display: none; } + #tabs .tCont.active { + display: block; } + #tabs pre { + background: transparent; + font-family: "Inconsolata", "Monaco", "Andale Mono", "Lucida Console", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace; + line-height: 1.55em; + font-size: 14px; } + #tabs #result { + padding: 0; + height: calc(100vh - 50px); } + #tabs #result iframe { + width: 100%; + height: 100%; + border: none; + display: block; + margin: 0; } + +#resources h3 { + font-size: 11px; + color: #7f94a1; + line-height: 23px; + text-transform: uppercase; + letter-spacing: 1px; } + +#resources ul { + border-top: solid 1px #cfd6d9; } + #resources ul li { + border-bottom: solid 1px #cfd6d9; + padding: 7px 0; } + #resources ul a { + color: #1C90F3; } + +/* + +JSFiddle Light (c) Oskar Krawczyk + +*/ +.hljs-comment, +.hljs-quote { + color: #abb8c6; } + +.hljs-variable, +.hljs-template-variable, +.hljs-regexp, +.hljs-deletion, +.hljs-keyword, +.hljs-selector-id, +.hljs-selector-class, +.hljs-selector-tag, +.hljs-attr { + color: #e38800; } + +.hljs-built_in, +.hljs-builtin-name, +.hljs-literal, +.hljs-type, +.hljs-params, +.hljs-meta, +.hljs-link { + color: #8d44eb; } + +.hljs-selector-id, +.hljs-selector-class, +.hljs-selector-tag, +.hljs-attr { + color: #e77600; } + +.hljs-attribute { + color: #108de8; } + +.hljs-string, +.hljs-symbol, +.hljs-bullet, +.hljs-addition { + color: #2AAB51; } + +.hljs-subst, +.hljs-number { + color: #ED6E55; } + +.hljs-title, +.hljs-section, +.hljs-name { + color: #fa3d58; } + +.hljs { + display: block; + overflow-x: auto; } + +.hljs-emphasis { + font-style: italic; } + +.hljs-strong { + font-weight: bold; } + +header { + background-color: #ffffff; } + +body { + background-color: #f3f5f6; } diff --git a/t/embedded_files/embed.js b/t/embedded_files/embed.js new file mode 100644 index 0000000000..776ee00229 --- /dev/null +++ b/t/embedded_files/embed.js @@ -0,0 +1,184 @@ +(function() { + var Embed, Utils, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + Utils = (function() { + function Utils() {} + + Utils.prototype.eachElement = function(array, callback, scope) { + var i, results; + if (scope == null) { + scope = this; + } + i = 0; + results = []; + while (i < array.length) { + callback.call(scope, array[i], i); + results.push(i++); + } + return results; + }; + + Utils.prototype.pushMessage = function(name, value) { + if (value == null) { + value = {}; + } + return window.parent.postMessage([name, value], "*"); + }; + + Utils.prototype.addEvent = function(element, event, fn, useCapture) { + if (useCapture == null) { + useCapture = false; + } + return element.addEventListener(event, fn, useCapture); + }; + + Utils.prototype.setStyles = function(element, styles) { + var key, results; + results = []; + for (key in styles) { + results.push(element.style[key] = styles[key]); + } + return results; + }; + + return Utils; + + })(); + + Embed = (function(superClass) { + extend(Embed, superClass); + + function Embed() { + this.switchTab = bind(this.switchTab, this); + this.loadResult = bind(this.loadResult, this); + this.repositionHighlight = bind(this.repositionHighlight, this); + this.predender = bind(this.predender, this); + this.setHeight = bind(this.setHeight, this); + this.setupEvents = bind(this.setupEvents, this); + this.setupDefaults = bind(this.setupDefaults, this); + this.elements = { + tabs: document.querySelectorAll("#tabs .tCont"), + actions: document.querySelectorAll("#actions a"), + hl: document.querySelector(".hl"), + pre: document.querySelectorAll("pre") + }; + this.setupDefaults(); + } + + Embed.prototype.setupDefaults = function() { + this.setupEvents(); + this.eachElement(this.elements.pre, function(element) { + return hljs.highlightBlock(element); + }); + this.repositionHighlight(this.elements.actions[0], false); + return this.setHeight(this.elements.tabs[0]); + }; + + Embed.prototype.setupEvents = function() { + this.eachElement(this.elements.actions, (function(_this) { + return function(action, index) { + return action.addEventListener("click", function(event) { + return _this.switchTab(event, action, index); + }); + }; + })(this)); + if (this.elements.actions[0].dataset.triggerType === "result") { + return this.loadResult(); + } + }; + + Embed.prototype.setHeight = function(element) { + var activeTab, height; + activeTab = element.getBoundingClientRect(); + height = activeTab.height; + return this.pushMessage("embed", { + slug: slug, + height: height + }); + }; + + Embed.prototype.predender = function() { + var head, prefetch, prerender; + head = document.getElementsByTagName("head")[0]; + prefetch = document.createElement("link"); + prefetch.setAttribute("rel", "prefetch"); + prefetch.setAttribute("href", show_src); + head.appendChild(prefetch); + prerender = document.createElement("link"); + prerender.setAttribute("rel", "prerender"); + prerender.setAttribute("href", show_src); + return head.appendChild(prerender); + }; + + Embed.prototype.repositionHighlight = function(action, animated) { + var position; + if (animated == null) { + animated = true; + } + position = action.getBoundingClientRect(); + if (animated) { + this.elements.hl.classList.add("animated"); + } + return this.setStyles(this.elements.hl, { + left: position.left + "px", + width: position.width + "px" + }); + }; + + Embed.prototype.loadResult = function(callback) { + var iframes, resultCont, resultsFrame; + iframes = document.querySelectorAll("#result iframe"); + resultsFrame = document.createElement("iframe"); + resultCont = document.querySelector("#result"); + this.eachElement(iframes, function(iframe) { + return iframe.parentNode.removeChild(iframe); + }); + resultsFrame.src = show_src; + resultsFrame.allowtransparency = true; + resultsFrame.allowfullscreen = true; + resultsFrame.frameBorder = "0"; + resultsFrame.sandbox = "allow-modals allow-forms allow-popups allow-scripts allow-same-origin"; + resultCont.appendChild(resultsFrame); + if (callback) { + return resultsFrame.addEventListener("load", (function(_this) { + return function() { + return callback.apply([_this]); + }; + })(this)); + } + }; + + Embed.prototype.switchTab = function(event, action, index) { + var actionParent; + event.preventDefault(); + event.stopPropagation(); + this.repositionHighlight(action); + actionParent = action.parentElement.parentElement.querySelectorAll("li"); + this.eachElement(this.elements.tabs, function(element) { + return element.classList.remove("active"); + }); + this.elements.tabs[index].classList.add("active"); + if (actionParent) { + this.eachElement(actionParent, function(element) { + return element.classList.remove("active"); + }); + action.parentElement.classList.add("active"); + } + this.setHeight(this.elements.tabs[index]); + if (action.dataset.triggerType === "result") { + return this.loadResult(); + } + }; + + return Embed; + + })(Utils); + + window.addEventListener("DOMContentLoaded", function(event) { + return this.EmbedManager = new Embed; + }); + +}).call(this); diff --git a/t/embedded_files/highlight.pack.js b/t/embedded_files/highlight.pack.js new file mode 100644 index 0000000000..b417075b44 --- /dev/null +++ b/t/embedded_files/highlight.pack.js @@ -0,0 +1,2 @@ +/*! highlight.js v9.0.0 | BSD3 License | git.io/hljslicense */ +!function(e){"undefined"!=typeof exports?e(exports):(self.hljs=e({}),"function"==typeof define&&define.amd&&define("hljs",[],function(){return self.hljs}))}(function(e){function n(e){return e.replace(/&/gm,"&").replace(//gm,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0==t.index}function a(e){return/^(no-?highlight|plain|text)$/i.test(e)}function i(e){var n,t,r,i=e.className+" ";if(i+=e.parentNode?e.parentNode.className:"",t=/\blang(?:uage)?-([\w-]+)\b/i.exec(i))return E(t[1])?t[1]:"no-highlight";for(i=i.split(/\s+/),n=0,r=i.length;r>n;n++)if(E(i[n])||a(i[n]))return i[n]}function o(e,n){var t,r={};for(t in e)r[t]=e[t];if(n)for(t in n)r[t]=n[t];return r}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3==i.nodeType?a+=i.nodeValue.length:1==i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!=r[0].offset?e[0].offset"}function u(e){l+=""}function c(e){("start"==e.event?o:u)(e.node)}for(var s=0,l="",f=[];e.length||r.length;){var g=i();if(l+=n(a.substr(s,g[0].offset-s)),s=g[0].offset,g==e){f.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g==e&&g.length&&g[0].offset==s);f.reverse().forEach(o)}else"start"==g[0].event?f.push(g[0].node):f.pop(),c(g.splice(0,1)[0])}return l+n(a.substr(s))}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var u={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");u[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):Object.keys(a.k).forEach(function(e){c(e,a.k[e])}),a.k=u}a.lR=t(a.l||/\b\w+\b/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),void 0===a.r&&(a.r=1),a.c||(a.c=[]);var s=[];a.c.forEach(function(e){e.v?e.v.forEach(function(n){s.push(o(e,n))}):s.push("self"==e?a:e)}),a.c=s,a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var l=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=l.length?t(l.join("|"),!0):{exec:function(){return null}}}}r(e)}function l(e,t,a,i){function o(e,n){for(var t=0;t";return i+=e+'">',i+n+o}function p(){if(!L.k)return n(M);var e="",t=0;L.lR.lastIndex=0;for(var r=L.lR.exec(M);r;){e+=n(M.substr(t,r.index-t));var a=g(L,r);a?(B+=a[1],e+=h(a[0],n(r[0]))):e+=n(r[0]),t=L.lR.lastIndex,r=L.lR.exec(M)}return e+n(M.substr(t))}function d(){var e="string"==typeof L.sL;if(e&&!R[L.sL])return n(M);var t=e?l(L.sL,M,!0,y[L.sL]):f(M,L.sL.length?L.sL:void 0);return L.r>0&&(B+=t.r),e&&(y[L.sL]=t.top),h(t.language,t.value,!1,!0)}function b(){return void 0!==L.sL?d():p()}function v(e,t){var r=e.cN?h(e.cN,"",!0):"";e.rB?(k+=r,M=""):e.eB?(k+=n(t)+r,M=""):(k+=r,M=t),L=Object.create(e,{parent:{value:L}})}function m(e,t){if(M+=e,void 0===t)return k+=b(),0;var r=o(t,L);if(r)return k+=b(),v(r,t),r.rB?0:t.length;var a=u(L,t);if(a){var i=L;i.rE||i.eE||(M+=t),k+=b();do L.cN&&(k+=""),B+=L.r,L=L.parent;while(L!=a.parent);return i.eE&&(k+=n(t)),M="",a.starts&&v(a.starts,""),i.rE?0:t.length}if(c(t,L))throw new Error('Illegal lexeme "'+t+'" for mode "'+(L.cN||"")+'"');return M+=t,t.length||1}var N=E(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var w,L=i||N,y={},k="";for(w=L;w!=N;w=w.parent)w.cN&&(k=h(w.cN,"",!0)+k);var M="",B=0;try{for(var C,j,I=0;;){if(L.t.lastIndex=I,C=L.t.exec(t),!C)break;j=m(t.substr(I,C.index-I),C[0]),I=C.index+j}for(m(t.substr(I)),w=L;w.parent;w=w.parent)w.cN&&(k+="");return{r:B,value:k,language:e,top:L}}catch(O){if(-1!=O.message.indexOf("Illegal"))return{r:0,value:n(t)};throw O}}function f(e,t){t=t||x.languages||Object.keys(R);var r={r:0,value:n(e)},a=r;return t.forEach(function(n){if(E(n)){var t=l(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}}),a.language&&(r.second_best=a),r}function g(e){return x.tabReplace&&(e=e.replace(/^((<[^>]+>|\t)+)/gm,function(e,n){return n.replace(/\t/g,x.tabReplace)})),x.useBR&&(e=e.replace(/\n/g,"
")),e}function h(e,n,t){var r=n?w[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function p(e){var n=i(e);if(!a(n)){var t;x.useBR?(t=document.createElementNS("http://www.w3.org/1999/xhtml","div"),t.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):t=e;var r=t.textContent,o=n?l(n,r,!0):f(r),s=u(t);if(s.length){var p=document.createElementNS("http://www.w3.org/1999/xhtml","div");p.innerHTML=o.value,o.value=c(s,u(p),r)}o.value=g(o.value),e.innerHTML=o.value,e.className=h(e.className,n,o.language),e.result={language:o.language,re:o.r},o.second_best&&(e.second_best={language:o.second_best.language,re:o.second_best.r})}}function d(e){x=o(x,e)}function b(){if(!b.called){b.called=!0;var e=document.querySelectorAll("pre code");Array.prototype.forEach.call(e,p)}}function v(){addEventListener("DOMContentLoaded",b,!1),addEventListener("load",b,!1)}function m(n,t){var r=R[n]=t(e);r.aliases&&r.aliases.forEach(function(e){w[e]=n})}function N(){return Object.keys(R)}function E(e){return e=(e||"").toLowerCase(),R[e]||R[w[e]]}var x={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},R={},w={};return e.highlight=l,e.highlightAuto=f,e.fixMarkup=g,e.highlightBlock=p,e.configure=d,e.initHighlighting=b,e.initHighlightingOnLoad=v,e.registerLanguage=m,e.listLanguages=N,e.getLanguage=E,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|like)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e});hljs.registerLanguage("xml",function(s){var t="[A-Za-z0-9\\._:-]+",e={b:/<\?(php)?(?!\w)/,e:/\?>/,sL:"php"},r={eW:!0,i:/]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xsl","plist"],cI:!0,c:[{cN:"meta",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},s.C("",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"tag",b:"|$)",e:">",k:{name:"style"},c:[r],starts:{e:"",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"|$)",e:">",k:{name:"script"},c:[r],starts:{e:"",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},e,{cN:"meta",b:/<\?\w+/,e:/\?>/,r:10},{cN:"tag",b:"",c:[{cN:"name",b:/[^\/><\s]+/,r:0},r]}]}});hljs.registerLanguage("coffeescript",function(e){var c={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",built_in:"npm require console print module global window document"},n="[A-Za-z$_][0-9A-Za-z$_]*",r={cN:"subst",b:/#\{/,e:/}/,k:c},s=[e.BNM,e.inherit(e.CNM,{starts:{e:"(\\s*/)?",r:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,r]},{b:/"/,e:/"/,c:[e.BE,r]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[r,e.HCM]},{b:"//[gim]*",r:0},{b:/\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/}]},{b:"@"+n},{b:"`",e:"`",eB:!0,eE:!0,sL:"javascript"}];r.c=s;var i=e.inherit(e.TM,{b:n}),t="(\\(.*\\))?\\s*\\B[-=]>",o={cN:"params",b:"\\([^\\(]",rB:!0,c:[{b:/\(/,e:/\)/,k:c,c:["self"].concat(s)}]};return{aliases:["coffee","cson","iced"],k:c,i:/\/\*/,c:s.concat([e.C("###","###"),e.HCM,{cN:"function",b:"^\\s*"+n+"\\s*=\\s*"+t,e:"[-=]>",rB:!0,c:[i,o]},{b:/[:\(,=]\s*/,r:0,c:[{cN:"function",b:t,e:"[-=]>",rB:!0,c:[o]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[i]},i]},{b:n+":",e:":",rB:!0,rE:!0,r:0}])}});hljs.registerLanguage("scss",function(e){var t="[a-zA-Z-][a-zA-Z0-9_-]*",i={cN:"variable",b:"(\\$"+t+")\\b"},r={cN:"number",b:"#[0-9A-Fa-f]+"};({cN:"attribute",b:"[A-Z\\_\\.\\-]+",e:":",eE:!0,i:"[^\\s]",starts:{eW:!0,eE:!0,c:[r,e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"meta",b:"!important"}]}});return{cI:!0,i:"[=/|']",c:[e.CLCM,e.CBCM,{cN:"selector-id",b:"\\#[A-Za-z0-9_-]+",r:0},{cN:"selector-class",b:"\\.[A-Za-z0-9_-]+",r:0},{cN:"selector-attr",b:"\\[",e:"\\]",i:"$"},{cN:"selector-tag",b:"\\b(a|abbr|acronym|address|area|article|aside|audio|b|base|big|blockquote|body|br|button|canvas|caption|cite|code|col|colgroup|command|datalist|dd|del|details|dfn|div|dl|dt|em|embed|fieldset|figcaption|figure|footer|form|frame|frameset|(h[1-6])|head|header|hgroup|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|map|mark|meta|meter|nav|noframes|noscript|object|ol|optgroup|option|output|p|param|pre|progress|q|rp|rt|ruby|samp|script|section|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|tt|ul|var|video)\\b",r:0},{b:":(visited|valid|root|right|required|read-write|read-only|out-range|optional|only-of-type|only-child|nth-of-type|nth-last-of-type|nth-last-child|nth-child|not|link|left|last-of-type|last-child|lang|invalid|indeterminate|in-range|hover|focus|first-of-type|first-line|first-letter|first-child|first|enabled|empty|disabled|default|checked|before|after|active)"},{b:"::(after|before|choices|first-letter|first-line|repeat-index|repeat-item|selection|value)"},i,{cN:"attribute",b:"\\b(z-index|word-wrap|word-spacing|word-break|width|widows|white-space|visibility|vertical-align|unicode-bidi|transition-timing-function|transition-property|transition-duration|transition-delay|transition|transform-style|transform-origin|transform|top|text-underline-position|text-transform|text-shadow|text-rendering|text-overflow|text-indent|text-decoration-style|text-decoration-line|text-decoration-color|text-decoration|text-align-last|text-align|tab-size|table-layout|right|resize|quotes|position|pointer-events|perspective-origin|perspective|page-break-inside|page-break-before|page-break-after|padding-top|padding-right|padding-left|padding-bottom|padding|overflow-y|overflow-x|overflow-wrap|overflow|outline-width|outline-style|outline-offset|outline-color|outline|orphans|order|opacity|object-position|object-fit|normal|none|nav-up|nav-right|nav-left|nav-index|nav-down|min-width|min-height|max-width|max-height|mask|marks|margin-top|margin-right|margin-left|margin-bottom|margin|list-style-type|list-style-position|list-style-image|list-style|line-height|letter-spacing|left|justify-content|initial|inherit|ime-mode|image-orientation|image-resolution|image-rendering|icon|hyphens|height|font-weight|font-variant-ligatures|font-variant|font-style|font-stretch|font-size-adjust|font-size|font-language-override|font-kerning|font-feature-settings|font-family|font|float|flex-wrap|flex-shrink|flex-grow|flex-flow|flex-direction|flex-basis|flex|filter|empty-cells|display|direction|cursor|counter-reset|counter-increment|content|column-width|column-span|column-rule-width|column-rule-style|column-rule-color|column-rule|column-gap|column-fill|column-count|columns|color|clip-path|clip|clear|caption-side|break-inside|break-before|break-after|box-sizing|box-shadow|box-decoration-break|bottom|border-width|border-top-width|border-top-style|border-top-right-radius|border-top-left-radius|border-top-color|border-top|border-style|border-spacing|border-right-width|border-right-style|border-right-color|border-right|border-radius|border-left-width|border-left-style|border-left-color|border-left|border-image-width|border-image-source|border-image-slice|border-image-repeat|border-image-outset|border-image|border-color|border-collapse|border-bottom-width|border-bottom-style|border-bottom-right-radius|border-bottom-left-radius|border-bottom-color|border-bottom|border|background-size|background-repeat|background-position|background-origin|background-image|background-color|background-clip|background-attachment|background-blend-mode|background|backface-visibility|auto|animation-timing-function|animation-play-state|animation-name|animation-iteration-count|animation-fill-mode|animation-duration|animation-direction|animation-delay|animation|align-self|align-items|align-content)\\b",i:"[^\\s]"},{b:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{b:":",e:";",c:[i,r,e.CSSNM,e.QSM,e.ASM,{cN:"meta",b:"!important"}]},{b:"@",e:"[{;]",k:"mixin include extend for if else each while charset import debug media page content font-face namespace warn",c:[i,e.QSM,e.ASM,r,e.CSSNM,{b:"\\s[A-Za-z0-9_.-]+",r:0}]}]}});hljs.registerLanguage("typescript",function(e){var r={keyword:"in if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const class public private protected get set super static implements enum export import declare type namespace abstract",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document any number boolean string void"};return{aliases:["ts"],k:r,c:[{cN:"meta",b:/^\s*['"]use strict['"]/},e.ASM,e.QSM,{cN:"string",b:"`",e:"`",c:[e.BE,{cN:"subst",b:"\\$\\{",e:"\\}"}]},e.CLCM,e.CBCM,{cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM],r:0},{cN:"function",b:"function",e:/[\{;]/,eE:!0,k:r,c:["self",e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:r,c:[e.CLCM,e.CBCM],i:/["'\(]/}],i:/\[|%/,r:0},{bK:"constructor",e:/\{/,eE:!0},{bK:"module",e:/\{/,eE:!0},{bK:"interface",e:/\{/,eE:!0,k:"interface extends"},{b:/\$[(.]/},{b:"\\."+e.IR,r:0}]}});hljs.registerLanguage("css",function(e){var c="[a-zA-Z-][a-zA-Z0-9_-]*",t={b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{eW:!0,eE:!0,c:[{b:/[\w-]+\s*\(/,rB:!0,c:[{cN:"built_in",b:/[\w-]+/}]},e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"number",b:"#[0-9A-Fa-f]+"},{cN:"meta",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,{cN:"selector-id",b:/#[A-Za-z0-9_-]+/},{cN:"selector-class",b:/\.[A-Za-z0-9_-]+/},{cN:"selector-attr",b:/\[/,e:/\]/,i:"$"},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"']+/},{b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{b:"@",e:"[{;]",c:[{cN:"keyword",b:/\S+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[e.ASM,e.QSM,e.CSSNM]}]},{cN:"selector-tag",b:c,r:0},{b:"{",e:"}",i:/\S/,c:[e.CBCM,t]}]}});hljs.registerLanguage("javascript",function(e){return{aliases:["js"],k:{keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await import from as",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},c:[{cN:"meta",r:10,b:/^\s*['"]use (strict|asm)['"]/},e.ASM,e.QSM,{cN:"string",b:"`",e:"`",c:[e.BE,{cN:"subst",b:"\\$\\{",e:"\\}"}]},e.CLCM,e.CBCM,{cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{b:/\s*[);\]]/,r:0,sL:"xml"}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:[e.CLCM,e.CBCM]}],i:/\[|%/},{b:/\$[(.]/},{b:"\\."+e.IR,r:0},{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor",e:/\{/,eE:!0}],i:/#/}}); \ No newline at end of file diff --git a/t/embedded_files/jquery-1.9.1.js b/t/embedded_files/jquery-1.9.1.js new file mode 100644 index 0000000000..e2c203fe97 --- /dev/null +++ b/t/embedded_files/jquery-1.9.1.js @@ -0,0 +1,9597 @@ +/*! + * jQuery JavaScript Library v1.9.1 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2013-2-4 + */ +(function( window, undefined ) { + +// Can't do this because several apps including ASP.NET trace +// the stack via arguments.caller.callee and Firefox dies if +// you try to trace through "use strict" call chains. (#13335) +// Support: Firefox 18+ +//"use strict"; +var + // The deferred used on DOM ready + readyList, + + // A central reference to the root jQuery(document) + rootjQuery, + + // Support: IE<9 + // For `typeof node.method` instead of `node.method !== undefined` + core_strundefined = typeof undefined, + + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + location = window.location, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // [[Class]] -> type pairs + class2type = {}, + + // List of deleted data cache ids, so we can reuse them + core_deletedIds = [], + + core_version = "1.9.1", + + // Save a reference to some core methods + core_concat = core_deletedIds.concat, + core_push = core_deletedIds.push, + core_slice = core_deletedIds.slice, + core_indexOf = core_deletedIds.indexOf, + core_toString = class2type.toString, + core_hasOwn = class2type.hasOwnProperty, + core_trim = core_version.trim, + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Used for matching numbers + core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, + + // Used for splitting on whitespace + core_rnotwhite = /\S+/g, + + // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, + rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }, + + // The ready event handler + completed = function( event ) { + + // readyState === "complete" is good enough for us to call the dom ready in oldIE + if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { + detach(); + jQuery.ready(); + } + }, + // Clean-up method for dom ready events + detach = function() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); + + } else { + document.detachEvent( "onreadystatechange", completed ); + window.detachEvent( "onload", completed ); + } + }; + +jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used + jquery: core_version, + + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + + // scripts is true for back-compat + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return core_slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; + }, + + slice: function() { + return this.pushStack( core_slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: core_push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var src, copyIsArray, copy, name, options, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger("ready").off("ready"); + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + isWindow: function( obj ) { + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + if ( obj == null ) { + return String( obj ); + } + return typeof obj === "object" || typeof obj === "function" ? + class2type[ core_toString.call(obj) ] || "object" : + typeof obj; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !core_hasOwn.call(obj, "constructor") && + !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || core_hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + // data: string of html + // context (optional): If specified, the fragment will be created in this context, defaults to document + // keepScripts (optional): If true, will include scripts passed in the html string + parseHTML: function( data, context, keepScripts ) { + if ( !data || typeof data !== "string" ) { + return null; + } + if ( typeof context === "boolean" ) { + keepScripts = context; + context = false; + } + context = context || document; + + var parsed = rsingleTag.exec( data ), + scripts = !keepScripts && []; + + // Single tag + if ( parsed ) { + return [ context.createElement( parsed[1] ) ]; + } + + parsed = jQuery.buildFragment( [ data ], context, scripts ); + if ( scripts ) { + jQuery( scripts ).remove(); + } + return jQuery.merge( [], parsed.childNodes ); + }, + + parseJSON: function( data ) { + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + if ( data === null ) { + return data; + } + + if ( typeof data === "string" ) { + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + if ( data ) { + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + } + } + } + + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + if ( !data || typeof data !== "string" ) { + return null; + } + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && jQuery.trim( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); + + if ( args ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } + } + + return obj; + }, + + // Use native String.trim function wherever possible + trim: core_trim && !core_trim.call("\uFEFF\xA0") ? + function( text ) { + return text == null ? + "" : + core_trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + core_push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( core_indexOf ) { + return core_indexOf.call( arr, elem, i ); + } + + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var l = second.length, + i = first.length, + j = 0; + + if ( typeof l === "number" ) { + for ( ; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var retVal, + ret = [], + i = 0, + length = elems.length; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, + i = 0, + length = elems.length, + isArray = isArraylike( elems ), + ret = []; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return core_concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var args, proxy, tmp; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = core_slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + // Multifunctional method to get and set values of a collection + // The value/s can optionally be executed if it's a function + access: function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + length = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < length; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; + }, + + now: function() { + return ( new Date() ).getTime(); + } +}); + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", completed ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", completed ); + + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} + + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { + + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } + + // detach all dom ready events + detach(); + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +function isArraylike( obj ) { + var length = obj.length, + type = jQuery.type( obj ); + + if ( jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || type !== "function" && + ( length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj ); +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // First callback to fire (used internally by add and fireWith) + firingStart, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( list && ( !fired || stack ) ) { + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var action = tuple[ 0 ], + fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = core_slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; + if( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); +jQuery.support = (function() { + + var support, all, a, + input, select, fragment, + opt, eventName, isSupported, i, + div = document.createElement("div"); + + // Setup + div.setAttribute( "className", "t" ); + div.innerHTML = "
a"; + + // Support tests won't run in some limited or non-browser environments + all = div.getElementsByTagName("*"); + a = div.getElementsByTagName("a")[ 0 ]; + if ( !all || !a || !all.length ) { + return {}; + } + + // First batch of tests + select = document.createElement("select"); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName("input")[ 0 ]; + + a.style.cssText = "top:1px;float:left;opacity:.5"; + support = { + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: div.firstChild.nodeType === 3, + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: a.getAttribute("href") === "/a", + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.5/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) + checkOn: !!input.value, + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Tests for enctype support on a form (#6743) + enctype: !!document.createElement("form").enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", + + // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode + boxModel: document.compatMode === "CSS1Compat", + + // Will be defined later + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true, + boxSizingReliable: true, + pixelPosition: false + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Support: IE<9 + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + // Check if we can trust getAttribute("value") + input = document.createElement("input"); + input.setAttribute( "value", "" ); + support.input = input.getAttribute( "value" ) === ""; + + // Check if an input maintains its value after becoming a radio + input.value = "t"; + input.setAttribute( "type", "radio" ); + support.radioValue = input.value === "t"; + + // #11217 - WebKit loses check when the name is after the checked attribute + input.setAttribute( "checked", "t" ); + input.setAttribute( "name", "t" ); + + fragment = document.createDocumentFragment(); + fragment.appendChild( input ); + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<9 + // Opera does not clone events (and typeof div.attachEvent === undefined). + // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() + if ( div.attachEvent ) { + div.attachEvent( "onclick", function() { + support.noCloneEvent = false; + }); + + div.cloneNode( true ).click(); + } + + // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) + // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php + for ( i in { submit: true, change: true, focusin: true }) { + div.setAttribute( eventName = "on" + i, "t" ); + + support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; + } + + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + // Run tests that need a body at doc ready + jQuery(function() { + var container, marginDiv, tds, + divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + container = document.createElement("div"); + container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; + + body.appendChild( container ).appendChild( div ); + + // Support: IE8 + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + div.innerHTML = "
t
"; + tds = div.getElementsByTagName("td"); + tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Support: IE8 + // Check if empty table cells still have offsetWidth/Height + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Check box-sizing and margin behavior + div.innerHTML = ""; + div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; + support.boxSizing = ( div.offsetWidth === 4 ); + support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); + + // Use window.getComputedStyle because jsdom on node.js will break without it. + if ( window.getComputedStyle ) { + support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; + support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. (#3333) + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + marginDiv = div.appendChild( document.createElement("div") ); + marginDiv.style.cssText = div.style.cssText = divReset; + marginDiv.style.marginRight = marginDiv.style.width = "0"; + div.style.width = "1px"; + + support.reliableMarginRight = + !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); + } + + if ( typeof div.style.zoom !== core_strundefined ) { + // Support: IE<8 + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + div.innerHTML = ""; + div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); + + // Support: IE6 + // Check if elements with layout shrink-wrap their children + div.style.display = "block"; + div.innerHTML = "
"; + div.firstChild.style.width = "5px"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); + + if ( support.inlineBlockNeedsLayout ) { + // Prevent IE 6 from affecting layout for positioned elements #11048 + // Prevent IE from shrinking the body in IE 7 mode #12869 + // Support: IE<8 + body.style.zoom = 1; + } + } + + body.removeChild( container ); + + // Null elements to avoid leaks in IE + container = div = tds = marginDiv = null; + }); + + // Null elements to avoid leaks in IE + all = select = fragment = opt = a = input = null; + + return support; +})(); + +var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, + rmultiDash = /([A-Z])/g; + +function internalData( elem, name, data, pvt /* Internal Use Only */ ){ + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; +} + +function internalRemoveData( elem, name, pvt ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var i, l, thisCache, + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); + } + } + } else { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = name.concat( jQuery.map( name, jQuery.camelCase ) ); + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + } else if ( jQuery.support.deleteExpando || cache != cache.window ) { + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } +} + +jQuery.extend({ + cache: {}, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data ) { + return internalData( elem, name, data ); + }, + + removeData: function( elem, name ) { + return internalRemoveData( elem, name ); + }, + + // For internal use only. + _data: function( elem, name, data ) { + return internalData( elem, name, data, true ); + }, + + _removeData: function( elem, name ) { + return internalRemoveData( elem, name, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + // Do not set data on non-element because it will not be cleared (#8335). + if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { + return false; + } + + var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; + + // nodes accept data unless otherwise specified; rejection can be conditional + return !noData || noData !== true && elem.getAttribute("classid") === noData; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var attrs, name, + elem = this[0], + i = 0, + data = null; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + attrs = elem.attributes; + for ( ; i < attrs.length; i++ ) { + name = attrs[i].name; + + if ( !name.indexOf( "data-" ) ) { + name = jQuery.camelCase( name.slice(5) ); + + dataAttr( elem, name, data[ name ] ); + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + return jQuery.access( this, function( value ) { + + if ( value === undefined ) { + // Try to fetch any internally stored data first + return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; + } + + this.each(function() { + jQuery.data( this, key, value ); + }); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + hooks.cur = fn; + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery._removeData( elem, type + "queue" ); + jQuery._removeData( elem, key ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var nodeHook, boolHook, + rclass = /[\t\r\n]/g, + rreturn = /\r/g, + rfocusable = /^(?:input|select|textarea|button|object)$/i, + rclickable = /^(?:a|area)$/i, + rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, + ruseDefault = /^(?:checked|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute, + getSetInput = jQuery.support.input; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classes, elem, cur, clazz, j, + i = 0, + len = this.length, + proceed = typeof value === "string" && value; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call( this, j, this.className ) ); + }); + } + + if ( proceed ) { + // The disjunction here is for better compressibility (see removeClass) + classes = ( value || "" ).match( core_rnotwhite ) || []; + + for ( ; i < len; i++ ) { + elem = this[ i ]; + cur = elem.nodeType === 1 && ( elem.className ? + ( " " + elem.className + " " ).replace( rclass, " " ) : + " " + ); + + if ( cur ) { + j = 0; + while ( (clazz = classes[j++]) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + elem.className = jQuery.trim( cur ); + + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, clazz, j, + i = 0, + len = this.length, + proceed = arguments.length === 0 || typeof value === "string" && value; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call( this, j, this.className ) ); + }); + } + if ( proceed ) { + classes = ( value || "" ).match( core_rnotwhite ) || []; + + for ( ; i < len; i++ ) { + elem = this[ i ]; + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( elem.className ? + ( " " + elem.className + " " ).replace( rclass, " " ) : + "" + ); + + if ( cur ) { + j = 0; + while ( (clazz = classes[j++]) ) { + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + elem.className = value ? jQuery.trim( cur ) : ""; + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.match( core_rnotwhite ) || []; + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space separated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + // Toggle whole class name + } else if ( type === core_strundefined || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // If the element has a class name or if we're passed "false", + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var ret, hooks, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var val, + self = jQuery(this); + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, option, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one" || index < 0, + values = one ? null : [], + max = one ? index + 1 : options.length, + i = index < 0 ? + max : + one ? index : 0; + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // oldIE doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + // Don't return options that are disabled or in a disabled optgroup + ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && + ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attr: function( elem, name, value ) { + var hooks, notxml, ret, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === core_strundefined ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + + } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, value + "" ); + return value; + } + + } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + // In IE9+, Flash objects don't have .getAttribute (#12945) + // Support: IE9+ + if ( typeof elem.getAttribute !== core_strundefined ) { + ret = elem.getAttribute( name ); + } + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var name, propName, + i = 0, + attrNames = value && value.match( core_rnotwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( (name = attrNames[i++]) ) { + propName = jQuery.propFix[ name ] || name; + + // Boolean attributes get special treatment (#10870) + if ( rboolean.test( name ) ) { + // Set corresponding property to false for boolean attributes + // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 + if ( !getSetAttribute && ruseDefault.test( name ) ) { + elem[ jQuery.camelCase( "default-" + name ) ] = + elem[ propName ] = false; + } else { + elem[ propName ] = false; + } + + // See #9699 for explanation of this approach (setting first, then removal) + } else { + jQuery.attr( elem, name, "" ); + } + + elem.removeAttribute( getSetAttribute ? name : propName ); + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to default in case type is set after value during creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + var + // Use .prop to determine if this attribute is understood as boolean + prop = jQuery.prop( elem, name ), + + // Fetch it accordingly + attr = typeof prop === "boolean" && elem.getAttribute( name ), + detail = typeof prop === "boolean" ? + + getSetInput && getSetAttribute ? + attr != null : + // oldIE fabricates an empty string for missing boolean attributes + // and conflates checked/selected into attroperties + ruseDefault.test( name ) ? + elem[ jQuery.camelCase( "default-" + name ) ] : + !!attr : + + // fetch an attribute node for properties not recognized as boolean + elem.getAttributeNode( name ); + + return detail && detail.value !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { + // IE<8 needs the *property* name + elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); + + // Use defaultChecked and defaultSelected for oldIE + } else { + elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; + } + + return name; + } +}; + +// fix oldIE value attroperty +if ( !getSetInput || !getSetAttribute ) { + jQuery.attrHooks.value = { + get: function( elem, name ) { + var ret = elem.getAttributeNode( name ); + return jQuery.nodeName( elem, "input" ) ? + + // Ignore the value *property* by using defaultValue + elem.defaultValue : + + ret && ret.specified ? ret.value : undefined; + }, + set: function( elem, value, name ) { + if ( jQuery.nodeName( elem, "input" ) ) { + // Does not return so that setAttribute is also used + elem.defaultValue = value; + } else { + // Use nodeHook if defined (#1954); otherwise setAttribute is fine + return nodeHook && nodeHook.set( elem, value, name ); + } + } + }; +} + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret = elem.getAttributeNode( name ); + return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? + ret.value : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + elem.setAttributeNode( + (ret = elem.ownerDocument.createAttribute( name )) + ); + } + + ret.value = value += ""; + + // Break association with cloned elements by also using setAttribute (#9646) + return name === "value" || value === elem.getAttribute( name ) ? + value : + undefined; + } + }; + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + nodeHook.set( elem, value === "" ? false : value, name ); + } + }; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); +} + + +// Some attributes require a special call on IE +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret == null ? undefined : ret; + } + }); + }); + + // href/src property should get the full normalized URL (#10299/#12915) + jQuery.each([ "href", "src" ], function( i, name ) { + jQuery.propHooks[ name ] = { + get: function( elem ) { + return elem.getAttribute( name, 4 ); + } + }; + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Note: IE uppercases css property names, but if we were to .toLowerCase() + // .cssText, that would destroy case senstitivity in URL's, like in "background" + return elem.style.cssText || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = value + "" ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); +var rformElems = /^(?:input|select|textarea)$/i, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + var tmp, events, t, handleObjIn, + special, eventHandle, handleObj, + handlers, type, namespaces, origType, + elemData = jQuery._data( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = ( types || "" ).match( core_rnotwhite ) || [""]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + var j, handleObj, tmp, + origCount, t, events, + special, handlers, type, + namespaces, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( core_rnotwhite ) || [""]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery._removeData( elem, "events" ); + } + }, + + trigger: function( event, data, elem, onlyHandlers ) { + var handle, ontype, cur, + bubbleType, special, tmp, i, + eventPath = [ elem || document ], + type = core_hasOwn.call( event, "type" ) ? event.type : event, + namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + event.isTrigger = true; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + try { + elem[ type ](); + } catch ( e ) { + // IE<9 dies on focus/blur to hidden element (#1486,#12518) + // only reproducible on winXP IE8 native, not IE9 in IE8 mode + } + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, ret, handleObj, matched, j, + handlerQueue = [], + args = core_slice.call( arguments ), + handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var sel, handleObj, matches, i, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + + for ( ; cur != this; cur = cur.parentNode || this ) { + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } + + return handlerQueue; + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: IE<9 + // Fix target property (#1925) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Support: Chrome 23+, Safari? + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Support: IE<9 + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) + event.metaKey = !!event.metaKey; + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var body, eventDoc, doc, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { + this.click(); + return false; + } + } + }, + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== document.activeElement && this.focus ) { + try { + this.focus(); + return false; + } catch ( e ) { + // Support: IE<9 + // If we error on focus to hidden element (#1486, #12518), + // let .trigger() run the handlers + } + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === document.activeElement && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + + beforeunload: { + postDispatch: function( event ) { + + // Even when returnValue equals to undefined Firefox will still show alert + if ( event.result !== undefined ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + var name = "on" + type; + + if ( elem.detachEvent ) { + + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === core_strundefined ) { + elem[ name ] = null; + } + + elem.detachEvent( name, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + if ( !e ) { + return; + } + + // If preventDefault exists, run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // Support: IE + // Otherwise set the returnValue property of the original event to false + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + if ( !e ) { + return; + } + // If stopPropagation exists, run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + + // Support: IE + // Set the cancelBubble property of the original event to true + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "submitBubbles" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "submitBubbles", true ); + } + }); + // return undefined since we don't need an event listener + }, + + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "changeBubbles", true ); + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return !rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var type, origFn; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + delegate: function( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate: function( selector, types, fn ) { + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +}); +/*! + * Sizzle CSS Selector Engine + * Copyright 2012 jQuery Foundation and other contributors + * Released under the MIT license + * http://sizzlejs.com/ + */ +(function( window, undefined ) { + +var i, + cachedruns, + Expr, + getText, + isXML, + compile, + hasDuplicate, + outermostContext, + + // Local document vars + setDocument, + document, + docElem, + documentIsXML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + sortOrder, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + support = {}, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Array methods + arr = [], + pop = arr.pop, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors + operators = "([*^$|!~]?=)", + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", + + // Prefer arguments quoted, + // then not containing pseudos/brackets, + // then attribute selectors/non-parenthetical expressions, + // then anything else + // These preferences are here to reduce the number of selectors + // needing tokenize in the PSEUDO preFilter + pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rsibling = /[\x20\t\r\n\f]*[+~]/, + + rnative = /^[^{]+\{\s*\[native code/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rescape = /'|\\/g, + rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, + funescape = function( _, escaped ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + return high !== high ? + escaped : + // BMP codepoint + high < 0 ? + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }; + +// Use a stripped-down slice if we can't use a native one +try { + slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; +} catch ( e ) { + slice = function( i ) { + var elem, + results = []; + while ( (elem = this[i++]) ) { + results.push( elem ); + } + return results; + }; +} + +/** + * For feature detection + * @param {Function} fn The function to test for native support + */ +function isNative( fn ) { + return rnative.test( fn + "" ); +} + +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var cache, + keys = []; + + return (cache = function( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key += " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key ] = value); + }); +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return fn( div ); + } catch (e) { + return false; + } finally { + // release memory in IE + div = null; + } +} + +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + + context = context || document; + results = results || []; + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { + return []; + } + + if ( !documentIsXML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { + push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); + return results; + } + } + + // QSA path + if ( support.qsa && !rbuggyQSA.test(selector) ) { + old = true; + nid = expando; + newContext = context; + newSelector = nodeType === 9 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); + } + newContext = rsibling.test( selector ) && context.parentNode || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, slice.call( newContext.querySelectorAll( + newSelector + ), 0 ) ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Detect xml + * @param {Element|Object} elem An element or a document + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var doc = node ? node.ownerDocument || node : preferredDoc; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Set our document + document = doc; + docElem = doc.documentElement; + + // Support tests + documentIsXML = isXML( doc ); + + // Check if getElementsByTagName("*") returns only elements + support.tagNameNoComments = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Check if attributes should be retrieved by attribute nodes + support.attributes = assert(function( div ) { + div.innerHTML = ""; + var type = typeof div.lastChild.getAttribute("multiple"); + // IE8 returns a string for some attributes even when not present + return type !== "boolean" && type !== "string"; + }); + + // Check if getElementsByClassName can be trusted + support.getByClassName = assert(function( div ) { + // Opera can't find a second classname (in 9.6) + div.innerHTML = ""; + if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { + return false; + } + + // Safari 3.2 caches class attributes and doesn't catch changes + div.lastChild.className = "e"; + return div.getElementsByClassName("e").length === 2; + }); + + // Check if getElementById returns elements by name + // Check if getElementsByName privileges form controls or returns elements by ID + support.getByName = assert(function( div ) { + // Inject content + div.id = expando + 0; + div.innerHTML = "
"; + docElem.insertBefore( div, docElem.firstChild ); + + // Test + var pass = doc.getElementsByName && + // buggy browsers will return fewer than the correct 2 + doc.getElementsByName( expando ).length === 2 + + // buggy browsers will return more than the correct 0 + doc.getElementsByName( expando + 0 ).length; + support.getIdNotName = !doc.getElementById( expando ); + + // Cleanup + docElem.removeChild( div ); + + return pass; + }); + + // IE6/7 return modified attributes + Expr.attrHandle = assert(function( div ) { + div.innerHTML = ""; + return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && + div.firstChild.getAttribute("href") === "#"; + }) ? + {} : + { + "href": function( elem ) { + return elem.getAttribute( "href", 2 ); + }, + "type": function( elem ) { + return elem.getAttribute("type"); + } + }; + + // ID find and filter + if ( support.getIdNotName ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && !documentIsXML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && !documentIsXML ) { + var m = context.getElementById( id ); + + return m ? + m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? + [m] : + undefined : + []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.tagNameNoComments ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Name + Expr.find["NAME"] = support.getByName && function( tag, context ) { + if ( typeof context.getElementsByName !== strundefined ) { + return context.getElementsByName( name ); + } + }; + + // Class + Expr.find["CLASS"] = support.getByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { + return context.getElementsByClassName( className ); + } + }; + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21), + // no need to also add to buggyMatches since matches checks buggyQSA + // A support test would require too much code (would include document ready) + rbuggyQSA = [ ":focus" ]; + + if ( (support.qsa = isNative(doc.querySelectorAll)) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explictly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // IE8 - Some boolean attributes are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + + // Opera 10-12/IE8 - ^= $= *= and empty values + // Should not select anything + div.innerHTML = ""; + if ( div.querySelectorAll("[i^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || + docElem.mozMatchesSelector || + docElem.webkitMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + // Document order sorting + sortOrder = docElem.compareDocumentPosition ? + function( a, b ) { + var compare; + + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { + if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { + if ( a === doc || contains( preferredDoc, a ) ) { + return -1; + } + if ( b === doc || contains( preferredDoc, b ) ) { + return 1; + } + return 0; + } + return compare & 4 ? -1 : 1; + } + + return a.compareDocumentPosition ? -1 : 1; + } : + function( a, b ) { + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Parentless nodes are either documents or disconnected + } else if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + // Always assume the presence of duplicates if sort doesn't + // pass them to our comparison function (as in Google Chrome). + hasDuplicate = false; + [0, 0].sort( sortOrder ); + support.detectDuplicates = hasDuplicate; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + // rbuggyQSA always contains :focus, so no need for an existence check + if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch(e) {} + } + + return Sizzle( expr, document, null, [elem] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + var val; + + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + if ( !documentIsXML ) { + name = name.toLowerCase(); + } + if ( (val = Expr.attrHandle[ name ]) ) { + return val( elem ); + } + if ( documentIsXML || support.attributes ) { + return elem.getAttribute( name ); + } + return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? + name : + val && val.specified ? val.value : null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +// Document sorting and removing duplicates +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + i = 1, + j = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( ; (elem = results[i]); i++ ) { + if ( elem === results[ i - 1 ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + return results; +}; + +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +// Returns a function to use in pseudos for input types +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +// Returns a function to use in pseudos for buttons +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +// Returns a function to use in pseudos for positionals +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + for ( ; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (see #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[5] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[4] ) { + match[2] = match[4]; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeName ) { + if ( nodeName === "*" ) { + return function() { return true; }; + } + + nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifider + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsXML ? + elem.getAttribute("xml:lang") || elem.getAttribute("lang") : + elem.lang) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +function tokenize( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( tokens = [] ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push( { + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + } ); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push( { + value: matched, + type: type, + matches: match + } ); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +} + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var data, cache, outerCache, + dirkey = dirruns + " " + doneName; + + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { + if ( (data = cache[1]) === true || data === cachedruns ) { + return data === true; + } + } else { + cache = outerCache[ dir ] = [ dirkey ]; + cache[1] = matcher( elem, context, xml ) || cachedruns; + if ( cache[1] === true ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + // A counter to specify which element is currently being matched + var matcherCachedRuns = 0, + bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, expandContext ) { + var elem, j, matcher, + setMatched = [], + matchedCount = 0, + i = "0", + unmatched = seed && [], + outermost = expandContext != null, + contextBackup = outermostContext, + // We must always have either seed elements or context + elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = matcherCachedRuns; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++matcherCachedRuns; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !group ) { + group = tokenize( selector ); + } + i = group.length; + while ( i-- ) { + cached = matcherFromTokens( group[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + } + return cached; +}; + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function select( selector, context, results, seed ) { + var i, tokens, token, type, find, + match = tokenize( selector ); + + if ( !seed ) { + // Try to minimize operations if there is only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + context.nodeType === 9 && !documentIsXML && + Expr.relative[ tokens[1].type ] ) { + + context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; + if ( !context ) { + return results; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && context.parentNode || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, slice.call( seed, 0 ) ); + return results; + } + + break; + } + } + } + } + } + + // Compile and execute a filtering function + // Provide `match` to avoid retokenization if we modified the selector above + compile( selector, match )( + seed, + context, + documentIsXML, + results, + rsibling.test( selector ) + ); + return results; +} + +// Deprecated +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Easy API for creating new setFilters +function setFilters() {} +Expr.filters = setFilters.prototype = Expr.pseudos; +Expr.setFilters = new setFilters(); + +// Initialize with the default document +setDocument(); + +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})( window ); +var runtil = /Until$/, + rparentsprev = /^(?:parents|prev(?:Until|All))/, + isSimple = /^.[^:#\[\.,]*$/, + rneedsContext = jQuery.expr.match.needsContext, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var i, ret, self, + len = this.length; + + if ( typeof selector !== "string" ) { + self = this; + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } + + ret = []; + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, this[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; + return ret; + }, + + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false) ); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true) ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + rneedsContext.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + ret = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + cur = this[i]; + + while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + } + cur = cur.parentNode; + } + } + + return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( jQuery.unique(all) ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +jQuery.fn.andSelf = jQuery.fn.addBack; + +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); + + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( this.length > 1 && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rtbody = /\s*$/g, + + // We have to close these tags to support XHTML (#13200) + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
", "
" ], + area: [ 1, "", "" ], + param: [ 1, "", "" ], + thead: [ 1, "", "
" ], + tr: [ 2, "", "
" ], + col: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, + // unless wrapped in a div with non-breaking characters in front of it. + _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
", "
" ] + }, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +jQuery.fn.extend({ + text: function( value ) { + return jQuery.access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + wrapAll: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapAll( html.call(this, i) ); + }); + } + + if ( this[0] ) { + // The elements to wrap the target around + var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); + + if ( this[0].parentNode ) { + wrap.insertBefore( this[0] ); + } + + wrap.map(function() { + var elem = this; + + while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { + elem = elem.firstChild; + } + + return elem; + }).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapInner( html.call(this, i) ); + }); + } + + return this.each(function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + }); + }, + + wrap: function( html ) { + var isFunction = jQuery.isFunction( html ); + + return this.each(function(i) { + jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); + }); + }, + + unwrap: function() { + return this.parent().each(function() { + if ( !jQuery.nodeName( this, "body" ) ) { + jQuery( this ).replaceWith( this.childNodes ); + } + }).end(); + }, + + append: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.insertBefore( elem, this.firstChild ); + } + }); + }, + + before: function() { + return this.domManip( arguments, false, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + }); + }, + + after: function() { + return this.domManip( arguments, false, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + }); + }, + + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem ) ); + } + + if ( elem.parentNode ) { + if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { + setGlobalEval( getAll( elem, "script" ) ); + } + elem.parentNode.removeChild( elem ); + } + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + + // If this is a select, ensure that it displays empty (#12336) + // Support: IE<9 + if ( elem.options && jQuery.nodeName( elem, "select" ) ) { + elem.options.length = 0; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function () { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return jQuery.access( this, function( value ) { + var elem = this[0] || {}, + i = 0, + l = this.length; + + if ( value === undefined ) { + return elem.nodeType === 1 ? + elem.innerHTML.replace( rinlinejQuery, "" ) : + undefined; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch(e) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function( value ) { + var isFunc = jQuery.isFunction( value ); + + // Make sure that the elements are removed from the DOM before they are inserted + // this can help fix replacing a parent with child elements + if ( !isFunc && typeof value !== "string" ) { + value = jQuery( value ).not( this ).detach(); + } + + return this.domManip( [ value ], true, function( elem ) { + var next = this.nextSibling, + parent = this.parentNode; + + if ( parent ) { + jQuery( this ).remove(); + parent.insertBefore( elem, next ); + } + }); + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, table, callback ) { + + // Flatten any nested arrays + args = core_concat.apply( [], args ); + + var first, node, hasScripts, + scripts, doc, fragment, + i = 0, + l = this.length, + set = this, + iNoClone = l - 1, + value = args[0], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { + return this.each(function( index ) { + var self = set.eq( index ); + if ( isFunction ) { + args[0] = value.call( this, index, table ? self.html() : undefined ); + } + self.domManip( args, table, callback ); + }); + } + + if ( l ) { + fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + table = table && jQuery.nodeName( first, "tr" ); + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( + table && jQuery.nodeName( this[i], "table" ) ? + findOrAppend( this[i], "tbody" ) : + this[i], + node, + i + ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + + if ( node.src ) { + // Hope ajax is available... + jQuery.ajax({ + url: node.src, + type: "GET", + dataType: "script", + async: false, + global: false, + "throws": true + }); + } else { + jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + } + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + } + } + + return this; + } +}); + +function findOrAppend( elem, tag ) { + return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + var attr = elem.getAttributeNode("type"); + elem.type = ( attr && attr.specified ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + if ( match ) { + elem.type = match[1]; + } else { + elem.removeAttribute("type"); + } + return elem; +} + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var elem, + i = 0; + for ( ; (elem = elems[i]) != null; i++ ) { + jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); + } +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function fixCloneNodeIssues( src, dest ) { + var nodeName, e, data; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + nodeName = dest.nodeName.toLowerCase(); + + // IE6-8 copies events bound via attachEvent when using cloneNode. + if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { + data = jQuery._data( dest ); + + for ( e in data.events ) { + jQuery.removeEvent( dest, e, data.handle ); + } + + // Event data gets referenced instead of copied if the expando gets copied too + dest.removeAttribute( jQuery.expando ); + } + + // IE blanks contents when cloning scripts, and tries to evaluate newly-set text + if ( nodeName === "script" && dest.text !== src.text ) { + disableScript( dest ).text = src.text; + restoreScript( dest ); + + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + } else if ( nodeName === "object" ) { + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; + } + + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { + dest.innerHTML = src.innerHTML; + } + + } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + + dest.defaultChecked = dest.checked = src.checked; + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.defaultSelected = dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + i = 0, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone(true); + jQuery( insert[i] )[ original ]( elems ); + + // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() + core_push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +}); + +function getAll( context, tag ) { + var elems, elem, + i = 0, + found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : + undefined; + + if ( !found ) { + for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { + if ( !tag || jQuery.nodeName( elem, tag ) ) { + found.push( elem ); + } else { + jQuery.merge( found, getAll( elem, tag ) ); + } + } + } + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], found ) : + found; +} + +// Used in buildFragment, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( manipulation_rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var destElements, node, clone, i, srcElements, + inPage = jQuery.contains( elem.ownerDocument, elem ); + + if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { + clone = elem.cloneNode( true ); + + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } + + if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + // Fix all IE cloning issues + for ( i = 0; (node = srcElements[i]) != null; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + fixCloneNodeIssues( node, destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0; (node = srcElements[i]) != null; i++ ) { + cloneCopyEvent( node, destElements[i] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + destElements = srcElements = node = null; + + // Return the cloned set + return clone; + }, + + buildFragment: function( elems, context, scripts, selection ) { + var j, elem, contains, + tmp, tag, tbody, wrap, + l = elems.length, + + // Ensure a safe fragment + safe = createSafeFragment( context ), + + nodes = [], + i = 0; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || safe.appendChild( context.createElement("div") ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + + tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; + + // Descend through wrappers to the right content + j = wrap[0]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Manually add leading whitespace removed by IE + if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); + } + + // Remove IE's autoinserted from table fragments + if ( !jQuery.support.tbody ) { + + // String was a , *may* have spurious + elem = tag === "table" && !rtbody.test( elem ) ? + tmp.firstChild : + + // String was a bare or + wrap[1] === "
" && !rtbody.test( elem ) ? + tmp : + 0; + + j = elem && elem.childNodes.length; + while ( j-- ) { + if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { + elem.removeChild( tbody ); + } + } + } + + jQuery.merge( nodes, tmp.childNodes ); + + // Fix #12392 for WebKit and IE > 9 + tmp.textContent = ""; + + // Fix #12392 for oldIE + while ( tmp.firstChild ) { + tmp.removeChild( tmp.firstChild ); + } + + // Remember the top-level container for proper cleanup + tmp = safe.lastChild; + } + } + } + + // Fix #11356: Clear elements from fragment + if ( tmp ) { + safe.removeChild( tmp ); + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !jQuery.support.appendChecked ) { + jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); + } + + i = 0; + while ( (elem = nodes[ i++ ]) ) { + + // #4087 - If origin and destination elements are the same, and this is + // that element, do not do anything + if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( safe.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( (elem = tmp[ j++ ]) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + tmp = null; + + return safe; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var elem, type, id, data, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = jQuery.support.deleteExpando, + special = jQuery.event.special; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( acceptData || jQuery.acceptData( elem ) ) { + + id = elem[ internalKey ]; + data = id && cache[ id ]; + + if ( data ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Remove cache only if it was not already removed by jQuery.event.remove + if ( cache[ id ] ) { + + delete cache[ id ]; + + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( deleteExpando ) { + delete elem[ internalKey ]; + + } else if ( typeof elem.removeAttribute !== core_strundefined ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + core_deletedIds.push( id ); + } + } + } + } + } +}); +var iframe, getStyles, curCSS, + ralpha = /alpha\([^)]*\)/i, + ropacity = /opacity\s*=\s*([^)]*)/, + rposition = /^(top|right|bottom|left)$/, + // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" + // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rmargin = /^margin/, + rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), + rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), + rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), + elemdisplay = { BODY: "block" }, + + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: 0, + fontWeight: 400 + }, + + cssExpand = [ "Top", "Right", "Bottom", "Left" ], + cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; + +// return a css property mapped to a potentially vendor prefixed property +function vendorPropName( style, name ) { + + // shortcut for names that are not vendor prefixed + if ( name in style ) { + return name; + } + + // check for vendor prefixed names + var capName = name.charAt(0).toUpperCase() + name.slice(1), + origName = name, + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in style ) { + return name; + } + } + + return origName; +} + +function isHidden( elem, el ) { + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); +} + +function showHide( elements, show ) { + var display, elem, hidden, + values = [], + index = 0, + length = elements.length; + + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + values[ index ] = jQuery._data( elem, "olddisplay" ); + display = elem.style.display; + if ( show ) { + // Reset the inline display of this element to learn if it is + // being hidden by cascaded rules or not + if ( !values[ index ] && display === "none" ) { + elem.style.display = ""; + } + + // Set elements which have been overridden with display: none + // in a stylesheet to whatever the default browser style is + // for such an element + if ( elem.style.display === "" && isHidden( elem ) ) { + values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); + } + } else { + + if ( !values[ index ] ) { + hidden = isHidden( elem ); + + if ( display && display !== "none" || !hidden ) { + jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); + } + } + } + } + + // Set the display of most of the elements in a second loop + // to avoid the constant reflow + for ( index = 0; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + if ( !show || elem.style.display === "none" || elem.style.display === "" ) { + elem.style.display = show ? values[ index ] || "" : "none"; + } + } + + return elements; +} + +jQuery.fn.extend({ + css: function( name, value ) { + return jQuery.access( this, function( elem, name, value ) { + var len, styles, + map = {}, + i = 0; + + if ( jQuery.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + }, + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + var bool = typeof state === "boolean"; + + return this.each(function() { + if ( bool ? state : isHidden( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + }); + } +}); + +jQuery.extend({ + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Exclude the following css properties to add px + cssNumber: { + "columnCount": true, + "fillOpacity": true, + "fontWeight": true, + "lineHeight": true, + "opacity": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: { + // normalize float css property + "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" + }, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = jQuery.camelCase( name ), + style = elem.style; + + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // convert relative number strings (+= or -=) to relative numbers. #7345 + if ( type === "string" && (ret = rrelNum.exec( value )) ) { + value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); + // Fixes bug #9237 + type = "number"; + } + + // Make sure that NaN and null values aren't set. See: #7116 + if ( value == null || type === "number" && isNaN( value ) ) { + return; + } + + // If a number was passed in, add 'px' to the (except for certain CSS properties) + if ( type === "number" && !jQuery.cssNumber[ origName ] ) { + value += "px"; + } + + // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, + // but it would mean to define eight (for every problematic property) identical functions + if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { + + // Wrapped to prevent IE from throwing errors when 'invalid' values are provided + // Fixes bug #5509 + try { + style[ name ] = value; + } catch(e) {} + } + + } else { + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var num, val, hooks, + origName = jQuery.camelCase( name ); + + // Make sure that we're working with the right name + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + //convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Return, converting to number if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; + } + return val; + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback, args ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.apply( elem, args || [] ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; + } +}); + +// NOTE: we've included the "window" in window.getComputedStyle +// because jsdom on node.js will break without it. +if ( window.getComputedStyle ) { + getStyles = function( elem ) { + return window.getComputedStyle( elem, null ); + }; + + curCSS = function( elem, name, _computed ) { + var width, minWidth, maxWidth, + computed = _computed || getStyles( elem ), + + // getPropertyValue is only needed for .css('filter') in IE9, see #12537 + ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, + style = elem.style; + + if ( computed ) { + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right + // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels + // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values + if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret; + }; +} else if ( document.documentElement.currentStyle ) { + getStyles = function( elem ) { + return elem.currentStyle; + }; + + curCSS = function( elem, name, _computed ) { + var left, rs, rsLeft, + computed = _computed || getStyles( elem ), + ret = computed ? computed[ name ] : undefined, + style = elem.style; + + // Avoid setting ret to empty string here + // so we don't default to auto + if ( ret == null && style && style[ name ] ) { + ret = style[ name ]; + } + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + // but not position css attributes, as those are proportional to the parent element instead + // and we can't measure the parent instead because it might trigger a "stacking dolls" problem + if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { + + // Remember the original values + left = style.left; + rs = elem.runtimeStyle; + rsLeft = rs && rs.left; + + // Put in the new values to get a computed value out + if ( rsLeft ) { + rs.left = elem.currentStyle.left; + } + style.left = name === "fontSize" ? "1em" : ret; + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + if ( rsLeft ) { + rs.left = rsLeft; + } + } + + return ret === "" ? "auto" : ret; + }; +} + +function setPositiveNumber( elem, value, subtract ) { + var matches = rnumsplit.exec( value ); + return matches ? + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : + value; +} + +function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { + var i = extra === ( isBorderBox ? "border" : "content" ) ? + // If we already have the right measurement, avoid augmentation + 4 : + // Otherwise initialize for horizontal or vertical properties + name === "width" ? 1 : 0, + + val = 0; + + for ( ; i < 4; i += 2 ) { + // both box models exclude margin, so add it if we want it + if ( extra === "margin" ) { + val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); + } + + if ( isBorderBox ) { + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // at this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } else { + // at this point, extra isn't content, so add padding + val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // at this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with offset property, which is equivalent to the border-box value + var valueIsBorderBox = true, + val = name === "width" ? elem.offsetWidth : elem.offsetHeight, + styles = getStyles( elem ), + isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // some non-html elements return undefined for offsetWidth, so check for null/undefined + // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 + // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 + if ( val <= 0 || val == null ) { + // Fall back to computed then uncomputed css if necessary + val = curCSS( elem, name, styles ); + if ( val < 0 || val == null ) { + val = elem.style[ name ]; + } + + // Computed unit is not pixels. Stop here and return. + if ( rnumnonpx.test(val) ) { + return val; + } + + // we need the check for style in case a browser which returns unreliable values + // for getComputedStyle silently falls back to the reliable elem.style + valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); + + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + } + + // use the active box-sizing model to add/subtract irrelevant styles + return ( val + + augmentWidthOrHeight( + elem, + name, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles + ) + ) + "px"; +} + +// Try to determine the default display value of an element +function css_defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + // Use the already-created iframe if possible + iframe = ( iframe || + jQuery("' : ''); + inst._keyEvent = false; + return html; + }, + + /* Generate the month and year header. */ + _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, + secondary, monthNames, monthNamesShort) { + var changeMonth = this._get(inst, 'changeMonth'); + var changeYear = this._get(inst, 'changeYear'); + var showMonthAfterYear = this._get(inst, 'showMonthAfterYear'); + var html = '
'; + var monthHtml = ''; + // month selection + if (secondary || !changeMonth) + monthHtml += '' + monthNames[drawMonth] + ''; + else { + var inMinYear = (minDate && minDate.getFullYear() == drawYear); + var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear); + monthHtml += ''; + } + if (!showMonthAfterYear) + html += monthHtml + (secondary || !(changeMonth && changeYear) ? ' ' : ''); + // year selection + if ( !inst.yearshtml ) { + inst.yearshtml = ''; + if (secondary || !changeYear) + html += '' + drawYear + ''; + else { + // determine range of years to display + var years = this._get(inst, 'yearRange').split(':'); + var thisYear = new Date().getFullYear(); + var determineYear = function(value) { + var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) : + (value.match(/[+-].*/) ? thisYear + parseInt(value, 10) : + parseInt(value, 10))); + return (isNaN(year) ? thisYear : year); + }; + var year = determineYear(years[0]); + var endYear = Math.max(year, determineYear(years[1] || '')); + year = (minDate ? Math.max(year, minDate.getFullYear()) : year); + endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); + inst.yearshtml += ''; + + html += inst.yearshtml; + inst.yearshtml = null; + } + } + html += this._get(inst, 'yearSuffix'); + if (showMonthAfterYear) + html += (secondary || !(changeMonth && changeYear) ? ' ' : '') + monthHtml; + html += '
'; // Close datepicker_header + return html; + }, + + /* Adjust one of the date sub-fields. */ + _adjustInstDate: function(inst, offset, period) { + var year = inst.drawYear + (period == 'Y' ? offset : 0); + var month = inst.drawMonth + (period == 'M' ? offset : 0); + var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + + (period == 'D' ? offset : 0); + var date = this._restrictMinMax(inst, + this._daylightSavingAdjust(new Date(year, month, day))); + inst.selectedDay = date.getDate(); + inst.drawMonth = inst.selectedMonth = date.getMonth(); + inst.drawYear = inst.selectedYear = date.getFullYear(); + if (period == 'M' || period == 'Y') + this._notifyChange(inst); + }, + + /* Ensure a date is within any min/max bounds. */ + _restrictMinMax: function(inst, date) { + var minDate = this._getMinMaxDate(inst, 'min'); + var maxDate = this._getMinMaxDate(inst, 'max'); + var newDate = (minDate && date < minDate ? minDate : date); + newDate = (maxDate && newDate > maxDate ? maxDate : newDate); + return newDate; + }, + + /* Notify change of month/year. */ + _notifyChange: function(inst) { + var onChange = this._get(inst, 'onChangeMonthYear'); + if (onChange) + onChange.apply((inst.input ? inst.input[0] : null), + [inst.selectedYear, inst.selectedMonth + 1, inst]); + }, + + /* Determine the number of months to show. */ + _getNumberOfMonths: function(inst) { + var numMonths = this._get(inst, 'numberOfMonths'); + return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths)); + }, + + /* Determine the current maximum date - ensure no time components are set. */ + _getMinMaxDate: function(inst, minMax) { + return this._determineDate(inst, this._get(inst, minMax + 'Date'), null); + }, + + /* Find the number of days in a given month. */ + _getDaysInMonth: function(year, month) { + return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); + }, + + /* Find the day of the week of the first of a month. */ + _getFirstDayOfMonth: function(year, month) { + return new Date(year, month, 1).getDay(); + }, + + /* Determines if we should allow a "next/prev" month display change. */ + _canAdjustMonth: function(inst, offset, curYear, curMonth) { + var numMonths = this._getNumberOfMonths(inst); + var date = this._daylightSavingAdjust(new Date(curYear, + curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); + if (offset < 0) + date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); + return this._isInRange(inst, date); + }, + + /* Is the given date in the accepted range? */ + _isInRange: function(inst, date) { + var minDate = this._getMinMaxDate(inst, 'min'); + var maxDate = this._getMinMaxDate(inst, 'max'); + return ((!minDate || date.getTime() >= minDate.getTime()) && + (!maxDate || date.getTime() <= maxDate.getTime())); + }, + + /* Provide the configuration settings for formatting/parsing. */ + _getFormatConfig: function(inst) { + var shortYearCutoff = this._get(inst, 'shortYearCutoff'); + shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : + new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); + return {shortYearCutoff: shortYearCutoff, + dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'), + monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')}; + }, + + /* Format the given date for display. */ + _formatDate: function(inst, day, month, year) { + if (!day) { + inst.currentDay = inst.selectedDay; + inst.currentMonth = inst.selectedMonth; + inst.currentYear = inst.selectedYear; + } + var date = (day ? (typeof day == 'object' ? day : + this._daylightSavingAdjust(new Date(year, month, day))) : + this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); + return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst)); + } +}); + +/* + * Bind hover events for datepicker elements. + * Done via delegate so the binding only occurs once in the lifetime of the parent div. + * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. + */ +function bindHover(dpDiv) { + var selector = 'button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a'; + return dpDiv.delegate(selector, 'mouseout', function() { + $(this).removeClass('ui-state-hover'); + if (this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover'); + if (this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover'); + }) + .delegate(selector, 'mouseover', function(){ + if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) { + $(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover'); + $(this).addClass('ui-state-hover'); + if (this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover'); + if (this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover'); + } + }); +} + +/* jQuery extend now ignores nulls! */ +function extendRemove(target, props) { + $.extend(target, props); + for (var name in props) + if (props[name] == null || props[name] == undefined) + target[name] = props[name]; + return target; +}; + +/* Invoke the datepicker functionality. + @param options string - a command, optionally followed by additional parameters or + Object - settings for attaching new datepicker functionality + @return jQuery object */ +$.fn.datepicker = function(options){ + + /* Verify an empty collection wasn't passed - Fixes #6976 */ + if ( !this.length ) { + return this; + } + + /* Initialise the date picker. */ + if (!$.datepicker.initialized) { + $(document).mousedown($.datepicker._checkExternalClick). + find(document.body).append($.datepicker.dpDiv); + $.datepicker.initialized = true; + } + + var otherArgs = Array.prototype.slice.call(arguments, 1); + if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget')) + return $.datepicker['_' + options + 'Datepicker']. + apply($.datepicker, [this[0]].concat(otherArgs)); + if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string') + return $.datepicker['_' + options + 'Datepicker']. + apply($.datepicker, [this[0]].concat(otherArgs)); + return this.each(function() { + typeof options == 'string' ? + $.datepicker['_' + options + 'Datepicker']. + apply($.datepicker, [this].concat(otherArgs)) : + $.datepicker._attachDatepicker(this, options); + }); +}; + +$.datepicker = new Datepicker(); // singleton instance +$.datepicker.initialized = false; +$.datepicker.uuid = new Date().getTime(); +$.datepicker.version = "1.9.2"; + +// Workaround for #4055 +// Add another global to avoid noConflict issues with inline event handlers +window['DP_jQuery_' + dpuuid] = $; + +})(jQuery); + +(function( $, undefined ) { + +var uiDialogClasses = "ui-dialog ui-widget ui-widget-content ui-corner-all ", + sizeRelatedOptions = { + buttons: true, + height: true, + maxHeight: true, + maxWidth: true, + minHeight: true, + minWidth: true, + width: true + }, + resizableRelatedOptions = { + maxHeight: true, + maxWidth: true, + minHeight: true, + minWidth: true + }; + +$.widget("ui.dialog", { + version: "1.9.2", + options: { + autoOpen: true, + buttons: {}, + closeOnEscape: true, + closeText: "close", + dialogClass: "", + draggable: true, + hide: null, + height: "auto", + maxHeight: false, + maxWidth: false, + minHeight: 150, + minWidth: 150, + modal: false, + position: { + my: "center", + at: "center", + of: window, + collision: "fit", + // ensure that the titlebar is never outside the document + using: function( pos ) { + var topOffset = $( this ).css( pos ).offset().top; + if ( topOffset < 0 ) { + $( this ).css( "top", pos.top - topOffset ); + } + } + }, + resizable: true, + show: null, + stack: true, + title: "", + width: 300, + zIndex: 1000 + }, + + _create: function() { + this.originalTitle = this.element.attr( "title" ); + // #5742 - .attr() might return a DOMElement + if ( typeof this.originalTitle !== "string" ) { + this.originalTitle = ""; + } + this.oldPosition = { + parent: this.element.parent(), + index: this.element.parent().children().index( this.element ) + }; + this.options.title = this.options.title || this.originalTitle; + var that = this, + options = this.options, + + title = options.title || " ", + uiDialog, + uiDialogTitlebar, + uiDialogTitlebarClose, + uiDialogTitle, + uiDialogButtonPane; + + uiDialog = ( this.uiDialog = $( "
" ) ) + .addClass( uiDialogClasses + options.dialogClass ) + .css({ + display: "none", + outline: 0, // TODO: move to stylesheet + zIndex: options.zIndex + }) + // setting tabIndex makes the div focusable + .attr( "tabIndex", -1) + .keydown(function( event ) { + if ( options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && + event.keyCode === $.ui.keyCode.ESCAPE ) { + that.close( event ); + event.preventDefault(); + } + }) + .mousedown(function( event ) { + that.moveToTop( false, event ); + }) + .appendTo( "body" ); + + this.element + .show() + .removeAttr( "title" ) + .addClass( "ui-dialog-content ui-widget-content" ) + .appendTo( uiDialog ); + + uiDialogTitlebar = ( this.uiDialogTitlebar = $( "
" ) ) + .addClass( "ui-dialog-titlebar ui-widget-header " + + "ui-corner-all ui-helper-clearfix" ) + .bind( "mousedown", function() { + // Dialog isn't getting focus when dragging (#8063) + uiDialog.focus(); + }) + .prependTo( uiDialog ); + + uiDialogTitlebarClose = $( "" ) + .addClass( "ui-dialog-titlebar-close ui-corner-all" ) + .attr( "role", "button" ) + .click(function( event ) { + event.preventDefault(); + that.close( event ); + }) + .appendTo( uiDialogTitlebar ); + + ( this.uiDialogTitlebarCloseText = $( "" ) ) + .addClass( "ui-icon ui-icon-closethick" ) + .text( options.closeText ) + .appendTo( uiDialogTitlebarClose ); + + uiDialogTitle = $( "" ) + .uniqueId() + .addClass( "ui-dialog-title" ) + .html( title ) + .prependTo( uiDialogTitlebar ); + + uiDialogButtonPane = ( this.uiDialogButtonPane = $( "
" ) ) + .addClass( "ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" ); + + ( this.uiButtonSet = $( "
" ) ) + .addClass( "ui-dialog-buttonset" ) + .appendTo( uiDialogButtonPane ); + + uiDialog.attr({ + role: "dialog", + "aria-labelledby": uiDialogTitle.attr( "id" ) + }); + + uiDialogTitlebar.find( "*" ).add( uiDialogTitlebar ).disableSelection(); + this._hoverable( uiDialogTitlebarClose ); + this._focusable( uiDialogTitlebarClose ); + + if ( options.draggable && $.fn.draggable ) { + this._makeDraggable(); + } + if ( options.resizable && $.fn.resizable ) { + this._makeResizable(); + } + + this._createButtons( options.buttons ); + this._isOpen = false; + + if ( $.fn.bgiframe ) { + uiDialog.bgiframe(); + } + + // prevent tabbing out of modal dialogs + this._on( uiDialog, { keydown: function( event ) { + if ( !options.modal || event.keyCode !== $.ui.keyCode.TAB ) { + return; + } + + var tabbables = $( ":tabbable", uiDialog ), + first = tabbables.filter( ":first" ), + last = tabbables.filter( ":last" ); + + if ( event.target === last[0] && !event.shiftKey ) { + first.focus( 1 ); + return false; + } else if ( event.target === first[0] && event.shiftKey ) { + last.focus( 1 ); + return false; + } + }}); + }, + + _init: function() { + if ( this.options.autoOpen ) { + this.open(); + } + }, + + _destroy: function() { + var next, + oldPosition = this.oldPosition; + + if ( this.overlay ) { + this.overlay.destroy(); + } + this.uiDialog.hide(); + this.element + .removeClass( "ui-dialog-content ui-widget-content" ) + .hide() + .appendTo( "body" ); + this.uiDialog.remove(); + + if ( this.originalTitle ) { + this.element.attr( "title", this.originalTitle ); + } + + next = oldPosition.parent.children().eq( oldPosition.index ); + // Don't try to place the dialog next to itself (#8613) + if ( next.length && next[ 0 ] !== this.element[ 0 ] ) { + next.before( this.element ); + } else { + oldPosition.parent.append( this.element ); + } + }, + + widget: function() { + return this.uiDialog; + }, + + close: function( event ) { + var that = this, + maxZ, thisZ; + + if ( !this._isOpen ) { + return; + } + + if ( false === this._trigger( "beforeClose", event ) ) { + return; + } + + this._isOpen = false; + + if ( this.overlay ) { + this.overlay.destroy(); + } + + if ( this.options.hide ) { + this._hide( this.uiDialog, this.options.hide, function() { + that._trigger( "close", event ); + }); + } else { + this.uiDialog.hide(); + this._trigger( "close", event ); + } + + $.ui.dialog.overlay.resize(); + + // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) + if ( this.options.modal ) { + maxZ = 0; + $( ".ui-dialog" ).each(function() { + if ( this !== that.uiDialog[0] ) { + thisZ = $( this ).css( "z-index" ); + if ( !isNaN( thisZ ) ) { + maxZ = Math.max( maxZ, thisZ ); + } + } + }); + $.ui.dialog.maxZ = maxZ; + } + + return this; + }, + + isOpen: function() { + return this._isOpen; + }, + + // the force parameter allows us to move modal dialogs to their correct + // position on open + moveToTop: function( force, event ) { + var options = this.options, + saveScroll; + + if ( ( options.modal && !force ) || + ( !options.stack && !options.modal ) ) { + return this._trigger( "focus", event ); + } + + if ( options.zIndex > $.ui.dialog.maxZ ) { + $.ui.dialog.maxZ = options.zIndex; + } + if ( this.overlay ) { + $.ui.dialog.maxZ += 1; + $.ui.dialog.overlay.maxZ = $.ui.dialog.maxZ; + this.overlay.$el.css( "z-index", $.ui.dialog.overlay.maxZ ); + } + + // Save and then restore scroll + // Opera 9.5+ resets when parent z-index is changed. + // http://bugs.jqueryui.com/ticket/3193 + saveScroll = { + scrollTop: this.element.scrollTop(), + scrollLeft: this.element.scrollLeft() + }; + $.ui.dialog.maxZ += 1; + this.uiDialog.css( "z-index", $.ui.dialog.maxZ ); + this.element.attr( saveScroll ); + this._trigger( "focus", event ); + + return this; + }, + + open: function() { + if ( this._isOpen ) { + return; + } + + var hasFocus, + options = this.options, + uiDialog = this.uiDialog; + + this._size(); + this._position( options.position ); + uiDialog.show( options.show ); + this.overlay = options.modal ? new $.ui.dialog.overlay( this ) : null; + this.moveToTop( true ); + + // set focus to the first tabbable element in the content area or the first button + // if there are no tabbable elements, set focus on the dialog itself + hasFocus = this.element.find( ":tabbable" ); + if ( !hasFocus.length ) { + hasFocus = this.uiDialogButtonPane.find( ":tabbable" ); + if ( !hasFocus.length ) { + hasFocus = uiDialog; + } + } + hasFocus.eq( 0 ).focus(); + + this._isOpen = true; + this._trigger( "open" ); + + return this; + }, + + _createButtons: function( buttons ) { + var that = this, + hasButtons = false; + + // if we already have a button pane, remove it + this.uiDialogButtonPane.remove(); + this.uiButtonSet.empty(); + + if ( typeof buttons === "object" && buttons !== null ) { + $.each( buttons, function() { + return !(hasButtons = true); + }); + } + if ( hasButtons ) { + $.each( buttons, function( name, props ) { + var button, click; + props = $.isFunction( props ) ? + { click: props, text: name } : + props; + // Default to a non-submitting button + props = $.extend( { type: "button" }, props ); + // Change the context for the click callback to be the main element + click = props.click; + props.click = function() { + click.apply( that.element[0], arguments ); + }; + button = $( "", props ) + .appendTo( that.uiButtonSet ); + if ( $.fn.button ) { + button.button(); + } + }); + this.uiDialog.addClass( "ui-dialog-buttons" ); + this.uiDialogButtonPane.appendTo( this.uiDialog ); + } else { + this.uiDialog.removeClass( "ui-dialog-buttons" ); + } + }, + + _makeDraggable: function() { + var that = this, + options = this.options; + + function filteredUi( ui ) { + return { + position: ui.position, + offset: ui.offset + }; + } + + this.uiDialog.draggable({ + cancel: ".ui-dialog-content, .ui-dialog-titlebar-close", + handle: ".ui-dialog-titlebar", + containment: "document", + start: function( event, ui ) { + $( this ) + .addClass( "ui-dialog-dragging" ); + that._trigger( "dragStart", event, filteredUi( ui ) ); + }, + drag: function( event, ui ) { + that._trigger( "drag", event, filteredUi( ui ) ); + }, + stop: function( event, ui ) { + options.position = [ + ui.position.left - that.document.scrollLeft(), + ui.position.top - that.document.scrollTop() + ]; + $( this ) + .removeClass( "ui-dialog-dragging" ); + that._trigger( "dragStop", event, filteredUi( ui ) ); + $.ui.dialog.overlay.resize(); + } + }); + }, + + _makeResizable: function( handles ) { + handles = (handles === undefined ? this.options.resizable : handles); + var that = this, + options = this.options, + // .ui-resizable has position: relative defined in the stylesheet + // but dialogs have to use absolute or fixed positioning + position = this.uiDialog.css( "position" ), + resizeHandles = typeof handles === 'string' ? + handles : + "n,e,s,w,se,sw,ne,nw"; + + function filteredUi( ui ) { + return { + originalPosition: ui.originalPosition, + originalSize: ui.originalSize, + position: ui.position, + size: ui.size + }; + } + + this.uiDialog.resizable({ + cancel: ".ui-dialog-content", + containment: "document", + alsoResize: this.element, + maxWidth: options.maxWidth, + maxHeight: options.maxHeight, + minWidth: options.minWidth, + minHeight: this._minHeight(), + handles: resizeHandles, + start: function( event, ui ) { + $( this ).addClass( "ui-dialog-resizing" ); + that._trigger( "resizeStart", event, filteredUi( ui ) ); + }, + resize: function( event, ui ) { + that._trigger( "resize", event, filteredUi( ui ) ); + }, + stop: function( event, ui ) { + $( this ).removeClass( "ui-dialog-resizing" ); + options.height = $( this ).height(); + options.width = $( this ).width(); + that._trigger( "resizeStop", event, filteredUi( ui ) ); + $.ui.dialog.overlay.resize(); + } + }) + .css( "position", position ) + .find( ".ui-resizable-se" ) + .addClass( "ui-icon ui-icon-grip-diagonal-se" ); + }, + + _minHeight: function() { + var options = this.options; + + if ( options.height === "auto" ) { + return options.minHeight; + } else { + return Math.min( options.minHeight, options.height ); + } + }, + + _position: function( position ) { + var myAt = [], + offset = [ 0, 0 ], + isVisible; + + if ( position ) { + // deep extending converts arrays to objects in jQuery <= 1.3.2 :-( + // if (typeof position == 'string' || $.isArray(position)) { + // myAt = $.isArray(position) ? position : position.split(' '); + + if ( typeof position === "string" || (typeof position === "object" && "0" in position ) ) { + myAt = position.split ? position.split( " " ) : [ position[ 0 ], position[ 1 ] ]; + if ( myAt.length === 1 ) { + myAt[ 1 ] = myAt[ 0 ]; + } + + $.each( [ "left", "top" ], function( i, offsetPosition ) { + if ( +myAt[ i ] === myAt[ i ] ) { + offset[ i ] = myAt[ i ]; + myAt[ i ] = offsetPosition; + } + }); + + position = { + my: myAt[0] + (offset[0] < 0 ? offset[0] : "+" + offset[0]) + " " + + myAt[1] + (offset[1] < 0 ? offset[1] : "+" + offset[1]), + at: myAt.join( " " ) + }; + } + + position = $.extend( {}, $.ui.dialog.prototype.options.position, position ); + } else { + position = $.ui.dialog.prototype.options.position; + } + + // need to show the dialog to get the actual offset in the position plugin + isVisible = this.uiDialog.is( ":visible" ); + if ( !isVisible ) { + this.uiDialog.show(); + } + this.uiDialog.position( position ); + if ( !isVisible ) { + this.uiDialog.hide(); + } + }, + + _setOptions: function( options ) { + var that = this, + resizableOptions = {}, + resize = false; + + $.each( options, function( key, value ) { + that._setOption( key, value ); + + if ( key in sizeRelatedOptions ) { + resize = true; + } + if ( key in resizableRelatedOptions ) { + resizableOptions[ key ] = value; + } + }); + + if ( resize ) { + this._size(); + } + if ( this.uiDialog.is( ":data(resizable)" ) ) { + this.uiDialog.resizable( "option", resizableOptions ); + } + }, + + _setOption: function( key, value ) { + var isDraggable, isResizable, + uiDialog = this.uiDialog; + + switch ( key ) { + case "buttons": + this._createButtons( value ); + break; + case "closeText": + // ensure that we always pass a string + this.uiDialogTitlebarCloseText.text( "" + value ); + break; + case "dialogClass": + uiDialog + .removeClass( this.options.dialogClass ) + .addClass( uiDialogClasses + value ); + break; + case "disabled": + if ( value ) { + uiDialog.addClass( "ui-dialog-disabled" ); + } else { + uiDialog.removeClass( "ui-dialog-disabled" ); + } + break; + case "draggable": + isDraggable = uiDialog.is( ":data(draggable)" ); + if ( isDraggable && !value ) { + uiDialog.draggable( "destroy" ); + } + + if ( !isDraggable && value ) { + this._makeDraggable(); + } + break; + case "position": + this._position( value ); + break; + case "resizable": + // currently resizable, becoming non-resizable + isResizable = uiDialog.is( ":data(resizable)" ); + if ( isResizable && !value ) { + uiDialog.resizable( "destroy" ); + } + + // currently resizable, changing handles + if ( isResizable && typeof value === "string" ) { + uiDialog.resizable( "option", "handles", value ); + } + + // currently non-resizable, becoming resizable + if ( !isResizable && value !== false ) { + this._makeResizable( value ); + } + break; + case "title": + // convert whatever was passed in o a string, for html() to not throw up + $( ".ui-dialog-title", this.uiDialogTitlebar ) + .html( "" + ( value || " " ) ); + break; + } + + this._super( key, value ); + }, + + _size: function() { + /* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content + * divs will both have width and height set, so we need to reset them + */ + var nonContentHeight, minContentHeight, autoHeight, + options = this.options, + isVisible = this.uiDialog.is( ":visible" ); + + // reset content sizing + this.element.show().css({ + width: "auto", + minHeight: 0, + height: 0 + }); + + if ( options.minWidth > options.width ) { + options.width = options.minWidth; + } + + // reset wrapper sizing + // determine the height of all the non-content elements + nonContentHeight = this.uiDialog.css({ + height: "auto", + width: options.width + }) + .outerHeight(); + minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); + + if ( options.height === "auto" ) { + // only needed for IE6 support + if ( $.support.minHeight ) { + this.element.css({ + minHeight: minContentHeight, + height: "auto" + }); + } else { + this.uiDialog.show(); + autoHeight = this.element.css( "height", "auto" ).height(); + if ( !isVisible ) { + this.uiDialog.hide(); + } + this.element.height( Math.max( autoHeight, minContentHeight ) ); + } + } else { + this.element.height( Math.max( options.height - nonContentHeight, 0 ) ); + } + + if (this.uiDialog.is( ":data(resizable)" ) ) { + this.uiDialog.resizable( "option", "minHeight", this._minHeight() ); + } + } +}); + +$.extend($.ui.dialog, { + uuid: 0, + maxZ: 0, + + getTitleId: function($el) { + var id = $el.attr( "id" ); + if ( !id ) { + this.uuid += 1; + id = this.uuid; + } + return "ui-dialog-title-" + id; + }, + + overlay: function( dialog ) { + this.$el = $.ui.dialog.overlay.create( dialog ); + } +}); + +$.extend( $.ui.dialog.overlay, { + instances: [], + // reuse old instances due to IE memory leak with alpha transparency (see #5185) + oldInstances: [], + maxZ: 0, + events: $.map( + "focus,mousedown,mouseup,keydown,keypress,click".split( "," ), + function( event ) { + return event + ".dialog-overlay"; + } + ).join( " " ), + create: function( dialog ) { + if ( this.instances.length === 0 ) { + // prevent use of anchors and inputs + // we use a setTimeout in case the overlay is created from an + // event that we're going to be cancelling (see #2804) + setTimeout(function() { + // handle $(el).dialog().dialog('close') (see #4065) + if ( $.ui.dialog.overlay.instances.length ) { + $( document ).bind( $.ui.dialog.overlay.events, function( event ) { + // stop events if the z-index of the target is < the z-index of the overlay + // we cannot return true when we don't want to cancel the event (#3523) + if ( $( event.target ).zIndex() < $.ui.dialog.overlay.maxZ ) { + return false; + } + }); + } + }, 1 ); + + // handle window resize + $( window ).bind( "resize.dialog-overlay", $.ui.dialog.overlay.resize ); + } + + var $el = ( this.oldInstances.pop() || $( "
" ).addClass( "ui-widget-overlay" ) ); + + // allow closing by pressing the escape key + $( document ).bind( "keydown.dialog-overlay", function( event ) { + var instances = $.ui.dialog.overlay.instances; + // only react to the event if we're the top overlay + if ( instances.length !== 0 && instances[ instances.length - 1 ] === $el && + dialog.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && + event.keyCode === $.ui.keyCode.ESCAPE ) { + + dialog.close( event ); + event.preventDefault(); + } + }); + + $el.appendTo( document.body ).css({ + width: this.width(), + height: this.height() + }); + + if ( $.fn.bgiframe ) { + $el.bgiframe(); + } + + this.instances.push( $el ); + return $el; + }, + + destroy: function( $el ) { + var indexOf = $.inArray( $el, this.instances ), + maxZ = 0; + + if ( indexOf !== -1 ) { + this.oldInstances.push( this.instances.splice( indexOf, 1 )[ 0 ] ); + } + + if ( this.instances.length === 0 ) { + $( [ document, window ] ).unbind( ".dialog-overlay" ); + } + + $el.height( 0 ).width( 0 ).remove(); + + // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) + $.each( this.instances, function() { + maxZ = Math.max( maxZ, this.css( "z-index" ) ); + }); + this.maxZ = maxZ; + }, + + height: function() { + var scrollHeight, + offsetHeight; + // handle IE + if ( $.ui.ie ) { + scrollHeight = Math.max( + document.documentElement.scrollHeight, + document.body.scrollHeight + ); + offsetHeight = Math.max( + document.documentElement.offsetHeight, + document.body.offsetHeight + ); + + if ( scrollHeight < offsetHeight ) { + return $( window ).height() + "px"; + } else { + return scrollHeight + "px"; + } + // handle "good" browsers + } else { + return $( document ).height() + "px"; + } + }, + + width: function() { + var scrollWidth, + offsetWidth; + // handle IE + if ( $.ui.ie ) { + scrollWidth = Math.max( + document.documentElement.scrollWidth, + document.body.scrollWidth + ); + offsetWidth = Math.max( + document.documentElement.offsetWidth, + document.body.offsetWidth + ); + + if ( scrollWidth < offsetWidth ) { + return $( window ).width() + "px"; + } else { + return scrollWidth + "px"; + } + // handle "good" browsers + } else { + return $( document ).width() + "px"; + } + }, + + resize: function() { + /* If the dialog is draggable and the user drags it past the + * right edge of the window, the document becomes wider so we + * need to stretch the overlay. If the user then drags the + * dialog back to the left, the document will become narrower, + * so we need to shrink the overlay to the appropriate size. + * This is handled by shrinking the overlay before setting it + * to the full document size. + */ + var $overlays = $( [] ); + $.each( $.ui.dialog.overlay.instances, function() { + $overlays = $overlays.add( this ); + }); + + $overlays.css({ + width: 0, + height: 0 + }).css({ + width: $.ui.dialog.overlay.width(), + height: $.ui.dialog.overlay.height() + }); + } +}); + +$.extend( $.ui.dialog.overlay.prototype, { + destroy: function() { + $.ui.dialog.overlay.destroy( this.$el ); + } +}); + +}( jQuery ) ); + +(function( $, undefined ) { + +var rvertical = /up|down|vertical/, + rpositivemotion = /up|left|vertical|horizontal/; + +$.effects.effect.blind = function( o, done ) { + // Create element + var el = $( this ), + props = [ "position", "top", "bottom", "left", "right", "height", "width" ], + mode = $.effects.setMode( el, o.mode || "hide" ), + direction = o.direction || "up", + vertical = rvertical.test( direction ), + ref = vertical ? "height" : "width", + ref2 = vertical ? "top" : "left", + motion = rpositivemotion.test( direction ), + animation = {}, + show = mode === "show", + wrapper, distance, margin; + + // if already wrapped, the wrapper's properties are my property. #6245 + if ( el.parent().is( ".ui-effects-wrapper" ) ) { + $.effects.save( el.parent(), props ); + } else { + $.effects.save( el, props ); + } + el.show(); + wrapper = $.effects.createWrapper( el ).css({ + overflow: "hidden" + }); + + distance = wrapper[ ref ](); + margin = parseFloat( wrapper.css( ref2 ) ) || 0; + + animation[ ref ] = show ? distance : 0; + if ( !motion ) { + el + .css( vertical ? "bottom" : "right", 0 ) + .css( vertical ? "top" : "left", "auto" ) + .css({ position: "absolute" }); + + animation[ ref2 ] = show ? margin : distance + margin; + } + + // start at 0 if we are showing + if ( show ) { + wrapper.css( ref, 0 ); + if ( ! motion ) { + wrapper.css( ref2, margin + distance ); + } + } + + // Animate + wrapper.animate( animation, { + duration: o.duration, + easing: o.easing, + queue: false, + complete: function() { + if ( mode === "hide" ) { + el.hide(); + } + $.effects.restore( el, props ); + $.effects.removeWrapper( el ); + done(); + } + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.effect.bounce = function( o, done ) { + var el = $( this ), + props = [ "position", "top", "bottom", "left", "right", "height", "width" ], + + // defaults: + mode = $.effects.setMode( el, o.mode || "effect" ), + hide = mode === "hide", + show = mode === "show", + direction = o.direction || "up", + distance = o.distance, + times = o.times || 5, + + // number of internal animations + anims = times * 2 + ( show || hide ? 1 : 0 ), + speed = o.duration / anims, + easing = o.easing, + + // utility: + ref = ( direction === "up" || direction === "down" ) ? "top" : "left", + motion = ( direction === "up" || direction === "left" ), + i, + upAnim, + downAnim, + + // we will need to re-assemble the queue to stack our animations in place + queue = el.queue(), + queuelen = queue.length; + + // Avoid touching opacity to prevent clearType and PNG issues in IE + if ( show || hide ) { + props.push( "opacity" ); + } + + $.effects.save( el, props ); + el.show(); + $.effects.createWrapper( el ); // Create Wrapper + + // default distance for the BIGGEST bounce is the outer Distance / 3 + if ( !distance ) { + distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3; + } + + if ( show ) { + downAnim = { opacity: 1 }; + downAnim[ ref ] = 0; + + // if we are showing, force opacity 0 and set the initial position + // then do the "first" animation + el.css( "opacity", 0 ) + .css( ref, motion ? -distance * 2 : distance * 2 ) + .animate( downAnim, speed, easing ); + } + + // start at the smallest distance if we are hiding + if ( hide ) { + distance = distance / Math.pow( 2, times - 1 ); + } + + downAnim = {}; + downAnim[ ref ] = 0; + // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here + for ( i = 0; i < times; i++ ) { + upAnim = {}; + upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; + + el.animate( upAnim, speed, easing ) + .animate( downAnim, speed, easing ); + + distance = hide ? distance * 2 : distance / 2; + } + + // Last Bounce when Hiding + if ( hide ) { + upAnim = { opacity: 0 }; + upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; + + el.animate( upAnim, speed, easing ); + } + + el.queue(function() { + if ( hide ) { + el.hide(); + } + $.effects.restore( el, props ); + $.effects.removeWrapper( el ); + done(); + }); + + // inject all the animations we just queued to be first in line (after "inprogress") + if ( queuelen > 1) { + queue.splice.apply( queue, + [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); + } + el.dequeue(); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.effect.clip = function( o, done ) { + // Create element + var el = $( this ), + props = [ "position", "top", "bottom", "left", "right", "height", "width" ], + mode = $.effects.setMode( el, o.mode || "hide" ), + show = mode === "show", + direction = o.direction || "vertical", + vert = direction === "vertical", + size = vert ? "height" : "width", + position = vert ? "top" : "left", + animation = {}, + wrapper, animate, distance; + + // Save & Show + $.effects.save( el, props ); + el.show(); + + // Create Wrapper + wrapper = $.effects.createWrapper( el ).css({ + overflow: "hidden" + }); + animate = ( el[0].tagName === "IMG" ) ? wrapper : el; + distance = animate[ size ](); + + // Shift + if ( show ) { + animate.css( size, 0 ); + animate.css( position, distance / 2 ); + } + + // Create Animation Object: + animation[ size ] = show ? distance : 0; + animation[ position ] = show ? 0 : distance / 2; + + // Animate + animate.animate( animation, { + queue: false, + duration: o.duration, + easing: o.easing, + complete: function() { + if ( !show ) { + el.hide(); + } + $.effects.restore( el, props ); + $.effects.removeWrapper( el ); + done(); + } + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.effect.drop = function( o, done ) { + + var el = $( this ), + props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ], + mode = $.effects.setMode( el, o.mode || "hide" ), + show = mode === "show", + direction = o.direction || "left", + ref = ( direction === "up" || direction === "down" ) ? "top" : "left", + motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg", + animation = { + opacity: show ? 1 : 0 + }, + distance; + + // Adjust + $.effects.save( el, props ); + el.show(); + $.effects.createWrapper( el ); + + distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2; + + if ( show ) { + el + .css( "opacity", 0 ) + .css( ref, motion === "pos" ? -distance : distance ); + } + + // Animation + animation[ ref ] = ( show ? + ( motion === "pos" ? "+=" : "-=" ) : + ( motion === "pos" ? "-=" : "+=" ) ) + + distance; + + // Animate + el.animate( animation, { + queue: false, + duration: o.duration, + easing: o.easing, + complete: function() { + if ( mode === "hide" ) { + el.hide(); + } + $.effects.restore( el, props ); + $.effects.removeWrapper( el ); + done(); + } + }); +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.effect.explode = function( o, done ) { + + var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3, + cells = rows, + el = $( this ), + mode = $.effects.setMode( el, o.mode || "hide" ), + show = mode === "show", + + // show and then visibility:hidden the element before calculating offset + offset = el.show().css( "visibility", "hidden" ).offset(), + + // width and height of a piece + width = Math.ceil( el.outerWidth() / cells ), + height = Math.ceil( el.outerHeight() / rows ), + pieces = [], + + // loop + i, j, left, top, mx, my; + + // children animate complete: + function childComplete() { + pieces.push( this ); + if ( pieces.length === rows * cells ) { + animComplete(); + } + } + + // clone the element for each row and cell. + for( i = 0; i < rows ; i++ ) { // ===> + top = offset.top + i * height; + my = i - ( rows - 1 ) / 2 ; + + for( j = 0; j < cells ; j++ ) { // ||| + left = offset.left + j * width; + mx = j - ( cells - 1 ) / 2 ; + + // Create a clone of the now hidden main element that will be absolute positioned + // within a wrapper div off the -left and -top equal to size of our pieces + el + .clone() + .appendTo( "body" ) + .wrap( "
" ) + .css({ + position: "absolute", + visibility: "visible", + left: -j * width, + top: -i * height + }) + + // select the wrapper - make it overflow: hidden and absolute positioned based on + // where the original was located +left and +top equal to the size of pieces + .parent() + .addClass( "ui-effects-explode" ) + .css({ + position: "absolute", + overflow: "hidden", + width: width, + height: height, + left: left + ( show ? mx * width : 0 ), + top: top + ( show ? my * height : 0 ), + opacity: show ? 0 : 1 + }).animate({ + left: left + ( show ? 0 : mx * width ), + top: top + ( show ? 0 : my * height ), + opacity: show ? 1 : 0 + }, o.duration || 500, o.easing, childComplete ); + } + } + + function animComplete() { + el.css({ + visibility: "visible" + }); + $( pieces ).remove(); + if ( !show ) { + el.hide(); + } + done(); + } +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.effect.fade = function( o, done ) { + var el = $( this ), + mode = $.effects.setMode( el, o.mode || "toggle" ); + + el.animate({ + opacity: mode + }, { + queue: false, + duration: o.duration, + easing: o.easing, + complete: done + }); +}; + +})( jQuery ); + +(function( $, undefined ) { + +$.effects.effect.fold = function( o, done ) { + + // Create element + var el = $( this ), + props = [ "position", "top", "bottom", "left", "right", "height", "width" ], + mode = $.effects.setMode( el, o.mode || "hide" ), + show = mode === "show", + hide = mode === "hide", + size = o.size || 15, + percent = /([0-9]+)%/.exec( size ), + horizFirst = !!o.horizFirst, + widthFirst = show !== horizFirst, + ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ], + duration = o.duration / 2, + wrapper, distance, + animation1 = {}, + animation2 = {}; + + $.effects.save( el, props ); + el.show(); + + // Create Wrapper + wrapper = $.effects.createWrapper( el ).css({ + overflow: "hidden" + }); + distance = widthFirst ? + [ wrapper.width(), wrapper.height() ] : + [ wrapper.height(), wrapper.width() ]; + + if ( percent ) { + size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ]; + } + if ( show ) { + wrapper.css( horizFirst ? { + height: 0, + width: size + } : { + height: size, + width: 0 + }); + } + + // Animation + animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size; + animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0; + + // Animate + wrapper + .animate( animation1, duration, o.easing ) + .animate( animation2, duration, o.easing, function() { + if ( hide ) { + el.hide(); + } + $.effects.restore( el, props ); + $.effects.removeWrapper( el ); + done(); + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.effect.highlight = function( o, done ) { + var elem = $( this ), + props = [ "backgroundImage", "backgroundColor", "opacity" ], + mode = $.effects.setMode( elem, o.mode || "show" ), + animation = { + backgroundColor: elem.css( "backgroundColor" ) + }; + + if (mode === "hide") { + animation.opacity = 0; + } + + $.effects.save( elem, props ); + + elem + .show() + .css({ + backgroundImage: "none", + backgroundColor: o.color || "#ffff99" + }) + .animate( animation, { + queue: false, + duration: o.duration, + easing: o.easing, + complete: function() { + if ( mode === "hide" ) { + elem.hide(); + } + $.effects.restore( elem, props ); + done(); + } + }); +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.effect.pulsate = function( o, done ) { + var elem = $( this ), + mode = $.effects.setMode( elem, o.mode || "show" ), + show = mode === "show", + hide = mode === "hide", + showhide = ( show || mode === "hide" ), + + // showing or hiding leaves of the "last" animation + anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ), + duration = o.duration / anims, + animateTo = 0, + queue = elem.queue(), + queuelen = queue.length, + i; + + if ( show || !elem.is(":visible")) { + elem.css( "opacity", 0 ).show(); + animateTo = 1; + } + + // anims - 1 opacity "toggles" + for ( i = 1; i < anims; i++ ) { + elem.animate({ + opacity: animateTo + }, duration, o.easing ); + animateTo = 1 - animateTo; + } + + elem.animate({ + opacity: animateTo + }, duration, o.easing); + + elem.queue(function() { + if ( hide ) { + elem.hide(); + } + done(); + }); + + // We just queued up "anims" animations, we need to put them next in the queue + if ( queuelen > 1 ) { + queue.splice.apply( queue, + [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); + } + elem.dequeue(); +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.effect.puff = function( o, done ) { + var elem = $( this ), + mode = $.effects.setMode( elem, o.mode || "hide" ), + hide = mode === "hide", + percent = parseInt( o.percent, 10 ) || 150, + factor = percent / 100, + original = { + height: elem.height(), + width: elem.width(), + outerHeight: elem.outerHeight(), + outerWidth: elem.outerWidth() + }; + + $.extend( o, { + effect: "scale", + queue: false, + fade: true, + mode: mode, + complete: done, + percent: hide ? percent : 100, + from: hide ? + original : + { + height: original.height * factor, + width: original.width * factor, + outerHeight: original.outerHeight * factor, + outerWidth: original.outerWidth * factor + } + }); + + elem.effect( o ); +}; + +$.effects.effect.scale = function( o, done ) { + + // Create element + var el = $( this ), + options = $.extend( true, {}, o ), + mode = $.effects.setMode( el, o.mode || "effect" ), + percent = parseInt( o.percent, 10 ) || + ( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ), + direction = o.direction || "both", + origin = o.origin, + original = { + height: el.height(), + width: el.width(), + outerHeight: el.outerHeight(), + outerWidth: el.outerWidth() + }, + factor = { + y: direction !== "horizontal" ? (percent / 100) : 1, + x: direction !== "vertical" ? (percent / 100) : 1 + }; + + // We are going to pass this effect to the size effect: + options.effect = "size"; + options.queue = false; + options.complete = done; + + // Set default origin and restore for show/hide + if ( mode !== "effect" ) { + options.origin = origin || ["middle","center"]; + options.restore = true; + } + + options.from = o.from || ( mode === "show" ? { + height: 0, + width: 0, + outerHeight: 0, + outerWidth: 0 + } : original ); + options.to = { + height: original.height * factor.y, + width: original.width * factor.x, + outerHeight: original.outerHeight * factor.y, + outerWidth: original.outerWidth * factor.x + }; + + // Fade option to support puff + if ( options.fade ) { + if ( mode === "show" ) { + options.from.opacity = 0; + options.to.opacity = 1; + } + if ( mode === "hide" ) { + options.from.opacity = 1; + options.to.opacity = 0; + } + } + + // Animate + el.effect( options ); + +}; + +$.effects.effect.size = function( o, done ) { + + // Create element + var original, baseline, factor, + el = $( this ), + props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ], + + // Always restore + props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ], + + // Copy for children + props2 = [ "width", "height", "overflow" ], + cProps = [ "fontSize" ], + vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ], + hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ], + + // Set options + mode = $.effects.setMode( el, o.mode || "effect" ), + restore = o.restore || mode !== "effect", + scale = o.scale || "both", + origin = o.origin || [ "middle", "center" ], + position = el.css( "position" ), + props = restore ? props0 : props1, + zero = { + height: 0, + width: 0, + outerHeight: 0, + outerWidth: 0 + }; + + if ( mode === "show" ) { + el.show(); + } + original = { + height: el.height(), + width: el.width(), + outerHeight: el.outerHeight(), + outerWidth: el.outerWidth() + }; + + if ( o.mode === "toggle" && mode === "show" ) { + el.from = o.to || zero; + el.to = o.from || original; + } else { + el.from = o.from || ( mode === "show" ? zero : original ); + el.to = o.to || ( mode === "hide" ? zero : original ); + } + + // Set scaling factor + factor = { + from: { + y: el.from.height / original.height, + x: el.from.width / original.width + }, + to: { + y: el.to.height / original.height, + x: el.to.width / original.width + } + }; + + // Scale the css box + if ( scale === "box" || scale === "both" ) { + + // Vertical props scaling + if ( factor.from.y !== factor.to.y ) { + props = props.concat( vProps ); + el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from ); + el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to ); + } + + // Horizontal props scaling + if ( factor.from.x !== factor.to.x ) { + props = props.concat( hProps ); + el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from ); + el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to ); + } + } + + // Scale the content + if ( scale === "content" || scale === "both" ) { + + // Vertical props scaling + if ( factor.from.y !== factor.to.y ) { + props = props.concat( cProps ).concat( props2 ); + el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from ); + el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to ); + } + } + + $.effects.save( el, props ); + el.show(); + $.effects.createWrapper( el ); + el.css( "overflow", "hidden" ).css( el.from ); + + // Adjust + if (origin) { // Calculate baseline shifts + baseline = $.effects.getBaseline( origin, original ); + el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y; + el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x; + el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y; + el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x; + } + el.css( el.from ); // set top & left + + // Animate + if ( scale === "content" || scale === "both" ) { // Scale the children + + // Add margins/font-size + vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps); + hProps = hProps.concat([ "marginLeft", "marginRight" ]); + props2 = props0.concat(vProps).concat(hProps); + + el.find( "*[width]" ).each( function(){ + var child = $( this ), + c_original = { + height: child.height(), + width: child.width(), + outerHeight: child.outerHeight(), + outerWidth: child.outerWidth() + }; + if (restore) { + $.effects.save(child, props2); + } + + child.from = { + height: c_original.height * factor.from.y, + width: c_original.width * factor.from.x, + outerHeight: c_original.outerHeight * factor.from.y, + outerWidth: c_original.outerWidth * factor.from.x + }; + child.to = { + height: c_original.height * factor.to.y, + width: c_original.width * factor.to.x, + outerHeight: c_original.height * factor.to.y, + outerWidth: c_original.width * factor.to.x + }; + + // Vertical props scaling + if ( factor.from.y !== factor.to.y ) { + child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from ); + child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to ); + } + + // Horizontal props scaling + if ( factor.from.x !== factor.to.x ) { + child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from ); + child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to ); + } + + // Animate children + child.css( child.from ); + child.animate( child.to, o.duration, o.easing, function() { + + // Restore children + if ( restore ) { + $.effects.restore( child, props2 ); + } + }); + }); + } + + // Animate + el.animate( el.to, { + queue: false, + duration: o.duration, + easing: o.easing, + complete: function() { + if ( el.to.opacity === 0 ) { + el.css( "opacity", el.from.opacity ); + } + if( mode === "hide" ) { + el.hide(); + } + $.effects.restore( el, props ); + if ( !restore ) { + + // we need to calculate our new positioning based on the scaling + if ( position === "static" ) { + el.css({ + position: "relative", + top: el.to.top, + left: el.to.left + }); + } else { + $.each([ "top", "left" ], function( idx, pos ) { + el.css( pos, function( _, str ) { + var val = parseInt( str, 10 ), + toRef = idx ? el.to.left : el.to.top; + + // if original was "auto", recalculate the new value from wrapper + if ( str === "auto" ) { + return toRef + "px"; + } + + return val + toRef + "px"; + }); + }); + } + } + + $.effects.removeWrapper( el ); + done(); + } + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.effect.shake = function( o, done ) { + + var el = $( this ), + props = [ "position", "top", "bottom", "left", "right", "height", "width" ], + mode = $.effects.setMode( el, o.mode || "effect" ), + direction = o.direction || "left", + distance = o.distance || 20, + times = o.times || 3, + anims = times * 2 + 1, + speed = Math.round(o.duration/anims), + ref = (direction === "up" || direction === "down") ? "top" : "left", + positiveMotion = (direction === "up" || direction === "left"), + animation = {}, + animation1 = {}, + animation2 = {}, + i, + + // we will need to re-assemble the queue to stack our animations in place + queue = el.queue(), + queuelen = queue.length; + + $.effects.save( el, props ); + el.show(); + $.effects.createWrapper( el ); + + // Animation + animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance; + animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2; + animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2; + + // Animate + el.animate( animation, speed, o.easing ); + + // Shakes + for ( i = 1; i < times; i++ ) { + el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing ); + } + el + .animate( animation1, speed, o.easing ) + .animate( animation, speed / 2, o.easing ) + .queue(function() { + if ( mode === "hide" ) { + el.hide(); + } + $.effects.restore( el, props ); + $.effects.removeWrapper( el ); + done(); + }); + + // inject all the animations we just queued to be first in line (after "inprogress") + if ( queuelen > 1) { + queue.splice.apply( queue, + [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); + } + el.dequeue(); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.effect.slide = function( o, done ) { + + // Create element + var el = $( this ), + props = [ "position", "top", "bottom", "left", "right", "width", "height" ], + mode = $.effects.setMode( el, o.mode || "show" ), + show = mode === "show", + direction = o.direction || "left", + ref = (direction === "up" || direction === "down") ? "top" : "left", + positiveMotion = (direction === "up" || direction === "left"), + distance, + animation = {}; + + // Adjust + $.effects.save( el, props ); + el.show(); + distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ); + + $.effects.createWrapper( el ).css({ + overflow: "hidden" + }); + + if ( show ) { + el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance ); + } + + // Animation + animation[ ref ] = ( show ? + ( positiveMotion ? "+=" : "-=") : + ( positiveMotion ? "-=" : "+=")) + + distance; + + // Animate + el.animate( animation, { + queue: false, + duration: o.duration, + easing: o.easing, + complete: function() { + if ( mode === "hide" ) { + el.hide(); + } + $.effects.restore( el, props ); + $.effects.removeWrapper( el ); + done(); + } + }); +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.effect.transfer = function( o, done ) { + var elem = $( this ), + target = $( o.to ), + targetFixed = target.css( "position" ) === "fixed", + body = $("body"), + fixTop = targetFixed ? body.scrollTop() : 0, + fixLeft = targetFixed ? body.scrollLeft() : 0, + endPosition = target.offset(), + animation = { + top: endPosition.top - fixTop , + left: endPosition.left - fixLeft , + height: target.innerHeight(), + width: target.innerWidth() + }, + startPosition = elem.offset(), + transfer = $( '
' ) + .appendTo( document.body ) + .addClass( o.className ) + .css({ + top: startPosition.top - fixTop , + left: startPosition.left - fixLeft , + height: elem.innerHeight(), + width: elem.innerWidth(), + position: targetFixed ? "fixed" : "absolute" + }) + .animate( animation, o.duration, o.easing, function() { + transfer.remove(); + done(); + }); +}; + +})(jQuery); + +(function( $, undefined ) { + +var mouseHandled = false; + +$.widget( "ui.menu", { + version: "1.9.2", + defaultElement: "
    ", + delay: 300, + options: { + icons: { + submenu: "ui-icon-carat-1-e" + }, + menus: "ul", + position: { + my: "left top", + at: "right top" + }, + role: "menu", + + // callbacks + blur: null, + focus: null, + select: null + }, + + _create: function() { + this.activeMenu = this.element; + this.element + .uniqueId() + .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" ) + .toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length ) + .attr({ + role: this.options.role, + tabIndex: 0 + }) + // need to catch all clicks on disabled menu + // not possible through _on + .bind( "click" + this.eventNamespace, $.proxy(function( event ) { + if ( this.options.disabled ) { + event.preventDefault(); + } + }, this )); + + if ( this.options.disabled ) { + this.element + .addClass( "ui-state-disabled" ) + .attr( "aria-disabled", "true" ); + } + + this._on({ + // Prevent focus from sticking to links inside menu after clicking + // them (focus should always stay on UL during navigation). + "mousedown .ui-menu-item > a": function( event ) { + event.preventDefault(); + }, + "click .ui-state-disabled > a": function( event ) { + event.preventDefault(); + }, + "click .ui-menu-item:has(a)": function( event ) { + var target = $( event.target ).closest( ".ui-menu-item" ); + if ( !mouseHandled && target.not( ".ui-state-disabled" ).length ) { + mouseHandled = true; + + this.select( event ); + // Open submenu on click + if ( target.has( ".ui-menu" ).length ) { + this.expand( event ); + } else if ( !this.element.is( ":focus" ) ) { + // Redirect focus to the menu + this.element.trigger( "focus", [ true ] ); + + // If the active item is on the top level, let it stay active. + // Otherwise, blur the active item since it is no longer visible. + if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) { + clearTimeout( this.timer ); + } + } + } + }, + "mouseenter .ui-menu-item": function( event ) { + var target = $( event.currentTarget ); + // Remove ui-state-active class from siblings of the newly focused menu item + // to avoid a jump caused by adjacent elements both having a class with a border + target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" ); + this.focus( event, target ); + }, + mouseleave: "collapseAll", + "mouseleave .ui-menu": "collapseAll", + focus: function( event, keepActiveItem ) { + // If there's already an active item, keep it active + // If not, activate the first item + var item = this.active || this.element.children( ".ui-menu-item" ).eq( 0 ); + + if ( !keepActiveItem ) { + this.focus( event, item ); + } + }, + blur: function( event ) { + this._delay(function() { + if ( !$.contains( this.element[0], this.document[0].activeElement ) ) { + this.collapseAll( event ); + } + }); + }, + keydown: "_keydown" + }); + + this.refresh(); + + // Clicks outside of a menu collapse any open menus + this._on( this.document, { + click: function( event ) { + if ( !$( event.target ).closest( ".ui-menu" ).length ) { + this.collapseAll( event ); + } + + // Reset the mouseHandled flag + mouseHandled = false; + } + }); + }, + + _destroy: function() { + // Destroy (sub)menus + this.element + .removeAttr( "aria-activedescendant" ) + .find( ".ui-menu" ).andSelf() + .removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" ) + .removeAttr( "role" ) + .removeAttr( "tabIndex" ) + .removeAttr( "aria-labelledby" ) + .removeAttr( "aria-expanded" ) + .removeAttr( "aria-hidden" ) + .removeAttr( "aria-disabled" ) + .removeUniqueId() + .show(); + + // Destroy menu items + this.element.find( ".ui-menu-item" ) + .removeClass( "ui-menu-item" ) + .removeAttr( "role" ) + .removeAttr( "aria-disabled" ) + .children( "a" ) + .removeUniqueId() + .removeClass( "ui-corner-all ui-state-hover" ) + .removeAttr( "tabIndex" ) + .removeAttr( "role" ) + .removeAttr( "aria-haspopup" ) + .children().each( function() { + var elem = $( this ); + if ( elem.data( "ui-menu-submenu-carat" ) ) { + elem.remove(); + } + }); + + // Destroy menu dividers + this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" ); + }, + + _keydown: function( event ) { + var match, prev, character, skip, regex, + preventDefault = true; + + function escape( value ) { + return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ); + } + + switch ( event.keyCode ) { + case $.ui.keyCode.PAGE_UP: + this.previousPage( event ); + break; + case $.ui.keyCode.PAGE_DOWN: + this.nextPage( event ); + break; + case $.ui.keyCode.HOME: + this._move( "first", "first", event ); + break; + case $.ui.keyCode.END: + this._move( "last", "last", event ); + break; + case $.ui.keyCode.UP: + this.previous( event ); + break; + case $.ui.keyCode.DOWN: + this.next( event ); + break; + case $.ui.keyCode.LEFT: + this.collapse( event ); + break; + case $.ui.keyCode.RIGHT: + if ( this.active && !this.active.is( ".ui-state-disabled" ) ) { + this.expand( event ); + } + break; + case $.ui.keyCode.ENTER: + case $.ui.keyCode.SPACE: + this._activate( event ); + break; + case $.ui.keyCode.ESCAPE: + this.collapse( event ); + break; + default: + preventDefault = false; + prev = this.previousFilter || ""; + character = String.fromCharCode( event.keyCode ); + skip = false; + + clearTimeout( this.filterTimer ); + + if ( character === prev ) { + skip = true; + } else { + character = prev + character; + } + + regex = new RegExp( "^" + escape( character ), "i" ); + match = this.activeMenu.children( ".ui-menu-item" ).filter(function() { + return regex.test( $( this ).children( "a" ).text() ); + }); + match = skip && match.index( this.active.next() ) !== -1 ? + this.active.nextAll( ".ui-menu-item" ) : + match; + + // If no matches on the current filter, reset to the last character pressed + // to move down the menu to the first item that starts with that character + if ( !match.length ) { + character = String.fromCharCode( event.keyCode ); + regex = new RegExp( "^" + escape( character ), "i" ); + match = this.activeMenu.children( ".ui-menu-item" ).filter(function() { + return regex.test( $( this ).children( "a" ).text() ); + }); + } + + if ( match.length ) { + this.focus( event, match ); + if ( match.length > 1 ) { + this.previousFilter = character; + this.filterTimer = this._delay(function() { + delete this.previousFilter; + }, 1000 ); + } else { + delete this.previousFilter; + } + } else { + delete this.previousFilter; + } + } + + if ( preventDefault ) { + event.preventDefault(); + } + }, + + _activate: function( event ) { + if ( !this.active.is( ".ui-state-disabled" ) ) { + if ( this.active.children( "a[aria-haspopup='true']" ).length ) { + this.expand( event ); + } else { + this.select( event ); + } + } + }, + + refresh: function() { + var menus, + icon = this.options.icons.submenu, + submenus = this.element.find( this.options.menus ); + + // Initialize nested menus + submenus.filter( ":not(.ui-menu)" ) + .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" ) + .hide() + .attr({ + role: this.options.role, + "aria-hidden": "true", + "aria-expanded": "false" + }) + .each(function() { + var menu = $( this ), + item = menu.prev( "a" ), + submenuCarat = $( "" ) + .addClass( "ui-menu-icon ui-icon " + icon ) + .data( "ui-menu-submenu-carat", true ); + + item + .attr( "aria-haspopup", "true" ) + .prepend( submenuCarat ); + menu.attr( "aria-labelledby", item.attr( "id" ) ); + }); + + menus = submenus.add( this.element ); + + // Don't refresh list items that are already adapted + menus.children( ":not(.ui-menu-item):has(a)" ) + .addClass( "ui-menu-item" ) + .attr( "role", "presentation" ) + .children( "a" ) + .uniqueId() + .addClass( "ui-corner-all" ) + .attr({ + tabIndex: -1, + role: this._itemRole() + }); + + // Initialize unlinked menu-items containing spaces and/or dashes only as dividers + menus.children( ":not(.ui-menu-item)" ).each(function() { + var item = $( this ); + // hyphen, em dash, en dash + if ( !/[^\-—–\s]/.test( item.text() ) ) { + item.addClass( "ui-widget-content ui-menu-divider" ); + } + }); + + // Add aria-disabled attribute to any disabled menu item + menus.children( ".ui-state-disabled" ).attr( "aria-disabled", "true" ); + + // If the active item has been removed, blur the menu + if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { + this.blur(); + } + }, + + _itemRole: function() { + return { + menu: "menuitem", + listbox: "option" + }[ this.options.role ]; + }, + + focus: function( event, item ) { + var nested, focused; + this.blur( event, event && event.type === "focus" ); + + this._scrollIntoView( item ); + + this.active = item.first(); + focused = this.active.children( "a" ).addClass( "ui-state-focus" ); + // Only update aria-activedescendant if there's a role + // otherwise we assume focus is managed elsewhere + if ( this.options.role ) { + this.element.attr( "aria-activedescendant", focused.attr( "id" ) ); + } + + // Highlight active parent menu item, if any + this.active + .parent() + .closest( ".ui-menu-item" ) + .children( "a:first" ) + .addClass( "ui-state-active" ); + + if ( event && event.type === "keydown" ) { + this._close(); + } else { + this.timer = this._delay(function() { + this._close(); + }, this.delay ); + } + + nested = item.children( ".ui-menu" ); + if ( nested.length && ( /^mouse/.test( event.type ) ) ) { + this._startOpening(nested); + } + this.activeMenu = item.parent(); + + this._trigger( "focus", event, { item: item } ); + }, + + _scrollIntoView: function( item ) { + var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight; + if ( this._hasScroll() ) { + borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0; + paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0; + offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop; + scroll = this.activeMenu.scrollTop(); + elementHeight = this.activeMenu.height(); + itemHeight = item.height(); + + if ( offset < 0 ) { + this.activeMenu.scrollTop( scroll + offset ); + } else if ( offset + itemHeight > elementHeight ) { + this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight ); + } + } + }, + + blur: function( event, fromFocus ) { + if ( !fromFocus ) { + clearTimeout( this.timer ); + } + + if ( !this.active ) { + return; + } + + this.active.children( "a" ).removeClass( "ui-state-focus" ); + this.active = null; + + this._trigger( "blur", event, { item: this.active } ); + }, + + _startOpening: function( submenu ) { + clearTimeout( this.timer ); + + // Don't open if already open fixes a Firefox bug that caused a .5 pixel + // shift in the submenu position when mousing over the carat icon + if ( submenu.attr( "aria-hidden" ) !== "true" ) { + return; + } + + this.timer = this._delay(function() { + this._close(); + this._open( submenu ); + }, this.delay ); + }, + + _open: function( submenu ) { + var position = $.extend({ + of: this.active + }, this.options.position ); + + clearTimeout( this.timer ); + this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) ) + .hide() + .attr( "aria-hidden", "true" ); + + submenu + .show() + .removeAttr( "aria-hidden" ) + .attr( "aria-expanded", "true" ) + .position( position ); + }, + + collapseAll: function( event, all ) { + clearTimeout( this.timer ); + this.timer = this._delay(function() { + // If we were passed an event, look for the submenu that contains the event + var currentMenu = all ? this.element : + $( event && event.target ).closest( this.element.find( ".ui-menu" ) ); + + // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway + if ( !currentMenu.length ) { + currentMenu = this.element; + } + + this._close( currentMenu ); + + this.blur( event ); + this.activeMenu = currentMenu; + }, this.delay ); + }, + + // With no arguments, closes the currently active menu - if nothing is active + // it closes all menus. If passed an argument, it will search for menus BELOW + _close: function( startMenu ) { + if ( !startMenu ) { + startMenu = this.active ? this.active.parent() : this.element; + } + + startMenu + .find( ".ui-menu" ) + .hide() + .attr( "aria-hidden", "true" ) + .attr( "aria-expanded", "false" ) + .end() + .find( "a.ui-state-active" ) + .removeClass( "ui-state-active" ); + }, + + collapse: function( event ) { + var newItem = this.active && + this.active.parent().closest( ".ui-menu-item", this.element ); + if ( newItem && newItem.length ) { + this._close(); + this.focus( event, newItem ); + } + }, + + expand: function( event ) { + var newItem = this.active && + this.active + .children( ".ui-menu " ) + .children( ".ui-menu-item" ) + .first(); + + if ( newItem && newItem.length ) { + this._open( newItem.parent() ); + + // Delay so Firefox will not hide activedescendant change in expanding submenu from AT + this._delay(function() { + this.focus( event, newItem ); + }); + } + }, + + next: function( event ) { + this._move( "next", "first", event ); + }, + + previous: function( event ) { + this._move( "prev", "last", event ); + }, + + isFirstItem: function() { + return this.active && !this.active.prevAll( ".ui-menu-item" ).length; + }, + + isLastItem: function() { + return this.active && !this.active.nextAll( ".ui-menu-item" ).length; + }, + + _move: function( direction, filter, event ) { + var next; + if ( this.active ) { + if ( direction === "first" || direction === "last" ) { + next = this.active + [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" ) + .eq( -1 ); + } else { + next = this.active + [ direction + "All" ]( ".ui-menu-item" ) + .eq( 0 ); + } + } + if ( !next || !next.length || !this.active ) { + next = this.activeMenu.children( ".ui-menu-item" )[ filter ](); + } + + this.focus( event, next ); + }, + + nextPage: function( event ) { + var item, base, height; + + if ( !this.active ) { + this.next( event ); + return; + } + if ( this.isLastItem() ) { + return; + } + if ( this._hasScroll() ) { + base = this.active.offset().top; + height = this.element.height(); + this.active.nextAll( ".ui-menu-item" ).each(function() { + item = $( this ); + return item.offset().top - base - height < 0; + }); + + this.focus( event, item ); + } else { + this.focus( event, this.activeMenu.children( ".ui-menu-item" ) + [ !this.active ? "first" : "last" ]() ); + } + }, + + previousPage: function( event ) { + var item, base, height; + if ( !this.active ) { + this.next( event ); + return; + } + if ( this.isFirstItem() ) { + return; + } + if ( this._hasScroll() ) { + base = this.active.offset().top; + height = this.element.height(); + this.active.prevAll( ".ui-menu-item" ).each(function() { + item = $( this ); + return item.offset().top - base + height > 0; + }); + + this.focus( event, item ); + } else { + this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() ); + } + }, + + _hasScroll: function() { + return this.element.outerHeight() < this.element.prop( "scrollHeight" ); + }, + + select: function( event ) { + // TODO: It should never be possible to not have an active item at this + // point, but the tests don't trigger mouseenter before click. + this.active = this.active || $( event.target ).closest( ".ui-menu-item" ); + var ui = { item: this.active }; + if ( !this.active.has( ".ui-menu" ).length ) { + this.collapseAll( event, true ); + } + this._trigger( "select", event, ui ); + } +}); + +}( jQuery )); + +(function( $, undefined ) { + +$.ui = $.ui || {}; + +var cachedScrollbarWidth, + max = Math.max, + abs = Math.abs, + round = Math.round, + rhorizontal = /left|center|right/, + rvertical = /top|center|bottom/, + roffset = /[\+\-]\d+%?/, + rposition = /^\w+/, + rpercent = /%$/, + _position = $.fn.position; + +function getOffsets( offsets, width, height ) { + return [ + parseInt( offsets[ 0 ], 10 ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), + parseInt( offsets[ 1 ], 10 ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) + ]; +} +function parseCss( element, property ) { + return parseInt( $.css( element, property ), 10 ) || 0; +} + +$.position = { + scrollbarWidth: function() { + if ( cachedScrollbarWidth !== undefined ) { + return cachedScrollbarWidth; + } + var w1, w2, + div = $( "
    " ), + innerDiv = div.children()[0]; + + $( "body" ).append( div ); + w1 = innerDiv.offsetWidth; + div.css( "overflow", "scroll" ); + + w2 = innerDiv.offsetWidth; + + if ( w1 === w2 ) { + w2 = div[0].clientWidth; + } + + div.remove(); + + return (cachedScrollbarWidth = w1 - w2); + }, + getScrollInfo: function( within ) { + var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ), + overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ), + hasOverflowX = overflowX === "scroll" || + ( overflowX === "auto" && within.width < within.element[0].scrollWidth ), + hasOverflowY = overflowY === "scroll" || + ( overflowY === "auto" && within.height < within.element[0].scrollHeight ); + return { + width: hasOverflowX ? $.position.scrollbarWidth() : 0, + height: hasOverflowY ? $.position.scrollbarWidth() : 0 + }; + }, + getWithinInfo: function( element ) { + var withinElement = $( element || window ), + isWindow = $.isWindow( withinElement[0] ); + return { + element: withinElement, + isWindow: isWindow, + offset: withinElement.offset() || { left: 0, top: 0 }, + scrollLeft: withinElement.scrollLeft(), + scrollTop: withinElement.scrollTop(), + width: isWindow ? withinElement.width() : withinElement.outerWidth(), + height: isWindow ? withinElement.height() : withinElement.outerHeight() + }; + } +}; + +$.fn.position = function( options ) { + if ( !options || !options.of ) { + return _position.apply( this, arguments ); + } + + // make a copy, we don't want to modify arguments + options = $.extend( {}, options ); + + var atOffset, targetWidth, targetHeight, targetOffset, basePosition, + target = $( options.of ), + within = $.position.getWithinInfo( options.within ), + scrollInfo = $.position.getScrollInfo( within ), + targetElem = target[0], + collision = ( options.collision || "flip" ).split( " " ), + offsets = {}; + + if ( targetElem.nodeType === 9 ) { + targetWidth = target.width(); + targetHeight = target.height(); + targetOffset = { top: 0, left: 0 }; + } else if ( $.isWindow( targetElem ) ) { + targetWidth = target.width(); + targetHeight = target.height(); + targetOffset = { top: target.scrollTop(), left: target.scrollLeft() }; + } else if ( targetElem.preventDefault ) { + // force left top to allow flipping + options.at = "left top"; + targetWidth = targetHeight = 0; + targetOffset = { top: targetElem.pageY, left: targetElem.pageX }; + } else { + targetWidth = target.outerWidth(); + targetHeight = target.outerHeight(); + targetOffset = target.offset(); + } + // clone to reuse original targetOffset later + basePosition = $.extend( {}, targetOffset ); + + // force my and at to have valid horizontal and vertical positions + // if a value is missing or invalid, it will be converted to center + $.each( [ "my", "at" ], function() { + var pos = ( options[ this ] || "" ).split( " " ), + horizontalOffset, + verticalOffset; + + if ( pos.length === 1) { + pos = rhorizontal.test( pos[ 0 ] ) ? + pos.concat( [ "center" ] ) : + rvertical.test( pos[ 0 ] ) ? + [ "center" ].concat( pos ) : + [ "center", "center" ]; + } + pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; + pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; + + // calculate offsets + horizontalOffset = roffset.exec( pos[ 0 ] ); + verticalOffset = roffset.exec( pos[ 1 ] ); + offsets[ this ] = [ + horizontalOffset ? horizontalOffset[ 0 ] : 0, + verticalOffset ? verticalOffset[ 0 ] : 0 + ]; + + // reduce to just the positions without the offsets + options[ this ] = [ + rposition.exec( pos[ 0 ] )[ 0 ], + rposition.exec( pos[ 1 ] )[ 0 ] + ]; + }); + + // normalize collision option + if ( collision.length === 1 ) { + collision[ 1 ] = collision[ 0 ]; + } + + if ( options.at[ 0 ] === "right" ) { + basePosition.left += targetWidth; + } else if ( options.at[ 0 ] === "center" ) { + basePosition.left += targetWidth / 2; + } + + if ( options.at[ 1 ] === "bottom" ) { + basePosition.top += targetHeight; + } else if ( options.at[ 1 ] === "center" ) { + basePosition.top += targetHeight / 2; + } + + atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); + basePosition.left += atOffset[ 0 ]; + basePosition.top += atOffset[ 1 ]; + + return this.each(function() { + var collisionPosition, using, + elem = $( this ), + elemWidth = elem.outerWidth(), + elemHeight = elem.outerHeight(), + marginLeft = parseCss( this, "marginLeft" ), + marginTop = parseCss( this, "marginTop" ), + collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, + collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, + position = $.extend( {}, basePosition ), + myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); + + if ( options.my[ 0 ] === "right" ) { + position.left -= elemWidth; + } else if ( options.my[ 0 ] === "center" ) { + position.left -= elemWidth / 2; + } + + if ( options.my[ 1 ] === "bottom" ) { + position.top -= elemHeight; + } else if ( options.my[ 1 ] === "center" ) { + position.top -= elemHeight / 2; + } + + position.left += myOffset[ 0 ]; + position.top += myOffset[ 1 ]; + + // if the browser doesn't support fractions, then round for consistent results + if ( !$.support.offsetFractions ) { + position.left = round( position.left ); + position.top = round( position.top ); + } + + collisionPosition = { + marginLeft: marginLeft, + marginTop: marginTop + }; + + $.each( [ "left", "top" ], function( i, dir ) { + if ( $.ui.position[ collision[ i ] ] ) { + $.ui.position[ collision[ i ] ][ dir ]( position, { + targetWidth: targetWidth, + targetHeight: targetHeight, + elemWidth: elemWidth, + elemHeight: elemHeight, + collisionPosition: collisionPosition, + collisionWidth: collisionWidth, + collisionHeight: collisionHeight, + offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], + my: options.my, + at: options.at, + within: within, + elem : elem + }); + } + }); + + if ( $.fn.bgiframe ) { + elem.bgiframe(); + } + + if ( options.using ) { + // adds feedback as second argument to using callback, if present + using = function( props ) { + var left = targetOffset.left - position.left, + right = left + targetWidth - elemWidth, + top = targetOffset.top - position.top, + bottom = top + targetHeight - elemHeight, + feedback = { + target: { + element: target, + left: targetOffset.left, + top: targetOffset.top, + width: targetWidth, + height: targetHeight + }, + element: { + element: elem, + left: position.left, + top: position.top, + width: elemWidth, + height: elemHeight + }, + horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", + vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" + }; + if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { + feedback.horizontal = "center"; + } + if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { + feedback.vertical = "middle"; + } + if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { + feedback.important = "horizontal"; + } else { + feedback.important = "vertical"; + } + options.using.call( this, props, feedback ); + }; + } + + elem.offset( $.extend( position, { using: using } ) ); + }); +}; + +$.ui.position = { + fit: { + left: function( position, data ) { + var within = data.within, + withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, + outerWidth = within.width, + collisionPosLeft = position.left - data.collisionPosition.marginLeft, + overLeft = withinOffset - collisionPosLeft, + overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, + newOverRight; + + // element is wider than within + if ( data.collisionWidth > outerWidth ) { + // element is initially over the left side of within + if ( overLeft > 0 && overRight <= 0 ) { + newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; + position.left += overLeft - newOverRight; + // element is initially over right side of within + } else if ( overRight > 0 && overLeft <= 0 ) { + position.left = withinOffset; + // element is initially over both left and right sides of within + } else { + if ( overLeft > overRight ) { + position.left = withinOffset + outerWidth - data.collisionWidth; + } else { + position.left = withinOffset; + } + } + // too far left -> align with left edge + } else if ( overLeft > 0 ) { + position.left += overLeft; + // too far right -> align with right edge + } else if ( overRight > 0 ) { + position.left -= overRight; + // adjust based on position and margin + } else { + position.left = max( position.left - collisionPosLeft, position.left ); + } + }, + top: function( position, data ) { + var within = data.within, + withinOffset = within.isWindow ? within.scrollTop : within.offset.top, + outerHeight = data.within.height, + collisionPosTop = position.top - data.collisionPosition.marginTop, + overTop = withinOffset - collisionPosTop, + overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, + newOverBottom; + + // element is taller than within + if ( data.collisionHeight > outerHeight ) { + // element is initially over the top of within + if ( overTop > 0 && overBottom <= 0 ) { + newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; + position.top += overTop - newOverBottom; + // element is initially over bottom of within + } else if ( overBottom > 0 && overTop <= 0 ) { + position.top = withinOffset; + // element is initially over both top and bottom of within + } else { + if ( overTop > overBottom ) { + position.top = withinOffset + outerHeight - data.collisionHeight; + } else { + position.top = withinOffset; + } + } + // too far up -> align with top + } else if ( overTop > 0 ) { + position.top += overTop; + // too far down -> align with bottom edge + } else if ( overBottom > 0 ) { + position.top -= overBottom; + // adjust based on position and margin + } else { + position.top = max( position.top - collisionPosTop, position.top ); + } + } + }, + flip: { + left: function( position, data ) { + var within = data.within, + withinOffset = within.offset.left + within.scrollLeft, + outerWidth = within.width, + offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, + collisionPosLeft = position.left - data.collisionPosition.marginLeft, + overLeft = collisionPosLeft - offsetLeft, + overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, + myOffset = data.my[ 0 ] === "left" ? + -data.elemWidth : + data.my[ 0 ] === "right" ? + data.elemWidth : + 0, + atOffset = data.at[ 0 ] === "left" ? + data.targetWidth : + data.at[ 0 ] === "right" ? + -data.targetWidth : + 0, + offset = -2 * data.offset[ 0 ], + newOverRight, + newOverLeft; + + if ( overLeft < 0 ) { + newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; + if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { + position.left += myOffset + atOffset + offset; + } + } + else if ( overRight > 0 ) { + newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; + if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { + position.left += myOffset + atOffset + offset; + } + } + }, + top: function( position, data ) { + var within = data.within, + withinOffset = within.offset.top + within.scrollTop, + outerHeight = within.height, + offsetTop = within.isWindow ? within.scrollTop : within.offset.top, + collisionPosTop = position.top - data.collisionPosition.marginTop, + overTop = collisionPosTop - offsetTop, + overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, + top = data.my[ 1 ] === "top", + myOffset = top ? + -data.elemHeight : + data.my[ 1 ] === "bottom" ? + data.elemHeight : + 0, + atOffset = data.at[ 1 ] === "top" ? + data.targetHeight : + data.at[ 1 ] === "bottom" ? + -data.targetHeight : + 0, + offset = -2 * data.offset[ 1 ], + newOverTop, + newOverBottom; + if ( overTop < 0 ) { + newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; + if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) { + position.top += myOffset + atOffset + offset; + } + } + else if ( overBottom > 0 ) { + newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; + if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) { + position.top += myOffset + atOffset + offset; + } + } + } + }, + flipfit: { + left: function() { + $.ui.position.flip.left.apply( this, arguments ); + $.ui.position.fit.left.apply( this, arguments ); + }, + top: function() { + $.ui.position.flip.top.apply( this, arguments ); + $.ui.position.fit.top.apply( this, arguments ); + } + } +}; + +// fraction support test +(function () { + var testElement, testElementParent, testElementStyle, offsetLeft, i, + body = document.getElementsByTagName( "body" )[ 0 ], + div = document.createElement( "div" ); + + //Create a "fake body" for testing based on method used in jQuery.support + testElement = document.createElement( body ? "div" : "body" ); + testElementStyle = { + visibility: "hidden", + width: 0, + height: 0, + border: 0, + margin: 0, + background: "none" + }; + if ( body ) { + $.extend( testElementStyle, { + position: "absolute", + left: "-1000px", + top: "-1000px" + }); + } + for ( i in testElementStyle ) { + testElement.style[ i ] = testElementStyle[ i ]; + } + testElement.appendChild( div ); + testElementParent = body || document.documentElement; + testElementParent.insertBefore( testElement, testElementParent.firstChild ); + + div.style.cssText = "position: absolute; left: 10.7432222px;"; + + offsetLeft = $( div ).offset().left; + $.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11; + + testElement.innerHTML = ""; + testElementParent.removeChild( testElement ); +})(); + +// DEPRECATED +if ( $.uiBackCompat !== false ) { + // offset option + (function( $ ) { + var _position = $.fn.position; + $.fn.position = function( options ) { + if ( !options || !options.offset ) { + return _position.call( this, options ); + } + var offset = options.offset.split( " " ), + at = options.at.split( " " ); + if ( offset.length === 1 ) { + offset[ 1 ] = offset[ 0 ]; + } + if ( /^\d/.test( offset[ 0 ] ) ) { + offset[ 0 ] = "+" + offset[ 0 ]; + } + if ( /^\d/.test( offset[ 1 ] ) ) { + offset[ 1 ] = "+" + offset[ 1 ]; + } + if ( at.length === 1 ) { + if ( /left|center|right/.test( at[ 0 ] ) ) { + at[ 1 ] = "center"; + } else { + at[ 1 ] = at[ 0 ]; + at[ 0 ] = "center"; + } + } + return _position.call( this, $.extend( options, { + at: at[ 0 ] + offset[ 0 ] + " " + at[ 1 ] + offset[ 1 ], + offset: undefined + } ) ); + }; + }( jQuery ) ); +} + +}( jQuery ) ); + +(function( $, undefined ) { + +$.widget( "ui.progressbar", { + version: "1.9.2", + options: { + value: 0, + max: 100 + }, + + min: 0, + + _create: function() { + this.element + .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) + .attr({ + role: "progressbar", + "aria-valuemin": this.min, + "aria-valuemax": this.options.max, + "aria-valuenow": this._value() + }); + + this.valueDiv = $( "
    " ) + .appendTo( this.element ); + + this.oldValue = this._value(); + this._refreshValue(); + }, + + _destroy: function() { + this.element + .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) + .removeAttr( "role" ) + .removeAttr( "aria-valuemin" ) + .removeAttr( "aria-valuemax" ) + .removeAttr( "aria-valuenow" ); + + this.valueDiv.remove(); + }, + + value: function( newValue ) { + if ( newValue === undefined ) { + return this._value(); + } + + this._setOption( "value", newValue ); + return this; + }, + + _setOption: function( key, value ) { + if ( key === "value" ) { + this.options.value = value; + this._refreshValue(); + if ( this._value() === this.options.max ) { + this._trigger( "complete" ); + } + } + + this._super( key, value ); + }, + + _value: function() { + var val = this.options.value; + // normalize invalid value + if ( typeof val !== "number" ) { + val = 0; + } + return Math.min( this.options.max, Math.max( this.min, val ) ); + }, + + _percentage: function() { + return 100 * this._value() / this.options.max; + }, + + _refreshValue: function() { + var value = this.value(), + percentage = this._percentage(); + + if ( this.oldValue !== value ) { + this.oldValue = value; + this._trigger( "change" ); + } + + this.valueDiv + .toggle( value > this.min ) + .toggleClass( "ui-corner-right", value === this.options.max ) + .width( percentage.toFixed(0) + "%" ); + this.element.attr( "aria-valuenow", value ); + } +}); + +})( jQuery ); + +(function( $, undefined ) { + +// number of pages in a slider +// (how many times can you page up/down to go through the whole range) +var numPages = 5; + +$.widget( "ui.slider", $.ui.mouse, { + version: "1.9.2", + widgetEventPrefix: "slide", + + options: { + animate: false, + distance: 0, + max: 100, + min: 0, + orientation: "horizontal", + range: false, + step: 1, + value: 0, + values: null + }, + + _create: function() { + var i, handleCount, + o = this.options, + existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), + handle = "", + handles = []; + + this._keySliding = false; + this._mouseSliding = false; + this._animateOff = true; + this._handleIndex = null; + this._detectOrientation(); + this._mouseInit(); + + this.element + .addClass( "ui-slider" + + " ui-slider-" + this.orientation + + " ui-widget" + + " ui-widget-content" + + " ui-corner-all" + + ( o.disabled ? " ui-slider-disabled ui-disabled" : "" ) ); + + this.range = $([]); + + if ( o.range ) { + if ( o.range === true ) { + if ( !o.values ) { + o.values = [ this._valueMin(), this._valueMin() ]; + } + if ( o.values.length && o.values.length !== 2 ) { + o.values = [ o.values[0], o.values[0] ]; + } + } + + this.range = $( "
    " ) + .appendTo( this.element ) + .addClass( "ui-slider-range" + + // note: this isn't the most fittingly semantic framework class for this element, + // but worked best visually with a variety of themes + " ui-widget-header" + + ( ( o.range === "min" || o.range === "max" ) ? " ui-slider-range-" + o.range : "" ) ); + } + + handleCount = ( o.values && o.values.length ) || 1; + + for ( i = existingHandles.length; i < handleCount; i++ ) { + handles.push( handle ); + } + + this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) ); + + this.handle = this.handles.eq( 0 ); + + this.handles.add( this.range ).filter( "a" ) + .click(function( event ) { + event.preventDefault(); + }) + .mouseenter(function() { + if ( !o.disabled ) { + $( this ).addClass( "ui-state-hover" ); + } + }) + .mouseleave(function() { + $( this ).removeClass( "ui-state-hover" ); + }) + .focus(function() { + if ( !o.disabled ) { + $( ".ui-slider .ui-state-focus" ).removeClass( "ui-state-focus" ); + $( this ).addClass( "ui-state-focus" ); + } else { + $( this ).blur(); + } + }) + .blur(function() { + $( this ).removeClass( "ui-state-focus" ); + }); + + this.handles.each(function( i ) { + $( this ).data( "ui-slider-handle-index", i ); + }); + + this._on( this.handles, { + keydown: function( event ) { + var allowed, curVal, newVal, step, + index = $( event.target ).data( "ui-slider-handle-index" ); + + switch ( event.keyCode ) { + case $.ui.keyCode.HOME: + case $.ui.keyCode.END: + case $.ui.keyCode.PAGE_UP: + case $.ui.keyCode.PAGE_DOWN: + case $.ui.keyCode.UP: + case $.ui.keyCode.RIGHT: + case $.ui.keyCode.DOWN: + case $.ui.keyCode.LEFT: + event.preventDefault(); + if ( !this._keySliding ) { + this._keySliding = true; + $( event.target ).addClass( "ui-state-active" ); + allowed = this._start( event, index ); + if ( allowed === false ) { + return; + } + } + break; + } + + step = this.options.step; + if ( this.options.values && this.options.values.length ) { + curVal = newVal = this.values( index ); + } else { + curVal = newVal = this.value(); + } + + switch ( event.keyCode ) { + case $.ui.keyCode.HOME: + newVal = this._valueMin(); + break; + case $.ui.keyCode.END: + newVal = this._valueMax(); + break; + case $.ui.keyCode.PAGE_UP: + newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) ); + break; + case $.ui.keyCode.PAGE_DOWN: + newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) ); + break; + case $.ui.keyCode.UP: + case $.ui.keyCode.RIGHT: + if ( curVal === this._valueMax() ) { + return; + } + newVal = this._trimAlignValue( curVal + step ); + break; + case $.ui.keyCode.DOWN: + case $.ui.keyCode.LEFT: + if ( curVal === this._valueMin() ) { + return; + } + newVal = this._trimAlignValue( curVal - step ); + break; + } + + this._slide( event, index, newVal ); + }, + keyup: function( event ) { + var index = $( event.target ).data( "ui-slider-handle-index" ); + + if ( this._keySliding ) { + this._keySliding = false; + this._stop( event, index ); + this._change( event, index ); + $( event.target ).removeClass( "ui-state-active" ); + } + } + }); + + this._refreshValue(); + + this._animateOff = false; + }, + + _destroy: function() { + this.handles.remove(); + this.range.remove(); + + this.element + .removeClass( "ui-slider" + + " ui-slider-horizontal" + + " ui-slider-vertical" + + " ui-slider-disabled" + + " ui-widget" + + " ui-widget-content" + + " ui-corner-all" ); + + this._mouseDestroy(); + }, + + _mouseCapture: function( event ) { + var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle, + that = this, + o = this.options; + + if ( o.disabled ) { + return false; + } + + this.elementSize = { + width: this.element.outerWidth(), + height: this.element.outerHeight() + }; + this.elementOffset = this.element.offset(); + + position = { x: event.pageX, y: event.pageY }; + normValue = this._normValueFromMouse( position ); + distance = this._valueMax() - this._valueMin() + 1; + this.handles.each(function( i ) { + var thisDistance = Math.abs( normValue - that.values(i) ); + if ( distance > thisDistance ) { + distance = thisDistance; + closestHandle = $( this ); + index = i; + } + }); + + // workaround for bug #3736 (if both handles of a range are at 0, + // the first is always used as the one with least distance, + // and moving it is obviously prevented by preventing negative ranges) + if( o.range === true && this.values(1) === o.min ) { + index += 1; + closestHandle = $( this.handles[index] ); + } + + allowed = this._start( event, index ); + if ( allowed === false ) { + return false; + } + this._mouseSliding = true; + + this._handleIndex = index; + + closestHandle + .addClass( "ui-state-active" ) + .focus(); + + offset = closestHandle.offset(); + mouseOverHandle = !$( event.target ).parents().andSelf().is( ".ui-slider-handle" ); + this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { + left: event.pageX - offset.left - ( closestHandle.width() / 2 ), + top: event.pageY - offset.top - + ( closestHandle.height() / 2 ) - + ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - + ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + + ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) + }; + + if ( !this.handles.hasClass( "ui-state-hover" ) ) { + this._slide( event, index, normValue ); + } + this._animateOff = true; + return true; + }, + + _mouseStart: function() { + return true; + }, + + _mouseDrag: function( event ) { + var position = { x: event.pageX, y: event.pageY }, + normValue = this._normValueFromMouse( position ); + + this._slide( event, this._handleIndex, normValue ); + + return false; + }, + + _mouseStop: function( event ) { + this.handles.removeClass( "ui-state-active" ); + this._mouseSliding = false; + + this._stop( event, this._handleIndex ); + this._change( event, this._handleIndex ); + + this._handleIndex = null; + this._clickOffset = null; + this._animateOff = false; + + return false; + }, + + _detectOrientation: function() { + this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal"; + }, + + _normValueFromMouse: function( position ) { + var pixelTotal, + pixelMouse, + percentMouse, + valueTotal, + valueMouse; + + if ( this.orientation === "horizontal" ) { + pixelTotal = this.elementSize.width; + pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); + } else { + pixelTotal = this.elementSize.height; + pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); + } + + percentMouse = ( pixelMouse / pixelTotal ); + if ( percentMouse > 1 ) { + percentMouse = 1; + } + if ( percentMouse < 0 ) { + percentMouse = 0; + } + if ( this.orientation === "vertical" ) { + percentMouse = 1 - percentMouse; + } + + valueTotal = this._valueMax() - this._valueMin(); + valueMouse = this._valueMin() + percentMouse * valueTotal; + + return this._trimAlignValue( valueMouse ); + }, + + _start: function( event, index ) { + var uiHash = { + handle: this.handles[ index ], + value: this.value() + }; + if ( this.options.values && this.options.values.length ) { + uiHash.value = this.values( index ); + uiHash.values = this.values(); + } + return this._trigger( "start", event, uiHash ); + }, + + _slide: function( event, index, newVal ) { + var otherVal, + newValues, + allowed; + + if ( this.options.values && this.options.values.length ) { + otherVal = this.values( index ? 0 : 1 ); + + if ( ( this.options.values.length === 2 && this.options.range === true ) && + ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) + ) { + newVal = otherVal; + } + + if ( newVal !== this.values( index ) ) { + newValues = this.values(); + newValues[ index ] = newVal; + // A slide can be canceled by returning false from the slide callback + allowed = this._trigger( "slide", event, { + handle: this.handles[ index ], + value: newVal, + values: newValues + } ); + otherVal = this.values( index ? 0 : 1 ); + if ( allowed !== false ) { + this.values( index, newVal, true ); + } + } + } else { + if ( newVal !== this.value() ) { + // A slide can be canceled by returning false from the slide callback + allowed = this._trigger( "slide", event, { + handle: this.handles[ index ], + value: newVal + } ); + if ( allowed !== false ) { + this.value( newVal ); + } + } + } + }, + + _stop: function( event, index ) { + var uiHash = { + handle: this.handles[ index ], + value: this.value() + }; + if ( this.options.values && this.options.values.length ) { + uiHash.value = this.values( index ); + uiHash.values = this.values(); + } + + this._trigger( "stop", event, uiHash ); + }, + + _change: function( event, index ) { + if ( !this._keySliding && !this._mouseSliding ) { + var uiHash = { + handle: this.handles[ index ], + value: this.value() + }; + if ( this.options.values && this.options.values.length ) { + uiHash.value = this.values( index ); + uiHash.values = this.values(); + } + + this._trigger( "change", event, uiHash ); + } + }, + + value: function( newValue ) { + if ( arguments.length ) { + this.options.value = this._trimAlignValue( newValue ); + this._refreshValue(); + this._change( null, 0 ); + return; + } + + return this._value(); + }, + + values: function( index, newValue ) { + var vals, + newValues, + i; + + if ( arguments.length > 1 ) { + this.options.values[ index ] = this._trimAlignValue( newValue ); + this._refreshValue(); + this._change( null, index ); + return; + } + + if ( arguments.length ) { + if ( $.isArray( arguments[ 0 ] ) ) { + vals = this.options.values; + newValues = arguments[ 0 ]; + for ( i = 0; i < vals.length; i += 1 ) { + vals[ i ] = this._trimAlignValue( newValues[ i ] ); + this._change( null, i ); + } + this._refreshValue(); + } else { + if ( this.options.values && this.options.values.length ) { + return this._values( index ); + } else { + return this.value(); + } + } + } else { + return this._values(); + } + }, + + _setOption: function( key, value ) { + var i, + valsLength = 0; + + if ( $.isArray( this.options.values ) ) { + valsLength = this.options.values.length; + } + + $.Widget.prototype._setOption.apply( this, arguments ); + + switch ( key ) { + case "disabled": + if ( value ) { + this.handles.filter( ".ui-state-focus" ).blur(); + this.handles.removeClass( "ui-state-hover" ); + this.handles.prop( "disabled", true ); + this.element.addClass( "ui-disabled" ); + } else { + this.handles.prop( "disabled", false ); + this.element.removeClass( "ui-disabled" ); + } + break; + case "orientation": + this._detectOrientation(); + this.element + .removeClass( "ui-slider-horizontal ui-slider-vertical" ) + .addClass( "ui-slider-" + this.orientation ); + this._refreshValue(); + break; + case "value": + this._animateOff = true; + this._refreshValue(); + this._change( null, 0 ); + this._animateOff = false; + break; + case "values": + this._animateOff = true; + this._refreshValue(); + for ( i = 0; i < valsLength; i += 1 ) { + this._change( null, i ); + } + this._animateOff = false; + break; + case "min": + case "max": + this._animateOff = true; + this._refreshValue(); + this._animateOff = false; + break; + } + }, + + //internal value getter + // _value() returns value trimmed by min and max, aligned by step + _value: function() { + var val = this.options.value; + val = this._trimAlignValue( val ); + + return val; + }, + + //internal values getter + // _values() returns array of values trimmed by min and max, aligned by step + // _values( index ) returns single value trimmed by min and max, aligned by step + _values: function( index ) { + var val, + vals, + i; + + if ( arguments.length ) { + val = this.options.values[ index ]; + val = this._trimAlignValue( val ); + + return val; + } else { + // .slice() creates a copy of the array + // this copy gets trimmed by min and max and then returned + vals = this.options.values.slice(); + for ( i = 0; i < vals.length; i+= 1) { + vals[ i ] = this._trimAlignValue( vals[ i ] ); + } + + return vals; + } + }, + + // returns the step-aligned value that val is closest to, between (inclusive) min and max + _trimAlignValue: function( val ) { + if ( val <= this._valueMin() ) { + return this._valueMin(); + } + if ( val >= this._valueMax() ) { + return this._valueMax(); + } + var step = ( this.options.step > 0 ) ? this.options.step : 1, + valModStep = (val - this._valueMin()) % step, + alignValue = val - valModStep; + + if ( Math.abs(valModStep) * 2 >= step ) { + alignValue += ( valModStep > 0 ) ? step : ( -step ); + } + + // Since JavaScript has problems with large floats, round + // the final value to 5 digits after the decimal point (see #4124) + return parseFloat( alignValue.toFixed(5) ); + }, + + _valueMin: function() { + return this.options.min; + }, + + _valueMax: function() { + return this.options.max; + }, + + _refreshValue: function() { + var lastValPercent, valPercent, value, valueMin, valueMax, + oRange = this.options.range, + o = this.options, + that = this, + animate = ( !this._animateOff ) ? o.animate : false, + _set = {}; + + if ( this.options.values && this.options.values.length ) { + this.handles.each(function( i ) { + valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100; + _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; + $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); + if ( that.options.range === true ) { + if ( that.orientation === "horizontal" ) { + if ( i === 0 ) { + that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); + } + if ( i === 1 ) { + that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); + } + } else { + if ( i === 0 ) { + that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); + } + if ( i === 1 ) { + that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); + } + } + } + lastValPercent = valPercent; + }); + } else { + value = this.value(); + valueMin = this._valueMin(); + valueMax = this._valueMax(); + valPercent = ( valueMax !== valueMin ) ? + ( value - valueMin ) / ( valueMax - valueMin ) * 100 : + 0; + _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; + this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); + + if ( oRange === "min" && this.orientation === "horizontal" ) { + this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); + } + if ( oRange === "max" && this.orientation === "horizontal" ) { + this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); + } + if ( oRange === "min" && this.orientation === "vertical" ) { + this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); + } + if ( oRange === "max" && this.orientation === "vertical" ) { + this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); + } + } + } + +}); + +}(jQuery)); + +(function( $ ) { + +function modifier( fn ) { + return function() { + var previous = this.element.val(); + fn.apply( this, arguments ); + this._refresh(); + if ( previous !== this.element.val() ) { + this._trigger( "change" ); + } + }; +} + +$.widget( "ui.spinner", { + version: "1.9.2", + defaultElement: "", + widgetEventPrefix: "spin", + options: { + culture: null, + icons: { + down: "ui-icon-triangle-1-s", + up: "ui-icon-triangle-1-n" + }, + incremental: true, + max: null, + min: null, + numberFormat: null, + page: 10, + step: 1, + + change: null, + spin: null, + start: null, + stop: null + }, + + _create: function() { + // handle string values that need to be parsed + this._setOption( "max", this.options.max ); + this._setOption( "min", this.options.min ); + this._setOption( "step", this.options.step ); + + // format the value, but don't constrain + this._value( this.element.val(), true ); + + this._draw(); + this._on( this._events ); + this._refresh(); + + // turning off autocomplete prevents the browser from remembering the + // value when navigating through history, so we re-enable autocomplete + // if the page is unloaded before the widget is destroyed. #7790 + this._on( this.window, { + beforeunload: function() { + this.element.removeAttr( "autocomplete" ); + } + }); + }, + + _getCreateOptions: function() { + var options = {}, + element = this.element; + + $.each( [ "min", "max", "step" ], function( i, option ) { + var value = element.attr( option ); + if ( value !== undefined && value.length ) { + options[ option ] = value; + } + }); + + return options; + }, + + _events: { + keydown: function( event ) { + if ( this._start( event ) && this._keydown( event ) ) { + event.preventDefault(); + } + }, + keyup: "_stop", + focus: function() { + this.previous = this.element.val(); + }, + blur: function( event ) { + if ( this.cancelBlur ) { + delete this.cancelBlur; + return; + } + + this._refresh(); + if ( this.previous !== this.element.val() ) { + this._trigger( "change", event ); + } + }, + mousewheel: function( event, delta ) { + if ( !delta ) { + return; + } + if ( !this.spinning && !this._start( event ) ) { + return false; + } + + this._spin( (delta > 0 ? 1 : -1) * this.options.step, event ); + clearTimeout( this.mousewheelTimer ); + this.mousewheelTimer = this._delay(function() { + if ( this.spinning ) { + this._stop( event ); + } + }, 100 ); + event.preventDefault(); + }, + "mousedown .ui-spinner-button": function( event ) { + var previous; + + // We never want the buttons to have focus; whenever the user is + // interacting with the spinner, the focus should be on the input. + // If the input is focused then this.previous is properly set from + // when the input first received focus. If the input is not focused + // then we need to set this.previous based on the value before spinning. + previous = this.element[0] === this.document[0].activeElement ? + this.previous : this.element.val(); + function checkFocus() { + var isActive = this.element[0] === this.document[0].activeElement; + if ( !isActive ) { + this.element.focus(); + this.previous = previous; + // support: IE + // IE sets focus asynchronously, so we need to check if focus + // moved off of the input because the user clicked on the button. + this._delay(function() { + this.previous = previous; + }); + } + } + + // ensure focus is on (or stays on) the text field + event.preventDefault(); + checkFocus.call( this ); + + // support: IE + // IE doesn't prevent moving focus even with event.preventDefault() + // so we set a flag to know when we should ignore the blur event + // and check (again) if focus moved off of the input. + this.cancelBlur = true; + this._delay(function() { + delete this.cancelBlur; + checkFocus.call( this ); + }); + + if ( this._start( event ) === false ) { + return; + } + + this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); + }, + "mouseup .ui-spinner-button": "_stop", + "mouseenter .ui-spinner-button": function( event ) { + // button will add ui-state-active if mouse was down while mouseleave and kept down + if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) { + return; + } + + if ( this._start( event ) === false ) { + return false; + } + this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); + }, + // TODO: do we really want to consider this a stop? + // shouldn't we just stop the repeater and wait until mouseup before + // we trigger the stop event? + "mouseleave .ui-spinner-button": "_stop" + }, + + _draw: function() { + var uiSpinner = this.uiSpinner = this.element + .addClass( "ui-spinner-input" ) + .attr( "autocomplete", "off" ) + .wrap( this._uiSpinnerHtml() ) + .parent() + // add buttons + .append( this._buttonHtml() ); + + this.element.attr( "role", "spinbutton" ); + + // button bindings + this.buttons = uiSpinner.find( ".ui-spinner-button" ) + .attr( "tabIndex", -1 ) + .button() + .removeClass( "ui-corner-all" ); + + // IE 6 doesn't understand height: 50% for the buttons + // unless the wrapper has an explicit height + if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) && + uiSpinner.height() > 0 ) { + uiSpinner.height( uiSpinner.height() ); + } + + // disable spinner if element was already disabled + if ( this.options.disabled ) { + this.disable(); + } + }, + + _keydown: function( event ) { + var options = this.options, + keyCode = $.ui.keyCode; + + switch ( event.keyCode ) { + case keyCode.UP: + this._repeat( null, 1, event ); + return true; + case keyCode.DOWN: + this._repeat( null, -1, event ); + return true; + case keyCode.PAGE_UP: + this._repeat( null, options.page, event ); + return true; + case keyCode.PAGE_DOWN: + this._repeat( null, -options.page, event ); + return true; + } + + return false; + }, + + _uiSpinnerHtml: function() { + return ""; + }, + + _buttonHtml: function() { + return "" + + "" + + "" + + "" + + "" + + "" + + ""; + }, + + _start: function( event ) { + if ( !this.spinning && this._trigger( "start", event ) === false ) { + return false; + } + + if ( !this.counter ) { + this.counter = 1; + } + this.spinning = true; + return true; + }, + + _repeat: function( i, steps, event ) { + i = i || 500; + + clearTimeout( this.timer ); + this.timer = this._delay(function() { + this._repeat( 40, steps, event ); + }, i ); + + this._spin( steps * this.options.step, event ); + }, + + _spin: function( step, event ) { + var value = this.value() || 0; + + if ( !this.counter ) { + this.counter = 1; + } + + value = this._adjustValue( value + step * this._increment( this.counter ) ); + + if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) { + this._value( value ); + this.counter++; + } + }, + + _increment: function( i ) { + var incremental = this.options.incremental; + + if ( incremental ) { + return $.isFunction( incremental ) ? + incremental( i ) : + Math.floor( i*i*i/50000 - i*i/500 + 17*i/200 + 1 ); + } + + return 1; + }, + + _precision: function() { + var precision = this._precisionOf( this.options.step ); + if ( this.options.min !== null ) { + precision = Math.max( precision, this._precisionOf( this.options.min ) ); + } + return precision; + }, + + _precisionOf: function( num ) { + var str = num.toString(), + decimal = str.indexOf( "." ); + return decimal === -1 ? 0 : str.length - decimal - 1; + }, + + _adjustValue: function( value ) { + var base, aboveMin, + options = this.options; + + // make sure we're at a valid step + // - find out where we are relative to the base (min or 0) + base = options.min !== null ? options.min : 0; + aboveMin = value - base; + // - round to the nearest step + aboveMin = Math.round(aboveMin / options.step) * options.step; + // - rounding is based on 0, so adjust back to our base + value = base + aboveMin; + + // fix precision from bad JS floating point math + value = parseFloat( value.toFixed( this._precision() ) ); + + // clamp the value + if ( options.max !== null && value > options.max) { + return options.max; + } + if ( options.min !== null && value < options.min ) { + return options.min; + } + + return value; + }, + + _stop: function( event ) { + if ( !this.spinning ) { + return; + } + + clearTimeout( this.timer ); + clearTimeout( this.mousewheelTimer ); + this.counter = 0; + this.spinning = false; + this._trigger( "stop", event ); + }, + + _setOption: function( key, value ) { + if ( key === "culture" || key === "numberFormat" ) { + var prevValue = this._parse( this.element.val() ); + this.options[ key ] = value; + this.element.val( this._format( prevValue ) ); + return; + } + + if ( key === "max" || key === "min" || key === "step" ) { + if ( typeof value === "string" ) { + value = this._parse( value ); + } + } + + this._super( key, value ); + + if ( key === "disabled" ) { + if ( value ) { + this.element.prop( "disabled", true ); + this.buttons.button( "disable" ); + } else { + this.element.prop( "disabled", false ); + this.buttons.button( "enable" ); + } + } + }, + + _setOptions: modifier(function( options ) { + this._super( options ); + this._value( this.element.val() ); + }), + + _parse: function( val ) { + if ( typeof val === "string" && val !== "" ) { + val = window.Globalize && this.options.numberFormat ? + Globalize.parseFloat( val, 10, this.options.culture ) : +val; + } + return val === "" || isNaN( val ) ? null : val; + }, + + _format: function( value ) { + if ( value === "" ) { + return ""; + } + return window.Globalize && this.options.numberFormat ? + Globalize.format( value, this.options.numberFormat, this.options.culture ) : + value; + }, + + _refresh: function() { + this.element.attr({ + "aria-valuemin": this.options.min, + "aria-valuemax": this.options.max, + // TODO: what should we do with values that can't be parsed? + "aria-valuenow": this._parse( this.element.val() ) + }); + }, + + // update the value without triggering change + _value: function( value, allowAny ) { + var parsed; + if ( value !== "" ) { + parsed = this._parse( value ); + if ( parsed !== null ) { + if ( !allowAny ) { + parsed = this._adjustValue( parsed ); + } + value = this._format( parsed ); + } + } + this.element.val( value ); + this._refresh(); + }, + + _destroy: function() { + this.element + .removeClass( "ui-spinner-input" ) + .prop( "disabled", false ) + .removeAttr( "autocomplete" ) + .removeAttr( "role" ) + .removeAttr( "aria-valuemin" ) + .removeAttr( "aria-valuemax" ) + .removeAttr( "aria-valuenow" ); + this.uiSpinner.replaceWith( this.element ); + }, + + stepUp: modifier(function( steps ) { + this._stepUp( steps ); + }), + _stepUp: function( steps ) { + this._spin( (steps || 1) * this.options.step ); + }, + + stepDown: modifier(function( steps ) { + this._stepDown( steps ); + }), + _stepDown: function( steps ) { + this._spin( (steps || 1) * -this.options.step ); + }, + + pageUp: modifier(function( pages ) { + this._stepUp( (pages || 1) * this.options.page ); + }), + + pageDown: modifier(function( pages ) { + this._stepDown( (pages || 1) * this.options.page ); + }), + + value: function( newVal ) { + if ( !arguments.length ) { + return this._parse( this.element.val() ); + } + modifier( this._value ).call( this, newVal ); + }, + + widget: function() { + return this.uiSpinner; + } +}); + +}( jQuery ) ); + +(function( $, undefined ) { + +var tabId = 0, + rhash = /#.*$/; + +function getNextTabId() { + return ++tabId; +} + +function isLocal( anchor ) { + return anchor.hash.length > 1 && + anchor.href.replace( rhash, "" ) === + location.href.replace( rhash, "" ) + // support: Safari 5.1 + // Safari 5.1 doesn't encode spaces in window.location + // but it does encode spaces from anchors (#8777) + .replace( /\s/g, "%20" ); +} + +$.widget( "ui.tabs", { + version: "1.9.2", + delay: 300, + options: { + active: null, + collapsible: false, + event: "click", + heightStyle: "content", + hide: null, + show: null, + + // callbacks + activate: null, + beforeActivate: null, + beforeLoad: null, + load: null + }, + + _create: function() { + var that = this, + options = this.options, + active = options.active, + locationHash = location.hash.substring( 1 ); + + this.running = false; + + this.element + .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ) + .toggleClass( "ui-tabs-collapsible", options.collapsible ) + // Prevent users from focusing disabled tabs via click + .delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) { + if ( $( this ).is( ".ui-state-disabled" ) ) { + event.preventDefault(); + } + }) + // support: IE <9 + // Preventing the default action in mousedown doesn't prevent IE + // from focusing the element, so if the anchor gets focused, blur. + // We don't have to worry about focusing the previously focused + // element since clicking on a non-focusable element should focus + // the body anyway. + .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() { + if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) { + this.blur(); + } + }); + + this._processTabs(); + + if ( active === null ) { + // check the fragment identifier in the URL + if ( locationHash ) { + this.tabs.each(function( i, tab ) { + if ( $( tab ).attr( "aria-controls" ) === locationHash ) { + active = i; + return false; + } + }); + } + + // check for a tab marked active via a class + if ( active === null ) { + active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) ); + } + + // no active tab, set to false + if ( active === null || active === -1 ) { + active = this.tabs.length ? 0 : false; + } + } + + // handle numbers: negative, out of range + if ( active !== false ) { + active = this.tabs.index( this.tabs.eq( active ) ); + if ( active === -1 ) { + active = options.collapsible ? false : 0; + } + } + options.active = active; + + // don't allow collapsible: false and active: false + if ( !options.collapsible && options.active === false && this.anchors.length ) { + options.active = 0; + } + + // Take disabling tabs via class attribute from HTML + // into account and update option properly. + if ( $.isArray( options.disabled ) ) { + options.disabled = $.unique( options.disabled.concat( + $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) { + return that.tabs.index( li ); + }) + ) ).sort(); + } + + // check for length avoids error when initializing empty list + if ( this.options.active !== false && this.anchors.length ) { + this.active = this._findActive( this.options.active ); + } else { + this.active = $(); + } + + this._refresh(); + + if ( this.active.length ) { + this.load( options.active ); + } + }, + + _getCreateEventData: function() { + return { + tab: this.active, + panel: !this.active.length ? $() : this._getPanelForTab( this.active ) + }; + }, + + _tabKeydown: function( event ) { + var focusedTab = $( this.document[0].activeElement ).closest( "li" ), + selectedIndex = this.tabs.index( focusedTab ), + goingForward = true; + + if ( this._handlePageNav( event ) ) { + return; + } + + switch ( event.keyCode ) { + case $.ui.keyCode.RIGHT: + case $.ui.keyCode.DOWN: + selectedIndex++; + break; + case $.ui.keyCode.UP: + case $.ui.keyCode.LEFT: + goingForward = false; + selectedIndex--; + break; + case $.ui.keyCode.END: + selectedIndex = this.anchors.length - 1; + break; + case $.ui.keyCode.HOME: + selectedIndex = 0; + break; + case $.ui.keyCode.SPACE: + // Activate only, no collapsing + event.preventDefault(); + clearTimeout( this.activating ); + this._activate( selectedIndex ); + return; + case $.ui.keyCode.ENTER: + // Toggle (cancel delayed activation, allow collapsing) + event.preventDefault(); + clearTimeout( this.activating ); + // Determine if we should collapse or activate + this._activate( selectedIndex === this.options.active ? false : selectedIndex ); + return; + default: + return; + } + + // Focus the appropriate tab, based on which key was pressed + event.preventDefault(); + clearTimeout( this.activating ); + selectedIndex = this._focusNextTab( selectedIndex, goingForward ); + + // Navigating with control key will prevent automatic activation + if ( !event.ctrlKey ) { + // Update aria-selected immediately so that AT think the tab is already selected. + // Otherwise AT may confuse the user by stating that they need to activate the tab, + // but the tab will already be activated by the time the announcement finishes. + focusedTab.attr( "aria-selected", "false" ); + this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" ); + + this.activating = this._delay(function() { + this.option( "active", selectedIndex ); + }, this.delay ); + } + }, + + _panelKeydown: function( event ) { + if ( this._handlePageNav( event ) ) { + return; + } + + // Ctrl+up moves focus to the current tab + if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) { + event.preventDefault(); + this.active.focus(); + } + }, + + // Alt+page up/down moves focus to the previous/next tab (and activates) + _handlePageNav: function( event ) { + if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) { + this._activate( this._focusNextTab( this.options.active - 1, false ) ); + return true; + } + if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) { + this._activate( this._focusNextTab( this.options.active + 1, true ) ); + return true; + } + }, + + _findNextTab: function( index, goingForward ) { + var lastTabIndex = this.tabs.length - 1; + + function constrain() { + if ( index > lastTabIndex ) { + index = 0; + } + if ( index < 0 ) { + index = lastTabIndex; + } + return index; + } + + while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) { + index = goingForward ? index + 1 : index - 1; + } + + return index; + }, + + _focusNextTab: function( index, goingForward ) { + index = this._findNextTab( index, goingForward ); + this.tabs.eq( index ).focus(); + return index; + }, + + _setOption: function( key, value ) { + if ( key === "active" ) { + // _activate() will handle invalid values and update this.options + this._activate( value ); + return; + } + + if ( key === "disabled" ) { + // don't use the widget factory's disabled handling + this._setupDisabled( value ); + return; + } + + this._super( key, value); + + if ( key === "collapsible" ) { + this.element.toggleClass( "ui-tabs-collapsible", value ); + // Setting collapsible: false while collapsed; open first panel + if ( !value && this.options.active === false ) { + this._activate( 0 ); + } + } + + if ( key === "event" ) { + this._setupEvents( value ); + } + + if ( key === "heightStyle" ) { + this._setupHeightStyle( value ); + } + }, + + _tabId: function( tab ) { + return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId(); + }, + + _sanitizeSelector: function( hash ) { + return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : ""; + }, + + refresh: function() { + var options = this.options, + lis = this.tablist.children( ":has(a[href])" ); + + // get disabled tabs from class attribute from HTML + // this will get converted to a boolean if needed in _refresh() + options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) { + return lis.index( tab ); + }); + + this._processTabs(); + + // was collapsed or no tabs + if ( options.active === false || !this.anchors.length ) { + options.active = false; + this.active = $(); + // was active, but active tab is gone + } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) { + // all remaining tabs are disabled + if ( this.tabs.length === options.disabled.length ) { + options.active = false; + this.active = $(); + // activate previous tab + } else { + this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) ); + } + // was active, active tab still exists + } else { + // make sure active index is correct + options.active = this.tabs.index( this.active ); + } + + this._refresh(); + }, + + _refresh: function() { + this._setupDisabled( this.options.disabled ); + this._setupEvents( this.options.event ); + this._setupHeightStyle( this.options.heightStyle ); + + this.tabs.not( this.active ).attr({ + "aria-selected": "false", + tabIndex: -1 + }); + this.panels.not( this._getPanelForTab( this.active ) ) + .hide() + .attr({ + "aria-expanded": "false", + "aria-hidden": "true" + }); + + // Make sure one tab is in the tab order + if ( !this.active.length ) { + this.tabs.eq( 0 ).attr( "tabIndex", 0 ); + } else { + this.active + .addClass( "ui-tabs-active ui-state-active" ) + .attr({ + "aria-selected": "true", + tabIndex: 0 + }); + this._getPanelForTab( this.active ) + .show() + .attr({ + "aria-expanded": "true", + "aria-hidden": "false" + }); + } + }, + + _processTabs: function() { + var that = this; + + this.tablist = this._getList() + .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) + .attr( "role", "tablist" ); + + this.tabs = this.tablist.find( "> li:has(a[href])" ) + .addClass( "ui-state-default ui-corner-top" ) + .attr({ + role: "tab", + tabIndex: -1 + }); + + this.anchors = this.tabs.map(function() { + return $( "a", this )[ 0 ]; + }) + .addClass( "ui-tabs-anchor" ) + .attr({ + role: "presentation", + tabIndex: -1 + }); + + this.panels = $(); + + this.anchors.each(function( i, anchor ) { + var selector, panel, panelId, + anchorId = $( anchor ).uniqueId().attr( "id" ), + tab = $( anchor ).closest( "li" ), + originalAriaControls = tab.attr( "aria-controls" ); + + // inline tab + if ( isLocal( anchor ) ) { + selector = anchor.hash; + panel = that.element.find( that._sanitizeSelector( selector ) ); + // remote tab + } else { + panelId = that._tabId( tab ); + selector = "#" + panelId; + panel = that.element.find( selector ); + if ( !panel.length ) { + panel = that._createPanel( panelId ); + panel.insertAfter( that.panels[ i - 1 ] || that.tablist ); + } + panel.attr( "aria-live", "polite" ); + } + + if ( panel.length) { + that.panels = that.panels.add( panel ); + } + if ( originalAriaControls ) { + tab.data( "ui-tabs-aria-controls", originalAriaControls ); + } + tab.attr({ + "aria-controls": selector.substring( 1 ), + "aria-labelledby": anchorId + }); + panel.attr( "aria-labelledby", anchorId ); + }); + + this.panels + .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) + .attr( "role", "tabpanel" ); + }, + + // allow overriding how to find the list for rare usage scenarios (#7715) + _getList: function() { + return this.element.find( "ol,ul" ).eq( 0 ); + }, + + _createPanel: function( id ) { + return $( "
    " ) + .attr( "id", id ) + .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) + .data( "ui-tabs-destroy", true ); + }, + + _setupDisabled: function( disabled ) { + if ( $.isArray( disabled ) ) { + if ( !disabled.length ) { + disabled = false; + } else if ( disabled.length === this.anchors.length ) { + disabled = true; + } + } + + // disable tabs + for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) { + if ( disabled === true || $.inArray( i, disabled ) !== -1 ) { + $( li ) + .addClass( "ui-state-disabled" ) + .attr( "aria-disabled", "true" ); + } else { + $( li ) + .removeClass( "ui-state-disabled" ) + .removeAttr( "aria-disabled" ); + } + } + + this.options.disabled = disabled; + }, + + _setupEvents: function( event ) { + var events = { + click: function( event ) { + event.preventDefault(); + } + }; + if ( event ) { + $.each( event.split(" "), function( index, eventName ) { + events[ eventName ] = "_eventHandler"; + }); + } + + this._off( this.anchors.add( this.tabs ).add( this.panels ) ); + this._on( this.anchors, events ); + this._on( this.tabs, { keydown: "_tabKeydown" } ); + this._on( this.panels, { keydown: "_panelKeydown" } ); + + this._focusable( this.tabs ); + this._hoverable( this.tabs ); + }, + + _setupHeightStyle: function( heightStyle ) { + var maxHeight, overflow, + parent = this.element.parent(); + + if ( heightStyle === "fill" ) { + // IE 6 treats height like minHeight, so we need to turn off overflow + // in order to get a reliable height + // we use the minHeight support test because we assume that only + // browsers that don't support minHeight will treat height as minHeight + if ( !$.support.minHeight ) { + overflow = parent.css( "overflow" ); + parent.css( "overflow", "hidden"); + } + maxHeight = parent.height(); + this.element.siblings( ":visible" ).each(function() { + var elem = $( this ), + position = elem.css( "position" ); + + if ( position === "absolute" || position === "fixed" ) { + return; + } + maxHeight -= elem.outerHeight( true ); + }); + if ( overflow ) { + parent.css( "overflow", overflow ); + } + + this.element.children().not( this.panels ).each(function() { + maxHeight -= $( this ).outerHeight( true ); + }); + + this.panels.each(function() { + $( this ).height( Math.max( 0, maxHeight - + $( this ).innerHeight() + $( this ).height() ) ); + }) + .css( "overflow", "auto" ); + } else if ( heightStyle === "auto" ) { + maxHeight = 0; + this.panels.each(function() { + maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() ); + }).height( maxHeight ); + } + }, + + _eventHandler: function( event ) { + var options = this.options, + active = this.active, + anchor = $( event.currentTarget ), + tab = anchor.closest( "li" ), + clickedIsActive = tab[ 0 ] === active[ 0 ], + collapsing = clickedIsActive && options.collapsible, + toShow = collapsing ? $() : this._getPanelForTab( tab ), + toHide = !active.length ? $() : this._getPanelForTab( active ), + eventData = { + oldTab: active, + oldPanel: toHide, + newTab: collapsing ? $() : tab, + newPanel: toShow + }; + + event.preventDefault(); + + if ( tab.hasClass( "ui-state-disabled" ) || + // tab is already loading + tab.hasClass( "ui-tabs-loading" ) || + // can't switch durning an animation + this.running || + // click on active header, but not collapsible + ( clickedIsActive && !options.collapsible ) || + // allow canceling activation + ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { + return; + } + + options.active = collapsing ? false : this.tabs.index( tab ); + + this.active = clickedIsActive ? $() : tab; + if ( this.xhr ) { + this.xhr.abort(); + } + + if ( !toHide.length && !toShow.length ) { + $.error( "jQuery UI Tabs: Mismatching fragment identifier." ); + } + + if ( toShow.length ) { + this.load( this.tabs.index( tab ), event ); + } + this._toggle( event, eventData ); + }, + + // handles show/hide for selecting tabs + _toggle: function( event, eventData ) { + var that = this, + toShow = eventData.newPanel, + toHide = eventData.oldPanel; + + this.running = true; + + function complete() { + that.running = false; + that._trigger( "activate", event, eventData ); + } + + function show() { + eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); + + if ( toShow.length && that.options.show ) { + that._show( toShow, that.options.show, complete ); + } else { + toShow.show(); + complete(); + } + } + + // start out by hiding, then showing, then completing + if ( toHide.length && this.options.hide ) { + this._hide( toHide, this.options.hide, function() { + eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); + show(); + }); + } else { + eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); + toHide.hide(); + show(); + } + + toHide.attr({ + "aria-expanded": "false", + "aria-hidden": "true" + }); + eventData.oldTab.attr( "aria-selected", "false" ); + // If we're switching tabs, remove the old tab from the tab order. + // If we're opening from collapsed state, remove the previous tab from the tab order. + // If we're collapsing, then keep the collapsing tab in the tab order. + if ( toShow.length && toHide.length ) { + eventData.oldTab.attr( "tabIndex", -1 ); + } else if ( toShow.length ) { + this.tabs.filter(function() { + return $( this ).attr( "tabIndex" ) === 0; + }) + .attr( "tabIndex", -1 ); + } + + toShow.attr({ + "aria-expanded": "true", + "aria-hidden": "false" + }); + eventData.newTab.attr({ + "aria-selected": "true", + tabIndex: 0 + }); + }, + + _activate: function( index ) { + var anchor, + active = this._findActive( index ); + + // trying to activate the already active panel + if ( active[ 0 ] === this.active[ 0 ] ) { + return; + } + + // trying to collapse, simulate a click on the current active header + if ( !active.length ) { + active = this.active; + } + + anchor = active.find( ".ui-tabs-anchor" )[ 0 ]; + this._eventHandler({ + target: anchor, + currentTarget: anchor, + preventDefault: $.noop + }); + }, + + _findActive: function( index ) { + return index === false ? $() : this.tabs.eq( index ); + }, + + _getIndex: function( index ) { + // meta-function to give users option to provide a href string instead of a numerical index. + if ( typeof index === "string" ) { + index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) ); + } + + return index; + }, + + _destroy: function() { + if ( this.xhr ) { + this.xhr.abort(); + } + + this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ); + + this.tablist + .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) + .removeAttr( "role" ); + + this.anchors + .removeClass( "ui-tabs-anchor" ) + .removeAttr( "role" ) + .removeAttr( "tabIndex" ) + .removeData( "href.tabs" ) + .removeData( "load.tabs" ) + .removeUniqueId(); + + this.tabs.add( this.panels ).each(function() { + if ( $.data( this, "ui-tabs-destroy" ) ) { + $( this ).remove(); + } else { + $( this ) + .removeClass( "ui-state-default ui-state-active ui-state-disabled " + + "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" ) + .removeAttr( "tabIndex" ) + .removeAttr( "aria-live" ) + .removeAttr( "aria-busy" ) + .removeAttr( "aria-selected" ) + .removeAttr( "aria-labelledby" ) + .removeAttr( "aria-hidden" ) + .removeAttr( "aria-expanded" ) + .removeAttr( "role" ); + } + }); + + this.tabs.each(function() { + var li = $( this ), + prev = li.data( "ui-tabs-aria-controls" ); + if ( prev ) { + li.attr( "aria-controls", prev ); + } else { + li.removeAttr( "aria-controls" ); + } + }); + + this.panels.show(); + + if ( this.options.heightStyle !== "content" ) { + this.panels.css( "height", "" ); + } + }, + + enable: function( index ) { + var disabled = this.options.disabled; + if ( disabled === false ) { + return; + } + + if ( index === undefined ) { + disabled = false; + } else { + index = this._getIndex( index ); + if ( $.isArray( disabled ) ) { + disabled = $.map( disabled, function( num ) { + return num !== index ? num : null; + }); + } else { + disabled = $.map( this.tabs, function( li, num ) { + return num !== index ? num : null; + }); + } + } + this._setupDisabled( disabled ); + }, + + disable: function( index ) { + var disabled = this.options.disabled; + if ( disabled === true ) { + return; + } + + if ( index === undefined ) { + disabled = true; + } else { + index = this._getIndex( index ); + if ( $.inArray( index, disabled ) !== -1 ) { + return; + } + if ( $.isArray( disabled ) ) { + disabled = $.merge( [ index ], disabled ).sort(); + } else { + disabled = [ index ]; + } + } + this._setupDisabled( disabled ); + }, + + load: function( index, event ) { + index = this._getIndex( index ); + var that = this, + tab = this.tabs.eq( index ), + anchor = tab.find( ".ui-tabs-anchor" ), + panel = this._getPanelForTab( tab ), + eventData = { + tab: tab, + panel: panel + }; + + // not remote + if ( isLocal( anchor[ 0 ] ) ) { + return; + } + + this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) ); + + // support: jQuery <1.8 + // jQuery <1.8 returns false if the request is canceled in beforeSend, + // but as of 1.8, $.ajax() always returns a jqXHR object. + if ( this.xhr && this.xhr.statusText !== "canceled" ) { + tab.addClass( "ui-tabs-loading" ); + panel.attr( "aria-busy", "true" ); + + this.xhr + .success(function( response ) { + // support: jQuery <1.8 + // http://bugs.jquery.com/ticket/11778 + setTimeout(function() { + panel.html( response ); + that._trigger( "load", event, eventData ); + }, 1 ); + }) + .complete(function( jqXHR, status ) { + // support: jQuery <1.8 + // http://bugs.jquery.com/ticket/11778 + setTimeout(function() { + if ( status === "abort" ) { + that.panels.stop( false, true ); + } + + tab.removeClass( "ui-tabs-loading" ); + panel.removeAttr( "aria-busy" ); + + if ( jqXHR === that.xhr ) { + delete that.xhr; + } + }, 1 ); + }); + } + }, + + // TODO: Remove this function in 1.10 when ajaxOptions is removed + _ajaxSettings: function( anchor, event, eventData ) { + var that = this; + return { + url: anchor.attr( "href" ), + beforeSend: function( jqXHR, settings ) { + return that._trigger( "beforeLoad", event, + $.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) ); + } + }; + }, + + _getPanelForTab: function( tab ) { + var id = $( tab ).attr( "aria-controls" ); + return this.element.find( this._sanitizeSelector( "#" + id ) ); + } +}); + +// DEPRECATED +if ( $.uiBackCompat !== false ) { + + // helper method for a lot of the back compat extensions + $.ui.tabs.prototype._ui = function( tab, panel ) { + return { + tab: tab, + panel: panel, + index: this.anchors.index( tab ) + }; + }; + + // url method + $.widget( "ui.tabs", $.ui.tabs, { + url: function( index, url ) { + this.anchors.eq( index ).attr( "href", url ); + } + }); + + // TODO: Remove _ajaxSettings() method when removing this extension + // ajaxOptions and cache options + $.widget( "ui.tabs", $.ui.tabs, { + options: { + ajaxOptions: null, + cache: false + }, + + _create: function() { + this._super(); + + var that = this; + + this._on({ tabsbeforeload: function( event, ui ) { + // tab is already cached + if ( $.data( ui.tab[ 0 ], "cache.tabs" ) ) { + event.preventDefault(); + return; + } + + ui.jqXHR.success(function() { + if ( that.options.cache ) { + $.data( ui.tab[ 0 ], "cache.tabs", true ); + } + }); + }}); + }, + + _ajaxSettings: function( anchor, event, ui ) { + var ajaxOptions = this.options.ajaxOptions; + return $.extend( {}, ajaxOptions, { + error: function( xhr, status ) { + try { + // Passing index avoid a race condition when this method is + // called after the user has selected another tab. + // Pass the anchor that initiated this request allows + // loadError to manipulate the tab content panel via $(a.hash) + ajaxOptions.error( + xhr, status, ui.tab.closest( "li" ).index(), ui.tab[ 0 ] ); + } + catch ( error ) {} + } + }, this._superApply( arguments ) ); + }, + + _setOption: function( key, value ) { + // reset cache if switching from cached to not cached + if ( key === "cache" && value === false ) { + this.anchors.removeData( "cache.tabs" ); + } + this._super( key, value ); + }, + + _destroy: function() { + this.anchors.removeData( "cache.tabs" ); + this._super(); + }, + + url: function( index ){ + this.anchors.eq( index ).removeData( "cache.tabs" ); + this._superApply( arguments ); + } + }); + + // abort method + $.widget( "ui.tabs", $.ui.tabs, { + abort: function() { + if ( this.xhr ) { + this.xhr.abort(); + } + } + }); + + // spinner + $.widget( "ui.tabs", $.ui.tabs, { + options: { + spinner: "Loading…" + }, + _create: function() { + this._super(); + this._on({ + tabsbeforeload: function( event, ui ) { + // Don't react to nested tabs or tabs that don't use a spinner + if ( event.target !== this.element[ 0 ] || + !this.options.spinner ) { + return; + } + + var span = ui.tab.find( "span" ), + html = span.html(); + span.html( this.options.spinner ); + ui.jqXHR.complete(function() { + span.html( html ); + }); + } + }); + } + }); + + // enable/disable events + $.widget( "ui.tabs", $.ui.tabs, { + options: { + enable: null, + disable: null + }, + + enable: function( index ) { + var options = this.options, + trigger; + + if ( index && options.disabled === true || + ( $.isArray( options.disabled ) && $.inArray( index, options.disabled ) !== -1 ) ) { + trigger = true; + } + + this._superApply( arguments ); + + if ( trigger ) { + this._trigger( "enable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); + } + }, + + disable: function( index ) { + var options = this.options, + trigger; + + if ( index && options.disabled === false || + ( $.isArray( options.disabled ) && $.inArray( index, options.disabled ) === -1 ) ) { + trigger = true; + } + + this._superApply( arguments ); + + if ( trigger ) { + this._trigger( "disable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); + } + } + }); + + // add/remove methods and events + $.widget( "ui.tabs", $.ui.tabs, { + options: { + add: null, + remove: null, + tabTemplate: "
  • #{label}
  • " + }, + + add: function( url, label, index ) { + if ( index === undefined ) { + index = this.anchors.length; + } + + var doInsertAfter, panel, + options = this.options, + li = $( options.tabTemplate + .replace( /#\{href\}/g, url ) + .replace( /#\{label\}/g, label ) ), + id = !url.indexOf( "#" ) ? + url.replace( "#", "" ) : + this._tabId( li ); + + li.addClass( "ui-state-default ui-corner-top" ).data( "ui-tabs-destroy", true ); + li.attr( "aria-controls", id ); + + doInsertAfter = index >= this.tabs.length; + + // try to find an existing element before creating a new one + panel = this.element.find( "#" + id ); + if ( !panel.length ) { + panel = this._createPanel( id ); + if ( doInsertAfter ) { + if ( index > 0 ) { + panel.insertAfter( this.panels.eq( -1 ) ); + } else { + panel.appendTo( this.element ); + } + } else { + panel.insertBefore( this.panels[ index ] ); + } + } + panel.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ).hide(); + + if ( doInsertAfter ) { + li.appendTo( this.tablist ); + } else { + li.insertBefore( this.tabs[ index ] ); + } + + options.disabled = $.map( options.disabled, function( n ) { + return n >= index ? ++n : n; + }); + + this.refresh(); + if ( this.tabs.length === 1 && options.active === false ) { + this.option( "active", 0 ); + } + + this._trigger( "add", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); + return this; + }, + + remove: function( index ) { + index = this._getIndex( index ); + var options = this.options, + tab = this.tabs.eq( index ).remove(), + panel = this._getPanelForTab( tab ).remove(); + + // If selected tab was removed focus tab to the right or + // in case the last tab was removed the tab to the left. + // We check for more than 2 tabs, because if there are only 2, + // then when we remove this tab, there will only be one tab left + // so we don't need to detect which tab to activate. + if ( tab.hasClass( "ui-tabs-active" ) && this.anchors.length > 2 ) { + this._activate( index + ( index + 1 < this.anchors.length ? 1 : -1 ) ); + } + + options.disabled = $.map( + $.grep( options.disabled, function( n ) { + return n !== index; + }), + function( n ) { + return n >= index ? --n : n; + }); + + this.refresh(); + + this._trigger( "remove", null, this._ui( tab.find( "a" )[ 0 ], panel[ 0 ] ) ); + return this; + } + }); + + // length method + $.widget( "ui.tabs", $.ui.tabs, { + length: function() { + return this.anchors.length; + } + }); + + // panel ids (idPrefix option + title attribute) + $.widget( "ui.tabs", $.ui.tabs, { + options: { + idPrefix: "ui-tabs-" + }, + + _tabId: function( tab ) { + var a = tab.is( "li" ) ? tab.find( "a[href]" ) : tab; + a = a[0]; + return $( a ).closest( "li" ).attr( "aria-controls" ) || + a.title && a.title.replace( /\s/g, "_" ).replace( /[^\w\u00c0-\uFFFF\-]/g, "" ) || + this.options.idPrefix + getNextTabId(); + } + }); + + // _createPanel method + $.widget( "ui.tabs", $.ui.tabs, { + options: { + panelTemplate: "
    " + }, + + _createPanel: function( id ) { + return $( this.options.panelTemplate ) + .attr( "id", id ) + .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) + .data( "ui-tabs-destroy", true ); + } + }); + + // selected option + $.widget( "ui.tabs", $.ui.tabs, { + _create: function() { + var options = this.options; + if ( options.active === null && options.selected !== undefined ) { + options.active = options.selected === -1 ? false : options.selected; + } + this._super(); + options.selected = options.active; + if ( options.selected === false ) { + options.selected = -1; + } + }, + + _setOption: function( key, value ) { + if ( key !== "selected" ) { + return this._super( key, value ); + } + + var options = this.options; + this._super( "active", value === -1 ? false : value ); + options.selected = options.active; + if ( options.selected === false ) { + options.selected = -1; + } + }, + + _eventHandler: function() { + this._superApply( arguments ); + this.options.selected = this.options.active; + if ( this.options.selected === false ) { + this.options.selected = -1; + } + } + }); + + // show and select event + $.widget( "ui.tabs", $.ui.tabs, { + options: { + show: null, + select: null + }, + _create: function() { + this._super(); + if ( this.options.active !== false ) { + this._trigger( "show", null, this._ui( + this.active.find( ".ui-tabs-anchor" )[ 0 ], + this._getPanelForTab( this.active )[ 0 ] ) ); + } + }, + _trigger: function( type, event, data ) { + var tab, panel, + ret = this._superApply( arguments ); + + if ( !ret ) { + return false; + } + + if ( type === "beforeActivate" ) { + tab = data.newTab.length ? data.newTab : data.oldTab; + panel = data.newPanel.length ? data.newPanel : data.oldPanel; + ret = this._super( "select", event, { + tab: tab.find( ".ui-tabs-anchor" )[ 0], + panel: panel[ 0 ], + index: tab.closest( "li" ).index() + }); + } else if ( type === "activate" && data.newTab.length ) { + ret = this._super( "show", event, { + tab: data.newTab.find( ".ui-tabs-anchor" )[ 0 ], + panel: data.newPanel[ 0 ], + index: data.newTab.closest( "li" ).index() + }); + } + return ret; + } + }); + + // select method + $.widget( "ui.tabs", $.ui.tabs, { + select: function( index ) { + index = this._getIndex( index ); + if ( index === -1 ) { + if ( this.options.collapsible && this.options.selected !== -1 ) { + index = this.options.selected; + } else { + return; + } + } + this.anchors.eq( index ).trigger( this.options.event + this.eventNamespace ); + } + }); + + // cookie option + (function() { + + var listId = 0; + + $.widget( "ui.tabs", $.ui.tabs, { + options: { + cookie: null // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true } + }, + _create: function() { + var options = this.options, + active; + if ( options.active == null && options.cookie ) { + active = parseInt( this._cookie(), 10 ); + if ( active === -1 ) { + active = false; + } + options.active = active; + } + this._super(); + }, + _cookie: function( active ) { + var cookie = [ this.cookie || + ( this.cookie = this.options.cookie.name || "ui-tabs-" + (++listId) ) ]; + if ( arguments.length ) { + cookie.push( active === false ? -1 : active ); + cookie.push( this.options.cookie ); + } + return $.cookie.apply( null, cookie ); + }, + _refresh: function() { + this._super(); + if ( this.options.cookie ) { + this._cookie( this.options.active, this.options.cookie ); + } + }, + _eventHandler: function() { + this._superApply( arguments ); + if ( this.options.cookie ) { + this._cookie( this.options.active, this.options.cookie ); + } + }, + _destroy: function() { + this._super(); + if ( this.options.cookie ) { + this._cookie( null, this.options.cookie ); + } + } + }); + + })(); + + // load event + $.widget( "ui.tabs", $.ui.tabs, { + _trigger: function( type, event, data ) { + var _data = $.extend( {}, data ); + if ( type === "load" ) { + _data.panel = _data.panel[ 0 ]; + _data.tab = _data.tab.find( ".ui-tabs-anchor" )[ 0 ]; + } + return this._super( type, event, _data ); + } + }); + + // fx option + // The new animation options (show, hide) conflict with the old show callback. + // The old fx option wins over show/hide anyway (always favor back-compat). + // If a user wants to use the new animation API, they must give up the old API. + $.widget( "ui.tabs", $.ui.tabs, { + options: { + fx: null // e.g. { height: "toggle", opacity: "toggle", duration: 200 } + }, + + _getFx: function() { + var hide, show, + fx = this.options.fx; + + if ( fx ) { + if ( $.isArray( fx ) ) { + hide = fx[ 0 ]; + show = fx[ 1 ]; + } else { + hide = show = fx; + } + } + + return fx ? { show: show, hide: hide } : null; + }, + + _toggle: function( event, eventData ) { + var that = this, + toShow = eventData.newPanel, + toHide = eventData.oldPanel, + fx = this._getFx(); + + if ( !fx ) { + return this._super( event, eventData ); + } + + that.running = true; + + function complete() { + that.running = false; + that._trigger( "activate", event, eventData ); + } + + function show() { + eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); + + if ( toShow.length && fx.show ) { + toShow + .animate( fx.show, fx.show.duration, function() { + complete(); + }); + } else { + toShow.show(); + complete(); + } + } + + // start out by hiding, then showing, then completing + if ( toHide.length && fx.hide ) { + toHide.animate( fx.hide, fx.hide.duration, function() { + eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); + show(); + }); + } else { + eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); + toHide.hide(); + show(); + } + } + }); +} + +})( jQuery ); + +(function( $ ) { + +var increments = 0; + +function addDescribedBy( elem, id ) { + var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ); + describedby.push( id ); + elem + .data( "ui-tooltip-id", id ) + .attr( "aria-describedby", $.trim( describedby.join( " " ) ) ); +} + +function removeDescribedBy( elem ) { + var id = elem.data( "ui-tooltip-id" ), + describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ), + index = $.inArray( id, describedby ); + if ( index !== -1 ) { + describedby.splice( index, 1 ); + } + + elem.removeData( "ui-tooltip-id" ); + describedby = $.trim( describedby.join( " " ) ); + if ( describedby ) { + elem.attr( "aria-describedby", describedby ); + } else { + elem.removeAttr( "aria-describedby" ); + } +} + +$.widget( "ui.tooltip", { + version: "1.9.2", + options: { + content: function() { + return $( this ).attr( "title" ); + }, + hide: true, + // Disabled elements have inconsistent behavior across browsers (#8661) + items: "[title]:not([disabled])", + position: { + my: "left top+15", + at: "left bottom", + collision: "flipfit flip" + }, + show: true, + tooltipClass: null, + track: false, + + // callbacks + close: null, + open: null + }, + + _create: function() { + this._on({ + mouseover: "open", + focusin: "open" + }); + + // IDs of generated tooltips, needed for destroy + this.tooltips = {}; + // IDs of parent tooltips where we removed the title attribute + this.parents = {}; + + if ( this.options.disabled ) { + this._disable(); + } + }, + + _setOption: function( key, value ) { + var that = this; + + if ( key === "disabled" ) { + this[ value ? "_disable" : "_enable" ](); + this.options[ key ] = value; + // disable element style changes + return; + } + + this._super( key, value ); + + if ( key === "content" ) { + $.each( this.tooltips, function( id, element ) { + that._updateContent( element ); + }); + } + }, + + _disable: function() { + var that = this; + + // close open tooltips + $.each( this.tooltips, function( id, element ) { + var event = $.Event( "blur" ); + event.target = event.currentTarget = element[0]; + that.close( event, true ); + }); + + // remove title attributes to prevent native tooltips + this.element.find( this.options.items ).andSelf().each(function() { + var element = $( this ); + if ( element.is( "[title]" ) ) { + element + .data( "ui-tooltip-title", element.attr( "title" ) ) + .attr( "title", "" ); + } + }); + }, + + _enable: function() { + // restore title attributes + this.element.find( this.options.items ).andSelf().each(function() { + var element = $( this ); + if ( element.data( "ui-tooltip-title" ) ) { + element.attr( "title", element.data( "ui-tooltip-title" ) ); + } + }); + }, + + open: function( event ) { + var that = this, + target = $( event ? event.target : this.element ) + // we need closest here due to mouseover bubbling, + // but always pointing at the same event target + .closest( this.options.items ); + + // No element to show a tooltip for or the tooltip is already open + if ( !target.length || target.data( "ui-tooltip-id" ) ) { + return; + } + + if ( target.attr( "title" ) ) { + target.data( "ui-tooltip-title", target.attr( "title" ) ); + } + + target.data( "ui-tooltip-open", true ); + + // kill parent tooltips, custom or native, for hover + if ( event && event.type === "mouseover" ) { + target.parents().each(function() { + var parent = $( this ), + blurEvent; + if ( parent.data( "ui-tooltip-open" ) ) { + blurEvent = $.Event( "blur" ); + blurEvent.target = blurEvent.currentTarget = this; + that.close( blurEvent, true ); + } + if ( parent.attr( "title" ) ) { + parent.uniqueId(); + that.parents[ this.id ] = { + element: this, + title: parent.attr( "title" ) + }; + parent.attr( "title", "" ); + } + }); + } + + this._updateContent( target, event ); + }, + + _updateContent: function( target, event ) { + var content, + contentOption = this.options.content, + that = this, + eventType = event ? event.type : null; + + if ( typeof contentOption === "string" ) { + return this._open( event, target, contentOption ); + } + + content = contentOption.call( target[0], function( response ) { + // ignore async response if tooltip was closed already + if ( !target.data( "ui-tooltip-open" ) ) { + return; + } + // IE may instantly serve a cached response for ajax requests + // delay this call to _open so the other call to _open runs first + that._delay(function() { + // jQuery creates a special event for focusin when it doesn't + // exist natively. To improve performance, the native event + // object is reused and the type is changed. Therefore, we can't + // rely on the type being correct after the event finished + // bubbling, so we set it back to the previous value. (#8740) + if ( event ) { + event.type = eventType; + } + this._open( event, target, response ); + }); + }); + if ( content ) { + this._open( event, target, content ); + } + }, + + _open: function( event, target, content ) { + var tooltip, events, delayedShow, + positionOption = $.extend( {}, this.options.position ); + + if ( !content ) { + return; + } + + // Content can be updated multiple times. If the tooltip already + // exists, then just update the content and bail. + tooltip = this._find( target ); + if ( tooltip.length ) { + tooltip.find( ".ui-tooltip-content" ).html( content ); + return; + } + + // if we have a title, clear it to prevent the native tooltip + // we have to check first to avoid defining a title if none exists + // (we don't want to cause an element to start matching [title]) + // + // We use removeAttr only for key events, to allow IE to export the correct + // accessible attributes. For mouse events, set to empty string to avoid + // native tooltip showing up (happens only when removing inside mouseover). + if ( target.is( "[title]" ) ) { + if ( event && event.type === "mouseover" ) { + target.attr( "title", "" ); + } else { + target.removeAttr( "title" ); + } + } + + tooltip = this._tooltip( target ); + addDescribedBy( target, tooltip.attr( "id" ) ); + tooltip.find( ".ui-tooltip-content" ).html( content ); + + function position( event ) { + positionOption.of = event; + if ( tooltip.is( ":hidden" ) ) { + return; + } + tooltip.position( positionOption ); + } + if ( this.options.track && event && /^mouse/.test( event.type ) ) { + this._on( this.document, { + mousemove: position + }); + // trigger once to override element-relative positioning + position( event ); + } else { + tooltip.position( $.extend({ + of: target + }, this.options.position ) ); + } + + tooltip.hide(); + + this._show( tooltip, this.options.show ); + // Handle tracking tooltips that are shown with a delay (#8644). As soon + // as the tooltip is visible, position the tooltip using the most recent + // event. + if ( this.options.show && this.options.show.delay ) { + delayedShow = setInterval(function() { + if ( tooltip.is( ":visible" ) ) { + position( positionOption.of ); + clearInterval( delayedShow ); + } + }, $.fx.interval ); + } + + this._trigger( "open", event, { tooltip: tooltip } ); + + events = { + keyup: function( event ) { + if ( event.keyCode === $.ui.keyCode.ESCAPE ) { + var fakeEvent = $.Event(event); + fakeEvent.currentTarget = target[0]; + this.close( fakeEvent, true ); + } + }, + remove: function() { + this._removeTooltip( tooltip ); + } + }; + if ( !event || event.type === "mouseover" ) { + events.mouseleave = "close"; + } + if ( !event || event.type === "focusin" ) { + events.focusout = "close"; + } + this._on( true, target, events ); + }, + + close: function( event ) { + var that = this, + target = $( event ? event.currentTarget : this.element ), + tooltip = this._find( target ); + + // disabling closes the tooltip, so we need to track when we're closing + // to avoid an infinite loop in case the tooltip becomes disabled on close + if ( this.closing ) { + return; + } + + // only set title if we had one before (see comment in _open()) + if ( target.data( "ui-tooltip-title" ) ) { + target.attr( "title", target.data( "ui-tooltip-title" ) ); + } + + removeDescribedBy( target ); + + tooltip.stop( true ); + this._hide( tooltip, this.options.hide, function() { + that._removeTooltip( $( this ) ); + }); + + target.removeData( "ui-tooltip-open" ); + this._off( target, "mouseleave focusout keyup" ); + // Remove 'remove' binding only on delegated targets + if ( target[0] !== this.element[0] ) { + this._off( target, "remove" ); + } + this._off( this.document, "mousemove" ); + + if ( event && event.type === "mouseleave" ) { + $.each( this.parents, function( id, parent ) { + $( parent.element ).attr( "title", parent.title ); + delete that.parents[ id ]; + }); + } + + this.closing = true; + this._trigger( "close", event, { tooltip: tooltip } ); + this.closing = false; + }, + + _tooltip: function( element ) { + var id = "ui-tooltip-" + increments++, + tooltip = $( "
    " ) + .attr({ + id: id, + role: "tooltip" + }) + .addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " + + ( this.options.tooltipClass || "" ) ); + $( "
    " ) + .addClass( "ui-tooltip-content" ) + .appendTo( tooltip ); + tooltip.appendTo( this.document[0].body ); + if ( $.fn.bgiframe ) { + tooltip.bgiframe(); + } + this.tooltips[ id ] = element; + return tooltip; + }, + + _find: function( target ) { + var id = target.data( "ui-tooltip-id" ); + return id ? $( "#" + id ) : $(); + }, + + _removeTooltip: function( tooltip ) { + tooltip.remove(); + delete this.tooltips[ tooltip.attr( "id" ) ]; + }, + + _destroy: function() { + var that = this; + + // close open tooltips + $.each( this.tooltips, function( id, element ) { + // Delegate to close method to handle common cleanup + var event = $.Event( "blur" ); + event.target = event.currentTarget = element[0]; + that.close( event, true ); + + // Remove immediately; destroying an open tooltip doesn't use the + // hide animation + $( "#" + id ).remove(); + + // Restore the title + if ( element.data( "ui-tooltip-title" ) ) { + element.attr( "title", element.data( "ui-tooltip-title" ) ); + element.removeData( "ui-tooltip-title" ); + } + }); + } +}); + +}( jQuery ) ); diff --git a/t/embedded_files/result-light.css b/t/embedded_files/result-light.css new file mode 100644 index 0000000000..e69de29bb2 diff --git a/t/embedded_files/saved_resource.html b/t/embedded_files/saved_resource.html new file mode 100644 index 0000000000..2c6c5158d0 --- /dev/null +++ b/t/embedded_files/saved_resource.html @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + enter matrix2 by mgage + + + + + + + + + + + + + + + +
    + + +
    + + [p1p2x3x4x5x6Pb + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +] + +
    + + + + + + + +
    \ No newline at end of file diff --git a/t/linebreak_at_commas_example.pg b/t/linebreak_at_commas_example.pg new file mode 100644 index 0000000000..6b2ab9d0ae --- /dev/null +++ b/t/linebreak_at_commas_example.pg @@ -0,0 +1,169 @@ +##DESCRIPTION +## Linear programming problem +##ENDDESCRIPTION + + +## DBsubject(Operations research) +## DBchapter(Linear programming) +## DBsection(Simplex method) +## Date(9/11/2013) +## Institution(U. of Rochester) +## Author(M. Gage) +## Level(1) +## KEYWORDS('algebra', 'inequality', 'fraction') + +######################################################################## + +DOCUMENT(); + +loadMacros( + "PGstandard.pl", # Standard macros for PG language + "MathObjects.pl", + "parserLinearInequality.pl", + "parserPopUp.pl", + "scaffold.pl", + "tableau.pl", + #"source.pl", # allows code to be displayed on certain sites. + "PGcourse.pl", # Customization file for the course +); + +# Print problem number and point value (weight) for the problem + +loadMacros( "PGML.pl",); # need to load after changing columns. + +TEXT(beginproblem()); + + +# Show which answers are correct and which ones are incorrect +$showPartialCorrectAnswers = 1; +Context("LinearInequality"); +Context()->variables->add( m2ny=>'Real', m2cal=>'Real',k2ny=>'Real',k2cal=>'Real'); +############################################################## +# +# Setup +# +# +#data + + +#data duckwheat problem +$kansas = 15; # schnupells produced +$mexico = 8; # schnupells produced +$newyork = 10; # schnupells consumed +$california = 13; +$mexico2newyork = 4; # transportation cost per shnupell +$mexico2california = 1; # transportation cost per shnupell +$kansas2newyork = 2; # transportation cost per shnupell +$kansas2california = 3; # transportation cost per shnupell + +# objective function +$popup = PopUp([qw(? Maximize Minimize)], 'Minimize'); +$objfunction = Compute("$mexico2newyork*m2ny + +$mexico2california*m2cal + $kansas2newyork*k2ny + +$kansas2california*k2cal ")->reduce; +$objfunction->{limits}=[[0,1],[2,5],[8,10],[11,12]]; +$objfunction->{checkUndefinedPoints}=1; +$objfunction2 = Formula("5*m2cal")->reduce; +$objfunction2->{checkUndefinedPoints}=1; +#constraints +$constraint0 = Compute(" k2ny + k2cal +<=$kansas"); +$constraint1 = Compute(" m2ny + m2cal +<=$mexico"); +$constraint2 = Compute(" m2ny + k2ny +>=$newyork"); +$constraint3 = Compute(" m2cal + k2cal +>=$california"); + +$constraints = List($constraint0, $constraint1,$constraint2, $constraint3); + + +#variable order: (m2ny, m2cal, k2ny, k2cal) +#matrix for normal form +$constraint_matrix = Matrix("[[ 0, 0, -1, -1], + [-1, -1, 0, 0 ], + [1, 0 , 1 , 0], + [0, 1, 0, 1]] +"); +$m = Matrix([['3',6,7],[2,1,8],[4,6,21],[-6,7,9]]); + +$rhs = Vector($kansas, $mexico, $newyork, $california); +############################################################## +# +# Text +# +# + +####################### +# scaffold + +# use linebreak_at_commas from tableau +# sub linebreak_at_commas { +# return sub { +# my $ans=shift; +# my $foo = $ans->{correct_ans_latex_string}; +# $foo =~ s/,/,~~~~~~~~/g; +# ($ans->{correct_ans_latex_string})=~ s/,/,~~~~~~~~/g; +# ($ans->{preview_latex_string})=~ s/,/,~~~~~~~~/g; +# #DEBUG_MESSAGE("foo", $foo); +# #DEBUG_MESSAGE( "correct", $ans->{correct_ans_latex_string} ); +# #DEBUG_MESSAGE( "preview", $ans->{preview_latex_string} ); +# #DEBUG_MESSAGE("section4ans1 ", pretty_print($ans, $displayMode)); +# $ans; +# }; +# } + +$foochecker = $constraints->cmp()->withPostFilter( +linebreak_at_commas() +); +BEGIN_PGML +Another word problem. Write out the equations for the LOP and the dual LOP. + +Duckwheat is produced in Kansas and Mexico and consumed in New York +and California. +Kansas produces [$kansas] shnupells of duckwheat and [$mexico]. +Meanwhile, New York consumes +[$newyork] shnupells and California [$california]. +The transportation costs per shnupell are [$mexico2newyork] +from Mexico to New York, [$mexico2california] from Mexico to California, +[$kansas2newyork] from Kansas to New York, and +[$kansas2california] and from Kansas to California. + +Write a linear program that decides the amounts of duckwheat +(in shnupells and fractions +of a shnupell) to be transported from each producer to each +consumer, so as to minimize +the overall transportation cost. + (In other words express this problem in a mathematical normal form.) + +* Write the objective function for the problem in terms of the +variables [`m2ny, m2cal, k2ny,k2cal`] which are +the volumes in shnupells for shipped from Mexico to New York, +Mexico to California, Kansas to New York and +Kansas to California in order to obtain the optimum +transportation cost. + +[@ ANS($popup->cmp), $popup->menu @]* +[`transportation cost = `] [@ ANS($objfunction->cmp()), ans_box(2,60) @]* + +* Now write the constraints for the mathematical linear +optimization problem (LOP) in standard form. +Separate each +of the constraint equations by a comma. The order of the constraint equations does not matter. + +[@ ANS($constraints->cmp()->withPostFilter( +linebreak_at_commas() ) +), ans_box(8, 80) @]* + +The variables must be non-negative: [`m2ny, m2cal, k2ny,k2cal\ge 0`] +but you don't need to include these conditions. + + + +END_PGML + + +# Comments used: ($ans->{correct_ans_latex_string})=~ s/,/,\\\\/g; inside PGML +# Used ($ans->{correct_ans_latex_string})=~ s/,/,~~~~~~~~/g; outside PGML + +ENDDOCUMENT(); \ No newline at end of file diff --git a/t/matrix_tableau_tests/linebreaks.pg b/t/matrix_tableau_tests/linebreaks.pg new file mode 100644 index 0000000000..d336c714a2 --- /dev/null +++ b/t/matrix_tableau_tests/linebreaks.pg @@ -0,0 +1,168 @@ +##DESCRIPTION +## Linear programming problem +##ENDDESCRIPTION + + +## DBsubject(Operations research) +## DBchapter(Linear programming) +## DBsection(Simplex method) +## Date(9/11/2013) +## Institution(U. of Rochester) +## Author(M. Gage) +## Level(1) +## KEYWORDS('algebra', 'inequality', 'fraction') + +######################################################################## + +DOCUMENT(); + +loadMacros( + "PGstandard.pl", # Standard macros for PG language + "MathObjects.pl", + "parserLinearInequality.pl", + "parserPopUp.pl", + "scaffold.pl", + "tableau.pl", + #"source.pl", # allows code to be displayed on certain sites. + "PGcourse.pl", # Customization file for the course +); + +# Print problem number and point value (weight) for the problem + +loadMacros( "PGML.pl",); # need to load after changing columns. + +TEXT(beginproblem()); + + +# Show which answers are correct and which ones are incorrect +$showPartialCorrectAnswers = 1; +Context("LinearInequality"); +Context()->variables->add( m2ny=>'Real', m2cal=>'Real',k2ny=>'Real',k2cal=>'Real'); +############################################################## +# +# Setup +# +# +#data + + +#data duckwheat problem +$kansas = 15; # schnupells produced +$mexico = 8; # schnupells produced +$newyork = 10; # schnupells consumed +$california = 13; +$mexico2newyork = 4; # transportation cost per shnupell +$mexico2california = 1; # transportation cost per shnupell +$kansas2newyork = 2; # transportation cost per shnupell +$kansas2california = 3; # transportation cost per shnupell + +# objective function +$popup = PopUp([qw(? Maximize Minimize)], 'Minimize'); +$objfunction = Compute("$mexico2newyork*m2ny + +$mexico2california*m2cal + $kansas2newyork*k2ny + +$kansas2california*k2cal ")->reduce; +$objfunction->{limits}=[[0,1],[2,5],[8,10],[11,12]]; +$objfunction->{checkUndefinedPoints}=1; +$objfunction2 = Formula("5*m2cal")->reduce; +$objfunction2->{checkUndefinedPoints}=1; +#constraints +$constraint0 = Compute(" k2ny + k2cal +<=$kansas"); +$constraint1 = Compute(" m2ny + m2cal +<=$mexico"); +$constraint2 = Compute(" m2ny + k2ny +>=$newyork"); +$constraint3 = Compute(" m2cal + k2cal +>=$california"); + +$constraints = List($constraint0, $constraint1,$constraint2, $constraint3); + + +#variable order: (m2ny, m2cal, k2ny, k2cal) +#matrix for normal form +$constraint_matrix = Matrix("[[ 0, 0, -1, -1], + [-1, -1, 0, 0 ], + [1, 0 , 1 , 0], + [0, 1, 0, 1]] +"); +$m = Matrix([['3',6,7],[2,1,8],[4,6,21],[-6,7,9]]); + +$rhs = Vector($kansas, $mexico, $newyork, $california); +############################################################## +# +# Text +# +# + +####################### +# scaffold + +#sub linebreak_at_commas { +# return sub { +# my $ans=shift; +# my $foo = $ans->{correct_ans_latex_string}; +# $foo =~ s/,/,~~~~~~~~/g; +# ($ans->{correct_ans_latex_string})=~ s/,/,~~~~~~~~/g; +# ($ans->{preview_latex_string})=~ s/,/,~~~~~~~~/g; +# #DEBUG_MESSAGE("foo", $foo); +# #DEBUG_MESSAGE( "correct", $ans->{correct_ans_latex_string} ); +# #DEBUG_MESSAGE( "preview", $ans->{preview_latex_string} ); +# #DEBUG_MESSAGE("section4ans1 ", pretty_print($ans, $displayMode)); +# $ans; +# }; +#} + +$foochecker = $constraints->cmp()->withPostFilter( +linebreak_at_commas() +); +BEGIN_PGML +Another word problem. Write out the equations for the LOP and the dual LOP. + +Duckwheat is produced in Kansas and Mexico and consumed in New York +and California. +Kansas produces [$kansas] shnupells of duckwheat and [$mexico]. +Meanwhile, New York consumes +[$newyork] shnupells and California [$california]. +The transportation costs per shnupell are [$mexico2newyork] +from Mexico to New York, [$mexico2california] from Mexico to California, +[$kansas2newyork] from Kansas to New York, and +[$kansas2california] and from Kansas to California. + +Write a linear program that decides the amounts of duckwheat +(in shnupells and fractions +of a shnupell) to be transported from each producer to each +consumer, so as to minimize +the overall transportation cost. + (In other words express this problem in a mathematical normal form.) + +* Write the objective function for the problem in terms of the +variables [`m2ny, m2cal, k2ny,k2cal`] which are +the volumes in shnupells for shipped from Mexico to New York, +Mexico to California, Kansas to New York and +Kansas to California in order to obtain the optimum +transportation cost. + +[@ ANS($popup->cmp), $popup->menu @]* +[`transportation cost = `] [@ ANS($objfunction->cmp()), ans_box(2,60) @]* + +* Now write the constraints for the mathematical linear +optimization problem (LOP) in standard form. +Separate each +of the constraint equations by a comma. The order of the constraint equations does not matter. + +[@ ANS($constraints->cmp()->withPostFilter( +linebreak_at_commas() ) +), ans_box(8, 80) @]* + +The variables must be non-negative: [`m2ny, m2cal, k2ny,k2cal\ge 0`] +but you don't need to include these conditions. + + + +END_PGML + + +# Comments used: ($ans->{correct_ans_latex_string})=~ s/,/,\\\\/g; inside PGML +# Used ($ans->{correct_ans_latex_string})=~ s/,/,~~~~~~~~/g; outside PGML + +ENDDOCUMENT(); \ No newline at end of file diff --git a/t/matrix_tableau_tests/matrix_test1.pg b/t/matrix_tableau_tests/matrix_test1.pg new file mode 100644 index 0000000000..c9b2c5f3bc --- /dev/null +++ b/t/matrix_tableau_tests/matrix_test1.pg @@ -0,0 +1,111 @@ +############################################## +DOCUMENT(); + +loadMacros( + "PGstandard.pl", # Standard macros for PG language + "MathObjects.pl", + "parserLinearInequality.pl", + "PGML.pl", + "tableau.pl", + "PGmatrixmacros.pl", + "LinearProgramming.pl", + #"source.pl", # allows code to be displayed on certain sites. + "PGcourse.pl", +); + +############################################## + +Context("Matrix"); # need Matrix context to allow string input into Matrix. + +#Construct a small test matrix. +$m = Matrix("[[3,6,7],[2,1,8],[4,6,21],[-6,7,9]]"); + + + $m_rows = $m->extract_rows([4,1]); #outputs an array reference + $m_cols = $m->extract_columns([3,2,1]); #outputs the columns as rows + $m1list = List($m_rows); + $m2list = List($m_cols); + $list_cols = $m->extract_columns_to_list(1,2); + $list_rows = $m->extract_rows_to_list(2,3); + + $m1matrix = Matrix($m_rows); + $m2matrix = Matrix($m_cols)->transpose; #matrix is built with rows and then needs to be transposed + + + $m3 = $m->row_slice([4,1]); + $m4 = $m->column_slice([3,2,1]); + + $submatrix1 = $m->submatrix(rows=>[2,3],columns=>[1,2]); + $submatrix2 = $m->submatrix(rows=>[2,3]); + $submatrix3 = $m->submatrix(columns=>[1,2]); + $submatrix4 = $m->submatrix(); + + +BEGIN_PGML + +Create a matrix: matrix m = [`[$m]`] + +Matrix indices start at 1. + +Extracting rows and columns from a matrix. +These are best displayed in PGML within a list. +It is best to place them in the list outside of PGML and then display. + +You can also group the extracted rows into a matrix and display. + +Matrix m = [`[$m]`] + +List rows 4,1 of the matrix m :[` [@ List($m_rows) @] `], + +or create the list before hand [`[$m1list]`] + +or matrix version [`[$m1matrix]`] + +You can do the same for columns. Notice that this does not +do exactly what you expect when you extract columns + +matrix m = [`[$m]`] + +List columns 3,2,1 of the matrix m: [@ List($m_cols) @] + +create the list before hand [`[$m2list]`] + +or create matrix version [`[$m2matrix]`] + + +Using the \[@ ... @\] escape to apply List doesn't +always do the best job +of interacting with TeX output as you can see in the first entries for List above. + +The two entries below show what happens if you extract rows or +columns into lists using +the method $m->extract_rows_to_list(). +It is the same as applying List() to the method +$m->extract_rows outside of PGML. + +matrix: [`[$m]`] + +Find the list of columns 1,2 of the matrix [`[$list_cols]`] + +Find the list of rows 2,3 of the matrix [`[$list_rows]`] + +The next two entries illustrate the $m->row_slice, $m->column_slice methods for shuffling or +selecting rows or columns from a matrix. The return type is Value::Matrix. The column +selection is done by doing row selection on the transpose -- this does what you expect +when selecting columns. + +Row slice (4,1) [`[$m3]`] + +Column slice (3,2,1) [`[$m4]`] + +This final group selects a rectangular submatrix of a matrix. ->submatrix. + +Select \[2,3\]x\[1,2\] to get [`[$submatrix1]`] of [`[$m]`] + +Select \[2,3\]x all to get [`[$submatrix2]`] + +Select all x \[1,2\] to get [`[$submatrix3]`] + +END_PGML + +ENDDOCUMENT(); \ No newline at end of file diff --git a/t/matrix_tableau_tests/matrix_test2.pg b/t/matrix_tableau_tests/matrix_test2.pg new file mode 100644 index 0000000000..b4822b4f02 --- /dev/null +++ b/t/matrix_tableau_tests/matrix_test2.pg @@ -0,0 +1,70 @@ + + +############################################## +DOCUMENT(); + +loadMacros( + "PGstandard.pl", # Standard macros for PG language + "MathObjects.pl", + "parserLinearInequality.pl", + "PGML.pl", + "tableau.pl", + "PGmatrixmacros.pl", + "LinearProgramming.pl", + #"source.pl", # allows code to be displayed on certain sites. + "PGcourse.pl", +); + +############################################## + +Context("Matrix"); # need Matrix context to allow string input into Matrix. + +$m = Matrix("[[3,6,7],[2,1,8],[4,6,21],[-6,7,9]]"); + +$v = ColumnVector(1,1,1); + +$m2 = $m*$v; + +$v2 = Vector($m2); + +$m2flat = Matrix( Vector($m*$v) ); +$v2c = ColumnVector($m2); + +$w = Vector(1,1,1,1); +$m3 = $w*$m; + +TEXT("#################",$BR); +@test_rows = map {" ".ref($_)." "} @{$m->extract_rows} ; +TEXT("extracted rows ", scalar(@test_rows), " | ",@test_rows,"|",$BR ); +@test_columns = map {" ".ref($_)." "} @{$m->extract_columns} ; +TEXT("extracted columns ", scalar(@test_columns), "|",join("|", @test_columns),"|",$BR ); + +TEXT($BR,"#################",$BR); +$rows = List($m->extract_rows); +$columns = List( map {ColumnVector($_)} @{$m->extract_columns}); +$columns2 = List( map {$_->transpose} @{$m->extract_columns}); # both of these work + +BEGIN_PGML +matrix [`[$m]`] + +vector [`[$v]`] + +result [`[$m]`]*[`[$v]`] is [$m2] and tex version: [`[$m2]`] + +Convert the result to a vector [`[$v2]`] or to a column vector [`[$v2c]`] + +and then convert to a matrix again [$m2flat] [`[$m2flat]`] + +Multiplication on the left of [`[$w]`] * [`[$m]`] is [$m3], + +the first row of which is [$m3->row(1)] and the tex version:[`[$m3]`] + +Extract rows [@ List($m->extract_rows) @] with tex version [` [$rows] `] + +Extract columns [@ List($m->extract_columns) @] with tex version + +[`[$columns]`] or [`[$columns2]`] + +END_PGML + +ENDDOCUMENT(); \ No newline at end of file diff --git a/t/matrix_tableau_tests/print_tableau_Test.pg b/t/matrix_tableau_tests/print_tableau_Test.pg new file mode 100644 index 0000000000..0ab1abddfc --- /dev/null +++ b/t/matrix_tableau_tests/print_tableau_Test.pg @@ -0,0 +1,69 @@ + + + +############################################## +DOCUMENT(); + +loadMacros( + "PGstandard.pl", # Standard macros for PG language + "MathObjects.pl", + "parserLinearInequality.pl", + "PGML.pl", + "tableau.pl", + "PGmatrixmacros.pl", + "LinearProgramming.pl", + #"source.pl", # allows code to be displayed on certain sites. + "PGcourse.pl", +); + +############################################## + +Context("Matrix"); # need Matrix context to allow string input into Matrix. + +$m = Matrix("[[3,6,7],[2,1,8],[4,6,21],[-6,7,9]]"); +$constraint_matrix = Matrix(" +[[ 0, 0, -1, -1], + [-1, -1, 0, 0 ], + [1, 0 , 1 , 0], + [0, 1, 0, 1]] +"); + +#TEXT ("created ". ref($m)); +#what are the best ways to display a matrix? + +$m1 = matrix_from_matrix_rows($m, [1,3,2]); +$m2 = matrix_from_matrix_cols($m, [3,2,1]); +$m3 = matrix_from_submatrix($m, rows=>[1,4], columns=>[1,2]); + +$list = matrix_rows_to_list($m, 2,3); + +$b = Matrix([1, 2, 3, 4]); +TEXT($BR, "vector", $b->data->[1]); +$c = Matrix([5, 6, 7]); +$t = Tableau->new(A=>$m,b=>$b, c=>$c); + +$basis2 = $t->basis(1,3,5,6); + +BEGIN_PGML + +[` [$m] `] + +Extract rows (1, 4 ) from Matrix + +[` [$m1] `] + + Extract the submatrix of rows (1,4) and columns (1, 2, 3) + + new submatrix is + [` [$m3] `] + +a list of rows 2 and 3 [`[$list]`] + +A matrix from rows (1,3,2) [`[$m1]`] +A matrix from cols (3,2,1) [`[$m2]`] + +A new matrix [`[$b]`] +END_PGML + +ENDDOCUMENT(); + diff --git a/t/matrix_tableau_tests/tableau_javascript.pg b/t/matrix_tableau_tests/tableau_javascript.pg new file mode 100644 index 0000000000..69a666c60f --- /dev/null +++ b/t/matrix_tableau_tests/tableau_javascript.pg @@ -0,0 +1,133 @@ +##DESCRIPTION + + + +##ENDDESCRIPTION + + +DOCUMENT(); # This should be the first executable line in the problem. + +loadMacros( + "PGstandard.pl", # Standard macros for PG language + "MathObjects.pl", + "AppletObjects.pl", + "PGML.pl", + "PGmatrixmacros.pl", + "LinearProgramming.pl", + "parserLinearInequality.pl", + #"gage_matrix_ops.pl", + "tableau.pl", + "quickMatrixEntry.pl", + #"source.pl", # used to display problem source button + "PGcourse.pl", # Customization file for the course +); + +TEXT(beginproblem()); +$showPartialCorrectAnswers = 1; + + + +#BEGIN_TEXT +# + +#
    +# +# +#
    +#END_TEXT + +INITIALIZE_QUICK_MATRIX_ENTRY(); + +############################################################## +# +# Setup +# +# +Context("Numeric"); +# Your resources: +$money_total = 6000; +$time_total = 600; + +# Bill +$bill_money_commitment = 5000; #dollars +$bill_time_commitment = 400; # hours +$bill_profit = 4500; +# Steve +$steve_money_commitment = 4000; +$steve_time_commitment = 500; +$steve_profit = 4500; + +Context()->variables->add(p1=>'Real',p2=>'Real'); +$objfun1 = Formula("${bill_profit}p1 + ${steve_profit}p2"); +#Hack to prevent domain conflict in answer. +# why can't the formula be defined within context "linearInequality"? + +Context("LinearInequality"); +Context()->variables->add(p1=>'Real',p2=>'Real'); +Context()->strings->add("Essay Answer" =>{}); +Context()->strings->add('Minimize'=>{},'Maximize'=>{}, "?"=>{}); +Context()->strings->add('Yes'=>{},'No'=>{}); +our $context=Context(); + +$original_matrix = Matrix([ +[$bill_money_commitment, $steve_money_commitment, 1, 0, 0,0,0, $money_total], +[$bill_time_commitment,$steve_time_commitment, 0, 1, 0,0,0, $time_total], +[1,0,0,0,1,0,0,1], +[0,1,0,0,0,1,0,1], +[-$bill_profit, -$steve_profit, 0, 0, 0,0,1, 0] +]); +$toplabels = [qw(p1 p2 x3 x4 x5 x6 P b)]; +$sidelabels = [' ', qw(cash hours p_1bound p_2obund objfunc) ]; +$matrix1 = $original_matrix; + + + +############################################################################## +# get information on current state +$tableau1 = $matrix1->wwMatrix->array_ref; # translate to the array reference +$basis1 = Set(3,4,5,6); +@statevars1 = get_tableau_variable_values($matrix1, $basis1); +# get z value +$statevars1 = ~~@statevars1; +$state1 = Matrix([[@statevars1]]); + +$matrix1->{top_labels}=$toplabels; +Context()->texStrings; + +BEGIN_TEXT + +Write the matrix/tableau representing the linear optimization problem above. Use +the convention that the objective function is listed on the bottom row and the coefficient in +front of the profit \(P\) is \(1\) or equivalently in the form \( -ax_1 -bx_2 +z = 0 \) +$PAR +We'll use x3 for the slack variable for the money constraint, x4 for the time constraint +slack variable and x5 and x6 for the slack variables for the contraints on p1 and p2. +\{MATRIX_ENTRY_BUTTON(1,5,9)\} +\{ANS($matrix1->cmp()), $matrix1->ans_array()\} + +\{MATRIX_ENTRY_BUTTON(2,5,7)\} +\{ANS($matrix1->cmp()), $matrix1->ans_array()\} +$PAR +END_TEXT + +BEGIN_SOLUTION +displayMode $displayMode $PAR +\[ \{lp_display_mm($matrix1, top_labels=>$toplabels).side_labels($sidelabels)\} \] + +END_SOLUTION +Context()->normalStrings; + + + +############################################################## +# +# Answers +# +# + + + +ENDDOCUMENT(); # This should be the last executable line in the problem. \ No newline at end of file diff --git a/t/matrix_tableau_tests/tableau_test1.pg b/t/matrix_tableau_tests/tableau_test1.pg new file mode 100644 index 0000000000..cc0a503fe7 --- /dev/null +++ b/t/matrix_tableau_tests/tableau_test1.pg @@ -0,0 +1,104 @@ + + + +############################################## +DOCUMENT(); + +loadMacros( + "PGstandard.pl", # Standard macros for PG language + "MathObjects.pl", + "parserLinearInequality.pl", + "PGML.pl", + "tableau.pl", + "PGmatrixmacros.pl", + "LinearProgramming.pl", + #"source.pl", # allows code to be displayed on certain sites. + "PGcourse.pl", +); + +############################################## + +Context("Matrix"); # need Matrix context to allow string input into Matrix. + +$m = Matrix("[[3,6,7],[2,1,8],[4,6,21],[-6,7,9]]"); +$constraint_matrix = Matrix(" +[[ 0, 0, -1, -1], + [-1, -1, 0, 0 ], + [1, 0 , 1 , 0], + [0, 1, 0, 1]] +"); + +#TEXT ("created ". ref($m)); +#what are the best ways to display a matrix? + +$m1 = $m->row_slice([4,1]); +$m2 = $m->column_slice([3,2,1]); + +$list = $m->extract_rows_to_list(2,3); + +$b = Matrix([1, 2, 3, 4]); +#TEXT($BR, "vector", $b->data->[1]); +$c = Matrix([5, 6, 7]); +$t = Tableau->new(A=>$m,b=>$b, c=>$c); + +$basis2 = $t->basis(1,3,4,6); +$t->current_tableau; + +$c_B = $t->{obj_row}->extract_columns($t->{basis} ); #basis coefficients +$c_B2 = Value::Vector->new(map {$_->value} @$c_B); +$c_4 = $t->current_tableau; + + +my $Badj = ($t->{B}->det) * ($t->{B}->inverse); +my $current_tableau = $Badj * $t->{M}; # the A | S | obj | b + +$correction_coeff = ($c_B2*$current_tableau)->row(1); +$obj_row_normalized = ($t->{B}->det) *$t->{obj_row}; +$current_coeff = $obj_row_normalized-$correction_coeff ; + +TEXT("obj_row ", $t->{obj_row}, $BR ); +TEXT("c_b is", @$c_B,$BR); +TEXT("c_b2 is", $c_B2,$BR); +TEXT("current coeff ", List($current_coeff),$BR); +BEGIN_PGML +matrix is [`[$m]`] + +b is [$b] + +and c is [$c] + +original tableau is [`[$t->{M}]`] + +and basis is [$t->basis] + +B is [`[$t->{B}]`] with determinant [$t->{B}->det] + +the objective row is [@ $t->{obj_row} @] + + +the coefficients associated with the basis are [@ List(@$c_B) @] + +the vector version of these coefficients is [$c_B2] + +the normalized objective row is [@ List($obj_row_normalized ) @] + +The correction coeff are [@ List($correction_coeff) @] + +The current coeff are [@ List($current_coeff) @] + +Print the current total tableau for the basis [@ Matrix($t->{basis}) @]: + +$t->current_tableau [`[$c_4]`] + +Here is the decorated version of the total tableau: + +[`[@ lp_display_mm($c_4, top_labels=>[qw(x1 x2 x3 x4 x5 x6 x7 w b)], +side_labels=>['\text{constraintA}', '', '\text{constraintC}', '\text{constraintD}', +'\text{objective_function}'])@]`] + + +END_PGML + +TEXT("array reference", pretty_print( convert_to_array_ref($c_4) )); +ENDDOCUMENT(); + diff --git a/t/matrix_tableau_tests/tableau_test2.pg b/t/matrix_tableau_tests/tableau_test2.pg new file mode 100644 index 0000000000..8b5a4cecff --- /dev/null +++ b/t/matrix_tableau_tests/tableau_test2.pg @@ -0,0 +1,82 @@ +# not ready for prime time. + + +# $b = Matrix([1, 2, 3, 4]); +# TEXT($BR, "vector", $b->data->[1]); +# $c = Matrix([5, 6, 7]); +# $t = Tableau->new(A=>$m,b=>$b, c=>$c); +# @tab = $t->assemble_matrix; +# warn($BR, "rows", join(' ', @{$tab[0]},"|",@{$tab[1]},"|", @{$tab[2]},"|", @{$tab[3]},"|", @{$tab[4]})); +# +# +# +# my @slice = ( 1..(($t->{M}->dimensions)[0]) ); +# DEBUG_MESSAGE("slice is ", @slice); +# +# +# my @matrix_rows = $t->{M}->extract_rows(); +# push @matrix_rows, $t->{obj_row}; +# $m4 = Matrix(@matrix_rows); +# +# $mod_obj_row = $t->{obj_row} ; +# + +# Find the column slice of columns 3,2,1 of the matrix [`[$m2]`] +# +# Output rows 2 and 3 of the matrix as a list [` [$list] `] +# +# Output the complete Tableau (A |S |b): [`[$t->{M}]`] +# +# Output the last row (the objective row): [`[@ Matrix($t->{obj_row}) @]`] +# +# Include the last row [` [$m4] `] +# +# Output the initial basis [`[@ List($t->{basis}) @]`] and the basis columns B: [` [$t->{B}] `] +# +# END_PGML +# TEXT("#############"); +# $basis2 = $t->basis(1,3,5,6); +# $obj_function_basis_coeff = List( matrix_extract_columns($t->{obj_row}, $t->{basis} ) ) ; +# +# @r1 = matrix_extract_columns($t->{obj_row}, $t->{basis}); +# $rtest = List(@r1); +# $r2 = Vector( Vector(@r1)*($t->{M}) ) ; +# TEXT("#############"); +# BEGIN_PGML +# set a new basis [`[$basis2]`] and print the new columns B [` [$t->{B}] `] +# +# the new basis is [$t->basis] and the basis coefficients using $t->current_state are [$t->current_state]. +# This [$obj_function_basis_coeff] should be the same as above. +# +# and this should be identical [@ List(@r1) @] +# +# +# final row [`[$t->{obj_row}]`] +# modifications for final row [` [$r2] `] +# modified final row [` [@ ($t->{obj_row}) - $r2 @] `] +# +# END_PGML +# +# TEXT("*********************"); +# +# +# TEXT("*********************"); +# +# +# BEGIN_PGML +# original tableau = [`[$t->{M}]`] +# +# original object row [`[$t->{obj_row}]`] +# +# here are the two together [`[$m4]`] +# +# +# change basis to [`[$t->basis]`] +# +# print new basis [`[$t->{B}]`] +# +# new tableau is [`[$t->current_state]`] +# +# new obj_row is [`[$t->{current_coeff}]`] +# +# END_PGML \ No newline at end of file diff --git a/t/pg_test_problems/pg_uses_cmplx_cmp.list b/t/pg_test_problems/pg_uses_cmplx_cmp.list new file mode 100644 index 0000000000..8e3d4404db --- /dev/null +++ b/t/pg_test_problems/pg_uses_cmplx_cmp.list @@ -0,0 +1,26 @@ +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/NAU/EE/ee188/irwin.08.011.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/NAU/EE/ee188/irwin.08.019.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/NAU/EE/ee188/irwin.08.038.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/NAU/EE/ee188/irwin.08.047.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/NAU/EE/ee188/irwin.08.076.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/NAU/EE/ee188/irwin.08.084.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/NAU/EE/ee188/irwin.09.058.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setAlgebra11ComplexNumbers/Divide.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setAlgebra11ComplexNumbers/Sqrt.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setAlgebra11ComplexNumbers/ur_cn_1_1.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setAlgebra11ComplexNumbers/ur_cn_1_14.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setAlgebra11ComplexNumbers/ur_cn_1_33.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setAlgebra11ComplexNumbers/ur_cn_1_6.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setAlgebra34Matrices/determinant_2x2a.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setComplexNumbers/ur_cn_1_13.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setComplexNumbers/ur_cn_1_14.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setComplexNumbers/ur_cn_1_2.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setComplexNumbers/ur_cn_1_32.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setComplexNumbers2AnalyticFunctions/ur_cn_2_10.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setComplexNumbers2AnalyticFunctions/ur_cn_2_11.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setComplexNumbers2AnalyticFunctions/ur_cn_2_3.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setComplexNumbers2AnalyticFunctions/ur_cn_2_4.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setComplexNumbers2AnalyticFunctions/ur_cn_2_5.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setComplexNumbers2AnalyticFunctions/ur_cn_2_6.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setComplexNumbers2AnalyticFunctions/ur_cn_2_7.pg +/Volumes/WW_test/opt/webwork/libraries/webwork-open-problem-library/OpenProblemLibrary/Rochester/setLinearAlgebra1Systems/ur_la_1_2.pg diff --git a/t/test_find_file_in_directories.pl b/t/test_find_file_in_directories.pl new file mode 100644 index 0000000000..acd51a12d4 --- /dev/null +++ b/t/test_find_file_in_directories.pl @@ -0,0 +1,43 @@ +#!/Volumes/WW_test/opt/local/bin/perl -w + + +use strict; + + +BEGIN { + die "WEBWORK_ROOT not found in environment. \n + WEBWORK_ROOT can be defined in your .cshrc or .bashrc file\n + It should be set to the webwork2 directory (e.g. /opt/webwork/webwork2)" + unless exists $ENV{WEBWORK_ROOT}; + # Unused variable, but define it twice to avoid an error message. + $WeBWorK::Constants::WEBWORK_DIRECTORY = $ENV{WEBWORK_ROOT}; + + # Define MP2 -- this would normally be done in webwork.apache2.4-config + $ENV{MOD_PERL_API_VERSION}=2; + print "Webwork root directory is $WeBWorK::Constants::WEBWORK_DIRECTORY\n\n"; + + + $WebworkBase::courseName = "gage_test"; + my $topDir = $WeBWorK::Constants::WEBWORK_DIRECTORY; + $topDir =~ s|webwork2?$||; # remove webwork2 link + $WebworkBase::RootWebwork2Dir = "$topDir/webwork2"; + $WebworkBase::RootPGDir = "$topDir/pg"; + $WebworkBase::RootCourseDir = "${topDir}courses"; + + eval "use lib '$WebworkBase::RootWebwork2Dir/lib'"; die $@ if $@; + eval "use lib '$WebworkBase::RootPGDir/lib'"; die $@ if $@; +} + use PGalias; + + my $file = "prob14.html"; + my @directories = ( + "$WebworkBase::RootCourseDir/$WebworkBase::courseName/templates/setaliasCheck/htmlAliasCheck", + "$WebworkBase::RootCourseDir/$WebworkBase::courseName/html", + "$WebworkBase::RootWebwork2Dir/htdocs", + ); + my $file_path = PGalias->find_file_in_directories($file, \@directories)//'not found'; + print "File found at: $file_path\n"; + + + +1; \ No newline at end of file