+
+
+
+
+
+
+
diff --git a/.project b/.project
new file mode 100644
index 0000000..ef52e02
--- /dev/null
+++ b/.project
@@ -0,0 +1,36 @@
+
+
+ MTRAM
+
+
+
+
+
+ org.eclipse.wst.jsdt.core.javascriptValidator
+
+
+
+
+ org.eclipse.wst.common.project.facet.core.builder
+
+
+
+
+ org.eclipse.jdt.core.javabuilder
+
+
+
+
+ org.eclipse.wst.validation.validationbuilder
+
+
+
+
+
+ org.eclipse.jem.workbench.JavaEMFNature
+ org.eclipse.wst.common.modulecore.ModuleCoreNature
+ org.eclipse.jdt.core.javanature
+ org.eclipse.wst.common.project.facet.core.nature
+ org.eclipse.wst.jsdt.core.jsNature
+
+
diff --git a/.settings/.jsdtscope b/.settings/.jsdtscope
new file mode 100644
index 0000000..3a28de0
--- /dev/null
+++ b/.settings/.jsdtscope
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.settings/oracle.eclipse.tools.webtier.ui.prefs b/.settings/oracle.eclipse.tools.webtier.ui.prefs
new file mode 100644
index 0000000..c2c4367
--- /dev/null
+++ b/.settings/oracle.eclipse.tools.webtier.ui.prefs
@@ -0,0 +1,22 @@
+#Fri Nov 27 15:27:32 ICT 2015
+//_hiddenCategory_\:http\://ckeditor.com=false
+//_hiddenCategory_\:http\://displaytag.sf.net=false
+//_hiddenCategory_\:http\://displaytag.sf.net/el=false
+//_hiddenCategory_\:http\://java.sun.com/jsp/jstl/core=false
+//_hiddenCategory_\:http\://java.sun.com/jsp/jstl/fmt=false
+//_hiddenCategory_\:http\://java.sun.com/jsp/jstl/sql=false
+//_hiddenCategory_\:http\://java.sun.com/jsp/jstl/xml=false
+//_hiddenCategory_\:http\://java.sun.com/jstl/core=false
+//_hiddenCategory_\:http\://java.sun.com/jstl/core_rt=false
+//_hiddenCategory_\:http\://java.sun.com/jstl/fmt=false
+//_hiddenCategory_\:http\://java.sun.com/jstl/fmt_rt=false
+//_hiddenCategory_\:http\://java.sun.com/jstl/sql=false
+//_hiddenCategory_\:http\://java.sun.com/jstl/sql_rt=false
+//_hiddenCategory_\:http\://java.sun.com/jstl/xml=false
+//_hiddenCategory_\:http\://java.sun.com/jstl/xml_rt=false
+//_hiddenCategory_\:http\://www.springframework.org/tags=false
+//_hiddenCategory_\:http\://www.springframework.org/tags/form=false
+_hiddenCategory_\:DataPalette=false
+_hiddenCategory_\:HTML=false
+_hiddenCategory_\:jsp11=false
+eclipse.preferences.version=1
diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..24f8ba3
--- /dev/null
+++ b/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,8 @@
+#Fri Nov 27 15:20:07 ICT 2015
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component
new file mode 100644
index 0000000..ca7bec4
--- /dev/null
+++ b/.settings/org.eclipse.wst.common.component
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
diff --git a/.settings/org.eclipse.wst.common.project.facet.core.xml b/.settings/org.eclipse.wst.common.project.facet.core.xml
new file mode 100644
index 0000000..bac9809
--- /dev/null
+++ b/.settings/org.eclipse.wst.common.project.facet.core.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
diff --git a/.settings/org.eclipse.wst.html.core.prefs b/.settings/org.eclipse.wst.html.core.prefs
new file mode 100644
index 0000000..3ca0668
--- /dev/null
+++ b/.settings/org.eclipse.wst.html.core.prefs
@@ -0,0 +1,39 @@
+#Mon Nov 30 14:22:08 ICT 2015
+attrDuplicate=2
+attrInvalidName=2
+attrInvalidValue=2
+attrNameMismatch=2
+attrUndefName=2
+attrUndefValue=2
+attrValueEqualsMissing=2
+attrValueMismatch=-1
+attrValueUnclosed=2
+cdataInvalidContent=2
+cdataUnclosed=1
+commentInvalidContent=2
+commentUnclosed=1
+docDoctypeUnclosed=1
+docDuplicateTag=1
+docInvalidChar=2
+docInvalidContent=2
+eclipse.preferences.version=1
+elemCoexistence=2
+elemDuplicate=2
+elemEndInvalidCase=1
+elemInvalidContent=2
+elemInvalidDirective=1
+elemInvalidEmptyTag=2
+elemInvalidName=1
+elemInvalidText=2
+elemMissingEnd=2
+elemMissingStart=2
+elemStartInvalidCase=2
+elemUnclosedEndTag=1
+elemUnclosedStartTag=1
+elemUnknownName=2
+elemUnnecessaryEnd=2
+piInvalidContent=2
+piUnclosed=1
+piUndefined=2
+refInvalidContent=2
+use-project-settings=true
diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.container b/.settings/org.eclipse.wst.jsdt.ui.superType.container
new file mode 100644
index 0000000..3bd5d0a
--- /dev/null
+++ b/.settings/org.eclipse.wst.jsdt.ui.superType.container
@@ -0,0 +1 @@
+org.eclipse.wst.jsdt.launching.baseBrowserLibrary
\ No newline at end of file
diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.name b/.settings/org.eclipse.wst.jsdt.ui.superType.name
new file mode 100644
index 0000000..05bd71b
--- /dev/null
+++ b/.settings/org.eclipse.wst.jsdt.ui.superType.name
@@ -0,0 +1 @@
+Window
\ No newline at end of file
diff --git a/.settings/org.eclipse.wst.validation.prefs b/.settings/org.eclipse.wst.validation.prefs
new file mode 100644
index 0000000..74b44c0
--- /dev/null
+++ b/.settings/org.eclipse.wst.validation.prefs
@@ -0,0 +1,9 @@
+#Mon Nov 30 11:11:55 ICT 2015
+DELEGATES_PREFERENCE=delegateValidatorList
+USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
+USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
+USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationtrueversion1.2.302.v201107140600
+eclipse.preferences.version=1
+override=true
+suspend=true
+vf.version=3
diff --git a/.settings/org.eclipse.wst.ws.service.policy.prefs b/.settings/org.eclipse.wst.ws.service.policy.prefs
new file mode 100644
index 0000000..559f253
--- /dev/null
+++ b/.settings/org.eclipse.wst.ws.service.policy.prefs
@@ -0,0 +1,3 @@
+#Fri Nov 27 15:15:45 ICT 2015
+eclipse.preferences.version=1
+org.eclipse.wst.ws.service.policy.projectEnabled=false
diff --git a/.svn/pristine/00/000e30d9e63927fe4fd3a439c9bf7e815ba59571.svn-base b/.svn/pristine/00/000e30d9e63927fe4fd3a439c9bf7e815ba59571.svn-base
new file mode 100644
index 0000000..78856a2
--- /dev/null
+++ b/.svn/pristine/00/000e30d9e63927fe4fd3a439c9bf7e815ba59571.svn-base
@@ -0,0 +1,13 @@
+/*
+ Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
+ For licensing, see LICENSE.html or http://ckeditor.com/license
+*/
+CKEDITOR.plugins.setLang("specialchar","cs",{euro:"Znak eura",lsquo:"Počáteční uvozovka jednoduchá",rsquo:"Koncová uvozovka jednoduchá",ldquo:"Počáteční uvozovka dvojitá",rdquo:"Koncová uvozovka dvojitá",ndash:"En pomlčka",mdash:"Em pomlčka",iexcl:"Obrácený vykřičník",cent:"Znak centu",pound:"Znak libry",curren:"Znak měny",yen:"Znak jenu",brvbar:"Přerušená svislá čára",sect:"Znak oddílu",uml:"Přehláska",copy:"Znak copyrightu",ordf:"Ženský indikátor rodu",laquo:"Znak dvojitých lomených uvozovek vlevo",
+not:"Logistický zápor",reg:"Znak registrace",macr:"Pomlčka nad",deg:"Znak stupně",sup2:"Dvojka jako horní index",sup3:"Trojka jako horní index",acute:"Čárka nad vpravo",micro:"Znak mikro",para:"Znak odstavce",middot:"Tečka uprostřed",cedil:"Ocásek vlevo",sup1:"Jednička jako horní index",ordm:"Mužský indikátor rodu",raquo:"Znak dvojitých lomených uvozovek vpravo",frac14:"Obyčejný zlomek jedna čtvrtina",frac12:"Obyčejný zlomek jedna polovina",frac34:"Obyčejný zlomek tři čtvrtiny",iquest:"Znak obráceného otazníku",
+Agrave:"Velké písmeno latinky A s čárkou nad vlevo",Aacute:"Velké písmeno latinky A s čárkou nad vpravo",Acirc:"Velké písmeno latinky A s vokáněm",Atilde:"Velké písmeno latinky A s tildou",Auml:"Velké písmeno latinky A s dvěma tečkami",Aring:"Velké písmeno latinky A s kroužkem nad",AElig:"Velké písmeno latinky Ae",Ccedil:"Velké písmeno latinky C s ocáskem vlevo",Egrave:"Velké písmeno latinky E s čárkou nad vlevo",Eacute:"Velké písmeno latinky E s čárkou nad vpravo",Ecirc:"Velké písmeno latinky E s vokáněm",
+Euml:"Velké písmeno latinky E s dvěma tečkami",Igrave:"Velké písmeno latinky I s čárkou nad vlevo",Iacute:"Velké písmeno latinky I s čárkou nad vpravo",Icirc:"Velké písmeno latinky I s vokáněm",Iuml:"Velké písmeno latinky I s dvěma tečkami",ETH:"Velké písmeno latinky Eth",Ntilde:"Velké písmeno latinky N s tildou",Ograve:"Velké písmeno latinky O s čárkou nad vlevo",Oacute:"Velké písmeno latinky O s čárkou nad vpravo",Ocirc:"Velké písmeno latinky O s vokáněm",Otilde:"Velké písmeno latinky O s tildou",
+Ouml:"Velké písmeno latinky O s dvěma tečkami",times:"Znak násobení",Oslash:"Velké písmeno latinky O přeškrtnuté",Ugrave:"Velké písmeno latinky U s čárkou nad vlevo",Uacute:"Velké písmeno latinky U s čárkou nad vpravo",Ucirc:"Velké písmeno latinky U s vokáněm",Uuml:"Velké písmeno latinky U s dvěma tečkami",Yacute:"Velké písmeno latinky Y s čárkou nad vpravo",THORN:"Velké písmeno latinky Thorn",szlig:"Malé písmeno latinky ostré s",agrave:"Malé písmeno latinky a s čárkou nad vlevo",aacute:"Malé písmeno latinky a s čárkou nad vpravo",
+acirc:"Malé písmeno latinky a s vokáněm",atilde:"Malé písmeno latinky a s tildou",auml:"Malé písmeno latinky a s dvěma tečkami",aring:"Malé písmeno latinky a s kroužkem nad",aelig:"Malé písmeno latinky ae",ccedil:"Malé písmeno latinky c s ocáskem vlevo",egrave:"Malé písmeno latinky e s čárkou nad vlevo",eacute:"Malé písmeno latinky e s čárkou nad vpravo",ecirc:"Malé písmeno latinky e s vokáněm",euml:"Malé písmeno latinky e s dvěma tečkami",igrave:"Malé písmeno latinky i s čárkou nad vlevo",iacute:"Malé písmeno latinky i s čárkou nad vpravo",
+icirc:"Malé písmeno latinky i s vokáněm",iuml:"Malé písmeno latinky i s dvěma tečkami",eth:"Malé písmeno latinky eth",ntilde:"Malé písmeno latinky n s tildou",ograve:"Malé písmeno latinky o s čárkou nad vlevo",oacute:"Malé písmeno latinky o s čárkou nad vpravo",ocirc:"Malé písmeno latinky o s vokáněm",otilde:"Malé písmeno latinky o s tildou",ouml:"Malé písmeno latinky o s dvěma tečkami",divide:"Znak dělení",oslash:"Malé písmeno latinky o přeškrtnuté",ugrave:"Malé písmeno latinky u s čárkou nad vlevo",
+uacute:"Malé písmeno latinky u s čárkou nad vpravo",ucirc:"Malé písmeno latinky u s vokáněm",uuml:"Malé písmeno latinky u s dvěma tečkami",yacute:"Malé písmeno latinky y s čárkou nad vpravo",thorn:"Malé písmeno latinky thorn",yuml:"Malé písmeno latinky y s dvěma tečkami",OElig:"Velká ligatura latinky OE",oelig:"Malá ligatura latinky OE",372:"Velké písmeno latinky W s vokáněm",374:"Velké písmeno latinky Y s vokáněm",373:"Malé písmeno latinky w s vokáněm",375:"Malé písmeno latinky y s vokáněm",sbquo:"Dolní 9 uvozovka jednoduchá",
+8219:"Horní obrácená 9 uvozovka jednoduchá",bdquo:"Dolní 9 uvozovka dvojitá",hellip:"Trojtečkový úvod",trade:"Obchodní značka",9658:"Černý ukazatel směřující vpravo",bull:"Kolečko",rarr:"Šipka vpravo",rArr:"Dvojitá šipka vpravo",hArr:"Dvojitá šipka vlevo a vpravo",diams:"Černé piky",asymp:"Téměř se rovná"});
\ No newline at end of file
diff --git a/.svn/pristine/00/0035656cafe40ecd6d13f428aefb8844d5a6f306.svn-base b/.svn/pristine/00/0035656cafe40ecd6d13f428aefb8844d5a6f306.svn-base
new file mode 100644
index 0000000..d37776a
Binary files /dev/null and b/.svn/pristine/00/0035656cafe40ecd6d13f428aefb8844d5a6f306.svn-base differ
diff --git a/.svn/pristine/00/0052a449a875c451e5646e1ae71c6621366af56d.svn-base b/.svn/pristine/00/0052a449a875c451e5646e1ae71c6621366af56d.svn-base
new file mode 100644
index 0000000..f9a4600
--- /dev/null
+++ b/.svn/pristine/00/0052a449a875c451e5646e1ae71c6621366af56d.svn-base
@@ -0,0 +1,248 @@
+<%@page language="java" contentType="text/html;charset=utf-8" pageEncoding="UTF-8" %>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/00/0077af54a40a95a5a37c18ae41bfaaf6f8305f3c.svn-base b/.svn/pristine/00/0077af54a40a95a5a37c18ae41bfaaf6f8305f3c.svn-base
new file mode 100644
index 0000000..8d6b76b
--- /dev/null
+++ b/.svn/pristine/00/0077af54a40a95a5a37c18ae41bfaaf6f8305f3c.svn-base
@@ -0,0 +1,60 @@
+
+package th.co.muangthai.endrprint.wfurlxml;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ *
Java class for getUrl complex type.
+ *
+ *
The following schema fragment specifies the expected content contained within this class.
+ *
+ *
+
+
+<%--End Body--%>
+
\ No newline at end of file
diff --git a/.svn/pristine/02/02e34b82020cd7a286276599b83a388ab59e9567.svn-base b/.svn/pristine/02/02e34b82020cd7a286276599b83a388ab59e9567.svn-base
new file mode 100644
index 0000000..a1b854b
Binary files /dev/null and b/.svn/pristine/02/02e34b82020cd7a286276599b83a388ab59e9567.svn-base differ
diff --git a/.svn/pristine/03/03106a6157d334854f334bed3f05c889a33c9139.svn-base b/.svn/pristine/03/03106a6157d334854f334bed3f05c889a33c9139.svn-base
new file mode 100644
index 0000000..2c70429
--- /dev/null
+++ b/.svn/pristine/03/03106a6157d334854f334bed3f05c889a33c9139.svn-base
@@ -0,0 +1,112 @@
+package th.co.muangthai.endrprint.model.bean.master;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import java.math.BigDecimal;
+import java.util.Date;
+import java.io.Serializable;
+import org.codehaus.jackson.annotate.JsonAutoDetect;
+import org.codehaus.jackson.map.annotate.JsonSerialize;
+import th.co.muangthai.endrprint.util.JsonDateSerializer;
+
+@JsonAutoDetect
+@Entity
+@Table(name = "MST_OPERID_TAB")
+public class MstOperidTabBean implements Serializable {
+
+ @Id
+ @Column(name = "OPERID")
+ private String operid;
+ @Column(name = "USERID")
+ private String userid;
+ @Column(name = "IDENTIFIELD")
+ private String identifield;
+ @Column(name = "OPER_NAME")
+ private String operName;
+ @Column(name = "LICIENSE_NAME")
+ private String licienseName;
+ @Column(name = "DEPCODE")
+ private String depcode;
+ @Column(name = "DEPARTMENT")
+ private String department;
+ @Column(name = "TEAM")
+ private String team;
+ @Column(name = "FLAG")
+ private String flag;
+
+ public void setOperid(String operid) {
+ this.operid = operid;
+ }
+
+ public String getOperid() {
+ return this.operid;
+ }
+
+ public void setUserid(String userid) {
+ this.userid = userid;
+ }
+
+ public String getUserid() {
+ return this.userid;
+ }
+
+ public void setIdentifield(String identifield) {
+ this.identifield = identifield;
+ }
+
+ public String getIdentifield() {
+ return this.identifield;
+ }
+
+ public void setOperName(String operName) {
+ this.operName = operName;
+ }
+
+ public String getOperName() {
+ return this.operName;
+ }
+
+ public void setLicienseName(String licienseName) {
+ this.licienseName = licienseName;
+ }
+
+ public String getLicienseName() {
+ return this.licienseName;
+ }
+
+ public void setDepcode(String depcode) {
+ this.depcode = depcode;
+ }
+
+ public String getDepcode() {
+ return this.depcode;
+ }
+
+ public void setDepartment(String department) {
+ this.department = department;
+ }
+
+ public String getDepartment() {
+ return this.department;
+ }
+
+ public void setTeam(String team) {
+ this.team = team;
+ }
+
+ public String getTeam() {
+ return this.team;
+ }
+
+ public void setFlag(String flag) {
+ this.flag = flag;
+ }
+
+ public String getFlag() {
+ return this.flag;
+ }
+
+
+}
\ No newline at end of file
diff --git a/.svn/pristine/03/03215a36ee94d6a03adb4f1b59b0db905fb64a87.svn-base b/.svn/pristine/03/03215a36ee94d6a03adb4f1b59b0db905fb64a87.svn-base
new file mode 100644
index 0000000..0af2f59
--- /dev/null
+++ b/.svn/pristine/03/03215a36ee94d6a03adb4f1b59b0db905fb64a87.svn-base
@@ -0,0 +1,9 @@
+/*
+ Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
+ For licensing, see LICENSE.html or http://ckeditor.com/license
+*/
+CKEDITOR.plugins.setLang("a11yhelp","km",{title:"Accessibility Instructions",contents:"Help Contents. To close this dialog press ESC.",legend:[{name:"ទូទៅ",items:[{name:"Editor Toolbar",legend:"Press ${toolbarFocus} to navigate to the toolbar. Move to the next and previous toolbar group with TAB and SHIFT-TAB. Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. Press SPACE or ENTER to activate the toolbar button."},{name:"Editor Dialog",legend:"Inside a dialog, press TAB to navigate to next dialog field, press SHIFT + TAB to move to previous field, press ENTER to submit dialog, press ESC to cancel dialog. For dialogs that have multiple tab pages, press ALT + F10 to navigate to tab-list. Then move to next tab with TAB OR RIGTH ARROW. Move to previous tab with SHIFT + TAB or LEFT ARROW. Press SPACE or ENTER to select the tab page."},
+{name:"Editor Context Menu",legend:"Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC."},{name:"Editor List Box",legend:"Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT + TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box."},
+{name:"Editor Element Path Bar",legend:"Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor."}]},{name:"Commands",items:[{name:" Undo command",legend:"Press ${undo}"},{name:" Redo command",legend:"Press ${redo}"},{name:" Bold command",legend:"Press ${bold}"},{name:" Italic command",legend:"Press ${italic}"},{name:" Underline command",
+legend:"Press ${underline}"},{name:" Link command",legend:"Press ${link}"},{name:" Toolbar Collapse command",legend:"Press ${toolbarCollapse}"},{name:" Access previous focus space command",legend:"Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."},{name:" Access next focus space command",legend:"Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."},
+{name:" Accessibility Help",legend:"Press ${a11yHelp}"}]}]});
\ No newline at end of file
diff --git a/.svn/pristine/03/03a1620bc49e483beed5f9cb73d417992c5976bd.svn-base b/.svn/pristine/03/03a1620bc49e483beed5f9cb73d417992c5976bd.svn-base
new file mode 100644
index 0000000..8c051a1
--- /dev/null
+++ b/.svn/pristine/03/03a1620bc49e483beed5f9cb73d417992c5976bd.svn-base
@@ -0,0 +1,356 @@
+.tabs-container {
+ overflow: hidden;
+}
+.tabs-header {
+ border-width: 1px;
+ border-style: solid;
+ border-bottom-width: 0;
+ position: relative;
+ padding: 0;
+ padding-top: 2px;
+ overflow: hidden;
+}
+.tabs-header-plain {
+ border: 0;
+ background: transparent;
+}
+.tabs-scroller-left,
+.tabs-scroller-right {
+ position: absolute;
+ top: auto;
+ bottom: 0;
+ width: 18px;
+ font-size: 1px;
+ display: none;
+ cursor: pointer;
+ border-width: 1px;
+ border-style: solid;
+}
+.tabs-scroller-left {
+ left: 0;
+}
+.tabs-scroller-right {
+ right: 0;
+}
+.tabs-tool {
+ position: absolute;
+ bottom: 0;
+ padding: 1px;
+ overflow: hidden;
+ border-width: 1px;
+ border-style: solid;
+}
+.tabs-header-plain .tabs-tool {
+ padding: 0 1px;
+}
+.tabs-wrap {
+ position: relative;
+ left: 0;
+ overflow: hidden;
+ width: 100%;
+ margin: 0;
+ padding: 0;
+}
+.tabs-scrolling {
+ margin-left: 18px;
+ margin-right: 18px;
+}
+.tabs-disabled {
+ opacity: 0.3;
+ filter: alpha(opacity=30);
+}
+.tabs {
+ list-style-type: none;
+ height: 26px;
+ margin: 0px;
+ padding: 0px;
+ padding-left: 4px;
+ width: 5000px;
+ border-style: solid;
+ border-width: 0 0 1px 0;
+}
+.tabs li {
+ float: left;
+ display: inline-block;
+ margin: 0 4px -1px 0;
+ padding: 0;
+ position: relative;
+ border: 0;
+}
+.tabs li a.tabs-inner {
+ display: inline-block;
+ text-decoration: none;
+ margin: 0;
+ padding: 0 10px;
+ height: 25px;
+ line-height: 25px;
+ text-align: center;
+ white-space: nowrap;
+ border-width: 1px;
+ border-style: solid;
+ -moz-border-radius: 5px 5px 0 0;
+ -webkit-border-radius: 5px 5px 0 0;
+ border-radius: 5px 5px 0 0;
+}
+.tabs li.tabs-selected a.tabs-inner {
+ font-weight: bold;
+ outline: none;
+}
+.tabs li.tabs-selected a:hover.tabs-inner {
+ cursor: default;
+ pointer: default;
+}
+.tabs li a.tabs-close,
+.tabs-p-tool {
+ position: absolute;
+ font-size: 1px;
+ display: block;
+ height: 12px;
+ padding: 0;
+ top: 50%;
+ margin-top: -6px;
+ overflow: hidden;
+}
+.tabs li a.tabs-close {
+ width: 12px;
+ right: 5px;
+ opacity: 0.6;
+ filter: alpha(opacity=60);
+}
+.tabs-p-tool {
+ right: 16px;
+}
+.tabs-p-tool a {
+ display: inline-block;
+ font-size: 1px;
+ width: 12px;
+ height: 12px;
+ margin: 0;
+ opacity: 0.6;
+ filter: alpha(opacity=60);
+}
+.tabs li a:hover.tabs-close,
+.tabs-p-tool a:hover {
+ opacity: 1;
+ filter: alpha(opacity=100);
+ cursor: hand;
+ cursor: pointer;
+}
+.tabs-with-icon {
+ padding-left: 18px;
+}
+.tabs-icon {
+ position: absolute;
+ width: 16px;
+ height: 16px;
+ left: 10px;
+ top: 50%;
+ margin-top: -8px;
+}
+.tabs-title {
+ font-size: 12px;
+}
+.tabs-closable {
+ padding-right: 8px;
+}
+.tabs-panels {
+ margin: 0px;
+ padding: 0px;
+ border-width: 1px;
+ border-style: solid;
+ border-top-width: 0;
+ overflow: hidden;
+}
+.tabs-header-bottom {
+ border-width: 0 1px 1px 1px;
+ padding: 0 0 2px 0;
+}
+.tabs-header-bottom .tabs {
+ border-width: 1px 0 0 0;
+}
+.tabs-header-bottom .tabs li {
+ margin: -1px 4px 0 0;
+}
+.tabs-header-bottom .tabs li a.tabs-inner {
+ -moz-border-radius: 0 0 5px 5px;
+ -webkit-border-radius: 0 0 5px 5px;
+ border-radius: 0 0 5px 5px;
+}
+.tabs-header-bottom .tabs-tool {
+ top: 0;
+}
+.tabs-header-bottom .tabs-scroller-left,
+.tabs-header-bottom .tabs-scroller-right {
+ top: 0;
+ bottom: auto;
+}
+.tabs-panels-top {
+ border-width: 1px 1px 0 1px;
+}
+.tabs-header-left {
+ float: left;
+ border-width: 1px 0 1px 1px;
+ padding: 0;
+}
+.tabs-header-right {
+ float: right;
+ border-width: 1px 1px 1px 0;
+ padding: 0;
+}
+.tabs-header-left .tabs-wrap,
+.tabs-header-right .tabs-wrap {
+ height: 100%;
+}
+.tabs-header-left .tabs {
+ height: 100%;
+ padding: 4px 0 0 4px;
+ border-width: 0 1px 0 0;
+}
+.tabs-header-right .tabs {
+ height: 100%;
+ padding: 4px 4px 0 0;
+ border-width: 0 0 0 1px;
+}
+.tabs-header-left .tabs li,
+.tabs-header-right .tabs li {
+ display: block;
+ width: 100%;
+ position: relative;
+}
+.tabs-header-left .tabs li {
+ left: auto;
+ right: 0;
+ margin: 0 -1px 4px 0;
+ float: right;
+}
+.tabs-header-right .tabs li {
+ left: 0;
+ right: auto;
+ margin: 0 0 4px -1px;
+ float: left;
+}
+.tabs-header-left .tabs li a.tabs-inner {
+ display: block;
+ text-align: left;
+ -moz-border-radius: 5px 0 0 5px;
+ -webkit-border-radius: 5px 0 0 5px;
+ border-radius: 5px 0 0 5px;
+}
+.tabs-header-right .tabs li a.tabs-inner {
+ display: block;
+ text-align: left;
+ -moz-border-radius: 0 5px 5px 0;
+ -webkit-border-radius: 0 5px 5px 0;
+ border-radius: 0 5px 5px 0;
+}
+.tabs-panels-right {
+ float: right;
+ border-width: 1px 1px 1px 0;
+}
+.tabs-panels-left {
+ float: left;
+ border-width: 1px 0 1px 1px;
+}
+.tabs-header-noborder,
+.tabs-panels-noborder {
+ border: 0px;
+}
+.tabs-header-plain {
+ border: 0px;
+ background: transparent;
+}
+.tabs-scroller-left {
+ background: #F2F2F2 url('images/tabs_icons.png') no-repeat 1px center;
+}
+.tabs-scroller-right {
+ background: #F2F2F2 url('images/tabs_icons.png') no-repeat -15px center;
+}
+.tabs li a.tabs-close {
+ background: url('images/tabs_icons.png') no-repeat -34px center;
+}
+.tabs li a.tabs-inner:hover {
+ background: #e6e6e6;
+ color: #00438a;
+ filter: none;
+}
+.tabs li.tabs-selected a.tabs-inner {
+ background-color: #ffffff;
+ color: #777;
+ background: -webkit-linear-gradient(top,#ffffff 0,#ffffff 100%);
+ background: -moz-linear-gradient(top,#ffffff 0,#ffffff 100%);
+ background: -o-linear-gradient(top,#ffffff 0,#ffffff 100%);
+ background: linear-gradient(to bottom,#ffffff 0,#ffffff 100%);
+ background-repeat: repeat-x;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#ffffff,GradientType=0);
+}
+.tabs-header-bottom .tabs li.tabs-selected a.tabs-inner {
+ background: -webkit-linear-gradient(top,#ffffff 0,#ffffff 100%);
+ background: -moz-linear-gradient(top,#ffffff 0,#ffffff 100%);
+ background: -o-linear-gradient(top,#ffffff 0,#ffffff 100%);
+ background: linear-gradient(to bottom,#ffffff 0,#ffffff 100%);
+ background-repeat: repeat-x;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#ffffff,GradientType=0);
+}
+.tabs-header-left .tabs li.tabs-selected a.tabs-inner {
+ background: -webkit-linear-gradient(left,#ffffff 0,#ffffff 100%);
+ background: -moz-linear-gradient(left,#ffffff 0,#ffffff 100%);
+ background: -o-linear-gradient(left,#ffffff 0,#ffffff 100%);
+ background: linear-gradient(to right,#ffffff 0,#ffffff 100%);
+ background-repeat: repeat-y;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#ffffff,GradientType=1);
+}
+.tabs-header-right .tabs li.tabs-selected a.tabs-inner {
+ background: -webkit-linear-gradient(left,#ffffff 0,#ffffff 100%);
+ background: -moz-linear-gradient(left,#ffffff 0,#ffffff 100%);
+ background: -o-linear-gradient(left,#ffffff 0,#ffffff 100%);
+ background: linear-gradient(to right,#ffffff 0,#ffffff 100%);
+ background-repeat: repeat-y;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#ffffff,GradientType=1);
+}
+.tabs li a.tabs-inner {
+ color: #777;
+ background-color: #F2F2F2;
+ background: -webkit-linear-gradient(top,#ffffff 0,#F2F2F2 100%);
+ background: -moz-linear-gradient(top,#ffffff 0,#F2F2F2 100%);
+ background: -o-linear-gradient(top,#ffffff 0,#F2F2F2 100%);
+ background: linear-gradient(to bottom,#ffffff 0,#F2F2F2 100%);
+ background-repeat: repeat-x;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#F2F2F2,GradientType=0);
+}
+.tabs-header,
+.tabs-tool {
+ background-color: #F2F2F2;
+}
+.tabs-header-plain {
+ background: transparent;
+}
+.tabs-header,
+.tabs-scroller-left,
+.tabs-scroller-right,
+.tabs-tool,
+.tabs,
+.tabs-panels,
+.tabs li a.tabs-inner,
+.tabs li.tabs-selected a.tabs-inner,
+.tabs-header-bottom .tabs li.tabs-selected a.tabs-inner,
+.tabs-header-left .tabs li.tabs-selected a.tabs-inner,
+.tabs-header-right .tabs li.tabs-selected a.tabs-inner {
+ border-color: #D4D4D4;
+}
+.tabs-p-tool a:hover,
+.tabs li a:hover.tabs-close,
+.tabs-scroller-over {
+ background-color: #e6e6e6;
+}
+.tabs li.tabs-selected a.tabs-inner {
+ border-bottom: 1px solid #ffffff;
+}
+.tabs-header-bottom .tabs li.tabs-selected a.tabs-inner {
+ border-top: 1px solid #ffffff;
+}
+.tabs-header-left .tabs li.tabs-selected a.tabs-inner {
+ border-right: 1px solid #ffffff;
+}
+.tabs-header-right .tabs li.tabs-selected a.tabs-inner {
+ border-left: 1px solid #ffffff;
+}
diff --git a/.svn/pristine/03/03dfb297ddfe8f489804ccac9d8e602be0a760c3.svn-base b/.svn/pristine/03/03dfb297ddfe8f489804ccac9d8e602be0a760c3.svn-base
new file mode 100644
index 0000000..cf70e61
--- /dev/null
+++ b/.svn/pristine/03/03dfb297ddfe8f489804ccac9d8e602be0a760c3.svn-base
@@ -0,0 +1,1264 @@
+Software License Agreement
+==========================
+
+CKEditor - The text editor for Internet - http://ckeditor.com
+Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
+
+Licensed under the terms of any of the following licenses at your
+choice:
+
+ - GNU General Public License Version 2 or later (the "GPL")
+ http://www.gnu.org/licenses/gpl.html
+ (See Appendix A)
+
+ - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
+ http://www.gnu.org/licenses/lgpl.html
+ (See Appendix B)
+
+ - Mozilla Public License Version 1.1 or later (the "MPL")
+ http://www.mozilla.org/MPL/MPL-1.1.html
+ (See Appendix C)
+
+You are not required to, but if you want to explicitly declare the
+license you have chosen to be bound to when using, reproducing,
+modifying and distributing this software, just include a text file
+titled "legal.txt" in your version of this software, indicating your
+license choice. In any case, your choice will not restrict any
+recipient of your version of this software to use, reproduce, modify
+and distribute this software under any of the above licenses.
+
+Sources of Intellectual Property Included in CKEditor
+-----------------------------------------------------
+
+Where not otherwise indicated, all CKEditor content is authored by
+CKSource engineers and consists of CKSource-owned intellectual
+property. In some specific instances, CKEditor will incorporate work
+done by developers outside of CKSource with their express permission.
+
+Trademarks
+----------
+
+CKEditor is a trademark of CKSource - Frederico Knabben. All other brand
+and product names are trademarks, registered trademarks or service
+marks of their respective holders.
+
+---
+
+Appendix A: The GPL License
+---------------------------
+
+GNU GENERAL PUBLIC LICENSE
+Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software-to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+GNU GENERAL PUBLIC LICENSE
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+END OF TERMS AND CONDITIONS
+
+
+Appendix B: The LGPL License
+----------------------------
+
+GNU LESSER GENERAL PUBLIC LICENSE
+Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software-to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages-typically libraries-of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+GNU LESSER GENERAL PUBLIC LICENSE
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+END OF TERMS AND CONDITIONS
+
+
+Appendix C: The MPL License
+---------------------------
+
+MOZILLA PUBLIC LICENSE
+Version 1.1
+
+1. Definitions.
+
+ 1.0.1. "Commercial Use" means distribution or otherwise making the
+ Covered Code available to a third party.
+
+ 1.1. "Contributor" means each entity that creates or contributes to
+ the creation of Modifications.
+
+ 1.2. "Contributor Version" means the combination of the Original
+ Code, prior Modifications used by a Contributor, and the Modifications
+ made by that particular Contributor.
+
+ 1.3. "Covered Code" means the Original Code or Modifications or the
+ combination of the Original Code and Modifications, in each case
+ including portions thereof.
+
+ 1.4. "Electronic Distribution Mechanism" means a mechanism generally
+ accepted in the software development community for the electronic
+ transfer of data.
+
+ 1.5. "Executable" means Covered Code in any form other than Source
+ Code.
+
+ 1.6. "Initial Developer" means the individual or entity identified
+ as the Initial Developer in the Source Code notice required by Exhibit
+ A.
+
+ 1.7. "Larger Work" means a work which combines Covered Code or
+ portions thereof with code not governed by the terms of this License.
+
+ 1.8. "License" means this document.
+
+ 1.8.1. "Licensable" means having the right to grant, to the maximum
+ extent possible, whether at the time of the initial grant or
+ subsequently acquired, any and all of the rights conveyed herein.
+
+ 1.9. "Modifications" means any addition to or deletion from the
+ substance or structure of either the Original Code or any previous
+ Modifications. When Covered Code is released as a series of files, a
+ Modification is:
+ A. Any addition to or deletion from the contents of a file
+ containing Original Code or previous Modifications.
+
+ B. Any new file that contains any part of the Original Code or
+ previous Modifications.
+
+ 1.10. "Original Code" means Source Code of computer software code
+ which is described in the Source Code notice required by Exhibit A as
+ Original Code, and which, at the time of its release under this
+ License is not already Covered Code governed by this License.
+
+ 1.10.1. "Patent Claims" means any patent claim(s), now owned or
+ hereafter acquired, including without limitation, method, process,
+ and apparatus claims, in any patent Licensable by grantor.
+
+ 1.11. "Source Code" means the preferred form of the Covered Code for
+ making modifications to it, including all modules it contains, plus
+ any associated interface definition files, scripts used to control
+ compilation and installation of an Executable, or source code
+ differential comparisons against either the Original Code or another
+ well known, available Covered Code of the Contributor's choice. The
+ Source Code can be in a compressed or archival form, provided the
+ appropriate decompression or de-archiving software is widely available
+ for no charge.
+
+ 1.12. "You" (or "Your") means an individual or a legal entity
+ exercising rights under, and complying with all of the terms of, this
+ License or a future version of this License issued under Section 6.1.
+ For legal entities, "You" includes any entity which controls, is
+ controlled by, or is under common control with You. For purposes of
+ this definition, "control" means (a) the power, direct or indirect,
+ to cause the direction or management of such entity, whether by
+ contract or otherwise, or (b) ownership of more than fifty percent
+ (50%) of the outstanding shares or beneficial ownership of such
+ entity.
+
+2. Source Code License.
+
+ 2.1. The Initial Developer Grant.
+ The Initial Developer hereby grants You a world-wide, royalty-free,
+ non-exclusive license, subject to third party intellectual property
+ claims:
+ (a) under intellectual property rights (other than patent or
+ trademark) Licensable by Initial Developer to use, reproduce,
+ modify, display, perform, sublicense and distribute the Original
+ Code (or portions thereof) with or without Modifications, and/or
+ as part of a Larger Work; and
+
+ (b) under Patents Claims infringed by the making, using or
+ selling of Original Code, to make, have made, use, practice,
+ sell, and offer for sale, and/or otherwise dispose of the
+ Original Code (or portions thereof).
+
+ (c) the licenses granted in this Section 2.1(a) and (b) are
+ effective on the date Initial Developer first distributes
+ Original Code under the terms of this License.
+
+ (d) Notwithstanding Section 2.1(b) above, no patent license is
+ granted: 1) for code that You delete from the Original Code; 2)
+ separate from the Original Code; or 3) for infringements caused
+ by: i) the modification of the Original Code or ii) the
+ combination of the Original Code with other software or devices.
+
+ 2.2. Contributor Grant.
+ Subject to third party intellectual property claims, each Contributor
+ hereby grants You a world-wide, royalty-free, non-exclusive license
+
+ (a) under intellectual property rights (other than patent or
+ trademark) Licensable by Contributor, to use, reproduce, modify,
+ display, perform, sublicense and distribute the Modifications
+ created by such Contributor (or portions thereof) either on an
+ unmodified basis, with other Modifications, as Covered Code
+ and/or as part of a Larger Work; and
+
+ (b) under Patent Claims infringed by the making, using, or
+ selling of Modifications made by that Contributor either alone
+ and/or in combination with its Contributor Version (or portions
+ of such combination), to make, use, sell, offer for sale, have
+ made, and/or otherwise dispose of: 1) Modifications made by that
+ Contributor (or portions thereof); and 2) the combination of
+ Modifications made by that Contributor with its Contributor
+ Version (or portions of such combination).
+
+ (c) the licenses granted in Sections 2.2(a) and 2.2(b) are
+ effective on the date Contributor first makes Commercial Use of
+ the Covered Code.
+
+ (d) Notwithstanding Section 2.2(b) above, no patent license is
+ granted: 1) for any code that Contributor has deleted from the
+ Contributor Version; 2) separate from the Contributor Version;
+ 3) for infringements caused by: i) third party modifications of
+ Contributor Version or ii) the combination of Modifications made
+ by that Contributor with other software (except as part of the
+ Contributor Version) or other devices; or 4) under Patent Claims
+ infringed by Covered Code in the absence of Modifications made by
+ that Contributor.
+
+3. Distribution Obligations.
+
+ 3.1. Application of License.
+ The Modifications which You create or to which You contribute are
+ governed by the terms of this License, including without limitation
+ Section 2.2. The Source Code version of Covered Code may be
+ distributed only under the terms of this License or a future version
+ of this License released under Section 6.1, and You must include a
+ copy of this License with every copy of the Source Code You
+ distribute. You may not offer or impose any terms on any Source Code
+ version that alters or restricts the applicable version of this
+ License or the recipients' rights hereunder. However, You may include
+ an additional document offering the additional rights described in
+ Section 3.5.
+
+ 3.2. Availability of Source Code.
+ Any Modification which You create or to which You contribute must be
+ made available in Source Code form under the terms of this License
+ either on the same media as an Executable version or via an accepted
+ Electronic Distribution Mechanism to anyone to whom you made an
+ Executable version available; and if made available via Electronic
+ Distribution Mechanism, must remain available for at least twelve (12)
+ months after the date it initially became available, or at least six
+ (6) months after a subsequent version of that particular Modification
+ has been made available to such recipients. You are responsible for
+ ensuring that the Source Code version remains available even if the
+ Electronic Distribution Mechanism is maintained by a third party.
+
+ 3.3. Description of Modifications.
+ You must cause all Covered Code to which You contribute to contain a
+ file documenting the changes You made to create that Covered Code and
+ the date of any change. You must include a prominent statement that
+ the Modification is derived, directly or indirectly, from Original
+ Code provided by the Initial Developer and including the name of the
+ Initial Developer in (a) the Source Code, and (b) in any notice in an
+ Executable version or related documentation in which You describe the
+ origin or ownership of the Covered Code.
+
+ 3.4. Intellectual Property Matters
+ (a) Third Party Claims.
+ If Contributor has knowledge that a license under a third party's
+ intellectual property rights is required to exercise the rights
+ granted by such Contributor under Sections 2.1 or 2.2,
+ Contributor must include a text file with the Source Code
+ distribution titled "LEGAL" which describes the claim and the
+ party making the claim in sufficient detail that a recipient will
+ know whom to contact. If Contributor obtains such knowledge after
+ the Modification is made available as described in Section 3.2,
+ Contributor shall promptly modify the LEGAL file in all copies
+ Contributor makes available thereafter and shall take other steps
+ (such as notifying appropriate mailing lists or newsgroups)
+ reasonably calculated to inform those who received the Covered
+ Code that new knowledge has been obtained.
+
+ (b) Contributor APIs.
+ If Contributor's Modifications include an application programming
+ interface and Contributor has knowledge of patent licenses which
+ are reasonably necessary to implement that API, Contributor must
+ also include this information in the LEGAL file.
+
+ (c) Representations.
+ Contributor represents that, except as disclosed pursuant to
+ Section 3.4(a) above, Contributor believes that Contributor's
+ Modifications are Contributor's original creation(s) and/or
+ Contributor has sufficient rights to grant the rights conveyed by
+ this License.
+
+ 3.5. Required Notices.
+ You must duplicate the notice in Exhibit A in each file of the Source
+ Code. If it is not possible to put such notice in a particular Source
+ Code file due to its structure, then You must include such notice in a
+ location (such as a relevant directory) where a user would be likely
+ to look for such a notice. If You created one or more Modification(s)
+ You may add your name as a Contributor to the notice described in
+ Exhibit A. You must also duplicate this License in any documentation
+ for the Source Code where You describe recipients' rights or ownership
+ rights relating to Covered Code. You may choose to offer, and to
+ charge a fee for, warranty, support, indemnity or liability
+ obligations to one or more recipients of Covered Code. However, You
+ may do so only on Your own behalf, and not on behalf of the Initial
+ Developer or any Contributor. You must make it absolutely clear than
+ any such warranty, support, indemnity or liability obligation is
+ offered by You alone, and You hereby agree to indemnify the Initial
+ Developer and every Contributor for any liability incurred by the
+ Initial Developer or such Contributor as a result of warranty,
+ support, indemnity or liability terms You offer.
+
+ 3.6. Distribution of Executable Versions.
+ You may distribute Covered Code in Executable form only if the
+ requirements of Section 3.1-3.5 have been met for that Covered Code,
+ and if You include a notice stating that the Source Code version of
+ the Covered Code is available under the terms of this License,
+ including a description of how and where You have fulfilled the
+ obligations of Section 3.2. The notice must be conspicuously included
+ in any notice in an Executable version, related documentation or
+ collateral in which You describe recipients' rights relating to the
+ Covered Code. You may distribute the Executable version of Covered
+ Code or ownership rights under a license of Your choice, which may
+ contain terms different from this License, provided that You are in
+ compliance with the terms of this License and that the license for the
+ Executable version does not attempt to limit or alter the recipient's
+ rights in the Source Code version from the rights set forth in this
+ License. If You distribute the Executable version under a different
+ license You must make it absolutely clear that any terms which differ
+ from this License are offered by You alone, not by the Initial
+ Developer or any Contributor. You hereby agree to indemnify the
+ Initial Developer and every Contributor for any liability incurred by
+ the Initial Developer or such Contributor as a result of any such
+ terms You offer.
+
+ 3.7. Larger Works.
+ You may create a Larger Work by combining Covered Code with other code
+ not governed by the terms of this License and distribute the Larger
+ Work as a single product. In such a case, You must make sure the
+ requirements of this License are fulfilled for the Covered Code.
+
+4. Inability to Comply Due to Statute or Regulation.
+
+ If it is impossible for You to comply with any of the terms of this
+ License with respect to some or all of the Covered Code due to
+ statute, judicial order, or regulation then You must: (a) comply with
+ the terms of this License to the maximum extent possible; and (b)
+ describe the limitations and the code they affect. Such description
+ must be included in the LEGAL file described in Section 3.4 and must
+ be included with all distributions of the Source Code. Except to the
+ extent prohibited by statute or regulation, such description must be
+ sufficiently detailed for a recipient of ordinary skill to be able to
+ understand it.
+
+5. Application of this License.
+
+ This License applies to code to which the Initial Developer has
+ attached the notice in Exhibit A and to related Covered Code.
+
+6. Versions of the License.
+
+ 6.1. New Versions.
+ Netscape Communications Corporation ("Netscape") may publish revised
+ and/or new versions of the License from time to time. Each version
+ will be given a distinguishing version number.
+
+ 6.2. Effect of New Versions.
+ Once Covered Code has been published under a particular version of the
+ License, You may always continue to use it under the terms of that
+ version. You may also choose to use such Covered Code under the terms
+ of any subsequent version of the License published by Netscape. No one
+ other than Netscape has the right to modify the terms applicable to
+ Covered Code created under this License.
+
+ 6.3. Derivative Works.
+ If You create or use a modified version of this License (which you may
+ only do in order to apply it to code which is not already Covered Code
+ governed by this License), You must (a) rename Your license so that
+ the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape",
+ "MPL", "NPL" or any confusingly similar phrase do not appear in your
+ license (except to note that your license differs from this License)
+ and (b) otherwise make it clear that Your version of the license
+ contains terms which differ from the Mozilla Public License and
+ Netscape Public License. (Filling in the name of the Initial
+ Developer, Original Code or Contributor in the notice described in
+ Exhibit A shall not of themselves be deemed to be modifications of
+ this License.)
+
+7. DISCLAIMER OF WARRANTY.
+
+ COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
+ WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF
+ DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING.
+ THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE
+ IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT,
+ YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE
+ COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER
+ OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF
+ ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
+
+8. TERMINATION.
+
+ 8.1. This License and the rights granted hereunder will terminate
+ automatically if You fail to comply with terms herein and fail to cure
+ such breach within 30 days of becoming aware of the breach. All
+ sublicenses to the Covered Code which are properly granted shall
+ survive any termination of this License. Provisions which, by their
+ nature, must remain in effect beyond the termination of this License
+ shall survive.
+
+ 8.2. If You initiate litigation by asserting a patent infringement
+ claim (excluding declatory judgment actions) against Initial Developer
+ or a Contributor (the Initial Developer or Contributor against whom
+ You file such action is referred to as "Participant") alleging that:
+
+ (a) such Participant's Contributor Version directly or indirectly
+ infringes any patent, then any and all rights granted by such
+ Participant to You under Sections 2.1 and/or 2.2 of this License
+ shall, upon 60 days notice from Participant terminate prospectively,
+ unless if within 60 days after receipt of notice You either: (i)
+ agree in writing to pay Participant a mutually agreeable reasonable
+ royalty for Your past and future use of Modifications made by such
+ Participant, or (ii) withdraw Your litigation claim with respect to
+ the Contributor Version against such Participant. If within 60 days
+ of notice, a reasonable royalty and payment arrangement are not
+ mutually agreed upon in writing by the parties or the litigation claim
+ is not withdrawn, the rights granted by Participant to You under
+ Sections 2.1 and/or 2.2 automatically terminate at the expiration of
+ the 60 day notice period specified above.
+
+ (b) any software, hardware, or device, other than such Participant's
+ Contributor Version, directly or indirectly infringes any patent, then
+ any rights granted to You by such Participant under Sections 2.1(b)
+ and 2.2(b) are revoked effective as of the date You first made, used,
+ sold, distributed, or had made, Modifications made by that
+ Participant.
+
+ 8.3. If You assert a patent infringement claim against Participant
+ alleging that such Participant's Contributor Version directly or
+ indirectly infringes any patent where such claim is resolved (such as
+ by license or settlement) prior to the initiation of patent
+ infringement litigation, then the reasonable value of the licenses
+ granted by such Participant under Sections 2.1 or 2.2 shall be taken
+ into account in determining the amount or value of any payment or
+ license.
+
+ 8.4. In the event of termination under Sections 8.1 or 8.2 above,
+ all end user license agreements (excluding distributors and resellers)
+ which have been validly granted by You or any distributor hereunder
+ prior to termination shall survive termination.
+
+9. LIMITATION OF LIABILITY.
+
+ UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
+ (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL
+ DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE,
+ OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR
+ ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY
+ CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL,
+ WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
+ COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
+ INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF
+ LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY
+ RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW
+ PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE
+ EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO
+ THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
+
+10. U.S. GOVERNMENT END USERS.
+
+ The Covered Code is a "commercial item," as that term is defined in
+ 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer
+ software" and "commercial computer software documentation," as such
+ terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48
+ C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995),
+ all U.S. Government End Users acquire Covered Code with only those
+ rights set forth herein.
+
+11. MISCELLANEOUS.
+
+ This License represents the complete agreement concerning subject
+ matter hereof. If any provision of this License is held to be
+ unenforceable, such provision shall be reformed only to the extent
+ necessary to make it enforceable. This License shall be governed by
+ California law provisions (except to the extent applicable law, if
+ any, provides otherwise), excluding its conflict-of-law provisions.
+ With respect to disputes in which at least one party is a citizen of,
+ or an entity chartered or registered to do business in the United
+ States of America, any litigation relating to this License shall be
+ subject to the jurisdiction of the Federal Courts of the Northern
+ District of California, with venue lying in Santa Clara County,
+ California, with the losing party responsible for costs, including
+ without limitation, court costs and reasonable attorneys' fees and
+ expenses. The application of the United Nations Convention on
+ Contracts for the International Sale of Goods is expressly excluded.
+ Any law or regulation which provides that the language of a contract
+ shall be construed against the drafter shall not apply to this
+ License.
+
+12. RESPONSIBILITY FOR CLAIMS.
+
+ As between Initial Developer and the Contributors, each party is
+ responsible for claims and damages arising, directly or indirectly,
+ out of its utilization of rights under this License and You agree to
+ work with Initial Developer and Contributors to distribute such
+ responsibility on an equitable basis. Nothing herein is intended or
+ shall be deemed to constitute any admission of liability.
+
+13. MULTIPLE-LICENSED CODE.
+
+ Initial Developer may designate portions of the Covered Code as
+ "Multiple-Licensed". "Multiple-Licensed" means that the Initial
+ Developer permits you to utilize portions of the Covered Code under
+ Your choice of the NPL or the alternative licenses, if any, specified
+ by the Initial Developer in the file described in Exhibit A.
+
+EXHIBIT A -Mozilla Public License.
+
+ ``The contents of this file are subject to the Mozilla Public License
+ Version 1.1 (the "License"); you may not use this file except in
+ compliance with the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS"
+ basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ License for the specific language governing rights and limitations
+ under the License.
+
+ The Original Code is ______________________________________.
+
+ The Initial Developer of the Original Code is ________________________.
+ Portions created by ______________________ are Copyright (C) ______
+ _______________________. All Rights Reserved.
+
+ Contributor(s): ______________________________________.
+
+ Alternatively, the contents of this file may be used under the terms
+ of the _____ license (the "[___] License"), in which case the
+ provisions of [______] License are applicable instead of those
+ above. If you wish to allow use of your version of this file only
+ under the terms of the [____] License and not to allow others to use
+ your version of this file under the MPL, indicate your decision by
+ deleting the provisions above and replace them with the notice and
+ other provisions required by the [___] License. If you do not delete
+ the provisions above, a recipient may use your version of this file
+ under either the MPL or the [___] License."
+
+ [NOTE: The text of this Exhibit A may differ slightly from the text of
+ the notices in the Source Code files of the Original Code. You should
+ use the text of this Exhibit A rather than the text found in the
+ Original Code Source Code for Your Modifications.]
diff --git a/.svn/pristine/04/0415b87f32852030c9c508b4a90ca8ed8ff3f60e.svn-base b/.svn/pristine/04/0415b87f32852030c9c508b4a90ca8ed8ff3f60e.svn-base
new file mode 100644
index 0000000..2ce0e49
Binary files /dev/null and b/.svn/pristine/04/0415b87f32852030c9c508b4a90ca8ed8ff3f60e.svn-base differ
diff --git a/.svn/pristine/04/0466eab062e9d1a3ce2c4631b6d09b5e5c0cbd1b.svn-base b/.svn/pristine/04/0466eab062e9d1a3ce2c4631b6d09b5e5c0cbd1b.svn-base
new file mode 100644
index 0000000..63a8a06
Binary files /dev/null and b/.svn/pristine/04/0466eab062e9d1a3ce2c4631b6d09b5e5c0cbd1b.svn-base differ
diff --git a/.svn/pristine/04/0469b430cd1567145ba800b22537588be2d1934d.svn-base b/.svn/pristine/04/0469b430cd1567145ba800b22537588be2d1934d.svn-base
new file mode 100644
index 0000000..0c90eb5
--- /dev/null
+++ b/.svn/pristine/04/0469b430cd1567145ba800b22537588be2d1934d.svn-base
@@ -0,0 +1,16 @@
+// Bordered & Pulled
+// -------------------------
+
+.@{fa-css-prefix}-border {
+ padding: .2em .25em .15em;
+ border: solid .08em @fa-border-color;
+ border-radius: .1em;
+}
+
+.pull-right { float: right; }
+.pull-left { float: left; }
+
+.@{fa-css-prefix} {
+ &.pull-left { margin-right: .3em; }
+ &.pull-right { margin-left: .3em; }
+}
diff --git a/.svn/pristine/04/04dd26fc5bcc0b877dd56c5f7d77ab073d11cf93.svn-base b/.svn/pristine/04/04dd26fc5bcc0b877dd56c5f7d77ab073d11cf93.svn-base
new file mode 100644
index 0000000..6ee751d
--- /dev/null
+++ b/.svn/pristine/04/04dd26fc5bcc0b877dd56c5f7d77ab073d11cf93.svn-base
@@ -0,0 +1,480 @@
+package th.co.muangthai.endrprint.controller.service;
+
+import org.apache.log4j.Logger;
+import org.springframework.beans.BeanUtils;
+import th.co.muangthai.endrprint.controller.AbstractMasterController;
+import th.co.muangthai.endrprint.model.bean.form.MsgErrorForm;
+import th.co.muangthai.endrprint.model.bean.form.data.PrinterDataTxtForm;
+import th.co.muangthai.endrprint.model.bean.form.data.PrintingDataForm;
+import th.co.muangthai.endrprint.model.bean.master.EndrUserLoginBean;
+import th.co.muangthai.endrprint.model.bean.tmp.EndrTmpDataPrintBean;
+import th.co.muangthai.endrprint.util.DateUtil;
+import th.co.muangthai.endrprint.util.SessionUtil;
+import th.co.muangthai.endrprint.util.TextContent;
+import th.co.muangthai.endrprint.controller.service.ftp.FTPUtil;
+
+import th.co.muangthai.endrprint.util.VSMUtil;
+
+import javax.servlet.http.HttpServletRequest;
+import java.io.*;
+import java.io.File;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * Service Controller For ENDR001Controller
+ */
+public class ENDR001Service extends AbstractMasterController {
+ private Logger log = Logger.getLogger(ENDR001Service.class);
+
+ FTPUtil ftpService = new FTPUtil();
+
+ /**
+ * Insert ENDR data to temp and update data
+ * Save ENDR data to .dat file and transfer text file to server by ftp process
+ * Delete text file when transfer text file is complete
+ * @param request
+ * @param lstPrintingData - list of ENDR Print data
+ * @param serverId - Id of printer
+ * @return Object[] results
+ */
+ public Object[] insertOrUpdateData(HttpServletRequest request ,List lstPrintingData ,BigDecimal serverId ,BigDecimal sType){
+
+ Object[] obj = new Object[1];
+ MsgErrorForm msgErrorForm = new MsgErrorForm();
+ msgErrorForm.setErrorFlag(getBigDecimal("0"));
+ msgErrorForm.setErrorDesc("Save successful");
+ obj[0] = msgErrorForm;
+
+ List printerDataTxtFormList = new ArrayList();
+
+ try {
+ EndrUserLoginBean loginForm = getUerLoginBean(request);
+ Date dateSave = new Date();
+
+ List endrTmpDataPrintList = new ArrayList();
+ EndrTmpDataPrintBean endrTmpDataPrintForm = new EndrTmpDataPrintBean();
+
+ String processId = DateUtil.toFormatString(new Date(), "ddMMyyyyHHmmss");
+
+ if (VSMUtil.isNotEmptyLst(lstPrintingData) && lstPrintingData.size()>0){
+ for (int i = 0 ; i< lstPrintingData.size() ; i++){
+ PrintingDataForm printingDataFormSet = new PrintingDataForm();
+ BeanUtils.copyProperties(lstPrintingData.get(i), printingDataFormSet);
+
+ endrTmpDataPrintForm = new EndrTmpDataPrintBean();
+ endrTmpDataPrintForm.setProcessId(processId);
+ endrTmpDataPrintForm.setTaskId(printingDataFormSet.getTaskId());
+ endrTmpDataPrintForm.setUserId(loginForm.getUserId());
+ endrTmpDataPrintForm.setServerId(serverId);
+
+ endrTmpDataPrintForm.setCreateBy(loginForm.getUserId());
+ endrTmpDataPrintForm.setCreateDate(dateSave);
+ endrTmpDataPrintForm.setUpdateBy(loginForm.getUserId());
+ endrTmpDataPrintForm.setUpdateDate(dateSave);
+
+ endrTmpDataPrintList.add(endrTmpDataPrintForm);
+ }
+ }
+ log.info("endrTmpDataPrintList size --> "+endrTmpDataPrintList.size());
+ log.info("processId --> "+processId);
+ boolean f = commonService.insertEndrTmpDataPrint(endrTmpDataPrintList);
+
+ if(!f){
+ msgErrorForm.setErrorFlag(getBigDecimal("1"));
+ msgErrorForm.setErrorDesc("Save error!!!");
+ }else{
+
+ //////////////////////////////////////////////////
+ // search data
+ printerDataTxtFormList = new ArrayList();
+ printerDataTxtFormList = commonService.searchPrinterDataTxtFormPkg(processId ,sType);
+ log.info("printerDataTxtFormList size --> "+printerDataTxtFormList.size());
+ if (VSMUtil.isNotEmptyLst(printerDataTxtFormList)){
+
+ List printerDataTxtFormListWrite = new ArrayList();
+ List printerDataTxtList = new ArrayList();
+ PrinterDataTxtForm form = null;
+
+ for (int i=0; i();
+ form = new PrinterDataTxtForm();
+ form = printerDataTxtFormList.get(i);
+ printerDataTxtList.add(form);
+ form.setPrinterDataTxtLst(printerDataTxtList);
+ printerDataTxtFormListWrite.add(form);
+ }else {
+ if (printerDataTxtFormList.size() > i+1){
+ if (VSMUtil.isNotEmpty(printerDataTxtFormList.get(i).getDatJob())){
+ if (printerDataTxtFormList.get(i).getDatJob().equals(printerDataTxtFormList.get(i+1).getDatJob())){
+
+ }else {
+
+ form = new PrinterDataTxtForm();
+ form = printerDataTxtFormList.get(i);
+ //printerDataTxtList.add(form);
+
+ printerDataTxtList = new ArrayList();
+ for (int j=0; j();
+ for (int j=0; j0){
+ List lst = new ArrayList();
+ for (PrinterDataTxtForm data : printerDataTxtFormListWrite){
+ lst = new ArrayList();
+ lst = data.getPrinterDataTxtLst();
+
+ //////////////////////////////////////////////////
+ // write text file
+ //Object[] objWriteTxt = writeTxtFile(printerDataTxtFormList ,request);
+ Object[] objWriteTxt = writeTxtFile(lst ,request);
+ msgErrorForm = (MsgErrorForm)objWriteTxt[0];
+ String filePath = (String)objWriteTxt[1];
+ PrinterDataTxtForm dataSetting = (PrinterDataTxtForm)objWriteTxt[2];
+
+ if (getBigDecimal("0").equals(msgErrorForm.getErrorFlag())){
+
+ String hostname = ""; // ip address
+ if (VSMUtil.IP_ADDR_PRINTER_PRO){
+ // ipAddrProduction
+ hostname = dataSetting.getIpAddrProd();
+ }else {
+ // ipAddrUAT
+ hostname = dataSetting.getIpAddrUat(); //"10.22.145.154";
+ }
+
+ int port = 21; //port
+ String username = dataSetting.getFtpUsername(); // "Thawarom-BSD";
+ String password = dataSetting.getFtpPassword(); // "kireida";
+
+ String fileName = dataSetting.getDatJob()+".dat"; //fileName.dat
+ String ftpDirectory = dataSetting.getFtpDirectory(); // directoryName
+
+ //////////////////////////////////////////////////
+ // ftp file upload
+ Object[] objFtpUpload = ftpUploadFile(hostname ,port ,username ,password ,filePath ,fileName ,ftpDirectory);
+ msgErrorForm = (MsgErrorForm)objFtpUpload[0];
+ if (getBigDecimal("0").equals(msgErrorForm.getErrorFlag())){
+ msgErrorForm.setErrorDesc("Process successful");
+ }
+
+ String ftpDirectoryTmp = SessionUtil.getPathFile("100001");
+ if (VSMUtil.isNotEmpty(ftpDirectoryTmp)){
+
+ Object[] objFtpUploadTmp = ftpUploadFile(hostname ,port ,username ,password ,filePath ,fileName ,ftpDirectory+ftpDirectoryTmp);
+ //msgErrorForm = (MsgErrorForm)objFtpUploadTmp[0];
+ //if (getBigDecimal("0").equals(msgErrorForm.getErrorFlag())){
+ // msgErrorForm.setErrorDesc("Process successful");
+ //}
+ }
+
+
+ //if (getBigDecimal("0").equals(msgErrorForm.getErrorFlag())){
+ //
+ // //////////////////////////////////////////////////
+ // // delete source file when upload file is successful
+ // Object[] objDeleteFile = deleteTxtFile(filePath);
+ // msgErrorForm = (MsgErrorForm)objDeleteFile[0];
+ // if (getBigDecimal("0").equals(msgErrorForm.getErrorFlag())){
+ // msgErrorForm.setErrorDesc("Process successful");
+ // }
+ //}
+ }
+ }
+ }
+
+ boolean s = commonService.updateFinishFtp(processId ,sType);
+
+ //if (!s){
+
+ //}
+
+ }else{
+ msgErrorForm.setErrorFlag(getBigDecimal("1"));
+ msgErrorForm.setErrorDesc("No data found");
+ }
+ }
+
+ }catch (Exception e){
+ msgErrorForm.setErrorFlag(getBigDecimal("1"));
+ msgErrorForm.setErrorDesc("Data not found ,Invalid team");
+ log.error(e.toString(), e);
+ }
+ obj[0] = msgErrorForm;
+ return obj;
+ }
+
+ /**
+ * Write/Save .dat file
+ * @param printerDataTxtFormList - list of ENDR Print data
+ * @return Object[] results
+ */
+ public Object[] writeTxtFile(List printerDataTxtFormList ,HttpServletRequest request){
+
+ Object[] obj = new Object[3];
+ MsgErrorForm msgErrorForm = new MsgErrorForm();
+ msgErrorForm.setErrorFlag(getBigDecimal("0"));
+ msgErrorForm.setErrorDesc("Save successful");
+ obj[0] = msgErrorForm;
+
+ String filePath = "";
+ //String filePathTest = SessionUtil.getPathFile("100000");
+ PrinterDataTxtForm dataSetting = new PrinterDataTxtForm();
+
+ try {
+ EndrUserLoginBean loginForm = getUerLoginBean(request);
+
+ if (printerDataTxtFormList.size()>0){
+ for (PrinterDataTxtForm dataSet : printerDataTxtFormList){
+ dataSetting = new PrinterDataTxtForm();
+ dataSetting = dataSet;
+ //String a = SessionUtil.getPathFile("100000").substring(SessionUtil.getPathFile("100000").length()-1,SessionUtil.getPathFile("100000").length());
+ //String b = (dataSetting.getDatJob()+".dat").substring(0,1);
+ filePath = SessionUtil.getPathFile("100000")+dataSetting.getDatJob()+".dat"; //"D://txt/"+dataSet.getDatJob()+".dat"; //filePath = dataSet.getDatJob();
+ break;
+ }
+ }
+
+ log.info("writing file to "+filePath+" start ...");
+ log.info("writing file by "+loginForm.getUserId());
+ if (VSMUtil.isNotEmpty(dataSetting.getDatJob())){
+
+ File createPath = new File(SessionUtil.getPathFile("100000"));
+ if (!createPath.exists()){
+ createPath.mkdir();
+ }
+// BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath) ,"UTF-8"));
+ BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath),"TIS-620")); //
+// BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath) ,"MS-874"));
+
+
+ if (printerDataTxtFormList.size()>0){
+ for (int i=0; i lstPrintingData ,BigDecimal serverId ,BigDecimal sType){
+
+ Object[] obj = new Object[1];
+ MsgErrorForm msgErrorForm = new MsgErrorForm();
+ msgErrorForm.setErrorFlag(getBigDecimal("0"));
+ msgErrorForm.setErrorDesc("Save successful");
+ obj[0] = msgErrorForm;
+
+ try {
+ EndrUserLoginBean loginForm = getUerLoginBean(request);
+ Date dateSave = new Date();
+
+ List endrTmpDataPrintList = new ArrayList();
+ EndrTmpDataPrintBean endrTmpDataPrintForm = new EndrTmpDataPrintBean();
+
+ //String processId = DateUtil.toFormatString(new Date(), "ddMMyyyyHHmmss");
+ String processId = new Date().getTime()+"";
+
+ if (VSMUtil.isNotEmptyLst(lstPrintingData) && lstPrintingData.size()>0){
+ for (int i = 0 ; i< lstPrintingData.size() ; i++){
+ PrintingDataForm printingDataFormSet = new PrintingDataForm();
+ BeanUtils.copyProperties(lstPrintingData.get(i), printingDataFormSet);
+
+ endrTmpDataPrintForm = new EndrTmpDataPrintBean();
+ endrTmpDataPrintForm.setProcessId(processId);
+ endrTmpDataPrintForm.setTaskId(printingDataFormSet.getTaskId());
+ endrTmpDataPrintForm.setUserId(loginForm.getUserId());
+ endrTmpDataPrintForm.setServerId(serverId);
+
+ endrTmpDataPrintForm.setCreateBy(loginForm.getUserId());
+ endrTmpDataPrintForm.setCreateDate(dateSave);
+ endrTmpDataPrintForm.setUpdateBy(loginForm.getUserId());
+ endrTmpDataPrintForm.setUpdateDate(dateSave);
+
+ endrTmpDataPrintList.add(endrTmpDataPrintForm);
+ }
+ }
+
+ boolean f = commonService.insertEndrTmpDataPrint(endrTmpDataPrintList);
+
+ if(!f){
+ msgErrorForm.setErrorFlag(getBigDecimal("1"));
+ msgErrorForm.setErrorDesc("Save error!!!");
+ }else{
+
+ boolean s = commonService.updateReject(processId ,sType);
+
+ //if (!s){
+ //}
+ }
+
+ }catch (Exception e){
+ msgErrorForm.setErrorFlag(getBigDecimal("1"));
+ msgErrorForm.setErrorDesc("Data not found");
+ log.error(e.toString(), e);
+ }
+ obj[0] = msgErrorForm;
+ return obj;
+ }
+}
\ No newline at end of file
diff --git a/.svn/pristine/05/0500d39b0ca8eb50860d373a98866507bc24db10.svn-base b/.svn/pristine/05/0500d39b0ca8eb50860d373a98866507bc24db10.svn-base
new file mode 100644
index 0000000..97369b0
--- /dev/null
+++ b/.svn/pristine/05/0500d39b0ca8eb50860d373a98866507bc24db10.svn-base
@@ -0,0 +1,59 @@
+.spinner {
+ display: inline-block;
+ white-space: nowrap;
+ margin: 0;
+ padding: 0;
+ border-width: 1px;
+ border-style: solid;
+ overflow: hidden;
+ vertical-align: middle;
+}
+.spinner .spinner-text {
+ font-size: 12px;
+ border: 0px;
+ line-height: 20px;
+ height: 20px;
+ margin: 0;
+ padding: 0 2px;
+ *margin-top: -1px;
+ *height: 18px;
+ *line-height: 18px;
+ _height: 18px;
+ _line-height: 18px;
+ vertical-align: baseline;
+}
+.spinner-arrow {
+ display: inline-block;
+ overflow: hidden;
+ vertical-align: top;
+ margin: 0;
+ padding: 0;
+}
+.spinner-arrow-up,
+.spinner-arrow-down {
+ opacity: 0.6;
+ filter: alpha(opacity=60);
+ display: block;
+ font-size: 1px;
+ width: 18px;
+ height: 10px;
+}
+.spinner-arrow-hover {
+ opacity: 1.0;
+ filter: alpha(opacity=100);
+}
+.spinner-arrow-up {
+ background: url('images/spinner_arrows.png') no-repeat 1px center;
+}
+.spinner-arrow-down {
+ background: url('images/spinner_arrows.png') no-repeat -15px center;
+}
+.spinner {
+ border-color: #D4D4D4;
+}
+.spinner-arrow {
+ background-color: #F2F2F2;
+}
+.spinner-arrow-hover {
+ background-color: #e6e6e6;
+}
diff --git a/.svn/pristine/05/0511abe9863c2ea7084efa7e24d1d86c5b3974f1.svn-base b/.svn/pristine/05/0511abe9863c2ea7084efa7e24d1d86c5b3974f1.svn-base
new file mode 100644
index 0000000..da41706
--- /dev/null
+++ b/.svn/pristine/05/0511abe9863c2ea7084efa7e24d1d86c5b3974f1.svn-base
@@ -0,0 +1,6 @@
+/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
+//@ sourceMappingURL=jquery-1.10.2.min.map
+*/
+(function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML="
a",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "SearchPolicyDetailAdapterOutputCollection", propOrder = {
+ "searchPolicyDetailAdapterOutput"
+})
+public class SearchPolicyDetailAdapterOutputCollection {
+
+ @XmlElement(name = "SearchPolicyDetailAdapterOutput")
+ protected List searchPolicyDetailAdapterOutput;
+
+ /**
+ * Gets the value of the searchPolicyDetailAdapterOutput property.
+ *
+ *
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a set method for the searchPolicyDetailAdapterOutput property.
+ *
+ *
+ * For example, to add a new item, do as follows:
+ *
+ * Objects of the following type(s) are allowed in the list
+ * {@link SearchPolicyDetailAdapterOutput }
+ *
+ *
+ */
+ public List getSearchPolicyDetailAdapterOutput() {
+ if (searchPolicyDetailAdapterOutput == null) {
+ searchPolicyDetailAdapterOutput = new ArrayList();
+ }
+ return this.searchPolicyDetailAdapterOutput;
+ }
+
+}
diff --git a/.svn/pristine/06/061a8ca1b6f2e088e3ebfb052772b3ff930ddd74.svn-base b/.svn/pristine/06/061a8ca1b6f2e088e3ebfb052772b3ff930ddd74.svn-base
new file mode 100644
index 0000000..72eb423
--- /dev/null
+++ b/.svn/pristine/06/061a8ca1b6f2e088e3ebfb052772b3ff930ddd74.svn-base
@@ -0,0 +1,24 @@
+.combobox-item,
+.combobox-group {
+ font-size: 12px;
+ padding: 3px;
+ padding-right: 0px;
+}
+.combobox-item-disabled {
+ opacity: 0.5;
+ filter: alpha(opacity=50);
+}
+.combobox-gitem {
+ padding-left: 10px;
+}
+.combobox-group {
+ font-weight: bold;
+}
+.combobox-item-hover {
+ background-color: #eaf2ff;
+ color: #000000;
+}
+.combobox-item-selected {
+ background-color: #ffe48d;
+ color: #000000;
+}
diff --git a/.svn/pristine/06/06d12928acdf3bd3f0126be0f21e16f6820a35a7.svn-base b/.svn/pristine/06/06d12928acdf3bd3f0126be0f21e16f6820a35a7.svn-base
new file mode 100644
index 0000000..68d1125
--- /dev/null
+++ b/.svn/pristine/06/06d12928acdf3bd3f0126be0f21e16f6820a35a7.svn-base
@@ -0,0 +1,74 @@
+
+input[type="text"],
+input[type="password"],
+textarea,
+textarea.form-control {
+ height: 50px;
+ margin: 0;
+ padding: 0 20px;
+ vertical-align: middle;
+ background: #f8f8f8;
+ border: 3px solid #ddd;
+ font-family: 'Roboto', sans-serif;
+ font-size: 16px;
+ font-weight: 300;
+ line-height: 50px;
+ color: #888;
+ -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px;
+ -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none;
+ -o-transition: all .3s; -moz-transition: all .3s; -webkit-transition: all .3s; -ms-transition: all .3s; transition: all .3s;
+}
+
+textarea,
+textarea.form-control {
+ padding-top: 10px;
+ padding-bottom: 10px;
+ line-height: 30px;
+}
+
+input[type="text"]:focus,
+input[type="password"]:focus,
+textarea:focus,
+textarea.form-control:focus {
+ outline: 0;
+ background: #fff;
+ border: 3px solid #ccc;
+ -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none;
+}
+
+input[type="text"]:-moz-placeholder, input[type="password"]:-moz-placeholder,
+textarea:-moz-placeholder, textarea.form-control:-moz-placeholder { color: #888; }
+
+input[type="text"]:-ms-input-placeholder, input[type="password"]:-ms-input-placeholder,
+textarea:-ms-input-placeholder, textarea.form-control:-ms-input-placeholder { color: #888; }
+
+input[type="text"]::-webkit-input-placeholder, input[type="password"]::-webkit-input-placeholder,
+textarea::-webkit-input-placeholder, textarea.form-control::-webkit-input-placeholder { color: #888; }
+
+
+
+button.btn {
+ height: 50px;
+ margin: 0;
+ padding: 0 20px;
+ vertical-align: middle;
+ background: #4aaf51;
+ border: 0;
+ font-family: 'Roboto', sans-serif;
+ font-size: 16px;
+ font-weight: 300;
+ line-height: 50px;
+ color: #fff;
+ -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px;
+ text-shadow: none;
+ -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none;
+ -o-transition: all .3s; -moz-transition: all .3s; -webkit-transition: all .3s; -ms-transition: all .3s; transition: all .3s;
+}
+
+button.btn:hover { opacity: 0.6; color: #fff; }
+
+button.btn:active { outline: 0; opacity: 0.6; color: #fff; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; }
+
+button.btn:focus { outline: 0; opacity: 0.6; background: #4aaf51; color: #fff; }
+
+button.btn:active:focus, button.btn.active:focus { outline: 0; opacity: 0.6; background: #4aaf51; color: #fff; }
diff --git a/.svn/pristine/07/07419031cfeaa5ed2ab824a59dbb0b2dcf4c5433.svn-base b/.svn/pristine/07/07419031cfeaa5ed2ab824a59dbb0b2dcf4c5433.svn-base
new file mode 100644
index 0000000..b30311a
--- /dev/null
+++ b/.svn/pristine/07/07419031cfeaa5ed2ab824a59dbb0b2dcf4c5433.svn-base
@@ -0,0 +1,260 @@
+.datagrid .panel-body {
+ overflow: hidden;
+ position: relative;
+}
+.datagrid-view {
+ position: relative;
+ overflow: hidden;
+}
+.datagrid-view1,
+.datagrid-view2 {
+ position: absolute;
+ overflow: hidden;
+ top: 0;
+}
+.datagrid-view1 {
+ left: 0;
+}
+.datagrid-view2 {
+ right: 0;
+}
+.datagrid-mask {
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ opacity: 0.3;
+ filter: alpha(opacity=30);
+ display: none;
+}
+.datagrid-mask-msg {
+ position: absolute;
+ top: 50%;
+ margin-top: -20px;
+ padding: 10px 5px 10px 30px;
+ width: auto;
+ height: 16px;
+ border-width: 2px;
+ border-style: solid;
+ display: none;
+}
+.datagrid-sort-icon {
+ padding: 0;
+}
+.datagrid-toolbar {
+ height: auto;
+ padding: 1px 2px;
+ border-width: 0 0 1px 0;
+ border-style: solid;
+}
+.datagrid-btn-separator {
+ float: left;
+ height: 24px;
+ border-left: 1px solid #ccc;
+ border-right: 1px solid #fff;
+ margin: 2px 1px;
+}
+.datagrid .datagrid-pager {
+ display: block;
+ margin: 0;
+ border-width: 1px 0 0 0;
+ border-style: solid;
+}
+.datagrid .datagrid-pager-top {
+ border-width: 0 0 1px 0;
+}
+.datagrid-header {
+ overflow: hidden;
+ cursor: default;
+ border-width: 0 0 1px 0;
+ border-style: solid;
+}
+.datagrid-header-inner {
+ float: left;
+ width: 10000px;
+}
+.datagrid-header-row,
+.datagrid-row {
+ height: 25px;
+}
+.datagrid-header td,
+.datagrid-body td,
+.datagrid-footer td {
+ border-width: 0 1px 1px 0;
+ border-style: dotted;
+ margin: 0;
+ padding: 0;
+}
+.datagrid-cell,
+.datagrid-cell-group,
+.datagrid-header-rownumber,
+.datagrid-cell-rownumber {
+ margin: 0;
+ padding: 0 4px;
+ white-space: nowrap;
+ word-wrap: normal;
+ overflow: hidden;
+ height: 18px;
+ line-height: 18px;
+ font-size: 12px;
+}
+.datagrid-header .datagrid-cell {
+ height: auto;
+}
+.datagrid-header .datagrid-cell span {
+ font-size: 12px;
+}
+.datagrid-cell-group {
+ text-align: center;
+}
+.datagrid-header-rownumber,
+.datagrid-cell-rownumber {
+ width: 25px;
+ text-align: center;
+ margin: 0;
+ padding: 0;
+}
+.datagrid-body {
+ margin: 0;
+ padding: 0;
+ overflow: auto;
+ zoom: 1;
+}
+.datagrid-view1 .datagrid-body-inner {
+ padding-bottom: 20px;
+}
+.datagrid-view1 .datagrid-body {
+ overflow: hidden;
+}
+.datagrid-footer {
+ overflow: hidden;
+}
+.datagrid-footer-inner {
+ border-width: 1px 0 0 0;
+ border-style: solid;
+ width: 10000px;
+ float: left;
+}
+.datagrid-row-editing .datagrid-cell {
+ height: auto;
+}
+.datagrid-header-check,
+.datagrid-cell-check {
+ padding: 0;
+ width: 27px;
+ height: 18px;
+ font-size: 1px;
+ text-align: center;
+ overflow: hidden;
+}
+.datagrid-header-check input,
+.datagrid-cell-check input {
+ margin: 0;
+ padding: 0;
+ width: 15px;
+ height: 18px;
+}
+.datagrid-resize-proxy {
+ position: absolute;
+ width: 1px;
+ height: 10000px;
+ top: 0;
+ cursor: e-resize;
+ display: none;
+}
+.datagrid-body .datagrid-editable {
+ margin: 0;
+ padding: 0;
+}
+.datagrid-body .datagrid-editable table {
+ width: 100%;
+ height: 100%;
+}
+.datagrid-body .datagrid-editable td {
+ border: 0;
+ margin: 0;
+ padding: 0;
+}
+.datagrid-body .datagrid-editable .datagrid-editable-input {
+ margin: 0;
+ padding: 2px;
+ border-width: 1px;
+ border-style: solid;
+}
+.datagrid-sort-desc .datagrid-sort-icon {
+ padding: 0 13px 0 0;
+ background: url('images/datagrid_icons.png') no-repeat -16px center;
+}
+.datagrid-sort-asc .datagrid-sort-icon {
+ padding: 0 13px 0 0;
+ background: url('images/datagrid_icons.png') no-repeat 0px center;
+}
+.datagrid-row-collapse {
+ background: url('images/datagrid_icons.png') no-repeat -48px center;
+}
+.datagrid-row-expand {
+ background: url('images/datagrid_icons.png') no-repeat -32px center;
+}
+.datagrid-mask-msg {
+ background: #ffffff url('images/loading.gif') no-repeat scroll 5px center;
+}
+.datagrid-header,
+.datagrid-td-rownumber {
+ background-color: #fafafa;
+ background: -webkit-linear-gradient(top,#fdfdfd 0,#f5f5f5 100%);
+ background: -moz-linear-gradient(top,#fdfdfd 0,#f5f5f5 100%);
+ background: -o-linear-gradient(top,#fdfdfd 0,#f5f5f5 100%);
+ background: linear-gradient(to bottom,#fdfdfd 0,#f5f5f5 100%);
+ background-repeat: repeat-x;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fdfdfd,endColorstr=#f5f5f5,GradientType=0);
+}
+.datagrid-cell-rownumber {
+ color: #000000;
+}
+.datagrid-resize-proxy {
+ background: #bfbfbf;
+}
+.datagrid-mask {
+ background: #ccc;
+}
+.datagrid-mask-msg {
+ border-color: #D3D3D3;
+}
+.datagrid-toolbar,
+.datagrid-pager {
+ background: #fafafa;
+}
+.datagrid-header,
+.datagrid-toolbar,
+.datagrid-pager,
+.datagrid-footer-inner {
+ border-color: #ddd;
+}
+.datagrid-header td,
+.datagrid-body td,
+.datagrid-footer td {
+ border-color: #ccc;
+}
+.datagrid-htable,
+.datagrid-btable,
+.datagrid-ftable {
+ color: #000000;
+ border-collapse: separate;
+}
+.datagrid-row-alt {
+ background: #fafafa;
+}
+.datagrid-row-over,
+.datagrid-header td.datagrid-header-over {
+ background: #e2e2e2;
+ color: #000000;
+ cursor: default;
+}
+.datagrid-row-selected {
+ background: #0092DC;
+ color: #fff;
+}
+.datagrid-body .datagrid-editable .datagrid-editable-input {
+ border-color: #D3D3D3;
+}
diff --git a/.svn/pristine/07/0759f6c11f515ee799814c43e4a50281220014ca.svn-base b/.svn/pristine/07/0759f6c11f515ee799814c43e4a50281220014ca.svn-base
new file mode 100644
index 0000000..693667a
Binary files /dev/null and b/.svn/pristine/07/0759f6c11f515ee799814c43e4a50281220014ca.svn-base differ
diff --git a/.svn/pristine/07/0773c36136a0ac43a84c8b43f53b49d46df2d80e.svn-base b/.svn/pristine/07/0773c36136a0ac43a84c8b43f53b49d46df2d80e.svn-base
new file mode 100644
index 0000000..f97761e
Binary files /dev/null and b/.svn/pristine/07/0773c36136a0ac43a84c8b43f53b49d46df2d80e.svn-base differ
diff --git a/.svn/pristine/07/0791a4b05a42874c8ca665412b7be496aa7d8444.svn-base b/.svn/pristine/07/0791a4b05a42874c8ca665412b7be496aa7d8444.svn-base
new file mode 100644
index 0000000..50d8ce8
--- /dev/null
+++ b/.svn/pristine/07/0791a4b05a42874c8ca665412b7be496aa7d8444.svn-base
@@ -0,0 +1,15 @@
+/*
+ AngularJS v1.2.19
+ (c) 2010-2014 Google, Inc. http://angularjs.org
+ License: MIT
+*/
+(function(p,h,q){'use strict';function E(a){var d=[];s(d,h.noop).chars(a);return d.join("")}function k(a){var d={};a=a.split(",");var b;for(b=0;b=b;e--)d.end&&d.end(f[e]);f.length=b}}var c,g,f=[],l=a;for(f.last=function(){return f[f.length-1]};a;){g=!0;if(f.last()&&x[f.last()])a=a.replace(RegExp("(.*)<\\s*\\/\\s*"+f.last()+"[^>]*>","i"),function(c,a){a=a.replace(H,"$1").replace(I,"$1");d.chars&&d.chars(r(a));return""}),e("",f.last());else{if(0===a.indexOf("\x3c!--"))c=a.indexOf("--",4),0<=c&&a.lastIndexOf("--\x3e",c)===c&&(d.comment&&d.comment(a.substring(4,c)),a=a.substring(c+3),g=!1);else if(y.test(a)){if(c=a.match(y))a=
+a.replace(c[0],""),g=!1}else if(J.test(a)){if(c=a.match(z))a=a.substring(c[0].length),c[0].replace(z,e),g=!1}else K.test(a)&&(c=a.match(A))&&(a=a.substring(c[0].length),c[0].replace(A,b),g=!1);g&&(c=a.indexOf("<"),g=0>c?a:a.substring(0,c),a=0>c?"":a.substring(c),d.chars&&d.chars(r(g)))}if(a==l)throw L("badparse",a);l=a}e()}function r(a){if(!a)return"";var d=M.exec(a);a=d[1];var b=d[3];if(d=d[2])n.innerHTML=d.replace(//g,">")}function s(a,d){var b=!1,e=h.bind(a,a.push);return{start:function(a,g,f){a=h.lowercase(a);!b&&x[a]&&(b=a);b||!0!==C[a]||(e("<"),e(a),h.forEach(g,function(b,f){var g=h.lowercase(f),k="img"===a&&"src"===g||"background"===g;!0!==P[g]||!0===D[g]&&!d(b,k)||(e(" "),e(f),e('="'),e(B(b)),e('"'))}),
+e(f?"/>":">"))},end:function(a){a=h.lowercase(a);b||!0!==C[a]||(e(""),e(a),e(">"));a==b&&(b=!1)},chars:function(a){b||e(B(a))}}}var L=h.$$minErr("$sanitize"),A=/^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,z=/^<\s*\/\s*([\w:-]+)[^>]*>/,G=/([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,K=/^,J=/^<\s*\//,H=/\x3c!--(.*?)--\x3e/g,y=/]*?)>/i,I=/]/,b=/^mailto:/;return function(e,c){function g(a){a&&m.push(E(a))}function f(a,b){m.push("');g(b);m.push("")}if(!e)return e;
+for(var l,k=e,m=[],n,p;l=k.match(d);)n=l[0],l[2]==l[3]&&(n="mailto:"+n),p=l.index,g(k.substr(0,p)),f(n,l[0].replace(b,"")),k=k.substring(p+l[0].length);g(k);return a(m.join(""))}}])})(window,window.angular);
+//# sourceMappingURL=angular-sanitize.min.js.map
diff --git a/.svn/pristine/07/07d66a7f953aae7962f7c71d4f5d62061e1244b5.svn-base b/.svn/pristine/07/07d66a7f953aae7962f7c71d4f5d62061e1244b5.svn-base
new file mode 100644
index 0000000..529e1b5
--- /dev/null
+++ b/.svn/pristine/07/07d66a7f953aae7962f7c71d4f5d62061e1244b5.svn-base
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/08/080158aeb1bf6df59ec98b2bbed44da61d9c9ca3.svn-base b/.svn/pristine/08/080158aeb1bf6df59ec98b2bbed44da61d9c9ca3.svn-base
new file mode 100644
index 0000000..bb457c2
--- /dev/null
+++ b/.svn/pristine/08/080158aeb1bf6df59ec98b2bbed44da61d9c9ca3.svn-base
@@ -0,0 +1,15 @@
+/* FONT PATH
+ * -------------------------- */
+
+@font-face {
+ font-family: 'FontAwesome';
+ src: url('#{$fa-font-path}/fontawesome-webfont.eot?v=#{$fa-version}');
+ src: url('#{$fa-font-path}/fontawesome-webfont.eot?#iefix&v=#{$fa-version}') format('embedded-opentype'),
+ url('#{$fa-font-path}/fontawesome-webfont.woff2?v=#{$fa-version}') format('woff2'),
+ url('#{$fa-font-path}/fontawesome-webfont.woff?v=#{$fa-version}') format('woff'),
+ url('#{$fa-font-path}/fontawesome-webfont.ttf?v=#{$fa-version}') format('truetype'),
+ url('#{$fa-font-path}/fontawesome-webfont.svg?v=#{$fa-version}#fontawesomeregular') format('svg');
+// src: url('#{$fa-font-path}/FontAwesome.otf') format('opentype'); // used when developing fonts
+ font-weight: normal;
+ font-style: normal;
+}
diff --git a/.svn/pristine/08/08125211bff3b12cb7f10080516fb23b7b4814ae.svn-base b/.svn/pristine/08/08125211bff3b12cb7f10080516fb23b7b4814ae.svn-base
new file mode 100644
index 0000000..7a48b33
--- /dev/null
+++ b/.svn/pristine/08/08125211bff3b12cb7f10080516fb23b7b4814ae.svn-base
@@ -0,0 +1,356 @@
+.tabs-container {
+ overflow: hidden;
+}
+.tabs-header {
+ border-width: 1px;
+ border-style: solid;
+ border-bottom-width: 0;
+ position: relative;
+ padding: 0;
+ padding-top: 2px;
+ overflow: hidden;
+}
+.tabs-header-plain {
+ border: 0;
+ background: transparent;
+}
+.tabs-scroller-left,
+.tabs-scroller-right {
+ position: absolute;
+ top: auto;
+ bottom: 0;
+ width: 18px;
+ font-size: 1px;
+ display: none;
+ cursor: pointer;
+ border-width: 1px;
+ border-style: solid;
+}
+.tabs-scroller-left {
+ left: 0;
+}
+.tabs-scroller-right {
+ right: 0;
+}
+.tabs-tool {
+ position: absolute;
+ bottom: 0;
+ padding: 1px;
+ overflow: hidden;
+ border-width: 1px;
+ border-style: solid;
+}
+.tabs-header-plain .tabs-tool {
+ padding: 0 1px;
+}
+.tabs-wrap {
+ position: relative;
+ left: 0;
+ overflow: hidden;
+ width: 100%;
+ margin: 0;
+ padding: 0;
+}
+.tabs-scrolling {
+ margin-left: 18px;
+ margin-right: 18px;
+}
+.tabs-disabled {
+ opacity: 0.3;
+ filter: alpha(opacity=30);
+}
+.tabs {
+ list-style-type: none;
+ height: 26px;
+ margin: 0px;
+ padding: 0px;
+ padding-left: 4px;
+ width: 5000px;
+ border-style: solid;
+ border-width: 0 0 1px 0;
+}
+.tabs li {
+ float: left;
+ display: inline-block;
+ margin: 0 4px -1px 0;
+ padding: 0;
+ position: relative;
+ border: 0;
+}
+.tabs li a.tabs-inner {
+ display: inline-block;
+ text-decoration: none;
+ margin: 0;
+ padding: 0 10px;
+ height: 25px;
+ line-height: 25px;
+ text-align: center;
+ white-space: nowrap;
+ border-width: 1px;
+ border-style: solid;
+ -moz-border-radius: 5px 5px 0 0;
+ -webkit-border-radius: 5px 5px 0 0;
+ border-radius: 5px 5px 0 0;
+}
+.tabs li.tabs-selected a.tabs-inner {
+ font-weight: bold;
+ outline: none;
+}
+.tabs li.tabs-selected a:hover.tabs-inner {
+ cursor: default;
+ pointer: default;
+}
+.tabs li a.tabs-close,
+.tabs-p-tool {
+ position: absolute;
+ font-size: 1px;
+ display: block;
+ height: 12px;
+ padding: 0;
+ top: 50%;
+ margin-top: -6px;
+ overflow: hidden;
+}
+.tabs li a.tabs-close {
+ width: 12px;
+ right: 5px;
+ opacity: 0.6;
+ filter: alpha(opacity=60);
+}
+.tabs-p-tool {
+ right: 16px;
+}
+.tabs-p-tool a {
+ display: inline-block;
+ font-size: 1px;
+ width: 12px;
+ height: 12px;
+ margin: 0;
+ opacity: 0.6;
+ filter: alpha(opacity=60);
+}
+.tabs li a:hover.tabs-close,
+.tabs-p-tool a:hover {
+ opacity: 1;
+ filter: alpha(opacity=100);
+ cursor: hand;
+ cursor: pointer;
+}
+.tabs-with-icon {
+ padding-left: 18px;
+}
+.tabs-icon {
+ position: absolute;
+ width: 16px;
+ height: 16px;
+ left: 10px;
+ top: 50%;
+ margin-top: -8px;
+}
+.tabs-title {
+ font-size: 12px;
+}
+.tabs-closable {
+ padding-right: 8px;
+}
+.tabs-panels {
+ margin: 0px;
+ padding: 0px;
+ border-width: 1px;
+ border-style: solid;
+ border-top-width: 0;
+ overflow: hidden;
+}
+.tabs-header-bottom {
+ border-width: 0 1px 1px 1px;
+ padding: 0 0 2px 0;
+}
+.tabs-header-bottom .tabs {
+ border-width: 1px 0 0 0;
+}
+.tabs-header-bottom .tabs li {
+ margin: -1px 4px 0 0;
+}
+.tabs-header-bottom .tabs li a.tabs-inner {
+ -moz-border-radius: 0 0 5px 5px;
+ -webkit-border-radius: 0 0 5px 5px;
+ border-radius: 0 0 5px 5px;
+}
+.tabs-header-bottom .tabs-tool {
+ top: 0;
+}
+.tabs-header-bottom .tabs-scroller-left,
+.tabs-header-bottom .tabs-scroller-right {
+ top: 0;
+ bottom: auto;
+}
+.tabs-panels-top {
+ border-width: 1px 1px 0 1px;
+}
+.tabs-header-left {
+ float: left;
+ border-width: 1px 0 1px 1px;
+ padding: 0;
+}
+.tabs-header-right {
+ float: right;
+ border-width: 1px 1px 1px 0;
+ padding: 0;
+}
+.tabs-header-left .tabs-wrap,
+.tabs-header-right .tabs-wrap {
+ height: 100%;
+}
+.tabs-header-left .tabs {
+ height: 100%;
+ padding: 4px 0 0 4px;
+ border-width: 0 1px 0 0;
+}
+.tabs-header-right .tabs {
+ height: 100%;
+ padding: 4px 4px 0 0;
+ border-width: 0 0 0 1px;
+}
+.tabs-header-left .tabs li,
+.tabs-header-right .tabs li {
+ display: block;
+ width: 100%;
+ position: relative;
+}
+.tabs-header-left .tabs li {
+ left: auto;
+ right: 0;
+ margin: 0 -1px 4px 0;
+ float: right;
+}
+.tabs-header-right .tabs li {
+ left: 0;
+ right: auto;
+ margin: 0 0 4px -1px;
+ float: left;
+}
+.tabs-header-left .tabs li a.tabs-inner {
+ display: block;
+ text-align: left;
+ -moz-border-radius: 5px 0 0 5px;
+ -webkit-border-radius: 5px 0 0 5px;
+ border-radius: 5px 0 0 5px;
+}
+.tabs-header-right .tabs li a.tabs-inner {
+ display: block;
+ text-align: left;
+ -moz-border-radius: 0 5px 5px 0;
+ -webkit-border-radius: 0 5px 5px 0;
+ border-radius: 0 5px 5px 0;
+}
+.tabs-panels-right {
+ float: right;
+ border-width: 1px 1px 1px 0;
+}
+.tabs-panels-left {
+ float: left;
+ border-width: 1px 0 1px 1px;
+}
+.tabs-header-noborder,
+.tabs-panels-noborder {
+ border: 0px;
+}
+.tabs-header-plain {
+ border: 0px;
+ background: transparent;
+}
+.tabs-scroller-left {
+ background: #f3f3f3 url('images/tabs_icons.png') no-repeat 1px center;
+}
+.tabs-scroller-right {
+ background: #f3f3f3 url('images/tabs_icons.png') no-repeat -15px center;
+}
+.tabs li a.tabs-close {
+ background: url('images/tabs_icons.png') no-repeat -34px center;
+}
+.tabs li a.tabs-inner:hover {
+ background: #e2e2e2;
+ color: #000000;
+ filter: none;
+}
+.tabs li.tabs-selected a.tabs-inner {
+ background-color: #ffffff;
+ color: #575765;
+ background: -webkit-linear-gradient(top,#F8F8F8 0,#ffffff 100%);
+ background: -moz-linear-gradient(top,#F8F8F8 0,#ffffff 100%);
+ background: -o-linear-gradient(top,#F8F8F8 0,#ffffff 100%);
+ background: linear-gradient(to bottom,#F8F8F8 0,#ffffff 100%);
+ background-repeat: repeat-x;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#F8F8F8,endColorstr=#ffffff,GradientType=0);
+}
+.tabs-header-bottom .tabs li.tabs-selected a.tabs-inner {
+ background: -webkit-linear-gradient(top,#ffffff 0,#F8F8F8 100%);
+ background: -moz-linear-gradient(top,#ffffff 0,#F8F8F8 100%);
+ background: -o-linear-gradient(top,#ffffff 0,#F8F8F8 100%);
+ background: linear-gradient(to bottom,#ffffff 0,#F8F8F8 100%);
+ background-repeat: repeat-x;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#F8F8F8,GradientType=0);
+}
+.tabs-header-left .tabs li.tabs-selected a.tabs-inner {
+ background: -webkit-linear-gradient(left,#F8F8F8 0,#ffffff 100%);
+ background: -moz-linear-gradient(left,#F8F8F8 0,#ffffff 100%);
+ background: -o-linear-gradient(left,#F8F8F8 0,#ffffff 100%);
+ background: linear-gradient(to right,#F8F8F8 0,#ffffff 100%);
+ background-repeat: repeat-y;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#F8F8F8,endColorstr=#ffffff,GradientType=1);
+}
+.tabs-header-right .tabs li.tabs-selected a.tabs-inner {
+ background: -webkit-linear-gradient(left,#ffffff 0,#F8F8F8 100%);
+ background: -moz-linear-gradient(left,#ffffff 0,#F8F8F8 100%);
+ background: -o-linear-gradient(left,#ffffff 0,#F8F8F8 100%);
+ background: linear-gradient(to right,#ffffff 0,#F8F8F8 100%);
+ background-repeat: repeat-y;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#F8F8F8,GradientType=1);
+}
+.tabs li a.tabs-inner {
+ color: #575765;
+ background-color: #f3f3f3;
+ background: -webkit-linear-gradient(top,#F8F8F8 0,#eeeeee 100%);
+ background: -moz-linear-gradient(top,#F8F8F8 0,#eeeeee 100%);
+ background: -o-linear-gradient(top,#F8F8F8 0,#eeeeee 100%);
+ background: linear-gradient(to bottom,#F8F8F8 0,#eeeeee 100%);
+ background-repeat: repeat-x;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#F8F8F8,endColorstr=#eeeeee,GradientType=0);
+}
+.tabs-header,
+.tabs-tool {
+ background-color: #f3f3f3;
+}
+.tabs-header-plain {
+ background: transparent;
+}
+.tabs-header,
+.tabs-scroller-left,
+.tabs-scroller-right,
+.tabs-tool,
+.tabs,
+.tabs-panels,
+.tabs li a.tabs-inner,
+.tabs li.tabs-selected a.tabs-inner,
+.tabs-header-bottom .tabs li.tabs-selected a.tabs-inner,
+.tabs-header-left .tabs li.tabs-selected a.tabs-inner,
+.tabs-header-right .tabs li.tabs-selected a.tabs-inner {
+ border-color: #D3D3D3;
+}
+.tabs-p-tool a:hover,
+.tabs li a:hover.tabs-close,
+.tabs-scroller-over {
+ background-color: #e2e2e2;
+}
+.tabs li.tabs-selected a.tabs-inner {
+ border-bottom: 1px solid #ffffff;
+}
+.tabs-header-bottom .tabs li.tabs-selected a.tabs-inner {
+ border-top: 1px solid #ffffff;
+}
+.tabs-header-left .tabs li.tabs-selected a.tabs-inner {
+ border-right: 1px solid #ffffff;
+}
+.tabs-header-right .tabs li.tabs-selected a.tabs-inner {
+ border-left: 1px solid #ffffff;
+}
diff --git a/.svn/pristine/08/0820b0421b485d49b24506b469ec034e4c8c96ff.svn-base b/.svn/pristine/08/0820b0421b485d49b24506b469ec034e4c8c96ff.svn-base
new file mode 100644
index 0000000..dc1f626
--- /dev/null
+++ b/.svn/pristine/08/0820b0421b485d49b24506b469ec034e4c8c96ff.svn-base
@@ -0,0 +1,9783 @@
+/**
+ * Handsontable 0.9.9
+ * Handsontable is a simple jQuery plugin for editable tables with basic copy-paste compatibility with Excel and Google Docs
+ *
+ * Copyright 2012, Marcin Warpechowski
+ * Licensed under the MIT license.
+ * http://handsontable.com/
+ *
+ * Date: Sun Jun 30 2013 13:24:55 GMT+0200 (Central European Daylight Time)
+ */
+/*jslint white: true, browser: true, plusplus: true, indent: 4, maxerr: 50 */
+
+var Handsontable = { //class namespace
+ extension: {}, //extenstion namespace
+ helper: {} //helper namespace
+};
+
+(function ($, window, Handsontable) {
+ "use strict";
+Handsontable.activeGuid = null;
+
+/**
+ * Handsontable constructor
+ * @param rootElement The jQuery element in which Handsontable DOM will be inserted
+ * @param userSettings
+ * @constructor
+ */
+Handsontable.Core = function (rootElement, userSettings) {
+ var priv
+ , datamap
+ , grid
+ , selection
+ , editproxy
+ , autofill
+ , instance = this
+ , GridSettings = function () {
+ };
+
+ Handsontable.helper.inherit(GridSettings, DefaultSettings); //create grid settings as a copy of default settings
+ Handsontable.helper.extend(GridSettings.prototype, userSettings); //overwrite defaults with user settings
+
+ this.rootElement = rootElement;
+ var $document = $(document.documentElement);
+ var $body = $(document.body);
+ this.guid = 'ht_' + Handsontable.helper.randomString(); //this is the namespace for global events
+
+ if (!this.rootElement[0].id) {
+ this.rootElement[0].id = this.guid; //if root element does not have an id, assign a random id
+ }
+
+ priv = {
+ cellSettings: [],
+ columnSettings: [],
+ columnsSettingConflicts: ['data', 'width'],
+ settings: new GridSettings(), // current settings instance
+ settingsFromDOM: {},
+ selStart: new Handsontable.SelectionPoint(),
+ selEnd: new Handsontable.SelectionPoint(),
+ editProxy: false,
+ isPopulated: null,
+ scrollable: null,
+ undoRedo: null,
+ extensions: {},
+ colToProp: null,
+ propToCol: null,
+ dataSchema: null,
+ dataType: 'array',
+ firstRun: true
+ };
+
+ datamap = {
+ recursiveDuckSchema: function (obj) {
+ var schema;
+ if ($.isPlainObject(obj)) {
+ schema = {};
+ for (var i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ if ($.isPlainObject(obj[i])) {
+ schema[i] = datamap.recursiveDuckSchema(obj[i]);
+ }
+ else {
+ schema[i] = null;
+ }
+ }
+ }
+ }
+ else {
+ schema = [];
+ }
+ return schema;
+ },
+
+ recursiveDuckColumns: function (schema, lastCol, parent) {
+ var prop, i;
+ if (typeof lastCol === 'undefined') {
+ lastCol = 0;
+ parent = '';
+ }
+ if ($.isPlainObject(schema)) {
+ for (i in schema) {
+ if (schema.hasOwnProperty(i)) {
+ if (schema[i] === null) {
+ prop = parent + i;
+ priv.colToProp.push(prop);
+ priv.propToCol[prop] = lastCol;
+ lastCol++;
+ }
+ else {
+ lastCol = datamap.recursiveDuckColumns(schema[i], lastCol, i + '.');
+ }
+ }
+ }
+ }
+ return lastCol;
+ },
+
+ createMap: function () {
+ if (typeof datamap.getSchema() === "undefined") {
+ throw new Error("trying to create `columns` definition but you didnt' provide `schema` nor `data`");
+ }
+ var i, ilen, schema = datamap.getSchema();
+ priv.colToProp = [];
+ priv.propToCol = {};
+ if (priv.settings.columns) {
+ for (i = 0, ilen = priv.settings.columns.length; i < ilen; i++) {
+ priv.colToProp[i] = priv.settings.columns[i].data;
+ priv.propToCol[priv.settings.columns[i].data] = i;
+ }
+ }
+ else {
+ datamap.recursiveDuckColumns(schema);
+ }
+ },
+
+ colToProp: function (col) {
+ col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col);
+ if (priv.colToProp && typeof priv.colToProp[col] !== 'undefined') {
+ return priv.colToProp[col];
+ }
+ else {
+ return col;
+ }
+ },
+
+ propToCol: function (prop) {
+ var col;
+ if (typeof priv.propToCol[prop] !== 'undefined') {
+ col = priv.propToCol[prop];
+ }
+ else {
+ col = prop;
+ }
+ col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col);
+ return col;
+ },
+
+ getSchema: function () {
+ if (priv.settings.dataSchema) {
+ if (typeof priv.settings.dataSchema === 'function') {
+ return priv.settings.dataSchema();
+ }
+ return priv.settings.dataSchema;
+ }
+ return priv.duckDataSchema;
+ },
+
+ /**
+ * Creates row at the bottom of the data array
+ * @param {Number} [index] Optional. Index of the row before which the new row will be inserted
+ */
+ createRow: function (index) {
+ var row
+ , rowCount = instance.countRows();
+
+ if (typeof index !== 'number' || index >= rowCount) {
+ index = rowCount;
+ }
+
+ if (priv.dataType === 'array') {
+ row = [];
+ for (var c = 0, clen = instance.countCols(); c < clen; c++) {
+ row.push(null);
+ }
+ }
+ else if (priv.dataType === 'function') {
+ row = priv.settings.dataSchema(index);
+ }
+ else {
+ row = $.extend(true, {}, datamap.getSchema());
+ }
+
+ if (index === rowCount) {
+ GridSettings.prototype.data.push(row);
+ }
+ else {
+ GridSettings.prototype.data.splice(index, 0, row);
+ }
+
+ instance.PluginHooks.run('afterCreateRow', index);
+ instance.forceFullRender = true; //used when data was changed
+ },
+
+ /**
+ * Creates col at the right of the data array
+ * @param {Object} [index] Optional. Index of the column before which the new column will be inserted
+ */
+ createCol: function (index) {
+ if (priv.dataType === 'object' || priv.settings.columns) {
+ throw new Error("Cannot create new column. When data source in an object, you can only have as much columns as defined in first data row, data schema or in the 'columns' setting");
+ }
+ var r = 0, rlen = instance.countRows()
+ , data = GridSettings.prototype.data
+ , constructor = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts, Handsontable.TextCell);
+
+ if (typeof index !== 'number' || index >= instance.countCols()) {
+ for (; r < rlen; r++) {
+ if (typeof data[r] === 'undefined') {
+ data[r] = [];
+ }
+ data[r].push(null);
+ }
+ // Add new column constructor
+ priv.columnSettings.push(constructor);
+ }
+ else {
+ for (; r < rlen; r++) {
+ data[r].splice(index, 0, null);
+ }
+ // Add new column constructor at given index
+ priv.columnSettings.splice(index, 0, constructor);
+ }
+ instance.PluginHooks.run('afterCreateCol', index);
+ instance.forceFullRender = true; //used when data was changed
+ },
+
+ /**
+ * Removes row from the data array
+ * @param {Number} [index] Optional. Index of the row to be removed. If not provided, the last row will be removed
+ * @param {Number} [amount] Optional. Amount of the rows to be removed. If not provided, one row will be removed
+ */
+ removeRow: function (index, amount) {
+ if (!amount) {
+ amount = 1;
+ }
+ if (typeof index !== 'number') {
+ index = -amount;
+ }
+ GridSettings.prototype.data.splice(index, amount);
+ instance.PluginHooks.run('afterRemoveRow', index, amount);
+ instance.forceFullRender = true; //used when data was changed
+ },
+
+ /**
+ * Removes column from the data array
+ * @param {Number} [index] Optional. Index of the column to be removed. If not provided, the last column will be removed
+ * @param {Number} [amount] Optional. Amount of the columns to be removed. If not provided, one column will be removed
+ */
+ removeCol: function (index, amount) {
+ if (priv.dataType === 'object' || priv.settings.columns) {
+ throw new Error("cannot remove column with object data source or columns option specified");
+ }
+ if (!amount) {
+ amount = 1;
+ }
+ if (typeof index !== 'number') {
+ index = -amount;
+ }
+ var data = GridSettings.prototype.data;
+ for (var r = 0, rlen = instance.countRows(); r < rlen; r++) {
+ data[r].splice(index, amount);
+ }
+ instance.PluginHooks.run('afterRemoveCol', index, amount);
+ priv.columnSettings.splice(index, amount);
+ instance.forceFullRender = true; //used when data was changed
+ },
+
+ /**
+ * Add / removes data from the column
+ * @param {Number} col Index of column in which do you want to do splice.
+ * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
+ * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
+ * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
+ */
+ spliceCol: function (col, index, amount/*, elements...*/) {
+ var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : [];
+
+ var colData = instance.getDataAtCol(col);
+ var removed = colData.slice(index, index + amount);
+ var after = colData.slice(index + amount);
+
+ Handsontable.helper.extendArray(elements, after);
+ var i = 0;
+ while (i < amount) {
+ elements.push(null); //add null in place of removed elements
+ i++;
+ }
+ Handsontable.helper.to2dArray(elements);
+ instance.populateFromArray(index, col, elements, null, null, 'spliceCol');
+
+ return removed;
+ },
+
+ /**
+ * Add / removes data from the row
+ * @param {Number} row Index of row in which do you want to do splice.
+ * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
+ * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
+ * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
+ */
+ spliceRow: function (row, index, amount/*, elements...*/) {
+ var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : [];
+
+ var rowData = instance.getDataAtRow(row);
+ var removed = rowData.slice(index, index + amount);
+ var after = rowData.slice(index + amount);
+
+ Handsontable.helper.extendArray(elements, after);
+ var i = 0;
+ while (i < amount) {
+ elements.push(null); //add null in place of removed elements
+ i++;
+ }
+ instance.populateFromArray(row, index, [elements], null, null, 'spliceRow');
+
+ return removed;
+ },
+
+ /**
+ * Returns single value from the data array
+ * @param {Number} row
+ * @param {Number} prop
+ */
+ getVars: {},
+ get: function (row, prop) {
+ datamap.getVars.row = row;
+ datamap.getVars.prop = prop;
+ instance.PluginHooks.run('beforeGet', datamap.getVars);
+ if (typeof datamap.getVars.prop === 'string' && datamap.getVars.prop.indexOf('.') > -1) {
+ var sliced = datamap.getVars.prop.split(".");
+ var out = priv.settings.data[datamap.getVars.row];
+ if (!out) {
+ return null;
+ }
+ for (var i = 0, ilen = sliced.length; i < ilen; i++) {
+ out = out[sliced[i]];
+ if (typeof out === 'undefined') {
+ return null;
+ }
+ }
+ return out;
+ }
+ else if (typeof datamap.getVars.prop === 'function') {
+ /**
+ * allows for interacting with complex structures, for example
+ * d3/jQuery getter/setter properties:
+ *
+ * {columns: [{
+ * data: function(row, value){
+ * if(arguments.length === 1){
+ * return row.property();
+ * }
+ * row.property(value);
+ * }
+ * }]}
+ */
+ return datamap.getVars.prop(priv.settings.data.slice(
+ datamap.getVars.row,
+ datamap.getVars.row + 1
+ )[0]);
+ }
+ else {
+ return priv.settings.data[datamap.getVars.row] ? priv.settings.data[datamap.getVars.row][datamap.getVars.prop] : null;
+ }
+ },
+
+ /**
+ * Saves single value to the data array
+ * @param {Number} row
+ * @param {Number} prop
+ * @param {String} value
+ * @param {String} [source] Optional. Source of hook runner.
+ */
+ setVars: {},
+ set: function (row, prop, value, source) {
+ datamap.setVars.row = row;
+ datamap.setVars.prop = prop;
+ datamap.setVars.value = value;
+ instance.PluginHooks.run('beforeSet', datamap.setVars, source || "datamapGet");
+ if (typeof datamap.setVars.prop === 'string' && datamap.setVars.prop.indexOf('.') > -1) {
+ var sliced = datamap.setVars.prop.split(".");
+ var out = priv.settings.data[datamap.setVars.row];
+ for (var i = 0, ilen = sliced.length - 1; i < ilen; i++) {
+ out = out[sliced[i]];
+ }
+ out[sliced[i]] = datamap.setVars.value;
+ }
+ else if (typeof datamap.setVars.prop === 'function') {
+ /* see the `function` handler in `get` */
+ datamap.setVars.prop(priv.settings.data.slice(
+ datamap.setVars.row,
+ datamap.setVars.row + 1
+ )[0], datamap.setVars.value);
+ }
+ else {
+ priv.settings.data[datamap.setVars.row][datamap.setVars.prop] = datamap.setVars.value;
+ }
+ },
+
+ /**
+ * Clears the data array
+ */
+ clear: function () {
+ for (var r = 0; r < instance.countRows(); r++) {
+ for (var c = 0; c < instance.countCols(); c++) {
+ datamap.set(r, datamap.colToProp(c), '');
+ }
+ }
+ },
+
+ /**
+ * Returns the data array
+ * @return {Array}
+ */
+ getAll: function () {
+ return priv.settings.data;
+ },
+
+ /**
+ * Returns data range as array
+ * @param {Object} start Start selection position
+ * @param {Object} end End selection position
+ * @return {Array}
+ */
+ getRange: function (start, end) {
+ var r, rlen, c, clen, output = [], row;
+ rlen = Math.max(start.row, end.row);
+ clen = Math.max(start.col, end.col);
+ for (r = Math.min(start.row, end.row); r <= rlen; r++) {
+ row = [];
+ for (c = Math.min(start.col, end.col); c <= clen; c++) {
+ row.push(datamap.get(r, datamap.colToProp(c)));
+ }
+ output.push(row);
+ }
+ return output;
+ },
+
+ /**
+ * Return data as text (tab separated columns)
+ * @param {Object} start (Optional) Start selection position
+ * @param {Object} end (Optional) End selection position
+ * @return {String}
+ */
+ getText: function (start, end) {
+ return SheetClip.stringify(datamap.getRange(start, end));
+ }
+ };
+
+ grid = {
+ /**
+ * Inserts or removes rows and columns
+ * @param {String} action Possible values: "insert_row", "insert_col", "remove_row", "remove_col"
+ * @param {Number} index
+ * @param {Number} amount
+ * @param {String} [source] Optional. Source of hook runner.
+ * @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
+ */
+ alter: function (action, index, amount, source, keepEmptyRows) {
+ var oldData, newData, changes, r, rlen, c, clen, delta;
+ oldData = $.extend(true, [], datamap.getAll());
+
+ switch (action) {
+ case "insert_row":
+ if (!amount) {
+ amount = 1;
+ }
+ delta = 0;
+ while (delta < amount && instance.countRows() < priv.settings.maxRows) {
+ datamap.createRow(index);
+ delta++;
+ }
+ if (delta) {
+ if (priv.selStart.exists() && priv.selStart.row() >= index) {
+ priv.selStart.row(priv.selStart.row() + delta);
+ selection.transformEnd(delta, 0); //will call render() internally
+ }
+ else {
+ selection.refreshBorders(); //it will call render and prepare methods
+ }
+ }
+ break;
+
+ case "insert_col":
+ if (!amount) {
+ amount = 1;
+ }
+ delta = 0;
+ while (delta < amount && instance.countCols() < priv.settings.maxCols) {
+ datamap.createCol(index);
+ delta++;
+ }
+ if (delta) {
+ if (priv.selStart.exists() && priv.selStart.col() >= index) {
+ priv.selStart.col(priv.selStart.col() + delta);
+ selection.transformEnd(0, delta); //will call render() internally
+ }
+ else {
+ selection.refreshBorders(); //it will call render and prepare methods
+ }
+ }
+ break;
+
+ case "remove_row":
+ datamap.removeRow(index, amount);
+ grid.adjustRowsAndCols();
+ selection.refreshBorders(); //it will call render and prepare methods
+ break;
+
+ case "remove_col":
+ datamap.removeCol(index, amount);
+ grid.adjustRowsAndCols();
+ selection.refreshBorders(); //it will call render and prepare methods
+ break;
+
+ default:
+ throw new Error('There is no such action "' + action + '"');
+ break;
+ }
+
+ changes = [];
+ newData = datamap.getAll();
+ for (r = 0, rlen = newData.length; r < rlen; r++) {
+ for (c = 0, clen = newData[r].length; c < clen; c++) {
+ changes.push([r, c, oldData[r] ? oldData[r][c] : null, newData[r][c]]);
+ }
+ }
+ instance.PluginHooks.run('afterChange', changes, source || action);
+ if (!keepEmptyRows) {
+ grid.adjustRowsAndCols(); //makes sure that we did not add rows that will be removed in next refresh
+ }
+ },
+
+ /**
+ * Makes sure there are empty rows at the bottom of the table
+ */
+ adjustRowsAndCols: function () {
+ var r, rlen, emptyRows = instance.countEmptyRows(true), emptyCols;
+
+ //should I add empty rows to data source to meet minRows?
+ rlen = instance.countRows();
+ if (rlen < priv.settings.minRows) {
+ for (r = 0; r < priv.settings.minRows - rlen; r++) {
+ datamap.createRow();
+ }
+ }
+
+ //should I add empty rows to meet minSpareRows?
+ if (emptyRows < priv.settings.minSpareRows) {
+ for (; emptyRows < priv.settings.minSpareRows && instance.countRows() < priv.settings.maxRows; emptyRows++) {
+ datamap.createRow();
+ }
+ }
+
+ //count currently empty cols
+ emptyCols = instance.countEmptyCols(true);
+
+ //should I add empty cols to meet minCols?
+ if (!priv.settings.columns && instance.countCols() < priv.settings.minCols) {
+ for (; instance.countCols() < priv.settings.minCols; emptyCols++) {
+ datamap.createCol();
+ }
+ }
+
+ //should I add empty cols to meet minSpareCols?
+ if (!priv.settings.columns && priv.dataType === 'array' && emptyCols < priv.settings.minSpareCols) {
+ for (; emptyCols < priv.settings.minSpareCols && instance.countCols() < priv.settings.maxCols; emptyCols++) {
+ datamap.createCol();
+ }
+ }
+
+ if (priv.settings.enterBeginsEditing) {
+ for (; (((priv.settings.minRows || priv.settings.minSpareRows) && instance.countRows() > priv.settings.minRows) && (priv.settings.minSpareRows && emptyRows > priv.settings.minSpareRows)); emptyRows--) {
+ datamap.removeRow();
+ }
+ }
+
+ if (priv.settings.enterBeginsEditing && !priv.settings.columns) {
+ for (; (((priv.settings.minCols || priv.settings.minSpareCols) && instance.countCols() > priv.settings.minCols) && (priv.settings.minSpareCols && emptyCols > priv.settings.minSpareCols)); emptyCols--) {
+ datamap.removeCol();
+ }
+ }
+
+ var rowCount = instance.countRows();
+ var colCount = instance.countCols();
+
+ if (rowCount === 0 || colCount === 0) {
+ selection.deselect();
+ }
+
+ if (priv.selStart.exists()) {
+ var selectionChanged;
+ var fromRow = priv.selStart.row();
+ var fromCol = priv.selStart.col();
+ var toRow = priv.selEnd.row();
+ var toCol = priv.selEnd.col();
+
+ //if selection is outside, move selection to last row
+ if (fromRow > rowCount - 1) {
+ fromRow = rowCount - 1;
+ selectionChanged = true;
+ if (toRow > fromRow) {
+ toRow = fromRow;
+ }
+ } else if (toRow > rowCount - 1) {
+ toRow = rowCount - 1;
+ selectionChanged = true;
+ if (fromRow > toRow) {
+ fromRow = toRow;
+ }
+ }
+
+ //if selection is outside, move selection to last row
+ if (fromCol > colCount - 1) {
+ fromCol = colCount - 1;
+ selectionChanged = true;
+ if (toCol > fromCol) {
+ toCol = fromCol;
+ }
+ } else if (toCol > colCount - 1) {
+ toCol = colCount - 1;
+ selectionChanged = true;
+ if (fromCol > toCol) {
+ fromCol = toCol;
+ }
+ }
+
+ if (selectionChanged) {
+ instance.selectCell(fromRow, fromCol, toRow, toCol);
+ }
+ }
+ },
+
+ /**
+ * Populate cells at position with 2d array
+ * @param {Object} start Start selection position
+ * @param {Array} input 2d array
+ * @param {Object} [end] End selection position (only for drag-down mode)
+ * @param {String} [source="populateFromArray"]
+ * @param {String} [method="overwrite"]
+ * @return {Object|undefined} ending td in pasted area (only if any cell was changed)
+ */
+ populateFromArray: function (start, input, end, source, method) {
+ var r, rlen, c, clen, setData = [], current = {};
+ rlen = input.length;
+ if (rlen === 0) {
+ return false;
+ }
+
+ var repeatCol
+ , repeatRow
+ , cmax
+ , rmax;
+
+ // insert data with specified pasteMode method
+ switch (method) {
+ case 'shift_down' :
+ repeatCol = end ? end.col - start.col + 1 : 0;
+ repeatRow = end ? end.row - start.row + 1 : 0;
+ input = Handsontable.helper.translateRowsToColumns(input);
+ for (c = 0, clen = input.length, cmax = Math.max(clen, repeatCol); c < cmax; c++) {
+ if (c < clen) {
+ for (r = 0, rlen = input[c].length; r < repeatRow - rlen; r++) {
+ input[c].push(input[c][r % rlen]);
+ }
+ input[c].unshift(start.col + c, start.row, 0);
+ instance.spliceCol.apply(instance, input[c]);
+ }
+ else {
+ input[c % clen][0] = start.col + c;
+ instance.spliceCol.apply(instance, input[c % clen]);
+ }
+ }
+ break;
+
+ case 'shift_right' :
+ repeatCol = end ? end.col - start.col + 1 : 0;
+ repeatRow = end ? end.row - start.row + 1 : 0;
+ for (r = 0, rlen = input.length, rmax = Math.max(rlen, repeatRow); r < rmax; r++) {
+ if (r < rlen) {
+ for (c = 0, clen = input[r].length; c < repeatCol - clen; c++) {
+ input[r].push(input[r][c % clen]);
+ }
+ input[r].unshift(start.row + r, start.col, 0);
+ instance.spliceRow.apply(instance, input[r]);
+ }
+ else {
+ input[r % rlen][0] = start.row + r;
+ instance.spliceRow.apply(instance, input[r % rlen]);
+ }
+ }
+ break;
+
+ case 'overwrite' :
+ default:
+ // overwrite and other not specified options
+ current.row = start.row;
+ current.col = start.col;
+ for (r = 0; r < rlen; r++) {
+ if ((end && current.row > end.row) || (!priv.settings.minSpareRows && current.row > instance.countRows() - 1) || (current.row >= priv.settings.maxRows)) {
+ break;
+ }
+ current.col = start.col;
+ clen = input[r] ? input[r].length : 0;
+ for (c = 0; c < clen; c++) {
+ if ((end && current.col > end.col) || (!priv.settings.minSpareCols && current.col > instance.countCols() - 1) || (current.col >= priv.settings.maxCols)) {
+ break;
+ }
+ if (instance.getCellMeta(current.row, current.col).isWritable) {
+ setData.push([current.row, current.col, input[r][c]]);
+ }
+ current.col++;
+ if (end && c === clen - 1) {
+ c = -1;
+ }
+ }
+ current.row++;
+ if (end && r === rlen - 1) {
+ r = -1;
+ }
+ }
+ instance.setDataAtCell(setData, null, null, source || 'populateFromArray');
+ break;
+ }
+ },
+
+ /**
+ * Returns the top left (TL) and bottom right (BR) selection coordinates
+ * @param {Object[]} coordsArr
+ * @returns {Object}
+ */
+ getCornerCoords: function (coordsArr) {
+ function mapProp(func, array, prop) {
+ function getProp(el) {
+ return el[prop];
+ }
+
+ if (Array.prototype.map) {
+ return func.apply(Math, array.map(getProp));
+ }
+ return func.apply(Math, $.map(array, getProp));
+ }
+
+ return {
+ TL: {
+ row: mapProp(Math.min, coordsArr, "row"),
+ col: mapProp(Math.min, coordsArr, "col")
+ },
+ BR: {
+ row: mapProp(Math.max, coordsArr, "row"),
+ col: mapProp(Math.max, coordsArr, "col")
+ }
+ };
+ },
+
+ /**
+ * Returns array of td objects given start and end coordinates
+ */
+ getCellsAtCoords: function (start, end) {
+ var corners = grid.getCornerCoords([start, end]);
+ var r, c, output = [];
+ for (r = corners.TL.row; r <= corners.BR.row; r++) {
+ for (c = corners.TL.col; c <= corners.BR.col; c++) {
+ output.push(instance.view.getCellAtCoords({
+ row: r,
+ col: c
+ }));
+ }
+ }
+ return output;
+ }
+ };
+
+ this.selection = selection = { //this public assignment is only temporary
+ inProgress: false,
+
+ /**
+ * Sets inProgress to true. This enables onSelectionEnd and onSelectionEndByProp to function as desired
+ */
+ begin: function () {
+ instance.selection.inProgress = true;
+ },
+
+ /**
+ * Sets inProgress to false. Triggers onSelectionEnd and onSelectionEndByProp
+ */
+ finish: function () {
+ var sel = instance.getSelected();
+ instance.PluginHooks.run("afterSelectionEnd", sel[0], sel[1], sel[2], sel[3]);
+ instance.PluginHooks.run("afterSelectionEndByProp", sel[0], instance.colToProp(sel[1]), sel[2], instance.colToProp(sel[3]));
+ instance.selection.inProgress = false;
+ },
+
+ isInProgress: function () {
+ return instance.selection.inProgress;
+ },
+
+ /**
+ * Starts selection range on given td object
+ * @param {Object} coords
+ */
+ setRangeStart: function (coords) {
+ priv.selStart.coords(coords);
+ selection.setRangeEnd(coords);
+ },
+
+ /**
+ * Ends selection range on given td object
+ * @param {Object} coords
+ * @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to range end
+ */
+ setRangeEnd: function (coords, scrollToCell) {
+ instance.selection.begin();
+
+ priv.selEnd.coords(coords);
+ if (!priv.settings.multiSelect) {
+ priv.selStart.coords(coords);
+ }
+
+ //set up current selection
+ instance.view.wt.selections.current.clear();
+ instance.view.wt.selections.current.add(priv.selStart.arr());
+
+ //set up area selection
+ instance.view.wt.selections.area.clear();
+ if (selection.isMultiple()) {
+ instance.view.wt.selections.area.add(priv.selStart.arr());
+ instance.view.wt.selections.area.add(priv.selEnd.arr());
+ }
+
+ //set up highlight
+ if (priv.settings.currentRowClassName || priv.settings.currentColClassName) {
+ instance.view.wt.selections.highlight.clear();
+ instance.view.wt.selections.highlight.add(priv.selStart.arr());
+ instance.view.wt.selections.highlight.add(priv.selEnd.arr());
+ }
+
+ //trigger handlers
+ instance.PluginHooks.run("afterSelection", priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col());
+ instance.PluginHooks.run("afterSelectionByProp", priv.selStart.row(), datamap.colToProp(priv.selStart.col()), priv.selEnd.row(), datamap.colToProp(priv.selEnd.col()));
+
+ if (scrollToCell !== false) {
+ instance.view.scrollViewport(coords);
+
+ instance.view.wt.draw(true); //these two lines are needed to fix scrolling viewport when cell dimensions are significantly bigger than assumed by Walkontable
+ instance.view.scrollViewport(coords);
+ }
+ selection.refreshBorders();
+ },
+
+ /**
+ * Destroys editor, redraws borders around cells, prepares editor
+ * @param {Boolean} revertOriginal
+ * @param {Boolean} keepEditor
+ */
+ refreshBorders: function (revertOriginal, keepEditor) {
+ if (!keepEditor) {
+ editproxy.destroy(revertOriginal);
+ }
+ instance.view.render();
+ if (selection.isSelected() && !keepEditor) {
+ editproxy.prepare();
+ }
+ },
+
+ /**
+ * Returns information if we have a multiselection
+ * @return {Boolean}
+ */
+ isMultiple: function () {
+ return !(priv.selEnd.col() === priv.selStart.col() && priv.selEnd.row() === priv.selStart.row());
+ },
+
+ /**
+ * Selects cell relative to current cell (if possible)
+ */
+ transformStart: function (rowDelta, colDelta, force) {
+ if (priv.selStart.row() + rowDelta > instance.countRows() - 1) {
+ if (force && priv.settings.minSpareRows > 0) {
+ instance.alter("insert_row", instance.countRows());
+ }
+ else if (priv.settings.autoWrapCol && priv.selStart.col() + colDelta < instance.countCols() - 1) {
+ rowDelta = 1 - instance.countRows();
+ colDelta = 1;
+ }
+ }
+ else if (priv.settings.autoWrapCol && priv.selStart.row() + rowDelta < 0 && priv.selStart.col() + colDelta >= 0) {
+ rowDelta = instance.countRows() - 1;
+ colDelta = -1;
+ }
+ if (priv.selStart.col() + colDelta > instance.countCols() - 1) {
+ if (force && priv.settings.minSpareCols > 0) {
+ instance.alter("insert_col", instance.countCols());
+ }
+ else if (priv.settings.autoWrapRow && priv.selStart.row() + rowDelta < instance.countRows() - 1) {
+ rowDelta = 1;
+ colDelta = 1 - instance.countCols();
+ }
+ }
+ else if (priv.settings.autoWrapRow && priv.selStart.col() + colDelta < 0 && priv.selStart.row() + rowDelta >= 0) {
+ rowDelta = -1;
+ colDelta = instance.countCols() - 1;
+ }
+
+ var totalRows = instance.countRows();
+ var totalCols = instance.countCols();
+ var coords = {
+ row: (priv.selStart.row() + rowDelta),
+ col: priv.selStart.col() + colDelta
+ };
+
+ if (coords.row < 0) {
+ coords.row = 0;
+ }
+ else if (coords.row > 0 && coords.row >= totalRows) {
+ coords.row = totalRows - 1;
+ }
+
+ if (coords.col < 0) {
+ coords.col = 0;
+ }
+ else if (coords.col > 0 && coords.col >= totalCols) {
+ coords.col = totalCols - 1;
+ }
+
+ selection.setRangeStart(coords);
+ },
+
+ /**
+ * Sets selection end cell relative to current selection end cell (if possible)
+ */
+ transformEnd: function (rowDelta, colDelta) {
+ if (priv.selEnd.exists()) {
+ var totalRows = instance.countRows();
+ var totalCols = instance.countCols();
+ var coords = {
+ row: priv.selEnd.row() + rowDelta,
+ col: priv.selEnd.col() + colDelta
+ };
+
+ if (coords.row < 0) {
+ coords.row = 0;
+ }
+ else if (coords.row > 0 && coords.row >= totalRows) {
+ coords.row = totalRows - 1;
+ }
+
+ if (coords.col < 0) {
+ coords.col = 0;
+ }
+ else if (coords.col > 0 && coords.col >= totalCols) {
+ coords.col = totalCols - 1;
+ }
+
+ selection.setRangeEnd(coords);
+ }
+ },
+
+ /**
+ * Returns true if currently there is a selection on screen, false otherwise
+ * @return {Boolean}
+ */
+ isSelected: function () {
+ return priv.selEnd.exists();
+ },
+
+ /**
+ * Returns true if coords is within current selection coords
+ * @return {Boolean}
+ */
+ inInSelection: function (coords) {
+ if (!selection.isSelected()) {
+ return false;
+ }
+ var sel = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]);
+ return (sel.TL.row <= coords.row && sel.BR.row >= coords.row && sel.TL.col <= coords.col && sel.BR.col >= coords.col);
+ },
+
+ /**
+ * Deselects all selected cells
+ */
+ deselect: function () {
+ if (!selection.isSelected()) {
+ return;
+ }
+ instance.selection.inProgress = false; //needed by HT inception
+ priv.selEnd = new Handsontable.SelectionPoint(); //create new empty point to remove the existing one
+ instance.view.wt.selections.current.clear();
+ instance.view.wt.selections.area.clear();
+ editproxy.destroy();
+ selection.refreshBorders();
+ instance.PluginHooks.run('afterDeselect');
+ },
+
+ /**
+ * Select all cells
+ */
+ selectAll: function () {
+ if (!priv.settings.multiSelect) {
+ return;
+ }
+ selection.setRangeStart({
+ row: 0,
+ col: 0
+ });
+ selection.setRangeEnd({
+ row: instance.countRows() - 1,
+ col: instance.countCols() - 1
+ }, false);
+ },
+
+ /**
+ * Deletes data from selected cells
+ */
+ empty: function () {
+ if (!selection.isSelected()) {
+ return;
+ }
+ var corners = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]);
+ var r, c, changes = [];
+ for (r = corners.TL.row; r <= corners.BR.row; r++) {
+ for (c = corners.TL.col; c <= corners.BR.col; c++) {
+ if (instance.getCellMeta(r, c).isWritable) {
+ changes.push([r, c, '']);
+ }
+ }
+ }
+ instance.setDataAtCell(changes);
+ }
+ };
+
+ this.autofill = autofill = { //this public assignment is only temporary
+ handle: null,
+
+ /**
+ * Create fill handle and fill border objects
+ */
+ init: function () {
+ if (!autofill.handle) {
+ autofill.handle = {};
+ }
+ else {
+ autofill.handle.disabled = false;
+ }
+ },
+
+ /**
+ * Hide fill handle and fill border permanently
+ */
+ disable: function () {
+ autofill.handle.disabled = true;
+ },
+
+ /**
+ * Selects cells down to the last row in the left column, then fills down to that cell
+ */
+ selectAdjacent: function () {
+ var select, data, r, maxR, c;
+
+ if (selection.isMultiple()) {
+ select = instance.view.wt.selections.area.getCorners();
+ }
+ else {
+ select = instance.view.wt.selections.current.getCorners();
+ }
+
+ data = datamap.getAll();
+ rows : for (r = select[2] + 1; r < instance.countRows(); r++) {
+ for (c = select[1]; c <= select[3]; c++) {
+ if (data[r][c]) {
+ break rows;
+ }
+ }
+ if (!!data[r][select[1] - 1] || !!data[r][select[3] + 1]) {
+ maxR = r;
+ }
+ }
+ if (maxR) {
+ instance.view.wt.selections.fill.clear();
+ instance.view.wt.selections.fill.add([select[0], select[1]]);
+ instance.view.wt.selections.fill.add([maxR, select[3]]);
+ autofill.apply();
+ }
+ },
+
+ /**
+ * Apply fill values to the area in fill border, omitting the selection border
+ */
+ apply: function () {
+ var drag, select, start, end, _data;
+
+ autofill.handle.isDragged = 0;
+
+ drag = instance.view.wt.selections.fill.getCorners();
+ if (!drag) {
+ return;
+ }
+
+ instance.view.wt.selections.fill.clear();
+
+ if (selection.isMultiple()) {
+ select = instance.view.wt.selections.area.getCorners();
+ }
+ else {
+ select = instance.view.wt.selections.current.getCorners();
+ }
+
+ if (drag[0] === select[0] && drag[1] < select[1]) {
+ start = {
+ row: drag[0],
+ col: drag[1]
+ };
+ end = {
+ row: drag[2],
+ col: select[1] - 1
+ };
+ }
+ else if (drag[0] === select[0] && drag[3] > select[3]) {
+ start = {
+ row: drag[0],
+ col: select[3] + 1
+ };
+ end = {
+ row: drag[2],
+ col: drag[3]
+ };
+ }
+ else if (drag[0] < select[0] && drag[1] === select[1]) {
+ start = {
+ row: drag[0],
+ col: drag[1]
+ };
+ end = {
+ row: select[0] - 1,
+ col: drag[3]
+ };
+ }
+ else if (drag[2] > select[2] && drag[1] === select[1]) {
+ start = {
+ row: select[2] + 1,
+ col: drag[1]
+ };
+ end = {
+ row: drag[2],
+ col: drag[3]
+ };
+ }
+
+ if (start) {
+
+ _data = SheetClip.parse(datamap.getText(priv.selStart.coords(), priv.selEnd.coords()));
+ instance.PluginHooks.run('beforeAutofill', start, end, _data);
+
+ grid.populateFromArray(start, _data, end, 'autofill');
+
+ selection.setRangeStart({row: drag[0], col: drag[1]});
+ selection.setRangeEnd({row: drag[2], col: drag[3]});
+ }
+ /*else {
+ //reset to avoid some range bug
+ selection.refreshBorders();
+ }*/
+ },
+
+ /**
+ * Show fill border
+ */
+ showBorder: function (coords) {
+ coords.row = coords[0];
+ coords.col = coords[1];
+
+ var corners = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]);
+ if (priv.settings.fillHandle !== 'horizontal' && (corners.BR.row < coords.row || corners.TL.row > coords.row)) {
+ coords = [coords.row, corners.BR.col];
+ }
+ else if (priv.settings.fillHandle !== 'vertical') {
+ coords = [corners.BR.row, coords.col];
+ }
+ else {
+ return; //wrong direction
+ }
+
+ instance.view.wt.selections.fill.clear();
+ instance.view.wt.selections.fill.add([priv.selStart.coords().row, priv.selStart.coords().col]);
+ instance.view.wt.selections.fill.add([priv.selEnd.coords().row, priv.selEnd.coords().col]);
+ instance.view.wt.selections.fill.add(coords);
+ instance.view.render();
+ }
+ };
+
+ editproxy = { //this public assignment is only temporary
+ /**
+ * Create input field
+ */
+ init: function () {
+ priv.onCut = function onCut() {
+ if (Handsontable.activeGuid !== instance.guid) {
+ return;
+ }
+
+ selection.empty();
+ };
+
+ priv.onPaste = function onPaste(str) {
+ if (Handsontable.activeGuid !== instance.guid) {
+ return;
+ }
+
+ var input = str.replace(/^[\r\n]*/g, '').replace(/[\r\n]*$/g, '') //remove newline from the start and the end of the input
+ , inputArray = SheetClip.parse(input)
+ , coords = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()])
+ , areaStart = coords.TL
+ , areaEnd = {
+ row: Math.max(coords.BR.row, inputArray.length - 1 + coords.TL.row),
+ col: Math.max(coords.BR.col, inputArray[0].length - 1 + coords.TL.col)
+ };
+
+ instance.PluginHooks.once('afterChange', function (changes, source) {
+ if (changes && changes.length) {
+ instance.selectCell(areaStart.row, areaStart.col, areaEnd.row, areaEnd.col);
+ }
+ });
+
+ grid.populateFromArray(areaStart, inputArray, areaEnd, 'paste', priv.settings.pasteMode);
+ };
+
+ function onKeyDown(event) {
+ if (Handsontable.activeGuid !== instance.guid) {
+ return;
+ }
+
+ if (priv.settings.beforeOnKeyDown) { // HOT in HOT Plugin
+ priv.settings.beforeOnKeyDown.call(instance, event);
+ }
+
+ if ($body.children('.context-menu-list:visible').length) {
+ return;
+ }
+
+ if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) {
+ //when CTRL is pressed, prepare selectable text in textarea
+ //http://stackoverflow.com/questions/3902635/how-does-one-capture-a-macs-command-key-via-javascript
+ editproxy.setCopyableText();
+ return;
+ }
+
+ priv.lastKeyCode = event.keyCode;
+ if (selection.isSelected()) {
+ var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
+ if (Handsontable.helper.isPrintableChar(event.keyCode) && ctrlDown) {
+ if (event.keyCode === 65) { //CTRL + A
+ selection.selectAll(); //select all cells
+ editproxy.setCopyableText();
+ event.preventDefault();
+ }
+ else if (event.keyCode === 89 || (event.shiftKey && event.keyCode === 90)) { //CTRL + Y or CTRL + SHIFT + Z
+ priv.undoRedo && priv.undoRedo.redo();
+ }
+ else if (event.keyCode === 90) { //CTRL + Z
+ priv.undoRedo && priv.undoRedo.undo();
+ }
+ return;
+ }
+
+ var rangeModifier = event.shiftKey ? selection.setRangeEnd : selection.setRangeStart;
+
+ instance.PluginHooks.run('beforeKeyDown', event);
+ if (!event.isImmediatePropagationStopped()) {
+
+ switch (event.keyCode) {
+ case 38: /* arrow up */
+ if (event.shiftKey) {
+ selection.transformEnd(-1, 0);
+ }
+ else {
+ selection.transformStart(-1, 0);
+ }
+ event.preventDefault();
+ event.stopPropagation(); //required by HandsontableEditor
+ break;
+
+ case 9: /* tab */
+ var tabMoves = typeof priv.settings.tabMoves === 'function' ? priv.settings.tabMoves(event) : priv.settings.tabMoves;
+ if (event.shiftKey) {
+ selection.transformStart(-tabMoves.row, -tabMoves.col); //move selection left
+ }
+ else {
+ selection.transformStart(tabMoves.row, tabMoves.col, true); //move selection right (add a new column if needed)
+ }
+ event.preventDefault();
+ event.stopPropagation(); //required by HandsontableEditor
+ break;
+
+ case 39: /* arrow right */
+ if (event.shiftKey) {
+ selection.transformEnd(0, 1);
+ }
+ else {
+ selection.transformStart(0, 1);
+ }
+ event.preventDefault();
+ event.stopPropagation(); //required by HandsontableEditor
+ break;
+
+ case 37: /* arrow left */
+ if (event.shiftKey) {
+ selection.transformEnd(0, -1);
+ }
+ else {
+ selection.transformStart(0, -1);
+ }
+ event.preventDefault();
+ event.stopPropagation(); //required by HandsontableEditor
+ break;
+
+ case 8: /* backspace */
+ case 46: /* delete */
+ selection.empty(event);
+ event.preventDefault();
+ break;
+
+ case 40: /* arrow down */
+ if (event.shiftKey) {
+ selection.transformEnd(1, 0); //expanding selection down with shift
+ }
+ else {
+ selection.transformStart(1, 0); //move selection down
+ }
+ event.preventDefault();
+ event.stopPropagation(); //required by HandsontableEditor
+ break;
+
+ case 113: /* F2 */
+ event.preventDefault(); //prevent Opera from opening Go to Page dialog
+ break;
+
+ case 13: /* return/enter */
+ var enterMoves = typeof priv.settings.enterMoves === 'function' ? priv.settings.enterMoves(event) : priv.settings.enterMoves;
+
+ if (event.shiftKey) {
+ selection.transformStart(-enterMoves.row, -enterMoves.col); //move selection up
+ }
+ else {
+ selection.transformStart(enterMoves.row, enterMoves.col, true); //move selection down (add a new row if needed)
+ }
+
+ event.preventDefault(); //don't add newline to field
+ break;
+
+ case 36: /* home */
+ if (event.ctrlKey || event.metaKey) {
+ rangeModifier({row: 0, col: priv.selStart.col()});
+ }
+ else {
+ rangeModifier({row: priv.selStart.row(), col: 0});
+ }
+ event.preventDefault(); //don't scroll the window
+ event.stopPropagation(); //required by HandsontableEditor
+ break;
+
+ case 35: /* end */
+ if (event.ctrlKey || event.metaKey) {
+ rangeModifier({row: instance.countRows() - 1, col: priv.selStart.col()});
+ }
+ else {
+ rangeModifier({row: priv.selStart.row(), col: instance.countCols() - 1});
+ }
+ event.preventDefault(); //don't scroll the window
+ event.stopPropagation(); //required by HandsontableEditor
+ break;
+
+ case 33: /* pg up */
+ selection.transformStart(-instance.countVisibleRows(), 0);
+ instance.view.wt.scrollVertical(-instance.countVisibleRows());
+ instance.view.render();
+ event.preventDefault(); //don't page up the window
+ event.stopPropagation(); //required by HandsontableEditor
+ break;
+
+ case 34: /* pg down */
+ selection.transformStart(instance.countVisibleRows(), 0);
+ instance.view.wt.scrollVertical(instance.countVisibleRows());
+ instance.view.render();
+ event.preventDefault(); //don't page down the window
+ event.stopPropagation(); //required by HandsontableEditor
+ break;
+
+ default:
+ break;
+ }
+
+ }
+ }
+ }
+
+ instance.copyPaste = CopyPaste.getInstance();
+ instance.copyPaste.onCut(priv.onCut);
+ instance.copyPaste.onPaste(priv.onPaste);
+ $document.on('keydown.handsontable.' + instance.guid, onKeyDown);
+ },
+
+ /**
+ * Destroy current editor, if exists
+ * @param {Boolean} revertOriginal
+ */
+ destroy: function (revertOriginal) {
+ if (typeof priv.editorDestroyer === "function") {
+ var destroyer = priv.editorDestroyer; //this copy is needed, otherwise destroyer can enter an infinite loop
+ priv.editorDestroyer = null;
+ destroyer(revertOriginal);
+ }
+ },
+
+ /**
+ * Prepares copyable text in the invisible textarea
+ */
+ setCopyableText: function () {
+ var startRow = Math.min(priv.selStart.row(), priv.selEnd.row());
+ var startCol = Math.min(priv.selStart.col(), priv.selEnd.col());
+ var endRow = Math.max(priv.selStart.row(), priv.selEnd.row());
+ var endCol = Math.max(priv.selStart.col(), priv.selEnd.col());
+ var finalEndRow = Math.min(endRow, startRow + priv.settings.copyRowsLimit - 1);
+ var finalEndCol = Math.min(endCol, startCol + priv.settings.copyColsLimit - 1);
+
+ instance.copyPaste.copyable(datamap.getText({row: startRow, col: startCol}, {row: finalEndRow, col: finalEndCol}));
+
+ if (endRow !== finalEndRow || endCol !== finalEndCol) {
+ instance.PluginHooks.run("afterCopyLimit", endRow - startRow + 1, endCol - startCol + 1, priv.settings.copyRowsLimit, priv.settings.copyColsLimit);
+ }
+ },
+
+ /**
+ * Prepare text input to be displayed at given grid cell
+ */
+ prepare: function () {
+ if (!instance.getCellMeta(priv.selStart.row(), priv.selStart.col()).isWritable) {
+ return;
+ }
+
+ instance.listen();
+ var TD = instance.view.getCellAtCoords(priv.selStart.coords());
+ priv.editorDestroyer = instance.view.applyCellTypeMethod('editor', TD, priv.selStart.row(), priv.selStart.col());
+ //presumably TD can be removed from here. Cell editor should also listen for changes if editable cell is outside from viewport
+ }
+ };
+
+ this.init = function () {
+ instance.PluginHooks.run('beforeInit');
+ editproxy.init();
+
+ this.updateSettings(priv.settings, true);
+ this.parseSettingsFromDOM();
+ this.view = new Handsontable.TableView(this);
+
+ this.forceFullRender = true; //used when data was changed
+ this.view.render();
+
+ if (typeof priv.firstRun === 'object') {
+ instance.PluginHooks.run('afterChange', priv.firstRun[0], priv.firstRun[1]);
+ priv.firstRun = false;
+ }
+ instance.PluginHooks.run('afterInit');
+ };
+
+ function validateChanges(changes, source, callback) {
+ var waitingForValidator = 0;
+
+ for (var i = changes.length - 1; i >= 0; i--) {
+ if (changes[i] === null) {
+ changes.splice(i, 1);
+ }
+ else {
+ var cellProperties = instance.getCellMeta(changes[i][0], datamap.propToCol(changes[i][1]));
+
+ if (cellProperties.dataType === 'number' && typeof changes[i][3] === 'string') {
+ if (changes[i][3].length > 0 && /^-?[\d\s]*\.?\d*$/.test(changes[i][3])) {
+ changes[i][3] = numeral().unformat(changes[i][3] || '0'); //numeral cannot unformat empty string
+ }
+ }
+
+ if (cellProperties.validator) {
+ waitingForValidator++;
+ instance.validateCell(changes[i][3], cellProperties, (function (i, cellProperties) {
+ return function (result) {
+ if (typeof result !== 'boolean') {
+ throw new Error("Validation error: result is not boolean");
+ }
+ if (result === false && cellProperties.allowInvalid === false) {
+ changes.splice(i, 1);
+ --i;
+ }
+ waitingForValidator--;
+ resolve();
+ }
+ })(i, cellProperties)
+ , source);
+ }
+ }
+ }
+ resolve();
+
+ function resolve() {
+ var beforeChangeResult;
+ if (waitingForValidator === 0) {
+ if (changes.length) {
+ beforeChangeResult = instance.PluginHooks.execute("beforeChange", changes, source);
+ if (typeof beforeChangeResult === 'function') {
+ $.when(result).then(function () {
+ callback(); //called when async validators and async beforeChange are resolved
+ });
+ }
+ else if (beforeChangeResult === false) {
+ changes.splice(0, changes.length); //invalidate all changes (remove everything from array)
+ }
+ }
+ if (typeof beforeChangeResult !== 'function') {
+ callback(); //called when async validators are resolved and beforeChange was not async
+ }
+ }
+ }
+ }
+
+ /**
+ * Internal function to apply changes. Called after validateChanges
+ * @param {Array} changes Array in form of [row, prop, oldValue, newValue]
+ * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
+ */
+ function applyChanges(changes, source) {
+ var i = changes.length - 1;
+
+ if (i < 0) {
+ return;
+ }
+
+ for (; 0 <= i; i--) {
+ if (changes[i] === null) {
+ changes.splice(i, 1);
+ continue;
+ }
+
+ if (priv.settings.minSpareRows) {
+ while (changes[i][0] > instance.countRows() - 1) {
+ datamap.createRow();
+ }
+ }
+
+ if (priv.dataType === 'array' && priv.settings.minSpareCols) {
+ while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) {
+ datamap.createCol();
+ }
+ }
+
+ datamap.set(changes[i][0], changes[i][1], changes[i][3]);
+ }
+
+ instance.forceFullRender = true; //used when data was changed
+ grid.adjustRowsAndCols();
+ selection.refreshBorders();
+ instance.PluginHooks.run('afterChange', changes, source || 'edit');
+ }
+
+ this.validateCell = function (value, cellProperties, callback, source) {
+ var validator = cellProperties.validator;
+
+ if (Object.prototype.toString.call(validator) === '[object RegExp]') {
+ validator = (function (validator) {
+ return function (value, callback) {
+ callback(validator.test(value));
+ }
+ })(validator);
+ }
+
+ if (typeof validator === 'function') {
+ value = instance.PluginHooks.execute("beforeValidate", value, cellProperties.row, cellProperties.prop, source);
+
+ validator.call(cellProperties, value, function (valid) {
+ if (cellProperties.allowInvalid) {
+ cellProperties.valid = valid;
+ }
+ valid = instance.PluginHooks.execute("afterValidate", valid, value, cellProperties.row, cellProperties.prop, source);
+ callback(valid);
+ });
+ }
+ };
+
+ function setDataInputToArray(row, prop_or_col, value) {
+ if (typeof row === "object") { //is it an array of changes
+ return row;
+ }
+ else if ($.isPlainObject(value)) { //backwards compatibility
+ return value;
+ }
+ else {
+ return [
+ [row, prop_or_col, value]
+ ];
+ }
+ }
+
+ /**
+ * Set data at given cell
+ * @public
+ * @param {Number|Array} row or array of changes in format [[row, col, value], ...]
+ * @param {Number|String} col or source String
+ * @param {String} value
+ * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
+ */
+ this.setDataAtCell = function (row, col, value, source) {
+ var input = setDataInputToArray(row, col, value)
+ , i
+ , ilen
+ , changes = []
+ , prop;
+
+ for (i = 0, ilen = input.length; i < ilen; i++) {
+ if (typeof input[i] !== 'object') {
+ throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter');
+ }
+ if (typeof input[i][1] !== 'number') {
+ throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`');
+ }
+ prop = datamap.colToProp(input[i][1]);
+ changes.push([
+ input[i][0],
+ prop,
+ datamap.get(input[i][0], prop),
+ input[i][2]
+ ]);
+ }
+
+ if (!source && typeof row === "object") {
+ source = col;
+ }
+
+ validateChanges(changes, source, function () {
+ applyChanges(changes, source);
+ });
+ };
+
+
+ /**
+ * Set data at given row property
+ * @public
+ * @param {Number|Array} row or array of changes in format [[row, prop, value], ...]
+ * @param {String} prop or source String
+ * @param {String} value
+ * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
+ */
+ this.setDataAtRowProp = function (row, prop, value, source) {
+ var input = setDataInputToArray(row, prop, value)
+ , i
+ , ilen
+ , changes = [];
+
+ for (i = 0, ilen = input.length; i < ilen; i++) {
+ changes.push([
+ input[i][0],
+ input[i][1],
+ datamap.get(input[i][0], input[i][1]),
+ input[i][2]
+ ]);
+ }
+
+ if (!source && typeof row === "object") {
+ source = prop;
+ }
+
+ validateChanges(changes, source, function () {
+ applyChanges(changes, source);
+ });
+ };
+
+ /**
+ * Listen to keyboard input
+ */
+ this.listen = function () {
+ Handsontable.activeGuid = instance.guid;
+
+ if (document.activeElement && document.activeElement !== document.body) {
+ document.activeElement.blur();
+ }
+ else if (!document.activeElement) { //IE
+ document.body.focus();
+ }
+ };
+
+ /**
+ * Destroys current editor, renders and selects current cell. If revertOriginal != true, edited data is saved
+ * @param {Boolean} revertOriginal
+ */
+ this.destroyEditor = function (revertOriginal) {
+ selection.refreshBorders(revertOriginal);
+ };
+
+ /**
+ * Populate cells at position with 2d array
+ * @param {Number} row Start row
+ * @param {Number} col Start column
+ * @param {Array} input 2d array
+ * @param {Number=} endRow End row (use when you want to cut input when certain row is reached)
+ * @param {Number=} endCol End column (use when you want to cut input when certain column is reached)
+ * @param {String=} [source="populateFromArray"]
+ * @param {String=} [method="overwrite"]
+ * @return {Object|undefined} ending td in pasted area (only if any cell was changed)
+ */
+ this.populateFromArray = function (row, col, input, endRow, endCol, source, method) {
+ if (typeof input !== 'object') {
+ throw new Error("populateFromArray parameter `input` must be an array"); //API changed in 0.9-beta2, let's check if you use it correctly
+ }
+ return grid.populateFromArray({row: row, col: col}, input, typeof endRow === 'number' ? {row: endRow, col: endCol} : null, source, method);
+ };
+
+ /**
+ * Adds/removes data from the column
+ * @param {Number} col Index of column in which do you want to do splice.
+ * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
+ * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
+ * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
+ */
+ this.spliceCol = function (col, index, amount/*, elements... */) {
+ return datamap.spliceCol.apply(null, arguments);
+ };
+
+ /**
+ * Adds/removes data from the row
+ * @param {Number} row Index of column in which do you want to do splice.
+ * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
+ * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
+ * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
+ */
+ this.spliceRow = function (row, index, amount/*, elements... */) {
+ return datamap.spliceRow.apply(null, arguments);
+ };
+
+ /**
+ * Returns the top left (TL) and bottom right (BR) selection coordinates
+ * @param {Object[]} coordsArr
+ * @returns {Object}
+ */
+ this.getCornerCoords = function (coordsArr) {
+ return grid.getCornerCoords(coordsArr);
+ };
+
+ /**
+ * Returns current selection. Returns undefined if there is no selection.
+ * @public
+ * @return {Array} [`startRow`, `startCol`, `endRow`, `endCol`]
+ */
+ this.getSelected = function () { //https://github.com/warpech/jquery-handsontable/issues/44 //cjl
+ if (selection.isSelected()) {
+ return [priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col()];
+ }
+ };
+
+ /**
+ * Parse settings from DOM and CSS
+ * @public
+ */
+ this.parseSettingsFromDOM = function () {
+ var overflow = this.rootElement.css('overflow');
+ if (overflow === 'scroll' || overflow === 'auto') {
+ this.rootElement[0].style.overflow = 'visible';
+ priv.settingsFromDOM.overflow = overflow;
+ }
+ else if (priv.settings.width === void 0 || priv.settings.height === void 0) {
+ priv.settingsFromDOM.overflow = 'auto';
+ }
+
+ if (priv.settings.width === void 0) {
+ priv.settingsFromDOM.width = this.rootElement.width();
+ }
+ else {
+ priv.settingsFromDOM.width = void 0;
+ }
+
+ priv.settingsFromDOM.height = void 0;
+ if (priv.settings.height === void 0) {
+ if (priv.settingsFromDOM.overflow === 'scroll' || priv.settingsFromDOM.overflow === 'auto') {
+ //this needs to read only CSS/inline style and not actual height
+ //so we need to call getComputedStyle on cloned container
+ var clone = this.rootElement[0].cloneNode(false);
+ var parent = this.rootElement[0].parentNode;
+ if (parent) {
+ clone.removeAttribute('id');
+ parent.appendChild(clone);
+ var computedHeight = parseInt(window.getComputedStyle(clone, null).getPropertyValue('height'), 10);
+ if (computedHeight > 0) {
+ priv.settingsFromDOM.height = computedHeight;
+ }
+ parent.removeChild(clone);
+ }
+ }
+ }
+ };
+
+ /**
+ * Render visible data
+ * @public
+ */
+ this.render = function () {
+ if (instance.view) {
+ priv.cellSettings.length = 0; //clear cellSettings cache
+ instance.forceFullRender = true; //used when data was changed
+ instance.parseSettingsFromDOM();
+ selection.refreshBorders(null, true);
+ }
+ };
+
+ /**
+ * Load data from array
+ * @public
+ * @param {Array} data
+ */
+ this.loadData = function (data) {
+ if (!(data.push && data.splice)) { //check if data is array. Must use duck-type check so Backbone Collections also pass it
+ throw new Error("loadData only accepts array of objects or array of arrays (" + typeof data + " given)");
+ }
+
+ priv.isPopulated = false;
+ GridSettings.prototype.data = data;
+
+ if (priv.settings.dataSchema instanceof Array || data[0] instanceof Array) {
+ priv.dataType = 'array';
+ }
+ else if ($.isFunction(priv.settings.dataSchema)) {
+ priv.dataType = 'function';
+ }
+ else {
+ priv.dataType = 'object';
+ }
+
+ if (data[0]) {
+ priv.duckDataSchema = datamap.recursiveDuckSchema(data[0]);
+ }
+ else {
+ priv.duckDataSchema = {};
+ }
+ datamap.createMap();
+
+ grid.adjustRowsAndCols();
+ instance.PluginHooks.run('afterLoadData');
+
+ if (priv.firstRun) {
+ priv.firstRun = [null, 'loadData'];
+ }
+ else {
+ instance.PluginHooks.run('afterChange', null, 'loadData');
+ instance.render();
+ }
+ priv.isPopulated = true;
+ instance.clearUndo();
+ };
+
+ /**
+ * Return the current data object (the same that was passed by `data` configuration option or `loadData` method). Optionally you can provide cell range `r`, `c`, `r2`, `c2` to get only a fragment of grid data
+ * @public
+ * @param {Number} r (Optional) From row
+ * @param {Number} c (Optional) From col
+ * @param {Number} r2 (Optional) To row
+ * @param {Number} c2 (Optional) To col
+ * @return {Array|Object}
+ */
+ this.getData = function (r, c, r2, c2) {
+ if (typeof r === 'undefined') {
+ return datamap.getAll();
+ }
+ else {
+ return datamap.getRange({row: r, col: c}, {row: r2, col: c2});
+ }
+ };
+
+ /**
+ * Update settings
+ * @public
+ */
+ this.updateSettings = function (settings, init) {
+ var i, r, rlen, c, clen;
+
+ if (typeof settings.rows !== "undefined") {
+ throw new Error("'rows' setting is no longer supported. do you mean startRows, minRows or maxRows?");
+ }
+ if (typeof settings.cols !== "undefined") {
+ throw new Error("'cols' setting is no longer supported. do you mean startCols, minCols or maxCols?");
+ }
+
+ if (typeof settings.undo !== "undefined") {
+ if (priv.undoRedo && settings.undo === false) {
+ priv.undoRedo = null;
+ }
+ else if (!priv.undoRedo && settings.undo === true) {
+ priv.undoRedo = new Handsontable.UndoRedo(instance);
+ }
+ }
+
+ for (i in settings) {
+ if (i === 'data') {
+ continue; //loadData will be triggered later
+ }
+ else {
+ if (instance.PluginHooks.hooks.persistent[i] !== void 0 || instance.PluginHooks.legacy[i] !== void 0) {
+ instance.PluginHooks.add(i, settings[i]);
+ }
+ else {
+ // Update settings
+ if (!init && settings.hasOwnProperty(i)) {
+ GridSettings.prototype[i] = settings[i];
+ }
+
+ //launch extensions
+ if (Handsontable.extension[i]) {
+ priv.extensions[i] = new Handsontable.extension[i](instance, settings[i]);
+ }
+ }
+ }
+ }
+
+ // Load data or create data map
+ if (settings.data === void 0 && priv.settings.data === void 0) {
+ var data = [];
+ var row;
+ for (r = 0, rlen = priv.settings.startRows; r < rlen; r++) {
+ row = [];
+ for (c = 0, clen = priv.settings.startCols; c < clen; c++) {
+ row.push(null);
+ }
+ data.push(row);
+ }
+ instance.loadData(data); //data source created just now
+ }
+ else if (settings.data !== void 0) {
+ instance.loadData(settings.data); //data source given as option
+ }
+ else if (settings.columns !== void 0) {
+ datamap.createMap();
+ }
+
+ // Init columns constructors configuration
+ clen = instance.countCols();
+
+ //Clear cellSettings cache
+ priv.cellSettings.length = 0;
+
+ if (clen > 0) {
+ var prop, proto, column;
+
+ for (i = 0; i < clen; i++) {
+ priv.columnSettings[i] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts, Handsontable.TextCell);
+
+ // shortcut for prototype
+ proto = priv.columnSettings[i].prototype;
+
+ // Use settings provided by user
+ if (GridSettings.prototype.columns) {
+ column = GridSettings.prototype.columns[i];
+ for (prop in column) {
+ if (column.hasOwnProperty(prop)) {
+ proto[prop] = column[prop];
+ }
+ }
+ }
+ }
+ }
+
+ if (typeof settings.fillHandle !== "undefined") {
+ if (autofill.handle && settings.fillHandle === false) {
+ autofill.disable();
+ }
+ else if (!autofill.handle && settings.fillHandle !== false) {
+ autofill.init();
+ }
+ }
+
+ grid.adjustRowsAndCols();
+ if (instance.view) {
+ instance.forceFullRender = true; //used when data was changed
+ selection.refreshBorders(null, true);
+ }
+ };
+
+ /**
+ * Returns current settings object
+ * @return {Object}
+ */
+ this.getSettings = function () {
+ return priv.settings;
+ };
+
+ /**
+ * Returns current settingsFromDOM object
+ * @return {Object}
+ */
+ this.getSettingsFromDOM = function () {
+ return priv.settingsFromDOM;
+ };
+
+ /**
+ * Clears grid
+ * @public
+ */
+ this.clear = function () {
+ selection.selectAll();
+ selection.empty();
+ };
+
+ /**
+ * Return true if undo can be performed, false otherwise
+ * @public
+ */
+ this.isUndoAvailable = function () {
+ return priv.undoRedo && priv.undoRedo.isUndoAvailable();
+ };
+
+ /**
+ * Return true if redo can be performed, false otherwise
+ * @public
+ */
+ this.isRedoAvailable = function () {
+ return priv.undoRedo && priv.undoRedo.isRedoAvailable();
+ };
+
+ /**
+ * Undo last edit
+ * @public
+ */
+ this.undo = function () {
+ priv.undoRedo && priv.undoRedo.undo();
+ };
+
+ /**
+ * Redo edit (used to reverse an undo)
+ * @public
+ */
+ this.redo = function () {
+ priv.undoRedo && priv.undoRedo.redo();
+ };
+
+ /**
+ * Clears undo history
+ * @public
+ */
+ this.clearUndo = function () {
+ priv.undoRedo && priv.undoRedo.clear();
+ };
+
+ /**
+ * Inserts or removes rows and columns
+ * @param {String} action See grid.alter for possible values
+ * @param {Number} index
+ * @param {Number} amount
+ * @param {String} [source] Optional. Source of hook runner.
+ * @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
+ * @public
+ */
+ this.alter = function (action, index, amount, source, keepEmptyRows) {
+ grid.alter(action, index, amount, source, keepEmptyRows);
+ };
+
+ /**
+ * Returns
element corresponding to params row, col
+ * @param {Number} row
+ * @param {Number} col
+ * @public
+ * @return {Element}
+ */
+ this.getCell = function (row, col) {
+ return instance.view.getCellAtCoords({row: row, col: col});
+ };
+
+ /**
+ * Returns property name associated with column number
+ * @param {Number} col
+ * @public
+ * @return {String}
+ */
+ this.colToProp = function (col) {
+ return datamap.colToProp(col);
+ };
+
+ /**
+ * Returns column number associated with property name
+ * @param {String} prop
+ * @public
+ * @return {Number}
+ */
+ this.propToCol = function (prop) {
+ return datamap.propToCol(prop);
+ };
+
+ /**
+ * Return value at `row`, `col`
+ * @param {Number} row
+ * @param {Number} col
+ * @public
+ * @return value (mixed data type)
+ */
+ this.getDataAtCell = function (row, col) {
+ return datamap.get(row, datamap.colToProp(col));
+ };
+
+ /**
+ * Return value at `row`, `prop`
+ * @param {Number} row
+ * @param {String} prop
+ * @public
+ * @return value (mixed data type)
+ */
+ this.getDataAtRowProp = function (row, prop) {
+ return datamap.get(row, prop);
+ };
+
+ /**
+ * Return value at `col`
+ * @param {Number} col
+ * @public
+ * @return value (mixed data type)
+ */
+ this.getDataAtCol = function (col) {
+ return [].concat.apply([], datamap.getRange({row: 0, col: col}, {row: priv.settings.data.length - 1, col: col}));
+ };
+
+ /**
+ * Return value at `prop`
+ * @param {String} prop
+ * @public
+ * @return value (mixed data type)
+ */
+ this.getDataAtProp = function (prop) {
+ return [].concat.apply([], datamap.getRange({row: 0, col: datamap.propToCol(prop)}, {row: priv.settings.data.length - 1, col: datamap.propToCol(prop)}));
+ };
+
+ /**
+ * Return value at `row`
+ * @param {Number} row
+ * @public
+ * @return value (mixed data type)
+ */
+ this.getDataAtRow = function (row) {
+ return priv.settings.data[row];
+ };
+
+ /**
+ * Returns cell meta data object corresponding to params row, col
+ * @param {Number} row
+ * @param {Number} col
+ * @public
+ * @return {Object}
+ */
+ this.getCellMeta = function (row, col) {
+ var prop = datamap.colToProp(col)
+ , cellProperties
+ , type
+ , i;
+
+ col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col); //translate col of a moved column. warning: this must be done after datamap.colToProp
+
+ if ("undefined" === typeof priv.columnSettings[col]) {
+ priv.columnSettings[col] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts, Handsontable.TextCell);
+ }
+
+ if (!priv.cellSettings[row]) {
+ priv.cellSettings[row] = {}
+ }
+ if (!priv.cellSettings[row][col]) {
+ priv.cellSettings[row][col] = new priv.columnSettings[col]();
+ }
+
+ cellProperties = priv.cellSettings[row][col]; //retrieve cellProperties from cache
+
+ cellProperties.row = row;
+ cellProperties.col = col;
+ cellProperties.prop = prop;
+ cellProperties.instance = instance;
+
+ if (cellProperties.cells) {
+ var settings = cellProperties.cells.call(cellProperties, row, col, prop) || {}
+ , key;
+
+ for (key in settings) {
+ if (settings.hasOwnProperty(key)) {
+ cellProperties[key] = settings[key];
+ }
+ }
+ }
+
+ cellProperties.isWritable = !cellProperties.readOnly;
+
+ instance.PluginHooks.run('beforeGetCellMeta', row, col, cellProperties);
+
+ if (typeof cellProperties.type === 'string' && cellProperties.type !== 'text') {
+ type = Handsontable.cellTypes[cellProperties.type];
+ if (type === void 0) {
+ throw new Error('You declared cell type "' + cellProperties.type + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes');
+ }
+ }
+ else if (typeof cellProperties.type === 'object') {
+ type = cellProperties.type;
+ }
+
+ if (type) {
+ for (i in type) {
+ if (type.hasOwnProperty(i) && cellProperties[i] === Handsontable.cellTypes.text[i]) {
+ cellProperties[i] = type[i];
+ }
+ }
+ }
+
+ if (cellProperties.validator && cellProperties.valid === void 0) { //this is the first render of this cell and we need to know if it's valid
+ instance.validateCell(instance.getDataAtCell(row, col), cellProperties, function (res) {
+ }, 'getCellMeta');
+ }
+
+ instance.PluginHooks.run('afterGetCellMeta', row, col, cellProperties);
+
+ return cellProperties;
+ };
+
+ /**
+ * Return array of row headers (if they are enabled). If param `row` given, return header at given row as string
+ * @param {Number} row (Optional)
+ * @return {Array|String}
+ */
+ this.getRowHeader = function (row) {
+ if (row === void 0) {
+ var out = [];
+ for (var i = 0, ilen = instance.countRows(); i < ilen; i++) {
+ out.push(instance.getRowHeader(i));
+ }
+ return out;
+ }
+ else if (Object.prototype.toString.call(priv.settings.rowHeaders) === '[object Array]' && priv.settings.rowHeaders[row] !== void 0) {
+ return priv.settings.rowHeaders[row];
+ }
+ else if (typeof priv.settings.rowHeaders === 'function') {
+ return priv.settings.rowHeaders(row);
+ }
+ else if (priv.settings.rowHeaders && typeof priv.settings.rowHeaders !== 'string' && typeof priv.settings.rowHeaders !== 'number') {
+ return row + 1;
+ }
+ else {
+ return priv.settings.rowHeaders;
+ }
+ };
+
+ /**
+ * Return array of column headers (if they are enabled). If param `col` given, return header at given column as string
+ * @param {Number} col (Optional)
+ * @return {Array|String}
+ */
+ this.getColHeader = function (col) {
+ if (col === void 0) {
+ var out = [];
+ for (var i = 0, ilen = instance.countCols(); i < ilen; i++) {
+ out.push(instance.getColHeader(i));
+ }
+ return out;
+ }
+ else {
+ col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col);
+
+ if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].title) {
+ return priv.settings.columns[col].title;
+ }
+ else if (Object.prototype.toString.call(priv.settings.colHeaders) === '[object Array]' && priv.settings.colHeaders[col] !== void 0) {
+ return priv.settings.colHeaders[col];
+ }
+ else if (typeof priv.settings.colHeaders === 'function') {
+ return priv.settings.colHeaders(col);
+ }
+ else if (priv.settings.colHeaders && typeof priv.settings.colHeaders !== 'string' && typeof priv.settings.colHeaders !== 'number') {
+ return Handsontable.helper.spreadsheetColumnLabel(col);
+ }
+ else {
+ return priv.settings.colHeaders;
+ }
+ }
+ };
+
+ /**
+ * Return column width
+ * @param {Number} col
+ * @return {Number}
+ */
+ this.getColWidth = function (col) {
+ col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col);
+ var response = {};
+ if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].width) {
+ response.width = priv.settings.columns[col].width;
+ }
+ else if (Object.prototype.toString.call(priv.settings.colWidths) === '[object Array]' && priv.settings.colWidths[col] !== void 0) {
+ response.width = priv.settings.colWidths[col];
+ }
+ else {
+ response.width = 50;
+ }
+ instance.PluginHooks.run('afterGetColWidth', col, response);
+ return response.width;
+ };
+
+ /**
+ * Return total number of rows in grid
+ * @return {Number}
+ */
+ this.countRows = function () {
+ return priv.settings.data.length;
+ };
+
+ /**
+ * Return total number of columns in grid
+ * @return {Number}
+ */
+ this.countCols = function () {
+ if (priv.dataType === 'object' || priv.dataType === 'function') {
+ if (priv.settings.columns && priv.settings.columns.length) {
+ return priv.settings.columns.length;
+ }
+ else {
+ return priv.colToProp.length;
+ }
+ }
+ else if (priv.dataType === 'array') {
+ if (priv.settings.columns && priv.settings.columns.length) {
+ return priv.settings.columns.length;
+ }
+ else if (priv.settings.data && priv.settings.data[0] && priv.settings.data[0].length) {
+ return priv.settings.data[0].length;
+ }
+ else {
+ return 0;
+ }
+ }
+ };
+
+ /**
+ * Return index of first visible row
+ * @return {Number}
+ */
+ this.rowOffset = function () {
+ return instance.view.wt.getSetting('offsetRow');
+ };
+
+ /**
+ * Return index of first visible column
+ * @return {Number}
+ */
+ this.colOffset = function () {
+ return instance.view.wt.getSetting('offsetColumn');
+ };
+
+ /**
+ * Return number of visible rows. Returns -1 if table is not visible
+ * @return {Number}
+ */
+ this.countVisibleRows = function () {
+ return instance.view.wt.drawn ? instance.view.wt.wtTable.rowStrategy.countVisible() : -1;
+ };
+
+ /**
+ * Return number of visible columns. Returns -1 if table is not visible
+ * @return {Number}
+ */
+ this.countVisibleCols = function () {
+ return instance.view.wt.drawn ? instance.view.wt.wtTable.columnStrategy.countVisible() : -1;
+ };
+
+ /**
+ * Return number of empty rows
+ * @return {Boolean} ending If true, will only count empty rows at the end of the data source
+ */
+ this.countEmptyRows = function (ending) {
+ var i = instance.countRows() - 1
+ , empty = 0;
+ while (i >= 0) {
+ if (instance.isEmptyRow(i)) {
+ empty++;
+ }
+ else if (ending) {
+ break;
+ }
+ i--;
+ }
+ return empty;
+ };
+
+ /**
+ * Return number of empty columns
+ * @return {Boolean} ending If true, will only count empty columns at the end of the data source row
+ */
+ this.countEmptyCols = function (ending) {
+ if (instance.countRows() < 1) {
+ return 0;
+ }
+
+ var i = instance.countCols() - 1
+ , empty = 0;
+ while (i >= 0) {
+ if (instance.isEmptyCol(i)) {
+ empty++;
+ }
+ else if (ending) {
+ break;
+ }
+ i--;
+ }
+ return empty;
+ };
+
+ /**
+ * Return true if the row at the given index is empty, false otherwise
+ * @param {Number} r Row index
+ * @return {Boolean}
+ */
+ this.isEmptyRow = function (r) {
+ if (priv.settings.isEmptyRow) {
+ return priv.settings.isEmptyRow.call(instance, r);
+ }
+
+ var val;
+ for (var c = 0, clen = instance.countCols(); c < clen; c++) {
+ val = instance.getDataAtCell(r, c);
+ if (val !== '' && val !== null && typeof val !== 'undefined') {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * Return true if the column at the given index is empty, false otherwise
+ * @param {Number} c Column index
+ * @return {Boolean}
+ */
+ this.isEmptyCol = function (c) {
+ if (priv.settings.isEmptyCol) {
+ return priv.settings.isEmptyCol.call(instance, c);
+ }
+
+ var val;
+ for (var r = 0, rlen = instance.countRows(); r < rlen; r++) {
+ val = instance.getDataAtCell(r, c);
+ if (val !== '' && val !== null && typeof val !== 'undefined') {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * Selects cell on grid. Optionally selects range to another cell
+ * @param {Number} row
+ * @param {Number} col
+ * @param {Number} [endRow]
+ * @param {Number} [endCol]
+ * @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to the selection
+ * @public
+ * @return {Boolean}
+ */
+ this.selectCell = function (row, col, endRow, endCol, scrollToCell) {
+ if (typeof row !== 'number' || row < 0 || row >= instance.countRows()) {
+ return false;
+ }
+ if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) {
+ return false;
+ }
+ if (typeof endRow !== "undefined") {
+ if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) {
+ return false;
+ }
+ if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) {
+ return false;
+ }
+ }
+ priv.selStart.coords({row: row, col: col});
+ instance.listen(); //needed or otherwise prepare won't focus the cell. selectionSpec tests this (should move focus to selected cell)
+ if (typeof endRow === "undefined") {
+ selection.setRangeEnd({row: row, col: col}, scrollToCell);
+ }
+ else {
+ selection.setRangeEnd({row: endRow, col: endCol}, scrollToCell);
+ }
+
+ instance.selection.finish();
+ return true;
+ };
+
+ this.selectCellByProp = function (row, prop, endRow, endProp, scrollToCell) {
+ arguments[1] = datamap.propToCol(arguments[1]);
+ if (typeof arguments[3] !== "undefined") {
+ arguments[3] = datamap.propToCol(arguments[3]);
+ }
+ return instance.selectCell.apply(instance, arguments);
+ };
+
+ /**
+ * Deselects current sell selection on grid
+ * @public
+ */
+ this.deselectCell = function () {
+ selection.deselect();
+ };
+
+ /**
+ * Remove grid from DOM
+ * @public
+ */
+ this.destroy = function () {
+ instance.clearTimeouts();
+ if (instance.view) { //in case HT is destroyed before initialization has finished
+ instance.view.wt.destroy();
+ }
+ instance.rootElement.empty();
+ instance.rootElement.removeData('handsontable');
+ instance.rootElement.off('.handsontable');
+ $(window).off('.' + instance.guid);
+ $document.off('.' + instance.guid);
+ $body.off('.' + instance.guid);
+ instance.copyPaste.removeCallback(priv.onCut);
+ instance.copyPaste.removeCallback(priv.onPaste);
+ instance.PluginHooks.run('afterDestroy');
+ };
+
+ /**
+ * Return Handsontable instance
+ * @public
+ * @return {Object}
+ */
+ this.getInstance = function () {
+ return instance.rootElement.data("handsontable");
+ };
+
+ (function () {
+ // Create new instance of plugin hooks
+ instance.PluginHooks = new Handsontable.PluginHookClass();
+
+ // Upgrade methods to call of global PluginHooks instance
+ var _run = instance.PluginHooks.run
+ , _exe = instance.PluginHooks.execute;
+
+ instance.PluginHooks.run = function (key, p1, p2, p3, p4, p5) {
+ _run.call(this, instance, key, p1, p2, p3, p4, p5);
+ Handsontable.PluginHooks.run(instance, key, p1, p2, p3, p4, p5);
+ };
+
+ instance.PluginHooks.execute = function (key, p1, p2, p3, p4, p5) {
+ p1 = _exe.call(this, instance, key, p1, p2, p3, p4, p5);
+ p1 = Handsontable.PluginHooks.execute(instance, key, p1, p2, p3, p4, p5);
+
+ return p1;
+ };
+
+ // Map old API with new methods
+ instance.addHook = instance.PluginHooks.add;
+ instance.addHookOnce = instance.PluginHooks.once;
+
+ instance.removeHook = instance.PluginHooks.remove;
+
+ instance.runHooks = instance.PluginHooks.run;
+ instance.runHooksAndReturn = instance.PluginHooks.execute;
+
+ })();
+
+ this.timeouts = {};
+
+ /**
+ * Sets timeout. Purpose of this method is to clear all known timeouts when `destroy` method is called
+ * @public
+ */
+ this.registerTimeout = function (key, handle, ms) {
+ clearTimeout(this.timeouts[key]);
+ this.timeouts[key] = setTimeout(handle, ms || 0);
+ };
+
+ /**
+ * Clears all known timeouts
+ * @public
+ */
+ this.clearTimeouts = function () {
+ for (var key in this.timeouts) {
+ if (this.timeouts.hasOwnProperty(key)) {
+ clearTimeout(this.timeouts[key]);
+ }
+ }
+ };
+
+ /**
+ * Handsontable version
+ */
+ this.version = '0.9.9'; //inserted by grunt from package.json
+};
+
+var DefaultSettings = function () {
+};
+DefaultSettings.prototype = {
+ data: void 0,
+ width: void 0,
+ height: void 0,
+ startRows: 5,
+ startCols: 5,
+ minRows: 0,
+ minCols: 0,
+ maxRows: Infinity,
+ maxCols: Infinity,
+ minSpareRows: 0,
+ minSpareCols: 0,
+ multiSelect: true,
+ fillHandle: true,
+ fixedRowsTop: 0,
+ fixedColumnsLeft: 0,
+ undo: true,
+ outsideClickDeselects: true,
+ enterBeginsEditing: true,
+ enterMoves: {row: 1, col: 0},
+ tabMoves: {row: 0, col: 1},
+ autoWrapRow: false,
+ autoWrapCol: false,
+ copyRowsLimit: 1000,
+ copyColsLimit: 1000,
+ pasteMode: 'overwrite',
+ currentRowClassName: void 0,
+ currentColClassName: void 0,
+ stretchH: 'hybrid',
+ isEmptyRow: void 0,
+ isEmptyCol: void 0,
+ observeDOMVisibility: true,
+ allowInvalid: true,
+ invalidCellClassName: 'htInvalid',
+ fragmentSelection: false,
+ readOnly: false
+};
+
+$.fn.handsontable = function (action) {
+ var i
+ , ilen
+ , args
+ , output
+ , userSettings
+ , $this = this.first() // Use only first element from list
+ , instance = $this.data('handsontable');
+
+ // Init case
+ if (typeof action !== 'string') {
+ userSettings = action || {};
+ if (instance) {
+ instance.updateSettings(userSettings);
+ }
+ else {
+ instance = new Handsontable.Core($this, userSettings);
+ $this.data('handsontable', instance);
+ instance.init();
+ }
+
+ return $this;
+ }
+ // Action case
+ else {
+ args = [];
+ if (arguments.length > 1) {
+ for (i = 1, ilen = arguments.length; i < ilen; i++) {
+ args.push(arguments[i]);
+ }
+ }
+
+ if (instance) {
+ if (typeof instance[action] !== 'undefined') {
+ output = instance[action].apply(instance, args);
+ }
+ else {
+ throw new Error('Handsontable do not provide action: ' + action);
+ }
+ }
+
+ return output;
+ }
+};
+
+/**
+ * Handsontable TableView constructor
+ * @param {Object} instance
+ */
+Handsontable.TableView = function (instance) {
+ var that = this
+ , $window = $(window)
+ , $documentElement = $(document.documentElement);
+
+ this.instance = instance;
+ this.settings = instance.getSettings();
+ this.settingsFromDOM = instance.getSettingsFromDOM();
+
+ instance.rootElement.data('originalStyle', instance.rootElement.attr('style')); //needed to retrieve original style in jsFiddle link generator in HT examples. may be removed in future versions
+ instance.rootElement.addClass('handsontable');
+
+ var table = document.createElement('TABLE');
+ table.className = 'htCore';
+ table.appendChild(document.createElement('THEAD'));
+ table.appendChild(document.createElement('TBODY'));
+
+ instance.$table = $(table);
+ instance.rootElement.prepend(instance.$table);
+
+ $documentElement.on('keyup.' + instance.guid, function (event) {
+ if (instance.selection.isInProgress() && !event.shiftKey) {
+ instance.selection.finish();
+ }
+ });
+
+ var isMouseDown
+ , dragInterval;
+
+ $documentElement.on('mouseup.' + instance.guid, function (event) {
+ if (instance.selection.isInProgress() && event.which === 1) { //is left mouse button
+ instance.selection.finish();
+ }
+
+ isMouseDown = false;
+ clearInterval(dragInterval);
+ dragInterval = null;
+
+ if (instance.autofill.handle && instance.autofill.handle.isDragged) {
+ if (instance.autofill.handle.isDragged > 1) {
+ instance.autofill.apply();
+ }
+ instance.autofill.handle.isDragged = 0;
+ }
+ });
+
+ $documentElement.on('mousedown.' + instance.guid, function (event) {
+ var next = event.target;
+
+ if (next !== that.wt.wtTable.spreader) { //immediate click on "spreader" means click on the right side of vertical scrollbar
+ while (next !== document.documentElement) {
+ //X-HANDSONTABLE is the tag name in Web Components version of HOT. Removal of this breaks cell selection
+ if (next === null) {
+ return; //click on something that was a row but now is detached (possibly because your click triggered a rerender)
+ }
+ if (next === instance.rootElement[0] || next.nodeName === 'X-HANDSONTABLE' || next.id === 'context-menu-layer' || $(next).is('.context-menu-list') || $(next).is('.typeahead li')) {
+ return; //click inside container
+ }
+ next = next.parentNode;
+ }
+ }
+
+ if (that.settings.outsideClickDeselects) {
+ instance.deselectCell();
+ }
+ else {
+ instance.destroyEditor();
+ }
+ });
+
+ instance.$table.on('selectstart', function (event) {
+ if (that.settings.fragmentSelection) {
+ return;
+ }
+
+ //https://github.com/warpech/jquery-handsontable/issues/160
+ //selectstart is IE only event. Prevent text from being selected when performing drag down in IE8
+ event.preventDefault();
+ });
+
+ instance.$table.on('mouseenter', function () {
+ if (dragInterval) { //if dragInterval was set (that means mouse was really outside of table, not over an element that is outside of
in DOM
+ clearInterval(dragInterval);
+ dragInterval = null;
+ }
+ });
+
+ instance.$table.on('mouseleave', function (event) {
+ if (!(isMouseDown || (instance.autofill.handle && instance.autofill.handle.isDragged))) {
+ return;
+ }
+
+ var tolerance = 1 //this is needed because width() and height() contains stuff like cell borders
+ , offset = that.wt.wtDom.offset(table)
+ , offsetTop = offset.top + tolerance
+ , offsetLeft = offset.left + tolerance
+ , width = that.containerWidth - that.wt.getSetting('scrollbarWidth') - 2 * tolerance
+ , height = that.containerHeight - that.wt.getSetting('scrollbarHeight') - 2 * tolerance
+ , method
+ , row = 0
+ , col = 0
+ , dragFn;
+
+ if (event.pageY < offsetTop) { //top edge crossed
+ row = -1;
+ method = 'scrollVertical';
+ }
+ else if (event.pageY >= offsetTop + height) { //bottom edge crossed
+ row = 1;
+ method = 'scrollVertical';
+ }
+ else if (event.pageX < offsetLeft) { //left edge crossed
+ col = -1;
+ method = 'scrollHorizontal';
+ }
+ else if (event.pageX >= offsetLeft + width) { //right edge crossed
+ col = 1;
+ method = 'scrollHorizontal';
+ }
+
+ if (method) {
+ dragFn = function () {
+ if (isMouseDown || (instance.autofill.handle && instance.autofill.handle.isDragged)) {
+ //instance.selection.transformEnd(row, col);
+ that.wt[method](row + col).draw();
+ }
+ };
+ dragFn();
+ dragInterval = setInterval(dragFn, 100);
+ }
+ });
+
+ var clearTextSelection = function () {
+ //http://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript
+ if (window.getSelection) {
+ if (window.getSelection().empty) { // Chrome
+ window.getSelection().empty();
+ } else if (window.getSelection().removeAllRanges) { // Firefox
+ window.getSelection().removeAllRanges();
+ }
+ } else if (document.selection) { // IE?
+ document.selection.empty();
+ }
+ };
+
+ var walkontableConfig = {
+ table: table,
+ stretchH: this.settings.stretchH,
+ data: instance.getDataAtCell,
+ totalRows: instance.countRows,
+ totalColumns: instance.countCols,
+ scrollbarModelV: this.settings.scrollbarModelV,
+ scrollbarModelH: this.settings.scrollbarModelH,
+ offsetRow: 0,
+ offsetColumn: 0,
+ width: this.getWidth(),
+ height: this.getHeight(),
+ fixedColumnsLeft: function () {
+ return that.settings.fixedColumnsLeft;
+ },
+ fixedRowsTop: function () {
+ return that.settings.fixedRowsTop;
+ },
+ rowHeaders: function () {
+ return that.settings.rowHeaders ? [function (index, TH) {
+ that.appendRowHeader(index, TH);
+ }] : []
+ },
+ columnHeaders: function () {
+ return that.settings.colHeaders ? [function (index, TH) {
+ that.appendColHeader(index, TH);
+ }] : []
+ },
+ columnWidth: instance.getColWidth,
+ cellRenderer: function (row, column, TD) {
+ that.applyCellTypeMethod('renderer', TD, row, column);
+ },
+ selections: {
+ current: {
+ className: 'current',
+ border: {
+ width: 2,
+ color: '#5292F7',
+ style: 'solid',
+ cornerVisible: function () {
+ return that.settings.fillHandle && !that.isCellEdited() && !instance.selection.isMultiple()
+ }
+ }
+ },
+ area: {
+ className: 'area',
+ border: {
+ width: 1,
+ color: '#89AFF9',
+ style: 'solid',
+ cornerVisible: function () {
+ return that.settings.fillHandle && !that.isCellEdited() && instance.selection.isMultiple()
+ }
+ }
+ },
+ highlight: {
+ highlightRowClassName: that.settings.currentRowClassName,
+ highlightColumnClassName: that.settings.currentColClassName
+ },
+ fill: {
+ className: 'fill',
+ border: {
+ width: 1,
+ color: 'red',
+ style: 'solid'
+ }
+ }
+ },
+ hideBorderOnMouseDownOver: function () {
+ return that.settings.fragmentSelection;
+ },
+ onCellMouseDown: function (event, coords, TD) {
+ Handsontable.activeGuid = instance.guid;
+
+ isMouseDown = true;
+ var coordsObj = {row: coords[0], col: coords[1]};
+ if (event.button === 2 && instance.selection.inInSelection(coordsObj)) { //right mouse button
+ //do nothing
+ }
+ else if (event.shiftKey) {
+ instance.selection.setRangeEnd(coordsObj);
+ }
+ else {
+ instance.selection.setRangeStart(coordsObj);
+ }
+
+ if (!that.settings.fragmentSelection) {
+ event.preventDefault(); //disable text selection in Chrome
+ clearTextSelection();
+ }
+
+ if (that.settings.afterOnCellMouseDown) {
+ that.settings.afterOnCellMouseDown.call(instance, event, coords, TD);
+ }
+ },
+ /*onCellMouseOut: function (/*event, coords, TD* /) {
+ if (isMouseDown && that.settings.fragmentSelection === 'single') {
+ clearTextSelection(); //otherwise text selection blinks during multiple cells selection
+ }
+ },*/
+ onCellMouseOver: function (event, coords/*, TD*/) {
+ var coordsObj = {row: coords[0], col: coords[1]};
+ if (isMouseDown) {
+ /*if (that.settings.fragmentSelection === 'single') {
+ clearTextSelection(); //otherwise text selection blinks during multiple cells selection
+ }*/
+ instance.selection.setRangeEnd(coordsObj);
+ }
+ else if (instance.autofill.handle && instance.autofill.handle.isDragged) {
+ instance.autofill.handle.isDragged++;
+ instance.autofill.showBorder(coords);
+ }
+ },
+ onCellCornerMouseDown: function (event) {
+ instance.autofill.handle.isDragged = 1;
+ event.preventDefault();
+ },
+ onCellCornerDblClick: function () {
+ instance.autofill.selectAdjacent();
+ },
+ beforeDraw: function (force) {
+ that.beforeRender(force);
+ }
+ };
+
+ instance.PluginHooks.run('beforeInitWalkontable', walkontableConfig);
+
+ this.wt = new Walkontable(walkontableConfig);
+
+ $window.on('resize.' + instance.guid, function () {
+ instance.registerTimeout('resizeTimeout', function () {
+ instance.parseSettingsFromDOM();
+ var newWidth = that.getWidth();
+ var newHeight = that.getHeight();
+ if (walkontableConfig.width !== newWidth || walkontableConfig.height !== newHeight) {
+ instance.forceFullRender = true;
+ that.render();
+ walkontableConfig.width = newWidth;
+ walkontableConfig.height = newHeight;
+ }
+ }, 60);
+ });
+
+ $(that.wt.wtTable.spreader).on('mousedown.handsontable, contextmenu.handsontable', function (event) {
+ if (event.target === that.wt.wtTable.spreader && event.which === 3) { //right mouse button exactly on spreader means right clickon the right hand side of vertical scrollbar
+ event.stopPropagation();
+ }
+ });
+
+ $documentElement.on('click.' + instance.guid, function () {
+ if (that.settings.observeDOMVisibility) {
+ if (that.wt.drawInterrupted) {
+ that.instance.forceFullRender = true;
+ that.render();
+ }
+ }
+ });
+};
+
+Handsontable.TableView.prototype.isCellEdited = function () {
+ return (this.instance.textEditor && this.instance.textEditor.isCellEdited) || (this.instance.autocompleteEditor && this.instance.autocompleteEditor.isCellEdited) || (this.instance.handsontableEditor && this.instance.handsontableEditor.isCellEdited);
+};
+
+Handsontable.TableView.prototype.getWidth = function () {
+ var val = this.settings.width !== void 0 ? this.settings.width : this.settingsFromDOM.width;
+ return typeof val === 'function' ? val() : val;
+};
+
+Handsontable.TableView.prototype.getHeight = function () {
+ var val = this.settings.height !== void 0 ? this.settings.height : this.settingsFromDOM.height;
+ return typeof val === 'function' ? val() : val;
+};
+
+Handsontable.TableView.prototype.beforeRender = function (force) {
+ if (force) {
+ this.instance.PluginHooks.run('beforeRender');
+ this.wt.update('width', this.getWidth());
+ this.wt.update('height', this.getHeight());
+ }
+};
+
+Handsontable.TableView.prototype.render = function () {
+ this.wt.draw(!this.instance.forceFullRender);
+ this.instance.rootElement.triggerHandler('render.handsontable');
+ if (this.instance.forceFullRender) {
+ this.instance.PluginHooks.run('afterRender');
+ }
+ this.instance.forceFullRender = false;
+};
+
+Handsontable.TableView.prototype.applyCellTypeMethod = function (methodName, td, row, col) {
+ var prop = this.instance.colToProp(col)
+ , cellProperties = this.instance.getCellMeta(row, col)
+ , method = Handsontable.helper.getCellMethod(methodName, cellProperties[methodName]); //methodName is 'renderer' or 'editor'
+
+ return method(this.instance, td, row, col, prop, this.instance.getDataAtRowProp(row, prop), cellProperties);
+};
+
+/**
+ * Returns td object given coordinates
+ */
+Handsontable.TableView.prototype.getCellAtCoords = function (coords) {
+ var td = this.wt.wtTable.getCell([coords.row, coords.col]);
+ if (td < 0) { //there was an exit code (cell is out of bounds)
+ return null;
+ }
+ else {
+ return td;
+ }
+};
+
+/**
+ * Scroll viewport to selection
+ * @param coords
+ */
+Handsontable.TableView.prototype.scrollViewport = function (coords) {
+ this.wt.scrollViewport([coords.row, coords.col]);
+};
+
+/**
+ * Append row header to a TH element
+ * @param row
+ * @param TH
+ */
+Handsontable.TableView.prototype.appendRowHeader = function (row, TH) {
+ if (row > -1) {
+ this.wt.wtDom.fastInnerHTML(TH, this.instance.getRowHeader(row));
+ }
+ else {
+ this.wt.wtDom.empty(TH);
+ }
+};
+
+/**
+ * Append column header to a TH element
+ * @param col
+ * @param TH
+ */
+Handsontable.TableView.prototype.appendColHeader = function (col, TH) {
+ var DIV = document.createElement('DIV')
+ , SPAN = document.createElement('SPAN');
+
+ DIV.className = 'relative';
+ SPAN.className = 'colHeader';
+
+ this.wt.wtDom.fastInnerHTML(SPAN, this.instance.getColHeader(col));
+ DIV.appendChild(SPAN);
+
+ while (TH.firstChild) {
+ TH.removeChild(TH.firstChild); //empty TH node
+ }
+ TH.appendChild(DIV);
+ this.instance.PluginHooks.run('afterGetColHeader', col, TH);
+};
+
+/**
+ * Returns true if keyCode represents a printable character
+ * @param {Number} keyCode
+ * @return {Boolean}
+ */
+Handsontable.helper.isPrintableChar = function (keyCode) {
+ return ((keyCode == 32) || //space
+ (keyCode >= 48 && keyCode <= 57) || //0-9
+ (keyCode >= 96 && keyCode <= 111) || //numpad
+ (keyCode >= 186 && keyCode <= 192) || //;=,-./`
+ (keyCode >= 219 && keyCode <= 222) || //[]{}\|"'
+ keyCode >= 226 || //special chars (229 for Asian chars)
+ (keyCode >= 65 && keyCode <= 90)); //a-z
+};
+
+/**
+ * Converts a value to string
+ * @param value
+ * @return {String}
+ */
+Handsontable.helper.stringify = function (value) {
+ switch (typeof value) {
+ case 'string':
+ case 'number':
+ return value + '';
+ break;
+
+ case 'object':
+ if (value === null) {
+ return '';
+ }
+ else {
+ return value.toString();
+ }
+ break;
+
+ case 'undefined':
+ return '';
+ break;
+
+ default:
+ return value.toString();
+ }
+};
+
+/**
+ * Generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB, etc
+ * @param index
+ * @returns {String}
+ */
+Handsontable.helper.spreadsheetColumnLabel = function (index) {
+ var dividend = index + 1;
+ var columnLabel = '';
+ var modulo;
+ while (dividend > 0) {
+ modulo = (dividend - 1) % 26;
+ columnLabel = String.fromCharCode(65 + modulo) + columnLabel;
+ dividend = parseInt((dividend - modulo) / 26, 10);
+ }
+ return columnLabel;
+};
+
+/**
+ * Checks if value of n is a numeric one
+ * http://jsperf.com/isnan-vs-isnumeric/4
+ * @param n
+ * @returns {boolean}
+ */
+Handsontable.helper.isNumeric = function (n) {
+ var t = typeof n;
+ return t == 'number' ? !isNaN(n) && isFinite(n) :
+ t == 'string' ? !n.length ? false :
+ n.length == 1 ? /\d/.test(n) :
+ /^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) :
+ t == 'object' ? !!n && typeof n.valueOf() == "number" && !(n instanceof Date) : false;
+};
+
+/**
+ * Checks if child is a descendant of given parent node
+ * http://stackoverflow.com/questions/2234979/how-to-check-in-javascript-if-one-element-is-a-child-of-another
+ * @param parent
+ * @param child
+ * @returns {boolean}
+ */
+Handsontable.helper.isDescendant = function (parent, child) {
+ var node = child.parentNode;
+ while (node != null) {
+ if (node == parent) {
+ return true;
+ }
+ node = node.parentNode;
+ }
+ return false;
+};
+
+/**
+ * Generates a random hex string. Used as namespace for Handsontable instance events.
+ * @return {String} - 16 character random string: "92b1bfc74ec4"
+ */
+Handsontable.helper.randomString = function () {
+ function s4() {
+ return Math.floor((1 + Math.random()) * 0x10000)
+ .toString(16)
+ .substring(1);
+ }
+
+ return s4() + s4() + s4() + s4();
+};
+
+/**
+ * Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`.
+ * Creates temporary dummy function to call it as constructor.
+ * Described in ticket: https://github.com/warpech/jquery-handsontable/pull/516
+ * @param {Object} Child child class
+ * @param {Object} Parent parent class
+ * @return {Object} extended Child
+ */
+Handsontable.helper.inherit = function (Child, Parent) {
+ function Bridge() {
+ }
+
+ Bridge.prototype = Parent.prototype;
+ Child.prototype = new Bridge();
+ Child.prototype.constructor = Child;
+ return Child;
+};
+
+/**
+ * Perform shallow extend of a target object with extension's own properties
+ * @param {Object} target An object that will receive the new properties
+ * @param {Object} extension An object containing additional properties to merge into the target
+ */
+Handsontable.helper.extend = function (target, extension) {
+ for (var i in extension) {
+ if (extension.hasOwnProperty(i)) {
+ target[i] = extension[i];
+ }
+ }
+};
+
+/**
+ * Factory for columns constructors.
+ * @param {Object} GridSettings
+ * @param {Array} conflictList
+ * @param {Object} defaultCell
+ * @return {Object} ColumnSettings
+ */
+Handsontable.helper.columnFactory = function (GridSettings, conflictList, defaultCell) {
+ var i = 0, len = conflictList.length, ColumnSettings = function () {
+ };
+
+ // Inherit prototype from grid settings
+ ColumnSettings.prototype = new GridSettings();
+
+ // Clear conflict settings
+ for (; i < len; i++) {
+ ColumnSettings.prototype[conflictList[i]] = void 0;
+ }
+
+ // Inherit settings from default (text) cell
+ for (i in defaultCell) {
+ if (defaultCell.hasOwnProperty(i)) {
+ ColumnSettings.prototype[i] = defaultCell[i];
+ }
+ }
+
+ return ColumnSettings;
+};
+
+Handsontable.helper.translateRowsToColumns = function (input) {
+ var i
+ , ilen
+ , j
+ , jlen
+ , output = []
+ , olen = 0;
+
+ for (i = 0, ilen = input.length; i < ilen; i++) {
+ for (j = 0, jlen = input[i].length; j < jlen; j++) {
+ if (j == olen) {
+ output.push([]);
+ olen++;
+ }
+ output[j].push(input[i][j])
+ }
+ }
+ return output;
+};
+
+Handsontable.helper.to2dArray = function (arr) {
+ var i = 0
+ , ilen = arr.length;
+ while (i < ilen) {
+ arr[i] = [arr[i]];
+ i++;
+ }
+};
+
+Handsontable.helper.extendArray = function (arr, extension) {
+ var i = 0
+ , ilen = extension.length;
+ while (i < ilen) {
+ arr.push(extension[i]);
+ i++;
+ }
+};
+
+/**
+ * Returns cell renderer or editor function directly or through lookup map
+ */
+Handsontable.helper.getCellMethod = function (methodName, methodFunction) {
+ if (typeof methodFunction === 'string') {
+ var result = Handsontable.cellLookup[methodName][methodFunction];
+ if (result === void 0) {
+ throw new Error('You declared cell ' + methodName + ' "' + methodFunction + '" as a string that is not mapped to a known function. Cell ' + methodName + ' must be a function or a string mapped to a function in Handsontable.cellLookup.' + methodName + ' lookup object');
+ }
+ return result;
+ }
+ else {
+ return methodFunction;
+ }
+};
+/**
+ * Handsontable UndoRedo class
+ */
+Handsontable.UndoRedo = function (instance) {
+ var that = this;
+ this.instance = instance;
+ this.clear();
+ Handsontable.PluginHooks.add("afterChange", function (changes, origin) {
+ if (origin !== 'undo' && origin !== 'redo') {
+ that.add(changes, origin);
+ }
+ });
+};
+
+/**
+ * Undo operation from current revision
+ */
+Handsontable.UndoRedo.prototype.undo = function () {
+ var i, ilen;
+ if (this.isUndoAvailable()) {
+ var setData = $.extend(true, [], this.data[this.rev]);
+ for (i = 0, ilen = setData.length; i < ilen; i++) {
+ setData[i].splice(3, 1);
+ }
+ this.instance.setDataAtRowProp(setData, null, null, 'undo');
+ this.rev--;
+ }
+};
+
+/**
+ * Redo operation from current revision
+ */
+Handsontable.UndoRedo.prototype.redo = function () {
+ var i, ilen;
+ if (this.isRedoAvailable()) {
+ this.rev++;
+ var setData = $.extend(true, [], this.data[this.rev]);
+ for (i = 0, ilen = setData.length; i < ilen; i++) {
+ setData[i].splice(2, 1);
+ }
+ this.instance.setDataAtRowProp(setData, null, null, 'redo');
+ }
+};
+
+/**
+ * Returns true if undo point is available
+ * @return {Boolean}
+ */
+Handsontable.UndoRedo.prototype.isUndoAvailable = function () {
+ return (this.rev >= 0);
+};
+
+/**
+ * Returns true if redo point is available
+ * @return {Boolean}
+ */
+Handsontable.UndoRedo.prototype.isRedoAvailable = function () {
+ return (this.rev < this.data.length - 1);
+};
+
+/**
+ * Add new history poins
+ * @param changes
+ */
+Handsontable.UndoRedo.prototype.add = function (changes, source) {
+ this.rev++;
+ this.data.splice(this.rev); //if we are in point abcdef(g)hijk in history, remove everything after (g)
+ this.data.push(changes);
+};
+
+/**
+ * Clears undo history
+ */
+Handsontable.UndoRedo.prototype.clear = function () {
+ this.data = [];
+ this.rev = -1;
+};
+Handsontable.SelectionPoint = function () {
+ this._row = null; //private use intended
+ this._col = null;
+};
+
+Handsontable.SelectionPoint.prototype.exists = function () {
+ return (this._row !== null);
+};
+
+Handsontable.SelectionPoint.prototype.row = function (val) {
+ if (val !== void 0) {
+ this._row = val;
+ }
+ return this._row;
+};
+
+Handsontable.SelectionPoint.prototype.col = function (val) {
+ if (val !== void 0) {
+ this._col = val;
+ }
+ return this._col;
+};
+
+Handsontable.SelectionPoint.prototype.coords = function (coords) {
+ if (coords !== void 0) {
+ this._row = coords.row;
+ this._col = coords.col;
+ }
+ return {
+ row: this._row,
+ col: this._col
+ }
+};
+
+Handsontable.SelectionPoint.prototype.arr = function (arr) {
+ if (arr !== void 0) {
+ this._row = arr[0];
+ this._col = arr[1];
+ }
+ return [this._row, this._col]
+};
+/**
+ * Default text renderer
+ * @param {Object} instance Handsontable instance
+ * @param {Element} TD Table cell where to render
+ * @param {Number} row
+ * @param {Number} col
+ * @param {String|Number} prop Row object property name
+ * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
+ * @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
+ */
+Handsontable.TextRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
+ var escaped = Handsontable.helper.stringify(value);
+ instance.view.wt.wtDom.fastInnerText(TD, escaped); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
+ if (cellProperties.readOnly) {
+ instance.view.wt.wtDom.addClass(TD, 'htDimmed');
+ }
+ if (cellProperties.valid === false && cellProperties.invalidCellClassName) {
+ TD.className = cellProperties.invalidCellClassName;
+ }
+};
+var clonableTEXT = document.createElement('DIV');
+clonableTEXT.className = 'htAutocomplete';
+
+var clonableARROW = document.createElement('DIV');
+clonableARROW.className = 'htAutocompleteArrow';
+clonableARROW.appendChild(document.createTextNode('\u25BC'));
+//this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
+
+/**
+ * Autocomplete renderer
+ * @param {Object} instance Handsontable instance
+ * @param {Element} TD Table cell where to render
+ * @param {Number} row
+ * @param {Number} col
+ * @param {String|Number} prop Row object property name
+ * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
+ * @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
+ */
+Handsontable.AutocompleteRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
+ var TEXT = clonableTEXT.cloneNode(false); //this is faster than createElement
+ var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement
+
+ if (!instance.acArrowListener) {
+ //not very elegant but easy and fast
+ instance.acArrowListener = function () {
+ instance.view.wt.getSetting('onCellDblClick');
+ };
+ instance.rootElement.on('mouseup', '.htAutocompleteArrow', instance.acArrowListener); //this way we don't bind event listener to each arrow. We rely on propagation instead
+ }
+
+ Handsontable.TextRenderer(instance, TEXT, row, col, prop, value, cellProperties);
+
+ if (!TEXT.firstChild) { //http://jsperf.com/empty-node-if-needed
+ //otherwise empty fields appear borderless in demo/renderers.html (IE)
+ TEXT.appendChild(document.createTextNode('\u00A0')); //\u00A0 equals for a text node
+ //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
+ }
+
+ TEXT.appendChild(ARROW);
+ instance.view.wt.wtDom.empty(TD); //TODO identify under what circumstances this line can be removed
+ TD.appendChild(TEXT);
+};
+var clonableINPUT = document.createElement('INPUT');
+clonableINPUT.className = 'htCheckboxRendererInput';
+clonableINPUT.type = 'checkbox';
+clonableINPUT.setAttribute('autocomplete', 'off');
+
+/**
+ * Checkbox renderer
+ * @param {Object} instance Handsontable instance
+ * @param {Element} TD Table cell where to render
+ * @param {Number} row
+ * @param {Number} col
+ * @param {String|Number} prop Row object property name
+ * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
+ * @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
+ */
+Handsontable.CheckboxRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
+ if (typeof cellProperties.checkedTemplate === "undefined") {
+ cellProperties.checkedTemplate = true;
+ }
+ if (typeof cellProperties.uncheckedTemplate === "undefined") {
+ cellProperties.uncheckedTemplate = false;
+ }
+
+ instance.view.wt.wtDom.empty(TD); //TODO identify under what circumstances this line can be removed
+
+ var INPUT = clonableINPUT.cloneNode(false); //this is faster than createElement
+
+ if (value === cellProperties.checkedTemplate || value === Handsontable.helper.stringify(cellProperties.checkedTemplate)) {
+ INPUT.checked = true;
+ TD.appendChild(INPUT);
+ }
+ else if (value === cellProperties.uncheckedTemplate || value === Handsontable.helper.stringify(cellProperties.uncheckedTemplate)) {
+ TD.appendChild(INPUT);
+ }
+ else if (value === null) { //default value
+ INPUT.className += ' noValue';
+ TD.appendChild(INPUT);
+ }
+ else {
+ instance.view.wt.wtDom.fastInnerText(TD, '#bad value#'); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
+ }
+
+ var $input = $(INPUT);
+
+ if (cellProperties.readOnly) {
+ $input.on('click', function (event) {
+ event.preventDefault();
+ });
+ }
+ else {
+ $input.on('mousedown', function (event) {
+ if (!this.checked) {
+ instance.setDataAtRowProp(row, prop, cellProperties.checkedTemplate);
+ }
+ else {
+ instance.setDataAtRowProp(row, prop, cellProperties.uncheckedTemplate);
+ }
+
+ event.stopPropagation(); //otherwise can confuse cell mousedown handler
+ });
+
+ $input.on('mouseup', function (event) {
+ event.stopPropagation(); //otherwise can confuse cell dblclick handler
+ });
+ }
+
+ return TD;
+};
+/**
+ * Numeric cell renderer
+ * @param {Object} instance Handsontable instance
+ * @param {Element} TD Table cell where to render
+ * @param {Number} row
+ * @param {Number} col
+ * @param {String|Number} prop Row object property name
+ * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
+ * @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
+ */
+Handsontable.NumericRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
+ if (Handsontable.helper.isNumeric(value)) {
+ if (typeof cellProperties.language !== 'undefined') {
+ numeral.language(cellProperties.language)
+ }
+ value = numeral(value).format(cellProperties.format || '0'); //docs: http://numeraljs.com/
+ instance.view.wt.wtDom.addClass(TD, 'htNumeric');
+ }
+ Handsontable.TextRenderer(instance, TD, row, col, prop, value, cellProperties);
+};
+function HandsontableTextEditorClass(instance) {
+ this.isCellEdited = false;
+ this.instance = instance;
+ this.createElements();
+ this.bindEvents();
+}
+
+HandsontableTextEditorClass.prototype.createElements = function () {
+ this.wtDom = new WalkontableDom();
+
+ this.TEXTAREA = document.createElement('TEXTAREA');
+ this.TEXTAREA.className = 'handsontableInput';
+ this.textareaStyle = this.TEXTAREA.style;
+ this.textareaStyle.width = 0;
+ this.textareaStyle.height = 0;
+ this.$textarea = $(this.TEXTAREA);
+
+ this.TEXTAREA_PARENT = document.createElement('DIV');
+ this.TEXTAREA_PARENT.className = 'handsontableInputHolder';
+ this.textareaParentStyle = this.TEXTAREA_PARENT.style;
+ this.textareaParentStyle.top = 0;
+ this.textareaParentStyle.left = 0;
+ this.textareaParentStyle.display = 'none';
+ this.$textareaParent = $(this.TEXTAREA_PARENT);
+
+ this.$body = $(document.body);
+
+ this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);
+ this.instance.rootElement[0].appendChild(this.TEXTAREA_PARENT);
+
+ var that = this;
+ Handsontable.PluginHooks.add('afterRender', function () {
+ that.instance.registerTimeout('refresh_editor_dimensions', function () {
+ that.refreshDimensions();
+ }, 0);
+ });
+};
+
+HandsontableTextEditorClass.prototype.bindEvents = function () {
+ var that = this;
+ this.$textareaParent.off('.editor').on('keydown.editor', function (event) {
+ //if we are here then isCellEdited === true
+
+ that.instance.PluginHooks.run('beforeKeyDown', event);
+ if(event.isImmediatePropagationStopped()) { //event was cancelled in beforeKeyDown
+ return;
+ }
+
+ var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
+
+ if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) {
+ //when CTRL or its equivalent is pressed and cell is edited, don't prepare selectable text in textarea
+ event.stopImmediatePropagation();
+ return;
+ }
+
+ switch (event.keyCode) {
+ case 38: /* arrow up */
+ case 40: /* arrow down */
+ that.finishEditing(false);
+ break;
+
+ case 9: /* tab */
+ that.finishEditing(false);
+ event.preventDefault();
+ break;
+
+ case 39: /* arrow right */
+ if (that.getCaretPosition(that.TEXTAREA) === that.TEXTAREA.value.length) {
+ that.finishEditing(false);
+ }
+ else {
+ event.stopImmediatePropagation();
+ }
+ break;
+
+ case 37: /* arrow left */
+ if (that.getCaretPosition(that.TEXTAREA) === 0) {
+ that.finishEditing(false);
+ }
+ else {
+ event.stopImmediatePropagation();
+ }
+ break;
+
+ case 27: /* ESC */
+ that.instance.destroyEditor(true);
+ event.stopImmediatePropagation();
+ break;
+
+ case 13: /* return/enter */
+ var selected = that.instance.getSelected();
+ var isMultipleSelection = !(selected[0] === selected[2] && selected[1] === selected[3]);
+ if ((event.ctrlKey && !isMultipleSelection) || event.altKey) { //if ctrl+enter or alt+enter, add new line
+ that.TEXTAREA.value = that.TEXTAREA.value + '\n';
+ that.TEXTAREA.focus();
+ event.stopImmediatePropagation();
+ }
+ else {
+ that.finishEditing(false, ctrlDown);
+ }
+ event.preventDefault(); //don't add newline to field
+ break;
+
+ default:
+ event.stopImmediatePropagation(); //backspace, delete, home, end, CTRL+A, CTRL+C, CTRL+V, CTRL+X should only work locally when cell is edited (not in table context)
+ break;
+ }
+ });
+};
+
+HandsontableTextEditorClass.prototype.bindTemporaryEvents = function (td, row, col, prop, value, cellProperties) {
+ this.TD = td;
+ this.row = row;
+ this.col = col;
+ this.prop = prop;
+ this.originalValue = value;
+ this.cellProperties = cellProperties;
+
+ var that = this;
+
+ this.$body.on('keydown.editor.' + this.instance.guid, function (event) {
+ var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
+ if (!that.isCellEdited) {
+ if (Handsontable.helper.isPrintableChar(event.keyCode)) {
+ if (!ctrlDown) { //disregard CTRL-key shortcuts
+ that.beginEditing(row, col, prop);
+ }
+ }
+ else if (event.keyCode === 113) { //f2
+ that.beginEditing(row, col, prop, true); //show edit field
+ event.stopImmediatePropagation();
+ event.preventDefault(); //prevent Opera from opening Go to Page dialog
+ }
+ else if (event.keyCode === 13 && that.instance.getSettings().enterBeginsEditing) { //enter
+ var selected = that.instance.getSelected();
+ var isMultipleSelection = !(selected[0] === selected[2] && selected[1] === selected[3]);
+ if ((ctrlDown && !isMultipleSelection) || event.altKey) { //if ctrl+enter or alt+enter, add new line
+ that.beginEditing(row, col, prop, true, '\n'); //show edit field
+ }
+ else {
+ that.beginEditing(row, col, prop, true); //show edit field
+ }
+ event.preventDefault(); //prevent new line at the end of textarea
+ event.stopImmediatePropagation();
+ }
+ }
+ });
+
+ function onDblClick() {
+ that.beginEditing(row, col, prop, true);
+ }
+
+ this.instance.view.wt.update('onCellDblClick', onDblClick);
+};
+
+HandsontableTextEditorClass.prototype.unbindTemporaryEvents = function () {
+ this.$body.off(".editor");
+ this.instance.view.wt.update('onCellDblClick', null);
+};
+
+/**
+ * Returns caret position in edit proxy
+ * @author http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea
+ * @return {Number}
+ */
+HandsontableTextEditorClass.prototype.getCaretPosition = function (el) {
+ if (el.selectionStart) {
+ return el.selectionStart;
+ }
+ else if (document.selection) {
+ el.focus();
+ var r = document.selection.createRange();
+ if (r == null) {
+ return 0;
+ }
+ var re = el.createTextRange(),
+ rc = re.duplicate();
+ re.moveToBookmark(r.getBookmark());
+ rc.setEndPoint('EndToStart', re);
+ return rc.text.length;
+ }
+ return 0;
+};
+
+/**
+ * Sets caret position in edit proxy
+ * @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
+ * @param {Number}
+ */
+HandsontableTextEditorClass.prototype.setCaretPosition = function (el, pos) {
+ if (el.setSelectionRange) {
+ el.focus();
+ el.setSelectionRange(pos, pos);
+ }
+ else if (el.createTextRange) {
+ var range = el.createTextRange();
+ range.collapse(true);
+ range.moveEnd('character', pos);
+ range.moveStart('character', pos);
+ range.select();
+ }
+};
+
+HandsontableTextEditorClass.prototype.beginEditing = function (row, col, prop, useOriginalValue, suffix) {
+ if (this.isCellEdited) {
+ return;
+ }
+ this.isCellEdited = true;
+ this.row = row;
+ this.col = col;
+ this.prop = prop;
+
+ var coords = {row: row, col: col};
+ this.instance.view.scrollViewport(coords);
+ this.instance.view.render();
+
+ this.$textarea.on('cut.editor', function (event) {
+ event.stopPropagation();
+ });
+
+ this.$textarea.on('paste.editor', function (event) {
+ event.stopPropagation();
+ });
+
+ if (useOriginalValue) {
+ this.TEXTAREA.value = Handsontable.helper.stringify(this.originalValue) + (suffix || '');
+ }
+ else {
+ this.TEXTAREA.value = '';
+ }
+
+ this.refreshDimensions(); //need it instantly, to prevent https://github.com/warpech/jquery-handsontable/issues/348
+ this.TEXTAREA.focus();
+ this.setCaretPosition(this.TEXTAREA, this.TEXTAREA.value.length);
+};
+
+HandsontableTextEditorClass.prototype.refreshDimensions = function () {
+ if (!this.isCellEdited) {
+ return;
+ }
+
+ ///start prepare textarea position
+ this.TD = this.instance.getCell(this.row, this.col);
+ var $td = $(this.TD); //because old td may have been scrolled out with scrollViewport
+ var currentOffset = this.wtDom.offset(this.TD);
+ var containerOffset = this.wtDom.offset(this.instance.rootElement[0]);
+ var scrollTop = this.instance.rootElement.scrollTop();
+ var scrollLeft = this.instance.rootElement.scrollLeft();
+ var editTop = currentOffset.top - containerOffset.top + scrollTop - 1;
+ var editLeft = currentOffset.left - containerOffset.left + scrollLeft - 1;
+
+ var settings = this.instance.getSettings();
+ var rowHeadersCount = settings.rowHeaders === false ? 0 : 1;
+ var colHeadersCount = settings.colHeaders === false ? 0 : 1;
+
+ if (editTop < 0) {
+ editTop = 0;
+ }
+ if (editLeft < 0) {
+ editLeft = 0;
+ }
+
+ if (rowHeadersCount > 0 && parseInt($td.css('border-top-width'), 10) > 0) {
+ editTop += 1;
+ }
+ if (colHeadersCount > 0 && parseInt($td.css('border-left-width'), 10) > 0) {
+ editLeft += 1;
+ }
+
+ if ($.browser.msie && parseInt($.browser.version, 10) <= 7) {
+ editTop -= 1;
+ }
+
+ this.textareaParentStyle.top = editTop + 'px';
+ this.textareaParentStyle.left = editLeft + 'px';
+ ///end prepare textarea position
+
+ var width = $td.width()
+ , height = $td.outerHeight() - 4;
+
+ if (parseInt($td.css('border-top-width'), 10) > 0) {
+ height -= 1;
+ }
+ if (parseInt($td.css('border-left-width'), 10) > 0) {
+ if (rowHeadersCount > 0) {
+ width -= 1;
+ }
+ }
+
+ this.$textarea.autoResize({
+ maxHeight: 200,
+ minHeight: height,
+ minWidth: width,
+ maxWidth: Math.max(168, width),
+ animate: false,
+ extraSpace: 0
+ });
+
+ this.textareaParentStyle.display = 'block';
+};
+
+HandsontableTextEditorClass.prototype.finishEditing = function (isCancelled, ctrlDown) {
+ if (this.isCellEdited) {
+ this.isCellEdited = false;
+ if (!isCancelled) {
+ var val = [
+ [$.trim(this.TEXTAREA.value)]
+ ];
+ if (ctrlDown) { //if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells)
+ var sel = this.instance.getSelected();
+ this.instance.populateFromArray(sel[0], sel[1], val, sel[2], sel[3], 'edit');
+ }
+ else {
+ this.instance.populateFromArray(this.row, this.col, val, null, null, 'edit');
+ }
+ }
+ }
+
+ this.unbindTemporaryEvents();
+ if (document.activeElement === this.TEXTAREA) {
+ this.instance.listen(); //don't refocus the table if user focused some cell outside of HT on purpose
+ }
+
+ this.textareaParentStyle.display = 'none';
+};
+
+/**
+ * Default text editor
+ * @param {Object} instance Handsontable instance
+ * @param {Element} td Table cell where to render
+ * @param {Number} row
+ * @param {Number} col
+ * @param {String|Number} prop Row object property name
+ * @param value Original value (remember to escape unsafe HTML before inserting to DOM!)
+ * @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
+ */
+Handsontable.TextEditor = function (instance, td, row, col, prop, value, cellProperties) {
+ if (!instance.textEditor) {
+ instance.textEditor = new HandsontableTextEditorClass(instance);
+ }
+ instance.textEditor.bindTemporaryEvents(td, row, col, prop, value, cellProperties);
+ return function (isCancelled) {
+ instance.textEditor.finishEditing(isCancelled);
+ }
+};
+function HandsontableAutocompleteEditorClass(instance) {
+ this.isCellEdited = false;
+ this.instance = instance;
+ this.createElements();
+ this.bindEvents();
+ this.emptyStringLabel = '\u00A0\u00A0\u00A0'; //3 non-breaking spaces
+}
+
+Handsontable.helper.inherit(HandsontableAutocompleteEditorClass, HandsontableTextEditorClass);
+
+/**
+ * @see HandsontableTextEditorClass.prototype.createElements
+ */
+HandsontableAutocompleteEditorClass.prototype.createElements = function () {
+ HandsontableTextEditorClass.prototype.createElements.call(this);
+
+ this.$textarea.typeahead();
+ this.typeahead = this.$textarea.data('typeahead');
+ this.typeahead._render = this.typeahead.render;
+ this.typeahead.minLength = 0;
+
+ this.typeahead.lookup = function () {
+ var items;
+ this.query = this.$element.val();
+ items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source;
+ return items ? this.process(items) : this;
+ };
+
+ this.typeahead.matcher = function () {
+ return true;
+ };
+
+ var _process = this.typeahead.process;
+ var that = this;
+ this.typeahead.process = function (items) {
+ var cloned = false;
+ for (var i = 0, ilen = items.length; i < ilen; i++) {
+ if (items[i] === '') {
+ //this is needed because because of issue #254
+ //empty string ('') is a falsy value and breaks the loop in bootstrap-typeahead.js method `sorter`
+ //best solution would be to change line: `while (item = items.shift()) {`
+ // to: `while ((item = items.shift()) !== void 0) {`
+ if (!cloned) {
+ //need to clone items before applying emptyStringLabel
+ //(otherwise validateChanges fails for empty string)
+ items = $.extend([], items);
+ cloned = true;
+ }
+ items[i] = that.emptyStringLabel;
+ }
+ }
+ return _process.call(this, items);
+ };
+};
+
+/**
+ * @see HandsontableTextEditorClass.prototype.bindEvents
+ */
+HandsontableAutocompleteEditorClass.prototype.bindEvents = function () {
+ var that = this;
+
+ this.$textarea.off('keydown').off('keyup').off('keypress'); //unlisten
+
+ this.$textareaParent.off('.acEditor').on('keydown.acEditor', function (event) {
+ switch (event.keyCode) {
+ case 38: /* arrow up */
+ that.typeahead.prev();
+ event.stopImmediatePropagation(); //stops TextEditor and core onKeyDown handler
+ break;
+
+ case 40: /* arrow down */
+ that.typeahead.next();
+ event.stopImmediatePropagation(); //stops TextEditor and core onKeyDown handler
+ break;
+
+ case 13: /* enter */
+ event.preventDefault();
+ break;
+ }
+ });
+
+ this.$textareaParent.on('keyup.acEditor', function (event) {
+ if (Handsontable.helper.isPrintableChar(event.keyCode) || event.keyCode === 113 || event.keyCode === 13 || event.keyCode === 8 || event.keyCode === 46) {
+ that.typeahead.lookup();
+ }
+ });
+
+
+ HandsontableTextEditorClass.prototype.bindEvents.call(this);
+};
+/**
+ * @see HandsontableTextEditorClass.prototype.bindTemporaryEvents
+ */
+HandsontableAutocompleteEditorClass.prototype.bindTemporaryEvents = function (td, row, col, prop, value, cellProperties) {
+ var that = this
+ , i
+ , j;
+
+ this.typeahead.select = function () {
+ var output = this.hide(); //need to hide it before destroyEditor, because destroyEditor checks if menu is expanded
+ that.instance.destroyEditor(true);
+ var val = this.$menu.find('.active').attr('data-value');
+ if (val === that.emptyStringLabel) {
+ val = '';
+ }
+ if (typeof cellProperties.onSelect === 'function') {
+ cellProperties.onSelect(row, col, prop, val, this.$menu.find('.active').index());
+ }
+ else {
+ that.instance.setDataAtRowProp(row, prop, val);
+ }
+ return output;
+ };
+
+ this.typeahead.render = function (items) {
+ that.typeahead._render.call(this, items);
+ if (!cellProperties.strict) {
+ this.$menu.find('li:eq(0)').removeClass('active');
+ }
+ return this;
+ };
+
+ /* overwrite typeahead options and methods (matcher, sorter, highlighter, updater, etc) if provided in cellProperties */
+ for (i in cellProperties) {
+ // if (cellProperties.hasOwnProperty(i)) {
+ if (i === 'options') {
+ for (j in cellProperties.options) {
+ // if (cellProperties.options.hasOwnProperty(j)) {
+ this.typeahead.options[j] = cellProperties.options[j];
+ // }
+ }
+ }
+ else {
+ this.typeahead[i] = cellProperties[i];
+ }
+ // }
+ }
+
+ HandsontableTextEditorClass.prototype.bindTemporaryEvents.call(this, td, row, col, prop, value, cellProperties);
+
+ function onDblClick() {
+ that.beginEditing(row, col, prop, true);
+ that.instance.registerTimeout('IE9_align_fix', function () { //otherwise is misaligned in IE9
+ that.typeahead.lookup();
+ }, 1);
+ }
+
+ this.instance.view.wt.update('onCellDblClick', onDblClick);
+};
+/**
+ * @see HandsontableTextEditorClass.prototype.finishEditing
+ */
+HandsontableAutocompleteEditorClass.prototype.finishEditing = function (isCancelled, ctrlDown) {
+ if (!isCancelled) {
+ if (this.isMenuExpanded() && this.typeahead.$menu.find('.active').length) {
+ this.typeahead.select();
+ this.isCellEdited = false; //cell value was updated by this.typeahead.select (issue #405)
+ }
+ else if (this.cellProperties.strict) {
+ this.isCellEdited = false; //cell value was not picked from this.typeahead.select (issue #405)
+ }
+ }
+
+ HandsontableTextEditorClass.prototype.finishEditing.call(this, isCancelled, ctrlDown);
+};
+
+HandsontableAutocompleteEditorClass.prototype.isMenuExpanded = function () {
+ if (this.typeahead.$menu.is(":visible")) {
+ return this.typeahead;
+ }
+ else {
+ return false;
+ }
+};
+
+/**
+ * Autocomplete editor
+ * @param {Object} instance Handsontable instance
+ * @param {Element} td Table cell where to render
+ * @param {Number} row
+ * @param {Number} col
+ * @param {String|Number} prop Row object property name
+ * @param value Original value (remember to escape unsafe HTML before inserting to DOM!)
+ * @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
+ */
+Handsontable.AutocompleteEditor = function (instance, td, row, col, prop, value, cellProperties) {
+ if (!instance.autocompleteEditor) {
+ instance.autocompleteEditor = new HandsontableAutocompleteEditorClass(instance);
+ }
+ instance.autocompleteEditor.bindTemporaryEvents(td, row, col, prop, value, cellProperties);
+ return function (isCancelled) {
+ instance.autocompleteEditor.finishEditing(isCancelled);
+ }
+};
+function toggleCheckboxCell(instance, row, prop, cellProperties) {
+ if (Handsontable.helper.stringify(instance.getDataAtRowProp(row, prop)) === Handsontable.helper.stringify(cellProperties.checkedTemplate)) {
+ instance.setDataAtRowProp(row, prop, cellProperties.uncheckedTemplate);
+ }
+ else {
+ instance.setDataAtRowProp(row, prop, cellProperties.checkedTemplate);
+ }
+}
+
+/**
+ * Checkbox editor
+ * @param {Object} instance Handsontable instance
+ * @param {Element} td Table cell where to render
+ * @param {Number} row
+ * @param {Number} col
+ * @param {String|Number} prop Row object property name
+ * @param value Original value (remember to escape unsafe HTML before inserting to DOM!)
+ * @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
+ */
+Handsontable.CheckboxEditor = function (instance, td, row, col, prop, value, cellProperties) {
+ if (typeof cellProperties === "undefined") {
+ cellProperties = {};
+ }
+ if (typeof cellProperties.checkedTemplate === "undefined") {
+ cellProperties.checkedTemplate = true;
+ }
+ if (typeof cellProperties.uncheckedTemplate === "undefined") {
+ cellProperties.uncheckedTemplate = false;
+ }
+
+ instance.$table.on("keydown.editor", function (event) {
+ var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
+ if (!ctrlDown && Handsontable.helper.isPrintableChar(event.keyCode)) {
+ toggleCheckboxCell(instance, row, prop, cellProperties);
+ event.stopImmediatePropagation(); //stops core onKeyDown handler
+ event.preventDefault(); //some keys have special behavior, eg. space bar scrolls screen down
+ }
+ });
+
+ instance.view.wt.update('onCellDblClick', function () {
+ toggleCheckboxCell(instance, row, prop, cellProperties);
+ });
+
+ return function () {
+ instance.$table.off(".editor");
+ instance.view.wt.update('onCellDblClick', null);
+ }
+};
+
+
+
+function HandsontableDateEditorClass(instance) {
+ if (!$.datepicker) {
+ throw new Error("jQuery UI Datepicker dependency not found. Did you forget to include jquery-ui.custom.js or its substitute?");
+ }
+
+ this.isCellEdited = false;
+ this.instance = instance;
+ this.createElements();
+ this.bindEvents();
+}
+
+Handsontable.helper.inherit(HandsontableDateEditorClass, HandsontableTextEditorClass);
+
+/**
+ * @see HandsontableTextEditorClass.prototype.createElements
+ */
+HandsontableDateEditorClass.prototype.createElements = function () {
+ HandsontableTextEditorClass.prototype.createElements.call(this);
+
+ this.datePicker = document.createElement('DIV');
+ this.datePickerStyle = this.datePicker.style;
+ this.datePickerStyle.position = 'absolute';
+ this.datePickerStyle.top = 0;
+ this.datePickerStyle.left = 0;
+ this.datePickerStyle.zIndex = 99;
+ this.instance.rootElement[0].appendChild(this.datePicker);
+ this.$datePicker = $(this.datePicker);
+
+ var that = this;
+ var defaultOptions = {
+ dateFormat: "yy-mm-dd",
+ showButtonPanel: true,
+ changeMonth: true,
+ changeYear: true,
+ altField: this.$textarea,
+ onSelect: function () {
+ that.finishEditing(false);
+ }
+ };
+ this.$datePicker.datepicker(defaultOptions);
+ this.hideDatepicker();
+};
+
+/**
+ * @see HandsontableTextEditorClass.prototype.beginEditing
+ */
+HandsontableDateEditorClass.prototype.beginEditing = function (row, col, prop, useOriginalValue, suffix) {
+ HandsontableTextEditorClass.prototype.beginEditing.call(this, row, col, prop, useOriginalValue, suffix);
+ this.showDatepicker();
+};
+
+/**
+ * @see HandsontableTextEditorClass.prototype.finishEditing
+ */
+HandsontableDateEditorClass.prototype.finishEditing = function (isCancelled, ctrlDown) {
+ this.hideDatepicker();
+ HandsontableTextEditorClass.prototype.finishEditing.call(this, isCancelled, ctrlDown);
+};
+
+HandsontableDateEditorClass.prototype.showDatepicker = function () {
+ var $td = $(this.instance.dateEditor.TD);
+ var position = $td.position();
+ this.datePickerStyle.top = (position.top + $td.height()) + 'px';
+ this.datePickerStyle.left = position.left + 'px';
+
+ var dateOptions = {
+ defaultDate: this.originalValue || void 0
+ };
+ $.extend(dateOptions, this.cellProperties);
+ this.$datePicker.datepicker("option", dateOptions);
+ if (this.originalValue) {
+ this.$datePicker.datepicker("setDate", this.originalValue);
+ }
+ this.datePickerStyle.display = 'block';
+};
+
+HandsontableDateEditorClass.prototype.hideDatepicker = function () {
+ this.datePickerStyle.display = 'none';
+};
+
+/**
+ * Date editor (uses jQuery UI Datepicker)
+ * @param {Object} instance Handsontable instance
+ * @param {Element} td Table cell where to render
+ * @param {Number} row
+ * @param {Number} col
+ * @param {String|Number} prop Row object property name
+ * @param value Original value (remember to escape unsafe HTML before inserting to DOM!)
+ * @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
+ */
+Handsontable.DateEditor = function (instance, td, row, col, prop, value, cellProperties) {
+ if (!instance.dateEditor) {
+ instance.dateEditor = new HandsontableDateEditorClass(instance);
+ }
+ instance.dateEditor.bindTemporaryEvents(td, row, col, prop, value, cellProperties);
+ return function (isCancelled) {
+ instance.dateEditor.finishEditing(isCancelled);
+ }
+};
+/**
+ * This is inception. Using Handsontable as Handsontable editor
+ */
+
+function HandsontableHandsontableEditorClass(instance) {
+ this.isCellEdited = false;
+ this.instance = instance;
+ this.createElements();
+ this.bindEvents();
+}
+
+Handsontable.helper.inherit(HandsontableHandsontableEditorClass, HandsontableTextEditorClass);
+
+HandsontableHandsontableEditorClass.prototype.createElements = function () {
+ HandsontableTextEditorClass.prototype.createElements.call(this);
+
+ var DIV = document.createElement('DIV');
+ DIV.className = 'handsontableEditor';
+ this.TEXTAREA_PARENT.appendChild(DIV);
+
+ this.$htContainer = $(DIV);
+};
+
+HandsontableHandsontableEditorClass.prototype.bindTemporaryEvents = function (td, row, col, prop, value, cellProperties) {
+ var parent = this;
+
+ var options = {
+ colHeaders: true,
+ cells: function () {
+ return {
+ readOnly: true
+ }
+ },
+ fillHandle: false,
+ width: 2000,
+ //width: 'auto',
+ afterOnCellMouseDown: function () {
+ var sel = this.getSelected();
+ parent.TEXTAREA.value = this.getDataAtCell(sel[0], sel[1]);
+ parent.instance.destroyEditor();
+ },
+ beforeOnKeyDown: function (event) {
+ switch (event.keyCode) {
+ case 27: //esc
+ parent.instance.destroyEditor(true);
+ break;
+
+ case 13: //enter
+ var sel = this.getSelected();
+ parent.TEXTAREA.value = this.getDataAtCell(sel[0], sel[1]);
+ parent.instance.destroyEditor();
+ break;
+ }
+ }
+ };
+
+ if (cellProperties.handsontable) {
+ options = $.extend(options, cellProperties.handsontable);
+ }
+
+ this.$htContainer.handsontable(options);
+
+ HandsontableTextEditorClass.prototype.bindTemporaryEvents.call(this, td, row, col, prop, value, cellProperties);
+};
+
+HandsontableHandsontableEditorClass.prototype.beginEditing = function (row, col, prop, useOriginalValue, suffix) {
+ var onBeginEditing = this.instance.getSettings().onBeginEditing;
+ if (onBeginEditing && onBeginEditing() === false) {
+ return;
+ }
+
+ HandsontableTextEditorClass.prototype.beginEditing.call(this, row, col, prop, useOriginalValue, suffix);
+
+ this.$htContainer.handsontable('render');
+ this.$htContainer.handsontable('selectCell', 0, 0);
+};
+
+HandsontableHandsontableEditorClass.prototype.finishEditing = function (isCancelled, ctrlDown) {
+ if (Handsontable.helper.isDescendant(this.instance.rootElement[0], document.activeElement)) {
+ //var that = this;
+ setTimeout(function () {
+ //that.instance.listen(); //return the focus to the cell must be done after destroyer to work in IE7-9
+ }, 0);
+ //that.instance.listen(); //return the focus to the cell
+ }
+ this.$htContainer.handsontable('destroy');
+ HandsontableTextEditorClass.prototype.finishEditing.call(this, isCancelled, ctrlDown);
+};
+
+HandsontableHandsontableEditorClass.prototype.isMenuExpanded = function () {
+ if (this.typeahead.$menu.is(":visible")) {
+ return this.typeahead;
+ }
+ else {
+ return false;
+ }
+};
+
+/**
+ * Handsontable editor
+ * @param {Object} instance Handsontable instance
+ * @param {Element} td Table cell where to render
+ * @param {Number} row
+ * @param {Number} col
+ * @param {String|Number} prop Row object property name
+ * @param value Original value (remember to escape unsafe HTML before inserting to DOM!)
+ * @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
+ */
+Handsontable.HandsontableEditor = function (instance, td, row, col, prop, value, cellProperties) {
+ if (!instance.handsontableEditor) {
+ instance.handsontableEditor = new HandsontableHandsontableEditorClass(instance);
+ }
+ instance.handsontableEditor.bindTemporaryEvents(td, row, col, prop, value, cellProperties);
+
+ instance.registerEditor = instance.handsontableEditor;
+
+ return function (isCancelled) {
+ instance.handsontableEditor.finishEditing(isCancelled);
+ }
+};
+
+/**
+ * Numeric cell validator
+ * @param {*} value - Value of edited cell
+ * @param {*} calback - Callback called with validation result
+ */
+Handsontable.NumericValidator = function (value, callback) {
+ callback(/^-?\d*\.?\d*$/.test(value));
+}
+/**
+ * Function responsible for validation of autocomplete value
+ * @param {*} value - Value of edited cell
+ * @param {*} calback - Callback called with validation result
+ */
+var process = function (value, callback) {
+
+ var originalVal = value;
+ var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null;
+
+ return function (source) {
+ var found = false;
+ for (var s = 0, slen = source.length; s < slen; s++) {
+ if (originalVal === source[s]) {
+ found = true; //perfect match
+ break;
+ }
+ else if (lowercaseVal === source[s].toLowerCase()) {
+ // changes[i][3] = source[s]; //good match, fix the case << TODO?
+ found = true;
+ break;
+ }
+ }
+
+ callback(found);
+ }
+};
+
+/**
+ * Autocomplete cell validator
+ * @param {*} value - Value of edited cell
+ * @param {*} calback - Callback called with validation result
+ */
+Handsontable.AutocompleteValidator = function (value, callback) {
+ if (this.strict && this.source) {
+ $.isFunction(this.source) ? this.source(value, process(value, callback)) : process(value, callback)(this.source);
+ } else {
+ callback(true);
+ }
+}
+
+/**
+ * Cell type is just a shortcut for setting bunch of cellProperties (used in getCellMeta)
+ */
+
+Handsontable.AutocompleteCell = {
+ editor: Handsontable.AutocompleteEditor,
+ renderer: Handsontable.AutocompleteRenderer,
+ validator: Handsontable.AutocompleteValidator
+};
+
+Handsontable.CheckboxCell = {
+ editor: Handsontable.CheckboxEditor,
+ renderer: Handsontable.CheckboxRenderer
+};
+
+Handsontable.TextCell = {
+ editor: Handsontable.TextEditor,
+ renderer: Handsontable.TextRenderer
+};
+
+Handsontable.NumericCell = {
+ editor: Handsontable.TextEditor,
+ renderer: Handsontable.NumericRenderer,
+ validator: Handsontable.NumericValidator,
+ dataType: 'number'
+};
+
+Handsontable.DateCell = {
+ editor: Handsontable.DateEditor,
+ renderer: Handsontable.AutocompleteRenderer //displays small gray arrow on right side of the cell
+};
+
+Handsontable.HandsontableCell = {
+ editor: Handsontable.HandsontableEditor,
+ renderer: Handsontable.AutocompleteRenderer //displays small gray arrow on right side of the cell
+};
+
+//here setup the friendly aliases that are used by cellProperties.type
+Handsontable.cellTypes = {
+ text: Handsontable.TextCell,
+ date: Handsontable.DateCell,
+ numeric: Handsontable.NumericCell,
+ checkbox: Handsontable.CheckboxCell,
+ autocomplete: Handsontable.AutocompleteCell,
+ handsontable: Handsontable.HandsontableCell
+};
+
+//here setup the friendly aliases that are used by cellProperties.renderer and cellProperties.editor
+Handsontable.cellLookup = {
+ renderer: {
+ text: Handsontable.TextRenderer,
+ numeric: Handsontable.NumericRenderer,
+ checkbox: Handsontable.CheckboxRenderer,
+ autocomplete: Handsontable.AutocompleteRenderer
+ },
+ editor: {
+ text: Handsontable.TextEditor,
+ date: Handsontable.DateEditor,
+ checkbox: Handsontable.CheckboxEditor,
+ autocomplete: Handsontable.AutocompleteEditor,
+ handsontable: Handsontable.HandsontableEditor
+ },
+ validator: {
+ numeric: Handsontable.NumericValidator,
+ autocomplete: Handsontable.AutocompleteValidator
+ }
+};
+Handsontable.PluginHookClass = (function () {
+
+ var Hooks = function () {
+ return {
+ // Hooks
+ beforeInitWalkontable : [],
+
+ beforeInit : [],
+ beforeRender : [],
+ beforeChange : [],
+ beforeValidate: [],
+ beforeGet : [],
+ beforeSet : [],
+ beforeGetCellMeta : [],
+ beforeAutofill : [],
+ beforeKeyDown : [],
+
+ afterInit : [],
+ afterLoadData : [],
+ afterRender : [],
+ afterChange : [],
+ afterValidate: [],
+ afterGetCellMeta : [],
+ afterGetColHeader : [],
+ afterGetColWidth : [],
+ afterDestroy : [],
+ afterRemoveRow : [],
+ afterCreateRow : [],
+ afterRemoveCol : [],
+ afterCreateCol : [],
+ afterColumnResize : [],
+ afterColumnMove : [],
+ afterDeselect : [],
+ afterSelection : [],
+ afterSelectionByProp : [],
+ afterSelectionEnd : [],
+ afterSelectionEndByProp : [],
+ afterCopyLimit : [],
+
+ // Modifiers
+ modifyCol : []
+ }
+ };
+
+ var legacy = {
+ onBeforeChange: "beforeChange",
+ onChange: "afterChange",
+ onCreateRow: "afterCreateRow",
+ onCreateCol: "afterCreateCol",
+ onSelection: "afterSelection",
+ onCopyLimit: "afterCopyLimit",
+ onSelectionEnd: "afterSelectionEnd",
+ onSelectionByProp: "afterSelectionByProp",
+ onSelectionEndByProp: "afterSelectionEndByProp"
+ };
+
+ function PluginHookClass () {
+
+ this.hooks = {
+ once : Hooks(),
+ persistent : Hooks()
+ };
+
+ this.legacy = legacy;
+
+ }
+
+ var addHook = function (type) {
+ return function (key, fn) {
+ // provide support for old versions of HOT
+ if (key in legacy) {
+ key = legacy[key];
+ }
+
+ if (typeof this.hooks[type][key] === "undefined") {
+ this.hooks[type][key] = [];
+ }
+
+ if (fn instanceof Array) {
+ for (var i = 0, len = fn.length; i < len; i++) {
+ this.hooks[type][key].push(fn[i]);
+ }
+ } else {
+ this.hooks[type][key].push(fn);
+ }
+
+ return this;
+ };
+ };
+
+ PluginHookClass.prototype.add = addHook('persistent');
+ PluginHookClass.prototype.once = addHook('once');
+
+ PluginHookClass.prototype.remove = function (key, fn) {
+ var status = false
+ , hookTypes = ['persistent', 'once']
+ , type, x, lenx, i, leni;
+
+ // provide support for old versions of HOT
+ if (key in legacy) {
+ key = legacy[key];
+ }
+
+ for (x = 0, lenx = hookTypes.length; x < lenx; x++) {
+ type = hookTypes[x];
+ if (typeof this.hooks[type][key] !== 'undefined') {
+
+ for (i = 0, leni = this.hooks[type][key].length; i < leni; i++) {
+ if (this.hooks[type][key][i] == fn) {
+ this.hooks[type][key].splice(i, 1);
+ status = true;
+ break;
+ }
+ }
+
+ }
+ }
+
+ return status;
+ };
+
+ PluginHookClass.prototype.run = function (instance, key, p1, p2, p3, p4, p5) {
+ var hookTypes = ['persistent', 'once']
+ , type, x, lenx, i, leni;
+
+ // provide support for old versions of HOT
+ if (key in legacy) {
+ key = legacy[key];
+ }
+
+ //performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture
+ for (x = 0, lenx = hookTypes.length; x < lenx; x++) {
+ type = hookTypes[x];
+ if (typeof this.hooks[type][key] !== 'undefined') {
+
+ for (i = 0, leni = this.hooks[type][key].length; i < leni; i++) {
+ this.hooks[type][key][i].call(instance, p1, p2, p3, p4, p5);
+
+ if (type === 'once') {
+ this.hooks[type][key].splice(i, 1);
+ }
+ }
+
+ }
+ }
+ };
+
+ PluginHookClass.prototype.execute = function (instance, key, p1, p2, p3, p4, p5) {
+ var hookTypes = ['persistent', 'once']
+ , type, x, lenx, i, leni, res;
+
+ // provide support for old versions of HOT
+ if (key in legacy) {
+ key = legacy[key];
+ }
+
+ //performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture
+ for (x = 0, lenx = hookTypes.length; x < lenx; x++) {
+ type = hookTypes[x];
+ if (typeof this.hooks[type][key] !== 'undefined') {
+
+ for (i = 0, leni = this.hooks[type][key].length; i < leni; i++) {
+
+ res = this.hooks[type][key][i].call(instance, p1, p2, p3, p4, p5);
+ if (res !== void 0) {
+ p1 = res;
+ }
+
+ if (type === 'once') {
+ this.hooks[type][key].splice(i, 1);
+ }
+ }
+
+ }
+ }
+
+ return p1;
+ };
+
+ return PluginHookClass;
+
+})();
+
+Handsontable.PluginHooks = new Handsontable.PluginHookClass();
+function HandsontableAutoColumnSize() {
+ var that = this
+ , instance
+ , sampleCount = 5; //number of samples to take of each value length
+
+ this.beforeInit = function () {
+ this.autoColumnWidths = [];
+ this.autoColumnSizeTmp = {
+ thead: null,
+ theadTh: null,
+ theadStyle: null,
+ tbody: null,
+ tbodyTd: null,
+ noRenderer: null,
+ noRendererTd: null,
+ renderer: null,
+ rendererTd: null,
+ container: null,
+ containerStyle: null
+ };
+ };
+
+ this.determineColumnWidth = function (col) {
+ var tmp = instance.autoColumnSizeTmp
+ , d;
+
+ if (!tmp.container) {
+ d = document;
+
+ tmp.thead = d.createElement('table');
+ tmp.thead.appendChild(d.createElement('thead')).appendChild(d.createElement('tr')).appendChild(d.createElement('th'));
+ tmp.theadTh = tmp.thead.getElementsByTagName('th')[0];
+
+ tmp.thead.className = 'htTable';
+ tmp.theadStyle = tmp.thead.style;
+ tmp.theadStyle.tableLayout = 'auto';
+ tmp.theadStyle.width = 'auto';
+
+ tmp.tbody = tmp.thead.cloneNode(false);
+ tmp.tbody.appendChild(d.createElement('tbody')).appendChild(d.createElement('tr')).appendChild(d.createElement('td'));
+ tmp.tbodyTd = tmp.tbody.getElementsByTagName('td')[0];
+
+ tmp.noRenderer = tmp.tbody.cloneNode(true);
+ tmp.noRendererTd = tmp.noRenderer.getElementsByTagName('td')[0];
+
+ tmp.renderer = tmp.tbody.cloneNode(true);
+ tmp.rendererTd = tmp.renderer.getElementsByTagName('td')[0];
+
+ tmp.container = d.createElement('div');
+ tmp.container.className = instance.rootElement[0].className + ' hidden';
+ tmp.containerStyle = tmp.container.style;
+
+ tmp.container.appendChild(tmp.thead);
+ tmp.container.appendChild(tmp.tbody);
+ tmp.container.appendChild(tmp.noRenderer);
+ tmp.container.appendChild(tmp.renderer);
+
+ instance.rootElement[0].parentNode.appendChild(tmp.container);
+ }
+
+ tmp.container.className = instance.rootElement[0].className + ' hidden';
+ var cls = instance.$table[0].className;
+ tmp.thead.className = cls;
+ tmp.tbody.className = cls;
+
+ var rows = instance.countRows();
+ var samples = {};
+ var maxLen = 0;
+ for (var r = 0; r < rows; r++) {
+ var value = Handsontable.helper.stringify(instance.getDataAtCell(r, col));
+ var len = value.length;
+ if (len > maxLen) {
+ maxLen = len;
+ }
+ if (!samples[len]) {
+ samples[len] = {
+ needed: sampleCount,
+ strings: []
+ };
+ }
+ if (samples[len].needed) {
+ samples[len].strings.push(value);
+ samples[len].needed--;
+ }
+ }
+
+ var settings = instance.getSettings();
+ if (settings.colHeaders) {
+ instance.view.appendColHeader(col, tmp.theadTh); //TH innerHTML
+ }
+
+ var txt = '';
+ for (var i in samples) {
+ if (samples.hasOwnProperty(i)) {
+ for (var j = 0, jlen = samples[i].strings.length; j < jlen; j++) {
+ txt += samples[i].strings[j] + ' ';
+ }
+ }
+ }
+ tmp.tbodyTd.innerHTML = txt; //TD innerHTML
+
+ instance.view.wt.wtDom.empty(tmp.rendererTd);
+ instance.view.wt.wtDom.empty(tmp.noRendererTd);
+
+ tmp.containerStyle.display = 'block';
+
+ var width = instance.view.wt.wtDom.outerWidth(tmp.container);
+
+ var cellProperties = instance.getCellMeta(0, col);
+ if (cellProperties.renderer) {
+ var str = 9999999999;
+
+ tmp.noRendererTd.appendChild(document.createTextNode(str));
+ var renderer = Handsontable.helper.getCellMethod('renderer', cellProperties.renderer);
+ renderer(instance, tmp.rendererTd, 0, col, instance.colToProp(col), str, cellProperties);
+
+ width += instance.view.wt.wtDom.outerWidth(tmp.renderer) - instance.view.wt.wtDom.outerWidth(tmp.noRenderer); //add renderer overhead to the calculated width
+ }
+
+ tmp.containerStyle.display = 'none';
+
+ return width;
+ };
+
+ this.determineColumnsWidth = function () {
+ instance = this;
+ var settings = this.getSettings();
+ if (settings.autoColumnSize || !settings.colWidths) {
+ var cols = this.countCols();
+ for (var c = 0; c < cols; c++) {
+ this.autoColumnWidths[c] = that.determineColumnWidth(c);
+ }
+ }
+ };
+
+ this.getColWidth = function (col, response) {
+ if (this.autoColumnWidths[col] && this.autoColumnWidths[col] > response.width) {
+ response.width = this.autoColumnWidths[col];
+ }
+ };
+
+ this.afterDestroy = function () {
+ instance = this;
+ if (instance.autoColumnSizeTmp.container) {
+ instance.autoColumnSizeTmp.container.parentNode.removeChild(instance.autoColumnSizeTmp.container);
+ }
+ };
+}
+var htAutoColumnSize = new HandsontableAutoColumnSize();
+
+Handsontable.PluginHooks.add('beforeInit', htAutoColumnSize.beforeInit);
+Handsontable.PluginHooks.add('beforeRender', htAutoColumnSize.determineColumnsWidth);
+Handsontable.PluginHooks.add('afterGetColWidth', htAutoColumnSize.getColWidth);
+Handsontable.PluginHooks.add('afterDestroy', htAutoColumnSize.afterDestroy);
+
+/**
+ * This plugin sorts the view by a column (but does not sort the data source!)
+ * @constructor
+ */
+function HandsontableColumnSorting() {
+ var plugin = this;
+ var sortingEnabled;
+
+ this.afterInit = function () {
+ var instance = this;
+ if (this.getSettings().columnSorting) {
+ this.sortIndex = [];
+ this.rootElement.on('click.handsontable', '.columnSorting', function (e) {
+ var $target = $(e.target);
+ if ($target.is('.columnSorting')) {
+ var col = $target.closest('th').index();
+ if (instance.getSettings().rowHeaders) {
+ col--;
+ }
+ if (instance.sortColumn === col) {
+ instance.sortOrder = !instance.sortOrder;
+ }
+ else {
+ instance.sortColumn = col;
+ instance.sortOrder = true;
+ }
+ plugin.sort.call(instance);
+ instance.render();
+ }
+ });
+ }
+ };
+
+ this.sort = function () {
+ sortingEnabled = false;
+ var instance = this;
+ this.sortIndex.length = 0;
+ //var data = this.getData();
+ for (var i = 0, ilen = this.countRows(); i < ilen; i++) {
+ //this.sortIndex.push([i, data[i][this.sortColumn]]);
+ this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn)]);
+ }
+ this.sortIndex.sort(function (a, b) {
+ if (a[1] === b[1]) {
+ return 0;
+ }
+ if (a[1] === null) {
+ return 1;
+ }
+ if (b[1] === null) {
+ return -1;
+ }
+ if (a[1] < b[1]) return instance.sortOrder ? -1 : 1;
+ if (a[1] > b[1]) return instance.sortOrder ? 1 : -1;
+ return 0;
+ });
+ sortingEnabled = true;
+ };
+
+ this.translateRow = function (getVars) {
+ if (sortingEnabled && this.sortIndex && this.sortIndex.length) {
+ getVars.row = this.sortIndex[getVars.row][0];
+ }
+ };
+
+ this.getColHeader = function (col, TH) {
+ if (this.getSettings().columnSorting) {
+ $(TH).find('span.colHeader')[0].className += ' columnSorting';
+ }
+ };
+}
+var htSortColumn = new HandsontableColumnSorting();
+
+Handsontable.PluginHooks.add('afterInit', htSortColumn.afterInit);
+Handsontable.PluginHooks.add('beforeGet', htSortColumn.translateRow);
+Handsontable.PluginHooks.add('beforeSet', htSortColumn.translateRow);
+Handsontable.PluginHooks.add('afterGetColHeader', htSortColumn.getColHeader);
+function createContextMenu() {
+ var instance = this
+ , selectorId = instance.rootElement[0].id
+ , allItems = {
+ "row_above": {name: "Insert row above", disabled: isDisabled},
+ "row_below": {name: "Insert row below", disabled: isDisabled},
+ "hsep1": "---------",
+ "col_left": {name: "Insert column on the left", disabled: isDisabled},
+ "col_right": {name: "Insert column on the right", disabled: isDisabled},
+ "hsep2": "---------",
+ "remove_row": {name: "Remove row", disabled: isDisabled},
+ "remove_col": {name: "Remove column", disabled: isDisabled},
+ "hsep3": "---------",
+ "undo": {name: "Undo", disabled: function () {
+ return !instance.isUndoAvailable();
+ }},
+ "redo": {name: "Redo", disabled: function () {
+ return !instance.isRedoAvailable();
+ }}
+ }
+ , defaultOptions = {
+ selector : "#" + selectorId + ' table, #' + selectorId + ' div',
+ trigger : 'right',
+ callback : onContextClick
+ }
+ , options = {}
+ , i
+ , ilen
+ , settings = instance.getSettings();
+
+ function onContextClick(key) {
+ var corners = instance.getSelected(); //[top left row, top left col, bottom right row, bottom right col]
+
+ if (!corners) {
+ return; //needed when there are 2 grids on a page
+ }
+
+ switch (key) {
+ case "row_above":
+ instance.alter("insert_row", corners[0]);
+ break;
+
+ case "row_below":
+ instance.alter("insert_row", corners[2] + 1);
+ break;
+
+ case "col_left":
+ instance.alter("insert_col", corners[1]);
+ break;
+
+ case "col_right":
+ instance.alter("insert_col", corners[3] + 1);
+ break;
+
+ case "remove_row":
+ instance.alter(key, corners[0], (corners[2] - corners[0]) + 1);
+ break;
+
+ case "remove_col":
+ instance.alter(key, corners[1], (corners[3] - corners[1]) + 1);
+ break;
+
+ case "undo":
+ instance.undo();
+ break;
+
+ case "redo":
+ instance.redo();
+ break;
+ }
+ }
+
+ function isDisabled(key) {
+ //TODO rewrite
+ /*if (instance.blockedCols.main.find('th.htRowHeader.active').length && (key === "remove_col" || key === "col_left" || key === "col_right")) {
+ return true;
+ }
+ else if (instance.blockedRows.main.find('th.htColHeader.active').length && (key === "remove_row" || key === "row_above" || key === "row_below")) {
+ return true;
+ }
+ else*/
+ if (instance.countRows() >= instance.getSettings().maxRows && (key === "row_above" || key === "row_below")) {
+ return true;
+ }
+ else if (instance.countCols() >= instance.getSettings().maxCols && (key === "col_left" || key === "col_right")) {
+ return true;
+ }
+ else {
+ return false;
+ }
+ }
+
+ if (!settings.contextMenu) {
+ return;
+ }
+ else if (settings.contextMenu === true) { //contextMenu is true
+ options.items = allItems;
+ }
+ else if (Object.prototype.toString.apply(settings.contextMenu) === '[object Array]') { //contextMenu is an array
+ options.items = {};
+ for (i = 0, ilen = settings.contextMenu.length; i < ilen; i++) {
+ var key = settings.contextMenu[i];
+ if (typeof allItems[key] === 'undefined') {
+ throw new Error('Context menu key "' + key + '" is not recognised');
+ }
+ options.items[key] = allItems[key];
+ }
+ }
+ else if (Object.prototype.toString.apply(settings.contextMenu) === '[object Object]') { //contextMenu is an options object as defined in http://medialize.github.com/jQuery-contextMenu/docs.html
+ options = settings.contextMenu;
+ if (options.items) {
+ for (i in options.items) {
+ if (options.items.hasOwnProperty(i) && allItems[i]) {
+ if (typeof options.items[i] === 'string') {
+ options.items[i] = allItems[i];
+ }
+ else {
+ options.items[i] = $.extend(true, allItems[i], options.items[i]);
+ }
+ }
+ }
+ }
+ else {
+ options.items = allItems;
+ }
+
+ if (options.callback) {
+ var handsontableCallback = defaultOptions.callback;
+ var customCallback = options.callback;
+ options.callback = function (key, options) {
+ handsontableCallback(key, options);
+ customCallback(key, options);
+ }
+ }
+ }
+
+ if (!selectorId) {
+ throw new Error("Handsontable container must have an id");
+ }
+
+ $.contextMenu($.extend(true, defaultOptions, options));
+}
+
+function destroyContextMenu() {
+ var id = this.rootElement[0].id;
+ $.contextMenu('destroy', "#" + id + ' table, #' + id + ' div');
+}
+
+Handsontable.PluginHooks.add('afterInit', createContextMenu);
+Handsontable.PluginHooks.add('afterDestroy', destroyContextMenu);
+/**
+ * This plugin adds support for legacy features, deprecated APIs, etc.
+ */
+
+/**
+ * Support for old autocomplete syntax
+ * For old syntax, see: https://github.com/warpech/jquery-handsontable/blob/8c9e701d090ea4620fe08b6a1a048672fadf6c7e/README.md#defining-autocomplete
+ */
+Handsontable.PluginHooks.add('beforeGetCellMeta', function (row, col, cellProperties) {
+ var settings = this.getSettings(), data = this.getData(), i, ilen, a;
+ if (settings.autoComplete) {
+ for (i = 0, ilen = settings.autoComplete.length; i < ilen; i++) {
+ if (settings.autoComplete[i].match(row, col, data)) {
+ if (typeof cellProperties.type === 'undefined') {
+ cellProperties.type = Handsontable.AutocompleteCell;
+ }
+ else {
+ if (typeof cellProperties.type.renderer === 'undefined') {
+ cellProperties.type.renderer = Handsontable.AutocompleteCell.renderer;
+ }
+ if (typeof cellProperties.type.editor === 'undefined') {
+ cellProperties.type.editor = Handsontable.AutocompleteCell.editor;
+ }
+ }
+ for (a in settings.autoComplete[i]) {
+ if (settings.autoComplete[i].hasOwnProperty(a) && a !== 'match' && typeof cellProperties[i] === 'undefined') {
+ if (a === 'source') {
+ cellProperties[a] = settings.autoComplete[i][a](row, col);
+ }
+ else {
+ cellProperties[a] = settings.autoComplete[i][a];
+ }
+ }
+ }
+ break;
+ }
+ }
+ }
+});
+function HandsontableManualColumnMove() {
+ var instance
+ , pressed
+ , startCol
+ , endCol
+ , startX
+ , startOffset;
+
+ var ghost = document.createElement('DIV')
+ , ghostStyle = ghost.style;
+
+ ghost.className = 'ghost';
+ ghostStyle.position = 'absolute';
+ ghostStyle.top = '25px';
+ ghostStyle.left = 0;
+ ghostStyle.width = '10px';
+ ghostStyle.height = '10px';
+ ghostStyle.backgroundColor = '#CCC';
+ ghostStyle.opacity = 0.7;
+
+ $(document).mousemove(function (e) {
+ if (pressed) {
+ ghostStyle.left = startOffset + e.pageX - startX + 6 + 'px';
+ if (ghostStyle.display === 'none') {
+ ghostStyle.display = 'block';
+ }
+ }
+ });
+
+ $(document).mouseup(function () {
+ if (pressed) {
+ if (startCol < endCol) {
+ endCol--;
+ }
+ if (instance.getSettings().rowHeaders) {
+ startCol--;
+ endCol--;
+ }
+ instance.manualColumnPositions.splice(endCol, 0, instance.manualColumnPositions.splice(startCol, 1)[0]);
+ $('.manualColumnMover.active').removeClass('active');
+ pressed = false;
+ instance.forceFullRender = true;
+ instance.view.render(); //updates all
+ ghostStyle.display = 'none';
+ instance.PluginHooks.run('afterColumnMove', startCol, endCol);
+ }
+ });
+
+ this.beforeInit = function () {
+ this.manualColumnPositions = [];
+ };
+
+ this.afterInit = function () {
+ if (this.getSettings().manualColumnMove) {
+ var that = this;
+ this.rootElement.on('mousedown.handsontable', '.manualColumnMover', function (e) {
+ instance = that;
+
+ var $resizer = $(e.target);
+ var th = $resizer.closest('th');
+ startCol = th.index();
+ pressed = true;
+ startX = e.pageX;
+
+ var $table = that.rootElement.find('.htCore');
+ $table.parent()[0].appendChild(ghost);
+ ghostStyle.width = $resizer.parent().width() + 'px';
+ ghostStyle.height = $table.height() + 'px';
+ startOffset = parseInt(th.offset().left - $table.offset().left, 10);
+ ghostStyle.left = startOffset + 6 + 'px';
+ });
+ this.rootElement.on('mouseenter.handsontable', 'td, th', function () {
+ if (pressed) {
+ $('.manualColumnMover.active').removeClass('active');
+ var $ths = that.rootElement.find('thead th');
+ endCol = $(this).index();
+ var $hover = $ths.eq(endCol).find('.manualColumnMover').addClass('active');
+ $ths.not($hover).removeClass('active');
+ }
+ });
+ }
+ };
+
+ this.modifyCol = function (col) {
+ //TODO test performance: http://jsperf.com/object-wrapper-vs-primitive/2
+ if (this.getSettings().manualColumnMove) {
+ if (typeof this.manualColumnPositions[col] === 'undefined') {
+ this.manualColumnPositions[col] = col;
+ }
+ return this.manualColumnPositions[col];
+ }
+ return col;
+ };
+
+ this.getColHeader = function (col, TH) {
+ if (this.getSettings().manualColumnMove) {
+ var DIV = document.createElement('DIV');
+ DIV.className = 'manualColumnMover';
+ TH.firstChild.appendChild(DIV);
+ }
+ };
+}
+var htManualColumnMove = new HandsontableManualColumnMove();
+
+Handsontable.PluginHooks.add('beforeInit', htManualColumnMove.beforeInit);
+Handsontable.PluginHooks.add('afterInit', htManualColumnMove.afterInit);
+Handsontable.PluginHooks.add('afterGetColHeader', htManualColumnMove.getColHeader);
+Handsontable.PluginHooks.add('modifyCol', htManualColumnMove.modifyCol);
+
+function HandsontableManualColumnResize() {
+ var pressed
+ , currentCol
+ , currentWidth
+ , autoresizeTimeout
+ , instance
+ , newSize
+ , start
+ , startX
+ , startWidth
+ , startOffset
+ , dblclick = 0
+ , resizer = document.createElement('DIV')
+ , line = document.createElement('DIV')
+ , lineStyle = line.style;
+
+ resizer.className = 'manualColumnResizer';
+
+ line.className = 'manualColumnResizerLine';
+ lineStyle.position ='absolute';
+ lineStyle.top = 0;
+ lineStyle.left = 0;
+ lineStyle.width = 0;
+ lineStyle.borderRight = '1px dashed #777';
+ line.appendChild(resizer);
+
+ $(document).mousemove(function (e) {
+ if (pressed) {
+ currentWidth = startWidth + (e.pageX - startX);
+ newSize = setManualSize(currentCol, currentWidth); //save col width
+ lineStyle.left = startOffset + currentWidth - 1 + 'px';
+ if (lineStyle.display === 'none') {
+ lineStyle.display = 'block';
+ }
+ }
+ });
+
+ $(document).mouseup(function () {
+ if (pressed) {
+ $('.manualColumnResizer.active').removeClass('active');
+ pressed = false;
+ instance.forceFullRender = true;
+ instance.view.render(); //updates all
+ lineStyle.display = 'none';
+ instance.PluginHooks.run('afterColumnResize', currentCol, newSize);
+ }
+ });
+
+ this.beforeInit = function () {
+ this.manualColumnWidths = [];
+ };
+
+ this.afterInit = function () {
+ if (this.getSettings().manualColumnResize) {
+ var that = this;
+
+ this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function (e) {
+ if (autoresizeTimeout == null) {
+ autoresizeTimeout = setTimeout(function () {
+ if (dblclick >= 2) {
+ setManualSize(currentCol, htAutoColumnSize.determineColumnWidth.call(instance, currentCol));
+ instance.PluginHooks.run('afterColumnResize', currentCol, newSize);
+ }
+ dblclick = 0;
+ autoresizeTimeout = null;
+ }, 500);
+ }
+ dblclick++;
+ });
+
+ this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function (e) {
+ var _resizer = e.target,
+ $table = that.rootElement.find('.htCore'),
+ $grandpa = $(_resizer.parentNode.parentNode);
+
+ instance = that;
+ currentCol = _resizer.getAttribute('rel');
+ start = $(that.rootElement[0].getElementsByTagName('col')[$grandpa.index()]);
+ pressed = true;
+ startX = e.pageX;
+ startWidth = start.width();
+ currentWidth = startWidth;
+
+ _resizer.className += ' active';
+
+ lineStyle.height = $table.height() + 'px';
+ $table.parent()[0].appendChild(line);
+ startOffset = parseInt($grandpa.offset().left - $table.offset().left, 10);
+ lineStyle.left = startOffset + currentWidth - 1 + 'px';
+ });
+ }
+ };
+
+ var setManualSize = function (col, width) {
+ width = Math.max(width, 20);
+ width = Math.min(width, 500);
+ instance.manualColumnWidths[col] = width;
+ return width;
+ };
+
+ this.getColHeader = function (col, TH) {
+ if (this.getSettings().manualColumnResize) {
+ var DIV = document.createElement('DIV');
+ DIV.className = 'manualColumnResizer';
+ DIV.setAttribute('rel', col);
+ TH.firstChild.appendChild(DIV);
+ }
+ };
+
+ this.getColWidth = function (col, response) {
+ if (this.getSettings().manualColumnResize && this.manualColumnWidths[col]) {
+ response.width = this.manualColumnWidths[col];
+ }
+ };
+}
+var htManualColumnResize = new HandsontableManualColumnResize();
+
+Handsontable.PluginHooks.add('beforeInit', htManualColumnResize.beforeInit);
+Handsontable.PluginHooks.add('afterInit', htManualColumnResize.afterInit);
+Handsontable.PluginHooks.add('afterGetColHeader', htManualColumnResize.getColHeader);
+Handsontable.PluginHooks.add('afterGetColWidth', htManualColumnResize.getColWidth);
+
+function HandsontableObserveChanges() {
+ // begin shim code
+ // fragments from https://github.com/Starcounter-Jack/JSON-Patch/blob/master/src/json-patch-duplex.js
+ //
+ // json-patch.js 0.3
+ // (c) 2013 Joachim Wester
+ // MIT license
+ var observeOps = {
+ 'new': function (patches, path) {
+ var patch = {
+ op: "add",
+ path: path + "/" + this.name,
+ value: this.object[this.name]
+ };
+ patches.push(patch);
+ },
+ deleted: function (patches, path) {
+ var patch = {
+ op: "remove",
+ path: path + "/" + this.name
+ };
+ patches.push(patch);
+ },
+ updated: function (patches, path) {
+ var patch = {
+ op: "replace",
+ path: path + "/" + this.name,
+ value: this.object[this.name]
+ };
+ patches.push(patch);
+ }
+ };
+
+ function markPaths(observer, node) {
+ for (var key in node) {
+ if (node.hasOwnProperty(key)) {
+ var kid = node[key];
+ if (kid instanceof Object) {
+ Object.unobserve(kid, observer);
+ kid.____Path = node.____Path + "/" + key;
+ markPaths(observer, kid);
+ }
+ }
+ }
+ }
+
+ function clearPaths(observer, node) {
+ delete node.____Path;
+ Object.observe(node, observer);
+ for (var i = 0, nodeLen = node.length; i < nodeLen; i++) {
+ var kid = node[i];
+ if (kid instanceof Object) {
+ clearPaths(observer, kid);
+ }
+ }
+ }
+
+ var beforeDict = [];
+ var callbacks = [];
+
+ function observe(obj, callback) {
+ var patches = [];
+ var root = obj;
+ if (Object.observe) {
+ var observer = function (arr) {
+ if (!root.___Path) {
+ Object.unobserve(root, observer);
+ root.____Path = "";
+ markPaths(observer, root);
+
+ for (var index = 0, arrLen = arr.length; i < arrLen; i++) {
+ var elem = arr[index];
+
+ if (elem.name != "____Path") {
+ observeOps[elem.type].call(elem, patches, elem.object.____Path);
+ }
+ }
+
+ clearPaths(observer, root);
+ }
+ if (callback) {
+ callback.call(patches);
+ }
+ };
+ } else {
+ observer = {
+ };
+ var mirror;
+ for (var i = 0, ilen = beforeDict.length; i < ilen; i++) {
+ if (beforeDict[i].obj === obj) {
+ mirror = beforeDict[i];
+ break;
+ }
+ }
+ if (!mirror) {
+ mirror = {
+ obj: obj
+ };
+ beforeDict.push(mirror);
+ }
+
+ mirror.value = deepCopy(obj);
+
+ if (callback) {
+ callbacks.push(callback);
+ var next;
+ var intervals = [
+ 100
+ ];
+ var currentInterval = 0;
+ var dirtyCheck = function () {
+ var temp = generate(observer);
+ if (temp.length > 0) {
+ observer.patches = [];
+ callback.call(null, temp);
+ }
+ };
+ var fastCheck = function () {
+ clearTimeout(next);
+ next = setTimeout(function () {
+ dirtyCheck();
+ currentInterval = 0;
+ next = setTimeout(slowCheck, intervals[currentInterval++]);
+ }, 0);
+ };
+ var slowCheck = function () {
+ dirtyCheck();
+ if (currentInterval == intervals.length) {
+ currentInterval = intervals.length - 1;
+ }
+ next = setTimeout(slowCheck, intervals[currentInterval++]);
+ };
+
+ if (window.addEventListener) {
+ window.addEventListener('mousedown', fastCheck);
+ window.addEventListener('mouseup', fastCheck);
+ window.addEventListener('keydown', fastCheck);
+ } else {
+ //IE8 has different syntax
+ window.attachEvent('onmousedown', fastCheck);
+ window.attachEvent('onmouseup', fastCheck);
+ window.attachEvent('onkeydown', fastCheck);
+ }
+
+ next = setTimeout(slowCheck, intervals[currentInterval++]);
+ }
+ }
+ observer.patches = patches;
+ observer.object = obj;
+ return _observe(observer, obj, patches);
+ }
+
+ /// Listen to changes on an object tree, accumulate patches
+ function _observe(observer, obj, patches) {
+ if (Object.observe) {
+ Object.observe(obj, observer);
+ }
+ for (var key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ var v = obj[key];
+ if (v && typeof (v) === "object") {
+ _observe(observer, v, patches);
+ }
+ }
+ }
+ return observer;
+ }
+
+ function generate(observer) {
+ if (Object.observe) {
+ Object.deliverChangeRecords(observer);
+ } else {
+ var mirror;
+ for (var i = 0, ilen = beforeDict.length; i < ilen; i++) {
+ if (beforeDict[i].obj === observer.object) {
+ mirror = beforeDict[i];
+ break;
+ }
+ }
+ _generate(mirror.value, observer.object, observer.patches, "");
+ }
+ return observer.patches;
+ }
+
+ function _generate(mirror, obj, patches, path) {
+ var newKeys = []
+ , oldKeys = []
+ , key;
+
+ for (key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ newKeys.push(key);
+ }
+ }
+
+ for (key in mirror) {
+ if (mirror.hasOwnProperty(key)) {
+ oldKeys.push(key);
+ }
+ }
+
+ var changed = false;
+ var deleted = false;
+ var t;
+ for (t = 0; t < oldKeys.length; t++) {
+ key = oldKeys[t];
+ var oldVal = mirror[key];
+ if (obj.hasOwnProperty(key)) {
+ var newVal = obj[key];
+ if (oldVal instanceof Object) {
+ _generate(oldVal, newVal, patches, path + "/" + key);
+ } else {
+ if (oldVal != newVal) {
+ changed = true;
+ patches.push({
+ op: "replace",
+ path: path + "/" + key,
+ value: newVal
+ });
+ mirror[key] = newVal;
+ }
+ }
+ } else {
+ patches.push({
+ op: "remove",
+ path: path + "/" + key
+ });
+ deleted = true;
+ }
+ }
+ if (!deleted && newKeys.length == oldKeys.length) {
+ return;
+ }
+ for (t = 0; t < newKeys.length; t++) {
+ key = newKeys[t];
+ if (!mirror.hasOwnProperty(key)) {
+ patches.push({
+ op: "add",
+ path: path + "/" + key,
+ value: obj[key]
+ });
+ }
+ }
+ }
+
+ //end shim code
+
+
+ this.afterLoadData = function () {
+ if (!this.observer && this.getSettings().observeChanges) {
+ var that = this;
+ this.observer = observe(this.getData(), function () {
+ that.render();
+ });
+ }
+ };
+
+ /*
+ Description: Performs JSON-safe deep cloning. Equivalent of JSON.parse(JSON.stringify()).
+ Based on deepClone7() by Kyle Simpson (https://github.com/getify)
+ Source: http://jsperf.com/deep-cloning-of-objects,
+ http://jsperf.com/structured-clone-objects/2
+ https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/The_structured_clone_algorithm
+ */
+
+ function deepCopy(objToBeCopied) {
+ if (objToBeCopied === null || !(objToBeCopied instanceof Object)) {
+ return objToBeCopied;
+ }
+ var copiedObj, fConstr = objToBeCopied.constructor;
+ copiedObj = new fConstr();
+ for (var sProp in objToBeCopied) {
+ if (objToBeCopied.hasOwnProperty(sProp)) {
+ copiedObj[sProp] = deepCopy(objToBeCopied[sProp]);
+ }
+ }
+ return copiedObj;
+ }
+
+}
+var htObserveChanges = new HandsontableObserveChanges();
+
+Handsontable.PluginHooks.add('afterLoadData', htObserveChanges.afterLoadData);
+/*
+ * jQuery.fn.autoResize 1.1+
+ * --
+ * https://github.com/warpech/jQuery.fn.autoResize
+ *
+ * This fork differs from others in a way that it autoresizes textarea in 2-dimensions (horizontally and vertically).
+ * It was originally forked from alexbardas's repo but maybe should be merged with dpashkevich's repo in future.
+ *
+ * originally forked from:
+ * https://github.com/jamespadolsey/jQuery.fn.autoResize
+ * which is now located here:
+ * https://github.com/alexbardas/jQuery.fn.autoResize
+ * though the mostly maintained for is here:
+ * https://github.com/dpashkevich/jQuery.fn.autoResize/network
+ *
+ * --
+ * This program is free software. It comes without any warranty, to
+ * the extent permitted by applicable law. You can redistribute it
+ * and/or modify it under the terms of the Do What The Fuck You Want
+ * To Public License, Version 2, as published by Sam Hocevar. See
+ * http://sam.zoy.org/wtfpl/COPYING for more details. */
+
+(function($){
+
+ autoResize.defaults = {
+ onResize: function(){},
+ animate: {
+ duration: 200,
+ complete: function(){}
+ },
+ extraSpace: 50,
+ minHeight: 'original',
+ maxHeight: 500,
+ minWidth: 'original',
+ maxWidth: 500
+ };
+
+ autoResize.cloneCSSProperties = [
+ 'lineHeight', 'textDecoration', 'letterSpacing',
+ 'fontSize', 'fontFamily', 'fontStyle', 'fontWeight',
+ 'textTransform', 'textAlign', 'direction', 'wordSpacing', 'fontSizeAdjust',
+ 'padding'
+ ];
+
+ autoResize.cloneCSSValues = {
+ position: 'absolute',
+ top: -9999,
+ left: -9999,
+ opacity: 0,
+ overflow: 'hidden',
+ border: '1px solid black',
+ padding: '0.49em' //this must be about the width of caps W character
+ };
+
+ autoResize.resizableFilterSelector = 'textarea,input:not(input[type]),input[type=text],input[type=password]';
+
+ autoResize.AutoResizer = AutoResizer;
+
+ $.fn.autoResize = autoResize;
+
+ function autoResize(config) {
+ this.filter(autoResize.resizableFilterSelector).each(function(){
+ new AutoResizer( $(this), config );
+ });
+ return this;
+ }
+
+ function AutoResizer(el, config) {
+
+ if(this.clones) return;
+
+ this.config = $.extend({}, autoResize.defaults, config);
+
+ this.el = el;
+
+ this.nodeName = el[0].nodeName.toLowerCase();
+
+ this.previousScrollTop = null;
+
+ if (config.maxWidth === 'original') config.maxWidth = el.width();
+ if (config.minWidth === 'original') config.minWidth = el.width();
+ if (config.maxHeight === 'original') config.maxHeight = el.height();
+ if (config.minHeight === 'original') config.minHeight = el.height();
+
+ if (this.nodeName === 'textarea') {
+ el.css({
+ resize: 'none',
+ overflowY: 'hidden'
+ });
+ }
+
+ el.data('AutoResizer', this);
+
+ this.createClone();
+ this.injectClone();
+ this.bind();
+
+ }
+
+ AutoResizer.prototype = {
+
+ bind: function() {
+
+ var check = $.proxy(function(){
+ this.check();
+ return true;
+ }, this);
+
+ this.unbind();
+
+ this.el
+ .bind('keyup.autoResize', check)
+ //.bind('keydown.autoResize', check)
+ .bind('change.autoResize', check);
+
+ this.check(null, true);
+
+ },
+
+ unbind: function() {
+ this.el.unbind('.autoResize');
+ },
+
+ createClone: function() {
+
+ var el = this.el,
+ self = this,
+ config = this.config;
+
+ this.clones = $();
+
+ if (config.minHeight !== 'original' || config.maxHeight !== 'original') {
+ this.hClone = el.clone().height('auto');
+ this.clones = this.clones.add(this.hClone);
+ }
+ if (config.minWidth !== 'original' || config.maxWidth !== 'original') {
+ this.wClone = $('').width('auto').css({
+ whiteSpace: 'nowrap',
+ 'float': 'left'
+ });
+ this.clones = this.clones.add(this.wClone);
+ }
+
+ $.each(autoResize.cloneCSSProperties, function(i, p){
+ self.clones.css(p, el.css(p));
+ });
+
+ this.clones
+ .removeAttr('name')
+ .removeAttr('id')
+ .attr('tabIndex', -1)
+ .css(autoResize.cloneCSSValues);
+
+ },
+
+ check: function(e, immediate) {
+
+ var config = this.config,
+ wClone = this.wClone,
+ hClone = this.hClone,
+ el = this.el,
+ value = el.val();
+
+ if (wClone) {
+
+ wClone.text(value);
+
+ // Calculate new width + whether to change
+ var cloneWidth = wClone.outerWidth(),
+ newWidth = (cloneWidth + config.extraSpace) >= config.minWidth ?
+ cloneWidth + config.extraSpace : config.minWidth,
+ currentWidth = el.width();
+
+ newWidth = Math.min(newWidth, config.maxWidth);
+
+ if (
+ (newWidth < currentWidth && newWidth >= config.minWidth) ||
+ (newWidth >= config.minWidth && newWidth <= config.maxWidth)
+ ) {
+
+ config.onResize.call(el);
+
+ el.scrollLeft(0);
+
+ config.animate && !immediate ?
+ el.stop(1,1).animate({
+ width: newWidth
+ }, config.animate)
+ : el.width(newWidth);
+
+ }
+
+ }
+
+ if (hClone) {
+
+ if (newWidth) {
+ hClone.width(newWidth);
+ }
+
+ hClone.height(0).val(value).scrollTop(10000);
+
+ var scrollTop = hClone[0].scrollTop + config.extraSpace;
+
+ // Don't do anything if scrollTop hasen't changed:
+ if (this.previousScrollTop === scrollTop) {
+ return;
+ }
+
+ this.previousScrollTop = scrollTop;
+
+ if (scrollTop >= config.maxHeight) {
+ el.css('overflowY', '');
+ return;
+ }
+
+ el.css('overflowY', 'hidden');
+
+ if (scrollTop < config.minHeight) {
+ scrollTop = config.minHeight;
+ }
+
+ config.onResize.call(el);
+
+ // Either animate or directly apply height:
+ config.animate && !immediate ?
+ el.stop(1,1).animate({
+ height: scrollTop
+ }, config.animate)
+ : el.height(scrollTop);
+ }
+ },
+
+ destroy: function() {
+ this.unbind();
+ this.el.removeData('AutoResizer');
+ this.clones.remove();
+ delete this.el;
+ delete this.hClone;
+ delete this.wClone;
+ delete this.clones;
+ },
+
+ injectClone: function() {
+ (
+ autoResize.cloneContainer ||
+ (autoResize.cloneContainer = $('').appendTo('body'))
+ ).empty().append(this.clones); //this should be refactored so that a node is never cloned more than once
+ }
+
+ };
+
+})(jQuery);
+/**
+ * SheetClip - Spreadsheet Clipboard Parser
+ * version 0.2
+ *
+ * This tiny library transforms JavaScript arrays to strings that are pasteable by LibreOffice, OpenOffice,
+ * Google Docs and Microsoft Excel.
+ *
+ * Copyright 2012, Marcin Warpechowski
+ * Licensed under the MIT license.
+ * http://github.com/warpech/sheetclip/
+ */
+/*jslint white: true*/
+(function (global) {
+ "use strict";
+
+ function countQuotes(str) {
+ return str.split('"').length - 1;
+ }
+
+ global.SheetClip = {
+ parse: function (str) {
+ var r, rlen, rows, arr = [], a = 0, c, clen, multiline, last;
+ rows = str.split('\n');
+ if (rows.length > 1 && rows[rows.length - 1] === '') {
+ rows.pop();
+ }
+ for (r = 0, rlen = rows.length; r < rlen; r += 1) {
+ rows[r] = rows[r].split('\t');
+ for (c = 0, clen = rows[r].length; c < clen; c += 1) {
+ if (!arr[a]) {
+ arr[a] = [];
+ }
+ if (multiline && c === 0) {
+ last = arr[a].length - 1;
+ arr[a][last] = arr[a][last] + '\n' + rows[r][0];
+ if (multiline && (countQuotes(rows[r][0]) & 1)) { //& 1 is a bitwise way of performing mod 2
+ multiline = false;
+ arr[a][last] = arr[a][last].substring(0, arr[a][last].length - 1).replace(/""/g, '"');
+ }
+ }
+ else {
+ if (c === clen - 1 && rows[r][c].indexOf('"') === 0) {
+ arr[a].push(rows[r][c].substring(1).replace(/""/g, '"'));
+ multiline = true;
+ }
+ else {
+ arr[a].push(rows[r][c].replace(/""/g, '"'));
+ multiline = false;
+ }
+ }
+ }
+ if (!multiline) {
+ a += 1;
+ }
+ }
+ return arr;
+ },
+
+ stringify: function (arr) {
+ var r, rlen, c, clen, str = '', val;
+ for (r = 0, rlen = arr.length; r < rlen; r += 1) {
+ for (c = 0, clen = arr[r].length; c < clen; c += 1) {
+ if (c > 0) {
+ str += '\t';
+ }
+ val = arr[r][c];
+ if (typeof val === 'string') {
+ if (val.indexOf('\n') > -1) {
+ str += '"' + val.replace(/"/g, '""') + '"';
+ }
+ else {
+ str += val;
+ }
+ }
+ else if (val === null || val === void 0) { //void 0 resolves to undefined
+ str += '';
+ }
+ else {
+ str += val;
+ }
+ }
+ str += '\n';
+ }
+ return str;
+ }
+ };
+}(window));
+/**
+ * CopyPaste.js
+ * Creates a textarea that stays hidden on the page and gets focused when user presses CTRL while not having a form input focused
+ * In future we may implement a better driver when better APIs are available
+ * @constructor
+ */
+var CopyPaste = (function () {
+ var instance;
+ return {
+ getInstance: function () {
+ if (!instance) {
+ instance = new CopyPasteClass();
+ }
+ return instance;
+ }
+ };
+})();
+
+function CopyPasteClass() {
+ var that = this
+ , style
+ , parent;
+
+ this.copyCallbacks = [];
+ this.cutCallbacks = [];
+ this.pasteCallbacks = [];
+
+ var listenerElement = document.documentElement;
+ parent = document.body;
+
+ if (document.getElementById('CopyPasteDiv')) {
+ this.elDiv = document.getElementById('CopyPasteDiv');
+ this.elTextarea = this.elDiv.firstChild;
+ }
+ else {
+ this.elDiv = document.createElement('DIV');
+ this.elDiv.id = 'CopyPasteDiv';
+ style = this.elDiv.style;
+ style.position = 'fixed';
+ style.top = 0;
+ style.left = 0;
+ parent.appendChild(this.elDiv);
+
+ this.elTextarea = document.createElement('TEXTAREA');
+ this.elTextarea.className = 'copyPaste';
+ style = this.elTextarea.style;
+ style.width = '1px';
+ style.height = '1px';
+ this.elDiv.appendChild(this.elTextarea);
+
+ if (typeof style.opacity !== 'undefined') {
+ style.opacity = 0;
+ }
+ else {
+ /*@cc_on @if (@_jscript)
+ if(typeof style.filter === 'string') {
+ style.filter = 'alpha(opacity=0)';
+ }
+ @end @*/
+ }
+ }
+
+ this._bindEvent(listenerElement, 'keydown', function (event) {
+ var isCtrlDown = false;
+ if (event.metaKey) { //mac
+ isCtrlDown = true;
+ }
+ else if (event.ctrlKey && navigator.userAgent.indexOf('Mac') === -1) { //pc
+ isCtrlDown = true;
+ }
+
+ if (isCtrlDown) {
+ if (document.activeElement !== that.elTextarea && that.getSelectionText() != '') {
+ return; //this is needed by fragmentSelection in Handsontable. Ignore copypaste.js behavior if fragment of cell text is selected
+ }
+
+ that.selectNodeText(that.elTextarea);
+ setTimeout(function () {
+ that.selectNodeText(that.elTextarea);
+ }, 0);
+ }
+
+ /* 67 = c
+ * 86 = v
+ * 88 = x
+ */
+ if (isCtrlDown && (event.keyCode === 67 || event.keyCode === 86 || event.keyCode === 88)) {
+ // that.selectNodeText(that.elTextarea);
+
+ if (event.keyCode === 88) { //works in all browsers, incl. Opera < 12.12
+ setTimeout(function () {
+ that.triggerCut(event);
+ }, 0);
+ }
+ else if (event.keyCode === 86) {
+ setTimeout(function () {
+ that.triggerPaste(event);
+ }, 0);
+ }
+ }
+ });
+}
+
+//http://jsperf.com/textara-selection
+//http://stackoverflow.com/questions/1502385/how-can-i-make-this-code-work-in-ie
+CopyPasteClass.prototype.selectNodeText = function (el) {
+ el.select();
+};
+
+//http://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text
+CopyPasteClass.prototype.getSelectionText = function () {
+ var text = "";
+ if (window.getSelection) {
+ text = window.getSelection().toString();
+ } else if (document.selection && document.selection.type != "Control") {
+ text = document.selection.createRange().text;
+ }
+ return text;
+};
+
+CopyPasteClass.prototype.copyable = function (str) {
+ if (typeof str !== 'string' && str.toString === void 0) {
+ throw new Error('copyable requires string parameter');
+ }
+ this.elTextarea.value = str;
+};
+
+CopyPasteClass.prototype.onCopy = function (fn) {
+ this.copyCallbacks.push(fn);
+};
+
+CopyPasteClass.prototype.onCut = function (fn) {
+ this.cutCallbacks.push(fn);
+};
+
+CopyPasteClass.prototype.onPaste = function (fn) {
+ this.pasteCallbacks.push(fn);
+};
+
+CopyPasteClass.prototype.removeCallback = function (fn) {
+ var i, ilen;
+ for (i = 0, ilen = this.copyCallbacks.length; i < ilen; i++) {
+ if (this.copyCallbacks[i] === fn) {
+ this.copyCallbacks.splice(i, 1);
+ return true;
+ }
+ }
+ for (i = 0, ilen = this.cutCallbacks.length; i < ilen; i++) {
+ if (this.cutCallbacks[i] === fn) {
+ this.cutCallbacks.splice(i, 1);
+ return true;
+ }
+ }
+ for (i = 0, ilen = this.pasteCallbacks.length; i < ilen; i++) {
+ if (this.pasteCallbacks[i] === fn) {
+ this.pasteCallbacks.splice(i, 1);
+ return true;
+ }
+ }
+ return false;
+};
+
+CopyPasteClass.prototype.triggerCut = function (event) {
+ var that = this;
+ if (that.cutCallbacks) {
+ setTimeout(function () {
+ for (var i = 0, ilen = that.cutCallbacks.length; i < ilen; i++) {
+ that.cutCallbacks[i](event);
+ }
+ }, 50);
+ }
+};
+
+CopyPasteClass.prototype.triggerPaste = function (event, str) {
+ var that = this;
+ if (that.pasteCallbacks) {
+ setTimeout(function () {
+ var val = (str || that.elTextarea.value).replace(/\n$/, ''); //remove trailing newline
+ for (var i = 0, ilen = that.pasteCallbacks.length; i < ilen; i++) {
+ that.pasteCallbacks[i](val, event);
+ }
+ }, 50);
+ }
+};
+
+//http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/
+//http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization
+CopyPasteClass.prototype._bindEvent = (function () {
+ if (document.addEventListener) {
+ return function (elem, type, cb) {
+ elem.addEventListener(type, cb, false);
+ };
+ }
+ else {
+ return function (elem, type, cb) {
+ elem.attachEvent('on' + type, function () {
+ var e = window['event'];
+ e.target = e.srcElement;
+ e.relatedTarget = e.relatedTarget || e.type == 'mouseover' ? e.fromElement : e.toElement;
+ if (e.target.nodeType === 3) e.target = e.target.parentNode; //Safari bug
+ return cb.call(elem, e)
+ });
+ };
+ }
+})();
+function WalkontableBorder(instance, settings) {
+ var style;
+
+ //reference to instance
+ this.instance = instance;
+ this.settings = settings;
+ this.wtDom = this.instance.wtDom;
+
+ this.main = document.createElement("div");
+ style = this.main.style;
+ style.position = 'absolute';
+ style.top = 0;
+ style.left = 0;
+// style.visibility = 'hidden';
+
+ for (var i = 0; i < 5; i++) {
+ var DIV = document.createElement('DIV');
+ DIV.className = 'wtBorder ' + (settings.className || '');
+ style = DIV.style;
+ style.backgroundColor = settings.border.color;
+ style.height = settings.border.width + 'px';
+ style.width = settings.border.width + 'px';
+ this.main.appendChild(DIV);
+ }
+
+ this.top = this.main.childNodes[0];
+ this.left = this.main.childNodes[1];
+ this.bottom = this.main.childNodes[2];
+ this.right = this.main.childNodes[3];
+
+
+ /*$(this.top).on(sss, function(event) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ $(this).hide();
+ });
+ $(this.left).on(sss, function(event) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ $(this).hide();
+ });
+ $(this.bottom).on(sss, function(event) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ $(this).hide();
+ });
+ $(this.right).on(sss, function(event) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ $(this).hide();
+ });*/
+
+ this.topStyle = this.top.style;
+ this.leftStyle = this.left.style;
+ this.bottomStyle = this.bottom.style;
+ this.rightStyle = this.right.style;
+
+ this.corner = this.main.childNodes[4];
+ this.corner.className += ' corner';
+ this.cornerStyle = this.corner.style;
+ this.cornerStyle.width = '5px';
+ this.cornerStyle.height = '5px';
+ this.cornerStyle.border = '2px solid #FFF';
+
+ this.disappear();
+ if (!instance.wtTable.bordersHolder) {
+ instance.wtTable.bordersHolder = document.createElement('div');
+ instance.wtTable.bordersHolder.className = 'htBorders';
+ instance.wtTable.hider.appendChild(instance.wtTable.bordersHolder);
+
+ }
+ instance.wtTable.bordersHolder.appendChild(this.main);
+
+ var down = false;
+ var $body = $(document.body);
+
+ $body.on('mousedown.walkontable.' + instance.guid, function () {
+ down = true;
+ });
+
+ $body.on('mouseup.walkontable.' + instance.guid, function () {
+ down = false
+ });
+
+ $(this.main.childNodes).on('mouseenter', function (event) {
+ if (!down || !instance.getSetting('hideBorderOnMouseDownOver')) {
+ return;
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+
+ var bounds = this.getBoundingClientRect();
+
+ var $this = $(this);
+ $this.hide();
+
+ var isOutside = function (event) {
+ if (event.clientY < Math.floor(bounds.top)) {
+ return true;
+ }
+ if (event.clientY > Math.ceil(bounds.top + bounds.height)) {
+ return true;
+ }
+ if (event.clientX < Math.floor(bounds.left)) {
+ return true;
+ }
+ if (event.clientX > Math.ceil(bounds.left + bounds.width)) {
+ return true;
+ }
+ };
+
+ $body.on('mousemove.border.' + instance.guid, function (event) {
+ if (isOutside(event)) {
+ $body.off('mousemove.border.' + instance.guid);
+ $this.show();
+ }
+ });
+ });
+}
+
+/**
+ * Show border around one or many cells
+ * @param {Array} corners
+ */
+WalkontableBorder.prototype.appear = function (corners) {
+ var isMultiple, fromTD, toTD, fromOffset, toOffset, containerOffset, top, minTop, left, minLeft, height, width;
+ if (this.disabled) {
+ return;
+ }
+
+ var instance = this.instance
+ , fromRow
+ , fromColumn
+ , toRow
+ , toColumn
+ , hideTop = false
+ , hideLeft = false
+ , hideBottom = false
+ , hideRight = false
+ , i
+ , ilen
+ , s;
+
+ if (!instance.wtTable.isRowInViewport(corners[0])) {
+ hideTop = true;
+ }
+
+ if (!instance.wtTable.isRowInViewport(corners[2])) {
+ hideBottom = true;
+ }
+
+ ilen = instance.wtTable.rowStrategy.countVisible();
+
+ for (i = 0; i < ilen; i++) {
+ s = instance.wtTable.rowFilter.visibleToSource(i);
+ if (s >= corners[0] && s <= corners[2]) {
+ fromRow = s;
+ break;
+ }
+ }
+
+ for (i = ilen - 1; i >= 0; i--) {
+ s = instance.wtTable.rowFilter.visibleToSource(i);
+ if (s >= corners[0] && s <= corners[2]) {
+ toRow = s;
+ break;
+ }
+ }
+
+ if (hideTop && hideBottom) {
+ hideLeft = true;
+ hideRight = true;
+ }
+ else {
+ if (!instance.wtTable.isColumnInViewport(corners[1])) {
+ hideLeft = true;
+ }
+
+ if (!instance.wtTable.isColumnInViewport(corners[3])) {
+ hideRight = true;
+ }
+
+ ilen = instance.wtTable.columnStrategy.countVisible();
+
+ for (i = 0; i < ilen; i++) {
+ s = instance.wtTable.columnFilter.visibleToSource(i);
+ if (s >= corners[1] && s <= corners[3]) {
+ fromColumn = s;
+ break;
+ }
+ }
+
+ for (i = ilen - 1; i >= 0; i--) {
+ s = instance.wtTable.columnFilter.visibleToSource(i);
+ if (s >= corners[1] && s <= corners[3]) {
+ toColumn = s;
+ break;
+ }
+ }
+ }
+
+ if (fromRow !== void 0 && fromColumn !== void 0) {
+ isMultiple = (fromRow !== toRow || fromColumn !== toColumn);
+ fromTD = instance.wtTable.getCell([fromRow, fromColumn]);
+ toTD = isMultiple ? instance.wtTable.getCell([toRow, toColumn]) : fromTD;
+ fromOffset = this.wtDom.offset(fromTD);
+ toOffset = isMultiple ? this.wtDom.offset(toTD) : fromOffset;
+ containerOffset = this.wtDom.offset(instance.wtTable.TABLE);
+
+ minTop = fromOffset.top;
+ height = toOffset.top + this.wtDom.outerHeight(toTD) - minTop;
+ minLeft = fromOffset.left;
+ width = toOffset.left + this.wtDom.outerWidth(toTD) - minLeft;
+
+ top = minTop - containerOffset.top - 1;
+ left = minLeft - containerOffset.left - 1;
+
+ var style = this.wtDom.getComputedStyle(fromTD);
+ if (parseInt(style['borderTopWidth'], 10) > 0) {
+ top += 1;
+ height -= 1;
+ }
+ if (parseInt(style['borderLeftWidth'], 10) > 0) {
+ left += 1;
+ width -= 1;
+ }
+ }
+ else {
+ this.disappear();
+ return;
+ }
+
+ if (hideTop) {
+ this.topStyle.display = 'none';
+ }
+ else {
+ this.topStyle.top = top + 'px';
+ this.topStyle.left = left + 'px';
+ this.topStyle.width = width + 'px';
+ this.topStyle.display = 'block';
+ }
+
+ if (hideLeft) {
+ this.leftStyle.display = 'none';
+ }
+ else {
+ this.leftStyle.top = top + 'px';
+ this.leftStyle.left = left + 'px';
+ this.leftStyle.height = height + 'px';
+ this.leftStyle.display = 'block';
+ }
+
+ var delta = Math.floor(this.settings.border.width / 2);
+
+ if (hideBottom) {
+ this.bottomStyle.display = 'none';
+ }
+ else {
+ this.bottomStyle.top = top + height - delta + 'px';
+ this.bottomStyle.left = left + 'px';
+ this.bottomStyle.width = width + 'px';
+ this.bottomStyle.display = 'block';
+ }
+
+ if (hideRight) {
+ this.rightStyle.display = 'none';
+ }
+ else {
+ this.rightStyle.top = top + 'px';
+ this.rightStyle.left = left + width - delta + 'px';
+ this.rightStyle.height = height + 1 + 'px';
+ this.rightStyle.display = 'block';
+ }
+
+ if (hideBottom || hideRight || !this.hasSetting(this.settings.border.cornerVisible)) {
+ this.cornerStyle.display = 'none';
+ }
+ else {
+ this.cornerStyle.top = top + height - 4 + 'px';
+ this.cornerStyle.left = left + width - 4 + 'px';
+ this.cornerStyle.display = 'block';
+ }
+};
+
+/**
+ * Hide border
+ */
+WalkontableBorder.prototype.disappear = function () {
+ this.topStyle.display = 'none';
+ this.leftStyle.display = 'none';
+ this.bottomStyle.display = 'none';
+ this.rightStyle.display = 'none';
+ this.cornerStyle.display = 'none';
+};
+
+WalkontableBorder.prototype.hasSetting = function (setting) {
+ if (typeof setting === 'function') {
+ return setting();
+ }
+ return !!setting;
+};
+/**
+ * WalkontableCellFilter
+ * @constructor
+ */
+function WalkontableCellFilter() {
+ this.offset = 0;
+ this.total = 0;
+ this.fixedCount = 0;
+}
+
+WalkontableCellFilter.prototype.source = function (n) {
+ return n;
+};
+
+WalkontableCellFilter.prototype.offsetted = function (n) {
+ return n + this.offset;
+};
+
+WalkontableCellFilter.prototype.unOffsetted = function (n) {
+ return n - this.offset;
+};
+
+WalkontableCellFilter.prototype.fixed = function (n) {
+ if (n < this.fixedCount) {
+ return n - this.offset;
+ }
+ else {
+ return n;
+ }
+};
+
+WalkontableCellFilter.prototype.unFixed = function (n) {
+ if (n < this.fixedCount) {
+ return n + this.offset;
+ }
+ else {
+ return n;
+ }
+};
+
+WalkontableCellFilter.prototype.visibleToSource = function (n) {
+ return this.source(this.offsetted(this.fixed(n)));
+};
+
+WalkontableCellFilter.prototype.sourceToVisible = function (n) {
+ return this.source(this.unOffsetted(this.unFixed(n)));
+};
+/**
+ * WalkontableCellStrategy
+ * @constructor
+ */
+function WalkontableCellStrategy() {
+}
+
+WalkontableCellStrategy.prototype.getSize = function (index) {
+ return this.cellSizes[index];
+};
+
+WalkontableCellStrategy.prototype.getContainerSize = function (proposedSize) {
+ return typeof this.containerSizeFn === 'function' ? this.containerSizeFn(proposedSize) : this.containerSizeFn;
+};
+
+WalkontableCellStrategy.prototype.countVisible = function () {
+ return this.cellCount;
+};
+
+WalkontableCellStrategy.prototype.isLastIncomplete = function () {
+ return this.remainingSize > 0;
+};
+/**
+ * WalkontableClassNameList
+ * @constructor
+ */
+function WalkontableClassNameCache() {
+ this.cache = [];
+}
+
+WalkontableClassNameCache.prototype.add = function (r, c, cls) {
+ if (!this.cache[r]) {
+ this.cache[r] = [];
+ }
+ if (!this.cache[r][c]) {
+ this.cache[r][c] = [];
+ }
+ this.cache[r][c][cls] = true;
+};
+
+WalkontableClassNameCache.prototype.test = function (r, c, cls) {
+ return (this.cache[r] && this.cache[r][c] && this.cache[r][c][cls]);
+};
+/**
+ * WalkontableColumnFilter
+ * @constructor
+ */
+function WalkontableColumnFilter() {
+ this.countTH = 0;
+}
+
+WalkontableColumnFilter.prototype = new WalkontableCellFilter();
+
+WalkontableColumnFilter.prototype.readSettings = function (instance) {
+ this.offset = instance.wtSettings.settings.offsetColumn;
+ this.total = instance.getSetting('totalColumns');
+ this.fixedCount = instance.getSetting('fixedColumnsLeft');
+ this.countTH = instance.getSetting('rowHeaders').length;
+};
+
+WalkontableColumnFilter.prototype.offsettedTH = function (n) {
+ return n - this.countTH;
+};
+
+WalkontableColumnFilter.prototype.unOffsettedTH = function (n) {
+ return n + this.countTH;
+};
+
+WalkontableColumnFilter.prototype.visibleRowHeadedColumnToSourceColumn = function (n) {
+ return this.visibleToSource(this.offsettedTH(n));
+};
+
+WalkontableColumnFilter.prototype.sourceColumnToVisibleRowHeadedColumn = function (n) {
+ return this.unOffsettedTH(this.sourceToVisible(n));
+};
+/**
+ * WalkontableColumnStrategy
+ * @param containerSizeFn
+ * @param sizeAtIndex
+ * @param strategy - all, last, none
+ * @constructor
+ */
+function WalkontableColumnStrategy(containerSizeFn, sizeAtIndex, strategy) {
+ var size
+ , i = 0;
+
+ this.containerSizeFn = containerSizeFn;
+ this.cellSizesSum = 0;
+ this.cellSizes = [];
+ this.cellStretch = [];
+ this.cellCount = 0;
+ this.remainingSize = 0;
+ this.strategy = strategy;
+
+ //step 1 - determine cells that fit containerSize and cache their widths
+ while (true) {
+ size = sizeAtIndex(i);
+ if (size === void 0) {
+ break; //total columns exceeded
+ }
+ if (this.cellSizesSum >= this.getContainerSize(this.cellSizesSum + size)) {
+ break; //total width exceeded
+ }
+ this.cellSizes.push(size);
+ this.cellSizesSum += size;
+ this.cellCount++;
+
+ i++;
+ }
+
+ var containerSize = this.getContainerSize(this.cellSizesSum);
+ this.remainingSize = this.cellSizesSum - containerSize;
+ //negative value means the last cell is fully visible and there is some space left for stretching
+ //positive value means the last cell is not fully visible
+}
+
+WalkontableColumnStrategy.prototype = new WalkontableCellStrategy();
+
+WalkontableColumnStrategy.prototype.getSize = function (index) {
+ return this.cellSizes[index] + (this.cellStretch[index] || 0);
+};
+
+WalkontableColumnStrategy.prototype.stretch = function () {
+ //step 2 - apply stretching strategy
+ var containerSize = this.getContainerSize(this.cellSizesSum)
+ , i = 0;
+ this.remainingSize = this.cellSizesSum - containerSize;
+
+ this.cellStretch.length = 0; //clear previous stretch
+
+ if (this.strategy === 'all') {
+ if (this.remainingSize < 0) {
+ var ratio = containerSize / this.cellSizesSum;
+ var newSize;
+
+ while (i < this.cellCount - 1) { //"i < this.cellCount - 1" is needed because last cellSize is adjusted after the loop
+ newSize = Math.floor(ratio * this.cellSizes[i]);
+ this.remainingSize += newSize - this.cellSizes[i];
+ this.cellStretch[i] = newSize - this.cellSizes[i];
+ i++;
+ }
+ this.cellStretch[this.cellCount - 1] = -this.remainingSize;
+ this.remainingSize = 0;
+ }
+ }
+ else if (this.strategy === 'last') {
+ if (this.remainingSize < 0) {
+ this.cellStretch[this.cellCount - 1] = -this.remainingSize;
+ this.remainingSize = 0;
+ }
+ }
+};
+function Walkontable(settings) {
+ var that = this,
+ originalHeaders = [];
+
+ this.guid = 'wt_' + (window.Handsontable ? Handsontable.helper.randomString() : ''); //this is the namespace for global events
+
+ //bootstrap from settings
+ this.wtSettings = new WalkontableSettings(this, settings);
+ this.wtDom = new WalkontableDom();
+ this.wtTable = new WalkontableTable(this);
+ this.wtScroll = new WalkontableScroll(this);
+ this.wtScrollbars = new WalkontableScrollbars(this);
+ this.wtViewport = new WalkontableViewport(this);
+ this.wtWheel = new WalkontableWheel(this);
+ this.wtEvent = new WalkontableEvent(this);
+
+ //find original headers
+ if (this.wtTable.THEAD.childNodes.length && this.wtTable.THEAD.childNodes[0].childNodes.length) {
+ for (var c = 0, clen = this.wtTable.THEAD.childNodes[0].childNodes.length; c < clen; c++) {
+ originalHeaders.push(this.wtTable.THEAD.childNodes[0].childNodes[c].innerHTML);
+ }
+ if (!this.getSetting('columnHeaders').length) {
+ this.update('columnHeaders', [function (column, TH) {
+ that.wtDom.fastInnerText(TH, originalHeaders[column]);
+ }]);
+ }
+ }
+
+ //initialize selections
+ this.selections = {};
+ var selectionsSettings = this.getSetting('selections');
+ if (selectionsSettings) {
+ for (var i in selectionsSettings) {
+ if (selectionsSettings.hasOwnProperty(i)) {
+ this.selections[i] = new WalkontableSelection(this, selectionsSettings[i]);
+ }
+ }
+ }
+
+ this.drawn = false;
+ this.drawInterrupted = false;
+}
+
+Walkontable.prototype.draw = function (selectionsOnly) {
+ this.drawInterrupted = false;
+ if (!selectionsOnly && !this.wtDom.isVisible(this.wtTable.TABLE)) {
+ this.drawInterrupted = true; //draw interrupted because TABLE is not visible
+ return;
+ }
+
+ this.getSetting('beforeDraw', !selectionsOnly);
+ selectionsOnly = selectionsOnly && this.getSetting('offsetRow') === this.lastOffsetRow && this.getSetting('offsetColumn') === this.lastOffsetColumn;
+ if (this.drawn) { //fix offsets that might have changed
+ this.scrollVertical(0);
+ this.scrollHorizontal(0);
+ }
+ this.lastOffsetRow = this.getSetting('offsetRow');
+ this.lastOffsetColumn = this.getSetting('offsetColumn');
+ this.wtTable.draw(selectionsOnly);
+ this.getSetting('onDraw');
+ return this;
+};
+
+Walkontable.prototype.update = function (settings, value) {
+ return this.wtSettings.update(settings, value);
+};
+
+Walkontable.prototype.scrollVertical = function (delta) {
+ return this.wtScroll.scrollVertical(delta);
+};
+
+Walkontable.prototype.scrollHorizontal = function (delta) {
+ return this.wtScroll.scrollHorizontal(delta);
+};
+
+Walkontable.prototype.scrollViewport = function (coords) {
+ this.wtScroll.scrollViewport(coords);
+ return this;
+};
+
+Walkontable.prototype.getViewport = function () {
+ return [
+ this.wtTable.rowFilter.visibleToSource(0),
+ this.wtTable.columnFilter.visibleToSource(0),
+ this.wtTable.getLastVisibleRow(),
+ this.wtTable.getLastVisibleColumn()
+ ];
+};
+
+Walkontable.prototype.getSetting = function (key, param1, param2, param3) {
+ return this.wtSettings.getSetting(key, param1, param2, param3);
+};
+
+Walkontable.prototype.hasSetting = function (key) {
+ return this.wtSettings.has(key);
+};
+
+Walkontable.prototype.destroy = function () {
+ $(document.body).off('.' + this.guid);
+ this.wtScrollbars.destroy();
+ clearTimeout(this.wheelTimeout);
+ clearTimeout(this.dblClickTimeout);
+};
+function WalkontableDom() {
+}
+
+//goes up the DOM tree (including given element) until it finds an element that matches the nodeName
+WalkontableDom.prototype.closest = function (elem, nodeNames, until) {
+ while (elem != null && elem !== until) {
+ if (elem.nodeType === 1 && nodeNames.indexOf(elem.nodeName) > -1) {
+ return elem;
+ }
+ elem = elem.parentNode;
+ }
+ return null;
+};
+
+//goes up the DOM tree and checks if element is child of another element
+WalkontableDom.prototype.isChildOf = function (child, parent) {
+ var node = child.parentNode;
+ while (node != null) {
+ if (node == parent) {
+ return true;
+ }
+ node = node.parentNode;
+ }
+ return false;
+};
+
+WalkontableDom.prototype.prevSiblings = function (elem) {
+ var out = [];
+ while ((elem = elem.previousSibling) != null) {
+ if (elem.nodeType === 1) {
+ out.push(elem);
+ }
+ }
+ return out;
+};
+
+if (document.documentElement.classList) {
+ // HTML5 classList API
+ WalkontableDom.prototype.hasClass = function (ele, cls) {
+ return ele.classList.contains(cls);
+ };
+
+ WalkontableDom.prototype.addClass = function (ele, cls) {
+ ele.classList.add(cls);
+ };
+
+ WalkontableDom.prototype.removeClass = function (ele, cls) {
+ ele.classList.remove(cls);
+ };
+}
+else {
+ //http://snipplr.com/view/3561/addclass-removeclass-hasclass/
+ WalkontableDom.prototype.hasClass = function (ele, cls) {
+ return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
+ };
+
+ WalkontableDom.prototype.addClass = function (ele, cls) {
+ if (!this.hasClass(ele, cls)) ele.className += " " + cls;
+ };
+
+ WalkontableDom.prototype.removeClass = function (ele, cls) {
+ if (this.hasClass(ele, cls)) { //is this really needed?
+ var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
+ ele.className = ele.className.replace(reg, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, ''); //last 2 replaces do right trim (see http://blog.stevenlevithan.com/archives/faster-trim-javascript)
+ }
+ };
+}
+
+/*//http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/
+ WalkontableDom.prototype.addEvent = (function () {
+ var that = this;
+ if (document.addEventListener) {
+ return function (elem, type, cb) {
+ if ((elem && !elem.length) || elem === window) {
+ elem.addEventListener(type, cb, false);
+ }
+ else if (elem && elem.length) {
+ var len = elem.length;
+ for (var i = 0; i < len; i++) {
+ that.addEvent(elem[i], type, cb);
+ }
+ }
+ };
+ }
+ else {
+ return function (elem, type, cb) {
+ if ((elem && !elem.length) || elem === window) {
+ elem.attachEvent('on' + type, function () {
+
+ //normalize
+ //http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization
+ var e = window['event'];
+ e.target = e.srcElement;
+ //e.offsetX = e.layerX;
+ //e.offsetY = e.layerY;
+ e.relatedTarget = e.relatedTarget || e.type == 'mouseover' ? e.fromElement : e.toElement;
+ if (e.target.nodeType === 3) e.target = e.target.parentNode; //Safari bug
+
+ return cb.call(elem, e)
+ });
+ }
+ else if (elem.length) {
+ var len = elem.length;
+ for (var i = 0; i < len; i++) {
+ that.addEvent(elem[i], type, cb);
+ }
+ }
+ };
+ }
+ })();
+
+ WalkontableDom.prototype.triggerEvent = function (element, eventName, target) {
+ var event;
+ if (document.createEvent) {
+ event = document.createEvent("MouseEvents");
+ event.initEvent(eventName, true, true);
+ } else {
+ event = document.createEventObject();
+ event.eventType = eventName;
+ }
+
+ event.eventName = eventName;
+ event.target = target;
+
+ if (document.createEvent) {
+ target.dispatchEvent(event);
+ } else {
+ target.fireEvent("on" + event.eventType, event);
+ }
+ };*/
+
+WalkontableDom.prototype.removeTextNodes = function (elem, parent) {
+ if (elem.nodeType === 3) {
+ parent.removeChild(elem); //bye text nodes!
+ }
+ else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(elem.nodeName) > -1) {
+ var childs = elem.childNodes;
+ for (var i = childs.length - 1; i >= 0; i--) {
+ this.removeTextNodes(childs[i], elem);
+ }
+ }
+};
+
+/**
+ * Remove childs function
+ * WARNING - this doesn't unload events and data attached by jQuery
+ * http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9
+ * @param element
+ * @returns {void}
+ */
+//
+WalkontableDom.prototype.empty = function (element) {
+ var child;
+ while (child = element.lastChild) {
+ element.removeChild(child);
+ }
+};
+
+WalkontableDom.prototype.HTML_CHARACTERS = /(<(.*)>|&(.*);)/;
+
+/**
+ * Insert content into element trying avoid innerHTML method.
+ * @return {void}
+ */
+WalkontableDom.prototype.fastInnerHTML = function (element, content) {
+ if (this.HTML_CHARACTERS.test(content)) {
+ element.innerHTML = content;
+ }
+ else {
+ this.fastInnerText(element, content);
+ }
+};
+
+/**
+ * Insert text content into element
+ * @return {void}
+ */
+if (document.createTextNode('test').textContent) { //STANDARDS
+ WalkontableDom.prototype.fastInnerText = function (element, content) {
+ var child = element.firstChild;
+ if (child && child.nodeType === 3 && child.nextSibling === null) {
+ //fast lane - replace existing text node
+ //http://jsperf.com/replace-text-vs-reuse
+ child.textContent = content;
+ }
+ else {
+ //slow lane - empty element and insert a text node
+ this.empty(element);
+ element.appendChild(document.createTextNode(content));
+ }
+ };
+}
+else { //IE8
+ WalkontableDom.prototype.fastInnerText = function (element, content) {
+ var child = element.firstChild;
+ if (child && child.nodeType === 3 && child.nextSibling === null) {
+ //fast lane - replace existing text node
+ //http://jsperf.com/replace-text-vs-reuse
+ child.data = content;
+ }
+ else {
+ //slow lane - empty element and insert a text node
+ this.empty(element);
+ element.appendChild(document.createTextNode(content));
+ }
+ };
+}
+
+/**
+ * Returns true if element is attached to the DOM and visible, false otherwise
+ * @param elem
+ * @returns {boolean}
+ */
+WalkontableDom.prototype.isVisible = function (elem) {
+ //fast method
+ try {//try/catch performance is not a problem here: http://jsperf.com/try-catch-performance-overhead/7
+ if (!elem.offsetParent) {
+ return false; //fixes problem with UI Bootstrap directive
+ }
+ }
+ catch (e) {
+ return false; //IE8 throws "Unspecified error" when offsetParent is not found - we catch it here
+ }
+
+// if (elem.offsetWidth > 0 || (elem.parentNode && elem.parentNode.offsetWidth > 0)) { //IE10 was mistaken here
+ if (elem.offsetWidth > 0) {
+ return true;
+ }
+
+ //slow method
+ var next = elem;
+ while (next !== document.documentElement) { //until reached
+ if (next === null) { //parent detached from DOM
+ return false;
+ }
+ else if (next.nodeType === 11) {
+ return true;
+ }
+ else if (next.style.display === 'none') {
+ return false;
+ }
+ next = next.parentNode;
+ }
+ return true;
+};
+
+/**
+ * Returns elements top and left offset relative to the document. In our usage case compatible with jQuery but 2x faster
+ * @param {HTMLElement} elem
+ * @return {Object}
+ */
+WalkontableDom.prototype.offset = function (elem) {
+ var offsetLeft = elem.offsetLeft
+ , offsetTop = elem.offsetTop
+ , lastElem = elem;
+
+ while (elem = elem.offsetParent) {
+ if (elem === document.body) { //from my observation, document.body always has scrollLeft/scrollTop == 0
+ break;
+ }
+ offsetLeft += elem.offsetLeft;
+ offsetTop += elem.offsetTop;
+ lastElem = elem;
+ }
+
+ if (lastElem && lastElem.style.position === 'fixed') { //slow - http://jsperf.com/offset-vs-getboundingclientrect/6
+ //if(lastElem !== document.body) { //faster but does gives false positive in Firefox
+ offsetLeft += window.pageXOffset || document.documentElement.scrollLeft;
+ offsetTop += window.pageYOffset || document.documentElement.scrollTop;
+ }
+
+ return {
+ left: offsetLeft,
+ top: offsetTop
+ };
+};
+
+WalkontableDom.prototype.getComputedStyle = function (elem) {
+ return elem.currentStyle || document.defaultView.getComputedStyle(elem);
+};
+
+WalkontableDom.prototype.outerWidth = function (elem) {
+ return elem.offsetWidth;
+};
+
+WalkontableDom.prototype.outerHeight = function (elem) {
+ if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
+ //fixes problem with Firefox ignoring
in TABLE.offsetHeight
+ //jQuery (1.10.1) still has this unsolved
+ //may be better to just switch to getBoundingClientRect
+ //http://bililite.com/blog/2009/03/27/finding-the-size-of-a-table/
+ //http://lists.w3.org/Archives/Public/www-style/2009Oct/0089.html
+ //http://bugs.jquery.com/ticket/2196
+ //http://lists.w3.org/Archives/Public/www-style/2009Oct/0140.html#start140
+ return elem.offsetHeight + elem.firstChild.offsetHeight;
+ }
+ else {
+ return elem.offsetHeight;
+ }
+};
+
+(function () {
+ var hasCaptionProblem;
+
+ function detectCaptionProblem() {
+ var TABLE = document.createElement('TABLE');
+ TABLE.style.borderSpacing = 0;
+ TABLE.style.borderWidth = 0;
+ TABLE.style.padding = 0;
+ var TBODY = document.createElement('TBODY');
+ TABLE.appendChild(TBODY);
+ TBODY.appendChild(document.createElement('TR'));
+ TBODY.firstChild.appendChild(document.createElement('TD'));
+ TBODY.firstChild.firstChild.innerHTML = '
t t
';
+
+ var CAPTION = document.createElement('CAPTION');
+ CAPTION.innerHTML = 'c c c c';
+ CAPTION.style.padding = 0;
+ CAPTION.style.margin = 0;
+ TABLE.insertBefore(CAPTION, TBODY);
+
+ document.body.appendChild(TABLE);
+ hasCaptionProblem = (TABLE.offsetHeight < 2 * TABLE.lastChild.offsetHeight); //boolean
+ document.body.removeChild(TABLE);
+ }
+
+ WalkontableDom.prototype.hasCaptionProblem = function () {
+ if (hasCaptionProblem === void 0) {
+ detectCaptionProblem();
+ }
+ return hasCaptionProblem;
+ };
+})();
+
+function WalkontableEvent(instance) {
+ var that = this;
+
+ //reference to instance
+ this.instance = instance;
+
+ this.wtDom = this.instance.wtDom;
+
+ var dblClickOrigin = [null, null, null, null];
+ this.instance.dblClickTimeout = null;
+
+ var onMouseDown = function (event) {
+ var cell = that.parentCell(event.target);
+
+ if (cell.TD && cell.TD.nodeName === 'TD') {
+ if (that.instance.hasSetting('onCellMouseDown')) {
+ that.instance.getSetting('onCellMouseDown', event, cell.coords, cell.TD);
+ }
+ }
+ else if (that.wtDom.hasClass(event.target, 'corner')) {
+ that.instance.getSetting('onCellCornerMouseDown', event, event.target);
+ }
+
+ if (event.button !== 2) { //if not right mouse button
+ if (cell.TD && cell.TD.nodeName === 'TD') {
+ dblClickOrigin.shift();
+ dblClickOrigin.push(cell.TD);
+ }
+ else if (that.wtDom.hasClass(event.target, 'corner')) {
+ dblClickOrigin.shift();
+ dblClickOrigin.push(event.target);
+ }
+ }
+ };
+
+ var lastMouseOver;
+ var onMouseOver = function (event) {
+ if (that.instance.hasSetting('onCellMouseOver')) {
+ var TABLE = that.instance.wtTable.TABLE;
+ var TD = that.wtDom.closest(event.target, ['TD', 'TH'], TABLE);
+ if (TD && TD !== lastMouseOver && that.wtDom.isChildOf(TD, TABLE)) {
+ lastMouseOver = TD;
+ if (TD.nodeName === 'TD') {
+ that.instance.getSetting('onCellMouseOver', event, that.instance.wtTable.getCoords(TD), TD);
+ }
+ }
+ }
+ };
+
+/* var lastMouseOut;
+ var onMouseOut = function (event) {
+ if (that.instance.hasSetting('onCellMouseOut')) {
+ var TABLE = that.instance.wtTable.TABLE;
+ var TD = that.wtDom.closest(event.target, ['TD', 'TH'], TABLE);
+ if (TD && TD !== lastMouseOut && that.wtDom.isChildOf(TD, TABLE)) {
+ lastMouseOut = TD;
+ if (TD.nodeName === 'TD') {
+ that.instance.getSetting('onCellMouseOut', event, that.instance.wtTable.getCoords(TD), TD);
+ }
+ }
+ }
+ };*/
+
+ var onMouseUp = function (event) {
+ if (event.button !== 2) { //if not right mouse button
+ var cell = that.parentCell(event.target);
+
+ if (cell.TD && cell.TD.nodeName === 'TD') {
+ dblClickOrigin.shift();
+ dblClickOrigin.push(cell.TD);
+ }
+ else {
+ dblClickOrigin.shift();
+ dblClickOrigin.push(event.target);
+ }
+
+ if (dblClickOrigin[3] !== null && dblClickOrigin[3] === dblClickOrigin[2]) {
+ if (that.instance.dblClickTimeout && dblClickOrigin[2] === dblClickOrigin[1] && dblClickOrigin[1] === dblClickOrigin[0]) {
+ if (cell.TD) {
+ that.instance.getSetting('onCellDblClick', event, cell.coords, cell.TD);
+ }
+ else if (that.wtDom.hasClass(event.target, 'corner')) {
+ that.instance.getSetting('onCellCornerDblClick', event, cell.coords, cell.TD);
+ }
+
+ clearTimeout(that.instance.dblClickTimeout);
+ that.instance.dblClickTimeout = null;
+ }
+ else {
+ clearTimeout(that.instance.dblClickTimeout);
+ that.instance.dblClickTimeout = setTimeout(function () {
+ that.instance.dblClickTimeout = null;
+ }, 500);
+ }
+ }
+ }
+ };
+
+ $(this.instance.wtTable.parent).on('mousedown', onMouseDown);
+ $(this.instance.wtTable.TABLE).on('mouseover', onMouseOver);
+// $(this.instance.wtTable.TABLE).on('mouseout', onMouseOut);
+ $(this.instance.wtTable.parent).on('mouseup', onMouseUp);
+}
+
+WalkontableEvent.prototype.parentCell = function (elem) {
+ var cell = {};
+ var TABLE = this.instance.wtTable.TABLE;
+ var TD = this.wtDom.closest(elem, ['TD', 'TH'], TABLE);
+ if (TD && this.wtDom.isChildOf(TD, TABLE)) {
+ cell.coords = this.instance.wtTable.getCoords(TD);
+ cell.TD = TD;
+ }
+ else if (this.wtDom.hasClass(elem, 'wtBorder') && this.wtDom.hasClass(elem, 'current') && !this.wtDom.hasClass(elem, 'corner')) {
+ cell.coords = this.instance.selections.current.selected[0];
+ cell.TD = this.instance.wtTable.getCell(cell.coords);
+ }
+ return cell;
+};
+function walkontableRangesIntersect() {
+ var from = arguments[0];
+ var to = arguments[1];
+ for (var i = 1, ilen = arguments.length / 2; i < ilen; i++) {
+ if (from <= arguments[2 * i + 1] && to >= arguments[2 * i]) {
+ return true;
+ }
+ }
+ return false;
+}
+//http://stackoverflow.com/questions/3629183/why-doesnt-indexof-work-on-an-array-ie8
+if (!Array.prototype.indexOf) {
+ Array.prototype.indexOf = function (elt /*, from*/) {
+ var len = this.length >>> 0;
+
+ var from = Number(arguments[1]) || 0;
+ from = (from < 0)
+ ? Math.ceil(from)
+ : Math.floor(from);
+ if (from < 0)
+ from += len;
+
+ for (; from < len; from++) {
+ if (from in this &&
+ this[from] === elt)
+ return from;
+ }
+ return -1;
+ };
+}
+
+/**
+ * http://notes.jetienne.com/2011/05/18/cancelRequestAnimFrame-for-paul-irish-requestAnimFrame.html
+ */
+window.requestAnimFrame = (function () {
+ return window.requestAnimationFrame ||
+ window.webkitRequestAnimationFrame ||
+ window.mozRequestAnimationFrame ||
+ window.oRequestAnimationFrame ||
+ window.msRequestAnimationFrame ||
+ function (/* function */ callback, /* DOMElement */ element) {
+ return window.setTimeout(callback, 1000 / 60);
+ };
+})();
+
+window.cancelRequestAnimFrame = (function () {
+ return window.cancelAnimationFrame ||
+ window.webkitCancelRequestAnimationFrame ||
+ window.mozCancelRequestAnimationFrame ||
+ window.oCancelRequestAnimationFrame ||
+ window.msCancelRequestAnimationFrame ||
+ clearTimeout
+})();
+
+//http://snipplr.com/view/13523/
+//modified for speed
+//http://jsperf.com/getcomputedstyle-vs-style-vs-css/8
+if (!window.getComputedStyle) {
+ (function () {
+ var elem;
+
+ var styleObj = {
+ getPropertyValue: function getPropertyValue(prop) {
+ if (prop == 'float') prop = 'styleFloat';
+ return elem.currentStyle[prop.toUpperCase()] || null;
+ }
+ }
+
+ window.getComputedStyle = function (el) {
+ elem = el;
+ return styleObj;
+ }
+ })();
+}
+/**
+ * WalkontableRowFilter
+ * @constructor
+ */
+function WalkontableRowFilter() {
+}
+
+WalkontableRowFilter.prototype = new WalkontableCellFilter();
+
+WalkontableRowFilter.prototype.readSettings = function (instance) {
+ this.offset = instance.wtSettings.settings.offsetRow;
+ this.total = instance.getSetting('totalRows');
+ this.fixedCount = instance.getSetting('fixedRowsTop');
+};
+/**
+ * WalkontableRowStrategy
+ * @param containerSizeFn
+ * @param sizeAtIndex
+ * @constructor
+ */
+function WalkontableRowStrategy(containerSizeFn, sizeAtIndex) {
+ this.containerSizeFn = containerSizeFn;
+ this.sizeAtIndex = sizeAtIndex;
+ this.cellSizesSum = 0;
+ this.cellSizes = [];
+ this.cellCount = 0;
+ this.remainingSize = -Infinity;
+}
+
+WalkontableRowStrategy.prototype = new WalkontableCellStrategy();
+
+WalkontableRowStrategy.prototype.add = function (i, TD) {
+ if (this.remainingSize < 0) {
+ var size = this.sizeAtIndex(i, TD);
+ if (size === void 0) {
+ return; //total rows exceeded
+ }
+ var containerSize = this.getContainerSize(this.cellSizesSum + size);
+ this.cellSizes.push(size);
+ this.cellSizesSum += size;
+ this.cellCount++;
+ this.remainingSize = this.cellSizesSum - containerSize;
+ }
+};
+
+WalkontableRowStrategy.prototype.remove = function () {
+ var size = this.cellSizes.pop();
+ this.cellSizesSum -= size;
+ this.cellCount--;
+ this.remainingSize += size;
+};
+function WalkontableScroll(instance) {
+ this.instance = instance;
+}
+
+WalkontableScroll.prototype.scrollVertical = function (delta) {
+ if (!this.instance.drawn) {
+ throw new Error('scrollVertical can only be called after table was drawn to DOM');
+ }
+
+ var instance = this.instance
+ , newOffset
+ , offset = instance.getSetting('offsetRow')
+ , fixedCount = instance.getSetting('fixedRowsTop')
+ , total = instance.getSetting('totalRows')
+ , maxSize = instance.wtViewport.getViewportHeight();
+
+ if (total > 0) {
+ newOffset = this.scrollLogicVertical(delta, offset, total, fixedCount, maxSize, function (row) {
+ if (row - offset < fixedCount && row - offset >= 0) {
+ return instance.getSetting('rowHeight', row - offset);
+ }
+ else {
+ return instance.getSetting('rowHeight', row);
+ }
+ }, function (isReverse) {
+ instance.wtTable.verticalRenderReverse = isReverse;
+ });
+ }
+ else {
+ newOffset = 0;
+ }
+
+ if (newOffset !== offset) {
+ this.instance.wtScrollbars.vertical.scrollTo(newOffset);
+ }
+ return instance;
+};
+
+WalkontableScroll.prototype.scrollHorizontal = function (delta) {
+ if (!this.instance.drawn) {
+ throw new Error('scrollHorizontal can only be called after table was drawn to DOM');
+ }
+
+ var instance = this.instance
+ , newOffset
+ , offset = instance.getSetting('offsetColumn')
+ , fixedCount = instance.getSetting('fixedColumnsLeft')
+ , total = instance.getSetting('totalColumns')
+ , maxSize = instance.wtViewport.getViewportWidth();
+
+ if (total > 0) {
+ newOffset = this.scrollLogicHorizontal(delta, offset, total, fixedCount, maxSize, function (col) {
+ if (col - offset < fixedCount && col - offset >= 0) {
+ return instance.getSetting('columnWidth', col - offset);
+ }
+ else {
+ return instance.getSetting('columnWidth', col);
+ }
+ });
+ }
+ else {
+ newOffset = 0;
+ }
+
+ if (newOffset !== offset) {
+ this.instance.wtScrollbars.horizontal.scrollTo(newOffset);
+ }
+ return instance;
+};
+
+WalkontableScroll.prototype.scrollLogicVertical = function (delta, offset, total, fixedCount, maxSize, cellSizeFn, setReverseRenderFn) {
+ var newOffset = offset + delta;
+
+ if (newOffset >= total - fixedCount) {
+ newOffset = total - fixedCount - 1;
+ setReverseRenderFn(true);
+ }
+ else if (newOffset < 0) {
+ newOffset = 0;
+ }
+
+ return newOffset;
+};
+
+WalkontableScroll.prototype.scrollLogicHorizontal = function (delta, offset, total, fixedCount, maxSize, cellSizeFn) {
+ var newOffset = offset + delta
+ , sum = 0
+ , col;
+
+ if (newOffset > fixedCount) {
+ if (newOffset >= total - fixedCount) {
+ newOffset = total - fixedCount - 1;
+ }
+
+ col = newOffset;
+ while (sum < maxSize && col < total) {
+ sum += cellSizeFn(col);
+ col++;
+ }
+
+ if (sum < maxSize) {
+ while (newOffset > 0) {
+ //if sum still less than available width, we cannot scroll that far (must move offset to the left)
+ sum += cellSizeFn(newOffset - 1);
+ if (sum < maxSize) {
+ newOffset--;
+ }
+ else {
+ break;
+ }
+ }
+ }
+ }
+ else if (newOffset < 0) {
+ newOffset = 0;
+ }
+
+ return newOffset;
+};
+
+/**
+ * Scrolls viewport to a cell by minimum number of cells
+ */
+WalkontableScroll.prototype.scrollViewport = function (coords) {
+ var offsetRow = this.instance.getSetting('offsetRow')
+ , offsetColumn = this.instance.getSetting('offsetColumn')
+ , lastVisibleRow = this.instance.wtTable.getLastVisibleRow()
+ , lastVisibleColumn = this.instance.wtTable.getLastVisibleColumn()
+ , totalRows = this.instance.getSetting('totalRows')
+ , totalColumns = this.instance.getSetting('totalColumns')
+ , fixedRowsTop = this.instance.getSetting('fixedRowsTop')
+ , fixedColumnsLeft = this.instance.getSetting('fixedColumnsLeft');
+
+ if (coords[0] < 0 || coords[0] > totalRows - 1) {
+ throw new Error('row ' + coords[0] + ' does not exist');
+ }
+ else if (coords[1] < 0 || coords[1] > totalColumns - 1) {
+ throw new Error('column ' + coords[1] + ' does not exist');
+ }
+
+ if (coords[0] > lastVisibleRow) {
+// this.scrollVertical(coords[0] - lastVisibleRow + 1);
+ this.scrollVertical(coords[0] - fixedRowsTop - offsetRow);
+ this.instance.wtTable.verticalRenderReverse = true;
+ }
+ else if (coords[0] === lastVisibleRow && this.instance.wtTable.rowStrategy.isLastIncomplete()) {
+// this.scrollVertical(coords[0] - lastVisibleRow + 1);
+ this.scrollVertical(coords[0] - fixedRowsTop - offsetRow);
+ this.instance.wtTable.verticalRenderReverse = true;
+ }
+ else if (coords[0] - fixedRowsTop < offsetRow) {
+ this.scrollVertical(coords[0] - fixedRowsTop - offsetRow);
+ }
+ else {
+ this.scrollVertical(0); //Craig's issue: remove row from the last scroll page should scroll viewport a row up if needed
+ }
+
+ if (coords[1] > lastVisibleColumn) {
+ this.scrollHorizontal(coords[1] - lastVisibleColumn + 1);
+ }
+ else if (coords[1] === lastVisibleColumn && this.instance.wtTable.columnStrategy.isLastIncomplete()) {
+ this.scrollHorizontal(coords[1] - lastVisibleColumn + 1);
+ }
+ else if (coords[1] - fixedColumnsLeft < offsetColumn) {
+ this.scrollHorizontal(coords[1] - fixedColumnsLeft - offsetColumn);
+ }
+ else {
+ this.scrollHorizontal(0); //Craig's issue
+ }
+
+ return this.instance;
+};
+
+function WalkontableScrollbar() {
+}
+
+WalkontableScrollbar.prototype.init = function () {
+ var that = this;
+
+ //reference to instance
+ this.$table = $(this.instance.wtTable.TABLE);
+
+ //create elements
+ this.slider = document.createElement('DIV');
+ this.sliderStyle = this.slider.style;
+ this.sliderStyle.position = 'absolute';
+ this.sliderStyle.top = '0';
+ this.sliderStyle.left = '0';
+ this.sliderStyle.display = 'none';
+ this.slider.className = 'dragdealer ' + this.type;
+
+ this.handle = document.createElement('DIV');
+ this.handleStyle = this.handle.style;
+ this.handle.className = 'handle';
+
+ this.slider.appendChild(this.handle);
+ this.container = this.instance.wtTable.parent;
+ this.container.appendChild(this.slider);
+
+ var firstRun = true;
+ this.dragTimeout = null;
+ var dragDelta;
+ var dragRender = function () {
+ that.onScroll(dragDelta);
+ };
+
+ this.dragdealer = new Dragdealer(this.slider, {
+ vertical: (this.type === 'vertical'),
+ horizontal: (this.type === 'horizontal'),
+ slide: false,
+ speed: 100,
+ animationCallback: function (x, y) {
+ if (firstRun) {
+ firstRun = false;
+ return;
+ }
+ that.skipRefresh = true;
+ dragDelta = that.type === 'vertical' ? y : x;
+ if (that.dragTimeout === null) {
+ that.dragTimeout = setInterval(dragRender, 100);
+ dragRender();
+ }
+ },
+ callback: function (x, y) {
+ that.skipRefresh = false;
+ clearInterval(that.dragTimeout);
+ that.dragTimeout = null;
+ dragDelta = that.type === 'vertical' ? y : x;
+ that.onScroll(dragDelta);
+ }
+ });
+ this.skipRefresh = false;
+};
+
+WalkontableScrollbar.prototype.onScroll = function (delta) {
+ if (this.instance.drawn) {
+ this.readSettings();
+ if (this.total > this.visibleCount) {
+ var newOffset = Math.round(this.handlePosition * this.total / this.sliderSize);
+
+ if (delta === 1) {
+ if (this.type === 'vertical') {
+ this.instance.scrollVertical(Infinity).draw();
+ }
+ else {
+ this.instance.scrollHorizontal(Infinity).draw();
+ }
+ }
+ else if (newOffset !== this.offset) { //is new offset different than old offset
+ if (this.type === 'vertical') {
+ this.instance.scrollVertical(newOffset - this.offset).draw();
+ }
+ else {
+ this.instance.scrollHorizontal(newOffset - this.offset).draw();
+ }
+ }
+ else {
+ this.refresh();
+ }
+ }
+ }
+};
+
+/**
+ * Returns what part of the scroller should the handle take
+ * @param viewportCount {Number} number of visible rows or columns
+ * @param totalCount {Number} total number of rows or columns
+ * @return {Number} 0..1
+ */
+WalkontableScrollbar.prototype.getHandleSizeRatio = function (viewportCount, totalCount) {
+ if (!totalCount || viewportCount > totalCount) {
+ return 1;
+ }
+ return viewportCount / totalCount;
+};
+
+WalkontableScrollbar.prototype.prepare = function () {
+ if (this.skipRefresh) {
+ return;
+ }
+ var ratio = this.getHandleSizeRatio(this.visibleCount, this.total);
+ if (((ratio === 1 || isNaN(ratio)) && this.scrollMode === 'auto') || this.scrollMode === 'none') {
+ //isNaN is needed because ratio equals NaN when totalRows/totalColumns equals 0
+ this.visible = false;
+ }
+ else {
+ this.visible = true;
+ }
+};
+
+WalkontableScrollbar.prototype.refresh = function () {
+ if (this.skipRefresh) {
+ return;
+ }
+ else if (!this.visible) {
+ this.sliderStyle.display = 'none';
+ return;
+ }
+
+ var ratio
+ , sliderSize
+ , handleSize
+ , handlePosition
+ , visibleCount = this.visibleCount
+ , tableWidth = this.instance.wtViewport.getWorkspaceWidth()
+ , tableHeight = this.instance.wtViewport.getWorkspaceHeight();
+
+ if (tableWidth === Infinity) {
+ tableWidth = this.instance.wtViewport.getWorkspaceActualWidth();
+ }
+
+ if (tableHeight === Infinity) {
+ tableHeight = this.instance.wtViewport.getWorkspaceActualHeight();
+ }
+
+ if (this.type === 'vertical') {
+ if (this.instance.wtTable.rowStrategy.isLastIncomplete()) {
+ visibleCount--;
+ }
+
+ sliderSize = tableHeight - 2; //2 is sliders border-width
+
+ this.sliderStyle.top = this.instance.wtDom.offset(this.$table[0]).top - this.instance.wtDom.offset(this.container).top + 'px';
+ this.sliderStyle.left = tableWidth - 1 + 'px'; //1 is sliders border-width
+ this.sliderStyle.height = Math.max(sliderSize, 0) + 'px';
+ }
+ else { //horizontal
+ if (this.instance.wtTable.columnStrategy.isLastIncomplete()) {
+ visibleCount--;
+ }
+
+ sliderSize = tableWidth - 2; //2 is sliders border-width
+
+ this.sliderStyle.left = this.instance.wtDom.offset(this.$table[0]).left - this.instance.wtDom.offset(this.container).left + 'px';
+ this.sliderStyle.top = tableHeight - 1 + 'px'; //1 is sliders border-width
+ this.sliderStyle.width = Math.max(sliderSize, 0) + 'px';
+ }
+
+ ratio = this.getHandleSizeRatio(visibleCount, this.total);
+ handleSize = Math.round(sliderSize * ratio);
+ if (handleSize < 10) {
+ handleSize = 15;
+ }
+
+ handlePosition = Math.floor(sliderSize * (this.offset / this.total));
+ if (handleSize + handlePosition > sliderSize) {
+ handlePosition = sliderSize - handleSize;
+ }
+
+ if (this.type === 'vertical') {
+ this.handleStyle.height = handleSize + 'px';
+ this.handleStyle.top = handlePosition + 'px';
+
+ }
+ else { //horizontal
+ this.handleStyle.width = handleSize + 'px';
+ this.handleStyle.left = handlePosition + 'px';
+ }
+
+ this.sliderStyle.display = 'block';
+};
+
+WalkontableScrollbar.prototype.destroy = function () {
+ clearInterval(this.dragdealer.interval);
+};
+
+///
+
+var WalkontableVerticalScrollbar = function (instance) {
+ this.instance = instance;
+ this.type = 'vertical';
+ this.init();
+};
+
+WalkontableVerticalScrollbar.prototype = new WalkontableScrollbar();
+
+WalkontableVerticalScrollbar.prototype.scrollTo = function (cell) {
+ this.instance.update('offsetRow', cell);
+};
+
+WalkontableVerticalScrollbar.prototype.readSettings = function () {
+ this.scrollMode = this.instance.getSetting('scrollV');
+ this.offset = this.instance.getSetting('offsetRow');
+ this.total = this.instance.getSetting('totalRows');
+ this.visibleCount = this.instance.wtTable.rowStrategy.countVisible();
+ if(this.visibleCount > 1 && this.instance.wtTable.rowStrategy.isLastIncomplete()) {
+ this.visibleCount--;
+ }
+ this.handlePosition = parseInt(this.handleStyle.top, 10);
+ this.sliderSize = parseInt(this.sliderStyle.height, 10);
+ this.fixedCount = this.instance.getSetting('fixedRowsTop');
+};
+
+///
+
+var WalkontableHorizontalScrollbar = function (instance) {
+ this.instance = instance;
+ this.type = 'horizontal';
+ this.init();
+};
+
+WalkontableHorizontalScrollbar.prototype = new WalkontableScrollbar();
+
+WalkontableHorizontalScrollbar.prototype.scrollTo = function (cell) {
+ this.instance.update('offsetColumn', cell);
+};
+
+WalkontableHorizontalScrollbar.prototype.readSettings = function () {
+ this.scrollMode = this.instance.getSetting('scrollH');
+ this.offset = this.instance.getSetting('offsetColumn');
+ this.total = this.instance.getSetting('totalColumns');
+ this.visibleCount = this.instance.wtTable.columnStrategy.countVisible();
+ if(this.visibleCount > 1 && this.instance.wtTable.columnStrategy.isLastIncomplete()) {
+ this.visibleCount--;
+ }
+ this.handlePosition = parseInt(this.handleStyle.left, 10);
+ this.sliderSize = parseInt(this.sliderStyle.width, 10);
+ this.fixedCount = this.instance.getSetting('fixedColumnsLeft');
+};
+function WalkontableScrollbarNative() {
+ this.lastWindowScrollPosition = NaN;
+}
+
+WalkontableScrollbarNative.prototype.init = function () {
+ this.fixedContainer = this.instance.wtTable.TABLE.parentNode.parentNode.parentNode;
+ this.fixed = this.instance.wtTable.TABLE.parentNode.parentNode;
+ this.TABLE = this.instance.wtTable.TABLE;
+ this.$scrollHandler = $(window); //in future remove jQuery from here
+
+ var that = this;
+ this.$scrollHandler.on('scroll.walkontable', function () {
+ if (!that.instance.wtTable.parent.parentNode) {
+ //Walkontable was detached from DOM, but this handler was not removed
+ that.destroy();
+ return;
+ }
+
+ that.onScroll();
+ });
+
+ this.readSettings();
+};
+
+WalkontableScrollbarNative.prototype.onScroll = function () {
+ this.readSettings();
+ if (this.windowScrollPosition === this.lastWindowScrollPosition) {
+ return;
+ }
+ this.lastWindowScrollPosition = this.windowScrollPosition;
+
+ var scrollDelta;
+ var newOffset = 0;
+
+ if (this.windowScrollPosition > this.tableParentOffset) {
+ scrollDelta = this.windowScrollPosition - this.tableParentOffset;
+ newOffset = Math.ceil(scrollDelta / 20, 10);
+ newOffset = Math.min(newOffset, this.total)
+ }
+
+ this.instance.update('offsetRow', newOffset);
+ this.instance.draw();
+};
+
+WalkontableScrollbarNative.prototype.prepare = function () {
+};
+
+WalkontableScrollbarNative.prototype.availableSize = function () {
+ var availableSize;
+
+ //var last = this.getLastCell();
+ if (this.windowScrollPosition > this.tableParentOffset /*&& last > -1*/) { //last -1 means that viewport is scrolled behind the table
+ if (this.instance.wtTable.getLastVisibleRow() === this.total - 1) {
+ availableSize = this.instance.wtDom.outerHeight(this.TABLE);
+ }
+ else {
+ availableSize = this.windowSize;
+ }
+ }
+ else {
+ availableSize = this.windowSize - (this.tableParentOffset - this.windowScrollPosition);
+ }
+
+ return availableSize;
+};
+
+WalkontableScrollbarNative.prototype.refresh = function () {
+ var last = this.getLastCell();
+ this.measureBefore = this.offset * this.cellSize;
+ this.measureInside = this.getTableSize();
+ if (last === -1) { //last -1 means that viewport is scrolled behind the table
+ this.measureAfter = 0;
+ }
+ else {
+ this.measureAfter = (this.total - last - 1) * this.cellSize;
+ }
+ this.applyToDOM();
+};
+
+WalkontableScrollbarNative.prototype.destroy = function () {
+ this.$scrollHandler.off('scroll.walkontable');
+};
+
+///
+
+var WalkontableVerticalScrollbarNative = function (instance) {
+ this.instance = instance;
+ this.type = 'vertical';
+ this.cellSize = 20;
+ this.init();
+};
+
+WalkontableVerticalScrollbarNative.prototype = new WalkontableScrollbarNative();
+
+WalkontableVerticalScrollbarNative.prototype.getLastCell = function () {
+ return this.instance.wtTable.getLastVisibleRow();
+};
+
+WalkontableVerticalScrollbarNative.prototype.getTableSize = function () {
+ return this.instance.wtDom.outerHeight(this.TABLE);
+};
+
+WalkontableVerticalScrollbarNative.prototype.applyToDOM = function () {
+ if (this.windowScrollPosition > this.tableParentOffset /*&& last > -1*/) { //last -1 means that viewport is scrolled behind the table
+ this.fixed.style.position = 'fixed';
+ this.fixed.style.top = '0';
+ this.fixed.style.left = this.tableParentOtherOffset;
+ }
+ else {
+ this.fixed.style.position = 'relative';
+ }
+
+ var debug = false;
+ if (debug) {
+ //this.fixedContainer.style.borderTop = this.measureBefore + 'px solid red';
+ //this.fixedContainer.style.borderBottom = (this.tableSize + this.measureAfter) + 'px solid blue';
+ }
+ else {
+ this.fixedContainer.style.paddingTop = this.measureBefore + 'px';
+ this.fixedContainer.style.paddingBottom = (this.measureInside + this.measureAfter) + 'px';
+ }
+};
+
+WalkontableVerticalScrollbarNative.prototype.scrollTo = function (cell) {
+ this.$scrollHandler.scrollTop(this.tableParentOffset + cell * this.cellSize);
+};
+
+WalkontableVerticalScrollbarNative.prototype.readSettings = function () {
+ var offset = this.instance.wtDom.offset(this.fixedContainer);
+ this.tableParentOffset = offset.top;
+ this.tableParentOtherOffset = offset.left;
+ this.windowSize = this.$scrollHandler.height();
+ this.windowScrollPosition = this.$scrollHandler.scrollTop();
+ this.offset = this.instance.getSetting('offsetRow');
+ this.total = this.instance.getSetting('totalRows');
+};
+
+///
+
+var WalkontableHorizontalScrollbarNative = function (instance) {
+ this.instance = instance;
+ this.type = 'horizontal';
+ this.cellSize = 50;
+ this.init();
+};
+
+WalkontableHorizontalScrollbarNative.prototype = new WalkontableScrollbarNative();
+
+WalkontableHorizontalScrollbarNative.prototype.getLastCell = function () {
+ return this.instance.wtTable.getLastVisibleColumn();
+};
+
+WalkontableHorizontalScrollbarNative.prototype.getTableSize = function () {
+ return this.instance.wtDom.outerWidth(this.TABLE);
+};
+
+WalkontableHorizontalScrollbarNative.prototype.applyToDOM = function () {
+ if (this.windowScrollPosition > this.tableParentOffset /*&& last > -1*/) { //last -1 means that viewport is scrolled behind the table
+ this.fixed.style.position = 'fixed';
+ this.fixed.style.left = '0';
+ this.fixed.style.top = this.tableParentOtherOffset;
+ }
+ else {
+ this.fixed.style.position = 'relative';
+ }
+
+ var debug = false;
+ if (debug) {
+ //this.fixedContainer.style.borderLeft = this.measureBefore + 'px solid red';
+ //this.fixedContainer.style.borderBottom = (this.tableSize + this.measureAfter) + 'px solid blue';
+ }
+ else {
+ this.fixedContainer.style.paddingLeft = this.measureBefore + 'px';
+ this.fixedContainer.style.paddingRight = (this.measureInside + this.measureAfter) + 'px';
+ }
+};
+
+WalkontableHorizontalScrollbarNative.prototype.scrollTo = function (cell) {
+ this.$scrollHandler.scrollLeft(this.tableParentOffset + cell * this.cellSize);
+};
+
+WalkontableHorizontalScrollbarNative.prototype.readSettings = function () {
+ var offset = this.instance.wtDom.offset(this.fixedContainer);
+ this.tableParentOffset = offset.left;
+ this.tableParentOtherOffset = offset.top;
+ this.windowSize = this.$scrollHandler.width();
+ this.windowScrollPosition = this.$scrollHandler.scrollLeft();
+ this.offset = this.instance.getSetting('offsetColumn');
+ this.total = this.instance.getSetting('totalColumns');
+};
+function WalkontableScrollbars(instance) {
+ switch (instance.getSetting('scrollbarModelV')) {
+ case 'dragdealer':
+ this.vertical = new WalkontableVerticalScrollbar(instance);
+ break;
+
+ case 'native':
+ this.vertical = new WalkontableVerticalScrollbarNative(instance);
+ break;
+ }
+
+ switch (instance.getSetting('scrollbarModelH')) {
+ case 'dragdealer':
+ this.horizontal = new WalkontableHorizontalScrollbar(instance);
+ break;
+
+ case 'native':
+ this.horizontal = new WalkontableHorizontalScrollbarNative(instance);
+ break;
+ }
+}
+
+WalkontableScrollbars.prototype.destroy = function () {
+ this.vertical.destroy();
+ this.horizontal.destroy();
+};
+
+WalkontableScrollbars.prototype.refresh = function () {
+ this.horizontal.readSettings();
+ this.vertical.readSettings();
+ this.horizontal.prepare();
+ this.vertical.prepare();
+ this.horizontal.refresh();
+ this.vertical.refresh();
+};
+function WalkontableSelection(instance, settings) {
+ this.instance = instance;
+ this.settings = settings;
+ this.selected = [];
+ if (settings.border) {
+ this.border = new WalkontableBorder(instance, settings);
+ }
+}
+
+WalkontableSelection.prototype.add = function (coords) {
+ this.selected.push(coords);
+};
+
+WalkontableSelection.prototype.clear = function () {
+ this.selected.length = 0; //http://jsperf.com/clear-arrayxxx
+};
+
+/**
+ * Returns the top left (TL) and bottom right (BR) selection coordinates
+ * @returns {Object}
+ */
+WalkontableSelection.prototype.getCorners = function () {
+ var minRow
+ , minColumn
+ , maxRow
+ , maxColumn
+ , i
+ , ilen = this.selected.length;
+
+ if (ilen > 0) {
+ minRow = maxRow = this.selected[0][0];
+ minColumn = maxColumn = this.selected[0][1];
+
+ if (ilen > 1) {
+ for (i = 1; i < ilen; i++) {
+ if (this.selected[i][0] < minRow) {
+ minRow = this.selected[i][0];
+ }
+ else if (this.selected[i][0] > maxRow) {
+ maxRow = this.selected[i][0];
+ }
+
+ if (this.selected[i][1] < minColumn) {
+ minColumn = this.selected[i][1];
+ }
+ else if (this.selected[i][1] > maxColumn) {
+ maxColumn = this.selected[i][1];
+ }
+ }
+ }
+ }
+
+ return [minRow, minColumn, maxRow, maxColumn];
+};
+
+WalkontableSelection.prototype.draw = function () {
+ var corners, r, c, source_r, source_c;
+
+ var visibleRows = this.instance.wtTable.rowStrategy.countVisible()
+ , visibleColumns = this.instance.wtTable.columnStrategy.countVisible();
+
+ if (this.selected.length) {
+ corners = this.getCorners();
+
+ for (r = 0; r < visibleRows; r++) {
+ for (c = 0; c < visibleColumns; c++) {
+ source_r = this.instance.wtTable.rowFilter.visibleToSource(r);
+ source_c = this.instance.wtTable.columnFilter.visibleToSource(c);
+
+ if (source_r >= corners[0] && source_r <= corners[2] && source_c >= corners[1] && source_c <= corners[3]) {
+ //selected cell
+ this.instance.wtTable.currentCellCache.add(r, c, this.settings.className);
+ }
+ else if (source_r >= corners[0] && source_r <= corners[2]) {
+ //selection is in this row
+ this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightRowClassName);
+ }
+ else if (source_c >= corners[1] && source_c <= corners[3]) {
+ //selection is in this column
+ this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightColumnClassName);
+ }
+ }
+ }
+
+ this.border && this.border.appear(corners); //warning! border.appear modifies corners!
+ }
+ else {
+ this.border && this.border.disappear();
+ }
+};
+
+function WalkontableSettings(instance, settings) {
+ var that = this;
+ this.instance = instance;
+
+ //default settings. void 0 means it is required, null means it can be empty
+ this.defaults = {
+ table: void 0,
+
+ //presentation mode
+ scrollH: 'auto', //values: scroll (always show scrollbar), auto (show scrollbar if table does not fit in the container), none (never show scrollbar)
+ scrollV: 'auto', //values: see above
+ scrollbarModelH: 'dragdealer', //values: dragdealer, native
+ scrollbarModelV: 'dragdealer', //values: dragdealer, native
+ stretchH: 'hybrid', //values: hybrid, all, last, none
+ currentRowClassName: null,
+ currentColumnClassName: null,
+
+ //data source
+ data: void 0,
+ offsetRow: 0,
+ offsetColumn: 0,
+ fixedColumnsLeft: 0,
+ fixedRowsTop: 0,
+ rowHeaders: function () {
+ return []
+ }, //this must be array of functions: [function (row, TH) {}]
+ columnHeaders: function () {
+ return []
+ }, //this must be array of functions: [function (column, TH) {}]
+ totalRows: void 0,
+ totalColumns: void 0,
+ width: null,
+ height: null,
+ cellRenderer: function (row, column, TD) {
+ var cellData = that.getSetting('data', row, column);
+ that.instance.wtDom.fastInnerText(TD, cellData === void 0 || cellData === null ? '' : cellData);
+ },
+ columnWidth: 50,
+ selections: null,
+ hideBorderOnMouseDownOver: false,
+
+ //callbacks
+ onCellMouseDown: null,
+ onCellMouseOver: null,
+// onCellMouseOut: null,
+ onCellDblClick: null,
+ onCellCornerMouseDown: null,
+ onCellCornerDblClick: null,
+ beforeDraw: null,
+ onDraw: null,
+
+ //constants
+ scrollbarWidth: 10,
+ scrollbarHeight: 10
+ };
+
+ //reference to settings
+ this.settings = {};
+ for (var i in this.defaults) {
+ if (this.defaults.hasOwnProperty(i)) {
+ if (settings[i] !== void 0) {
+ this.settings[i] = settings[i];
+ }
+ else if (this.defaults[i] === void 0) {
+ throw new Error('A required setting "' + i + '" was not provided');
+ }
+ else {
+ this.settings[i] = this.defaults[i];
+ }
+ }
+ }
+}
+
+/**
+ * generic methods
+ */
+
+WalkontableSettings.prototype.update = function (settings, value) {
+ if (value === void 0) { //settings is object
+ for (var i in settings) {
+ if (settings.hasOwnProperty(i)) {
+ this.settings[i] = settings[i];
+ }
+ }
+ }
+ else { //if value is defined then settings is the key
+ this.settings[settings] = value;
+ }
+ return this.instance;
+};
+
+WalkontableSettings.prototype.getSetting = function (key, param1, param2, param3) {
+ if (this[key]) {
+ return this[key](param1, param2, param3);
+ }
+ else {
+ return this._getSetting(key, param1, param2, param3);
+ }
+};
+
+WalkontableSettings.prototype._getSetting = function (key, param1, param2, param3) {
+ if (typeof this.settings[key] === 'function') {
+ return this.settings[key](param1, param2, param3);
+ }
+ else if (param1 !== void 0 && Object.prototype.toString.call(this.settings[key]) === '[object Array]') {
+ return this.settings[key][param1];
+ }
+ else {
+ return this.settings[key];
+ }
+};
+
+WalkontableSettings.prototype.has = function (key) {
+ return !!this.settings[key]
+};
+
+/**
+ * specific methods
+ */
+
+WalkontableSettings.prototype.rowHeight = function (row) {
+ var visible_r = this.instance.wtTable.rowFilter.sourceToVisible(row);
+ var size = this.instance.wtTable.rowStrategy.getSize(visible_r);
+ if (size !== void 0) {
+ return size;
+ }
+ return 20;
+};
+
+WalkontableSettings.prototype.columnWidth = function (column) {
+ return Math.min(200, this._getSetting('columnWidth', column));
+};
+/*var FLAG_VISIBLE_HORIZONTAL = 0x1; // 000001
+ var FLAG_VISIBLE_VERTICAL = 0x2; // 000010
+ var FLAG_PARTIALLY_VISIBLE_HORIZONTAL = 0x4; // 000100
+ var FLAG_PARTIALLY_VISIBLE_VERTICAL = 0x8; // 001000
+ var FLAG_NOT_VISIBLE_HORIZONTAL = 0x10; // 010000
+ var FLAG_NOT_VISIBLE_VERTICAL = 0x20; // 100000*/
+
+function WalkontableTable(instance) {
+ //reference to instance
+ this.instance = instance;
+ this.TABLE = this.instance.getSetting('table');
+ this.wtDom = this.instance.wtDom;
+ this.wtDom.removeTextNodes(this.TABLE);
+
+ //wtSpreader
+ var parent = this.TABLE.parentNode;
+ if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) {
+ var spreader = document.createElement('DIV');
+ spreader.className = 'wtSpreader';
+ if (parent) {
+ parent.insertBefore(spreader, this.TABLE); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
+ }
+ spreader.appendChild(this.TABLE);
+ }
+ this.spreader = this.TABLE.parentNode;
+
+ //wtHider
+ parent = this.spreader.parentNode;
+ if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) {
+ var hider = document.createElement('DIV');
+ hider.className = 'wtHider';
+ if (parent) {
+ parent.insertBefore(hider, this.spreader); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
+ }
+ hider.appendChild(this.spreader);
+ }
+ this.hider = this.spreader.parentNode;
+ this.hiderStyle = this.hider.style;
+ this.hiderStyle.position = 'relative';
+
+ //wtHolder
+ parent = this.hider.parentNode;
+ if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) {
+ var holder = document.createElement('DIV');
+ holder.style.position = 'relative';
+ holder.className = 'wtHolder';
+ if (parent) {
+ parent.insertBefore(holder, this.hider); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
+ }
+ holder.appendChild(this.hider);
+ }
+ this.parent = this.hider.parentNode;
+
+ //bootstrap from settings
+ this.TBODY = this.TABLE.getElementsByTagName('TBODY')[0];
+ if (!this.TBODY) {
+ this.TBODY = document.createElement('TBODY');
+ this.TABLE.appendChild(this.TBODY);
+ }
+ this.THEAD = this.TABLE.getElementsByTagName('THEAD')[0];
+ if (!this.THEAD) {
+ this.THEAD = document.createElement('THEAD');
+ this.TABLE.insertBefore(this.THEAD, this.TBODY);
+ }
+ this.COLGROUP = this.TABLE.getElementsByTagName('COLGROUP')[0];
+ if (!this.COLGROUP) {
+ this.COLGROUP = document.createElement('COLGROUP');
+ this.TABLE.insertBefore(this.COLGROUP, this.THEAD);
+ }
+
+ if (this.instance.getSetting('columnHeaders').length) {
+ if (!this.THEAD.childNodes.length) {
+ var TR = document.createElement('TR');
+ this.THEAD.appendChild(TR);
+ }
+ }
+
+ this.colgroupChildrenLength = this.COLGROUP.childNodes.length;
+ this.theadChildrenLength = this.THEAD.firstChild ? this.THEAD.firstChild.childNodes.length : 0;
+ this.tbodyChildrenLength = this.TBODY.childNodes.length;
+
+ this.oldCellCache = new WalkontableClassNameCache();
+ this.currentCellCache = new WalkontableClassNameCache();
+
+ this.rowFilter = new WalkontableRowFilter();
+ this.columnFilter = new WalkontableColumnFilter();
+
+ this.verticalRenderReverse = false;
+}
+
+WalkontableTable.prototype.refreshHiderDimensions = function () {
+ var height = this.instance.wtViewport.getWorkspaceHeight();
+ var width = this.instance.wtViewport.getWorkspaceWidth();
+
+ var spreaderStyle = this.spreader.style;
+
+ if (height !== Infinity || width !== Infinity) {
+ if (height === Infinity) {
+ height = this.instance.wtViewport.getWorkspaceActualHeight();
+ }
+ if (width === Infinity) {
+ width = this.instance.wtViewport.getWorkspaceActualWidth();
+ }
+
+ this.hiderStyle.overflow = 'hidden';
+
+ spreaderStyle.position = 'absolute';
+ spreaderStyle.top = '0';
+ spreaderStyle.left = '0';
+
+ if (this.instance.getSetting('scrollbarModelV') === 'dragdealer') {
+ spreaderStyle.height = '4000px';
+ }
+
+ if (this.instance.getSetting('scrollbarModelH') === 'dragdealer') {
+ spreaderStyle.width = '4000px';
+ }
+
+ this.hiderStyle.height = height + 'px';
+ this.hiderStyle.width = width + 'px';
+ }
+ else {
+ spreaderStyle.position = 'relative';
+ spreaderStyle.width = 'auto';
+ spreaderStyle.height = 'auto';
+ }
+};
+
+WalkontableTable.prototype.refreshStretching = function () {
+ var instance = this.instance
+ , stretchH = instance.getSetting('stretchH')
+ , totalRows = instance.getSetting('totalRows')
+ , totalColumns = instance.getSetting('totalColumns')
+ , offsetColumn = instance.getSetting('offsetColumn');
+
+ var containerWidthFn = function (cacheWidth) {
+ return that.instance.wtViewport.getViewportWidth(cacheWidth);
+ };
+
+ var that = this;
+
+ var columnWidthFn = function (i) {
+ var source_c = that.columnFilter.visibleToSource(i);
+ if (source_c < totalColumns) {
+ return instance.getSetting('columnWidth', source_c);
+ }
+ };
+
+ if (stretchH === 'hybrid') {
+ if (offsetColumn > 0) {
+ stretchH = 'last';
+ }
+ else {
+ stretchH = 'none';
+ }
+ }
+
+ var containerHeightFn = function (cacheHeight) {
+ return that.instance.wtViewport.getViewportHeight(cacheHeight);
+ };
+
+ var rowHeightFn = function (i, TD) {
+ var source_r = that.rowFilter.visibleToSource(i);
+ if (source_r < totalRows) {
+ if (that.verticalRenderReverse && i === 0) {
+ return that.wtDom.outerHeight(TD) - 1;
+ }
+ else {
+ return that.wtDom.outerHeight(TD);
+ }
+ }
+ };
+
+ this.columnStrategy = new WalkontableColumnStrategy(containerWidthFn, columnWidthFn, stretchH);
+ this.rowStrategy = new WalkontableRowStrategy(containerHeightFn, rowHeightFn);
+};
+
+WalkontableTable.prototype.adjustAvailableNodes = function () {
+ var displayTds
+ , rowHeaders = this.instance.getSetting('rowHeaders')
+ , displayThs = rowHeaders.length
+ , columnHeaders = this.instance.getSetting('columnHeaders')
+ , TR
+ , TD
+ , c;
+
+ //adjust COLGROUP
+ while (this.colgroupChildrenLength < displayThs) {
+ this.COLGROUP.appendChild(document.createElement('COL'));
+ this.colgroupChildrenLength++;
+ }
+
+ this.refreshStretching();
+ displayTds = this.columnStrategy.cellCount;
+
+ //adjust COLGROUP
+ while (this.colgroupChildrenLength < displayTds + displayThs) {
+ this.COLGROUP.appendChild(document.createElement('COL'));
+ this.colgroupChildrenLength++;
+ }
+ while (this.colgroupChildrenLength > displayTds + displayThs) {
+ this.COLGROUP.removeChild(this.COLGROUP.lastChild);
+ this.colgroupChildrenLength--;
+ }
+
+ //adjust THEAD
+ TR = this.THEAD.firstChild;
+ if (columnHeaders.length) {
+ if (!TR) {
+ TR = document.createElement('TR');
+ this.THEAD.appendChild(TR);
+ }
+
+ this.theadChildrenLength = TR.childNodes.length;
+ while (this.theadChildrenLength < displayTds + displayThs) {
+ TR.appendChild(document.createElement('TH'));
+ this.theadChildrenLength++;
+ }
+ while (this.theadChildrenLength > displayTds + displayThs) {
+ TR.removeChild(TR.lastChild);
+ this.theadChildrenLength--;
+ }
+ }
+ else if (TR) {
+ this.wtDom.empty(TR);
+ }
+
+ //draw COLGROUP
+ for (c = 0; c < this.colgroupChildrenLength; c++) {
+ if (c < displayThs) {
+ this.wtDom.addClass(this.COLGROUP.childNodes[c], 'rowHeader');
+ }
+ else {
+ this.wtDom.removeClass(this.COLGROUP.childNodes[c], 'rowHeader');
+ }
+ }
+
+ //draw THEAD
+ if (columnHeaders.length) {
+ TR = this.THEAD.firstChild;
+ if (displayThs) {
+ TD = TR.firstChild; //actually it is TH but let's reuse single variable
+ for (c = 0; c < displayThs; c++) {
+ rowHeaders[c](-displayThs + c, TD);
+ TD = TD.nextSibling;
+ }
+ }
+ }
+
+ for (c = 0; c < displayTds; c++) {
+ if (columnHeaders.length) {
+ columnHeaders[0](this.columnFilter.visibleToSource(c), TR.childNodes[displayThs + c]);
+ }
+ }
+};
+
+WalkontableTable.prototype.adjustColumns = function (TR, desiredCount) {
+ var count = TR.childNodes.length;
+ while (count < desiredCount) {
+ var TD = document.createElement('TD');
+ TR.appendChild(TD);
+ count++;
+ }
+ while (count > desiredCount) {
+ TR.removeChild(TR.lastChild);
+ count--;
+ }
+};
+
+WalkontableTable.prototype.draw = function (selectionsOnly) {
+ this.rowFilter.readSettings(this.instance);
+ this.columnFilter.readSettings(this.instance);
+
+ if (!selectionsOnly) {
+ this.tableOffset = this.wtDom.offset(this.TABLE);
+ this._doDraw();
+ }
+ else {
+ this.instance.wtScrollbars.refresh();
+ }
+
+ this.refreshPositions(selectionsOnly);
+
+ this.instance.drawn = true;
+ return this;
+};
+
+WalkontableTable.prototype._doDraw = function () {
+ var r = 0
+ , source_r
+ , c
+ , source_c
+ , offsetRow = this.instance.getSetting('offsetRow')
+ , totalRows = this.instance.getSetting('totalRows')
+ , totalColumns = this.instance.getSetting('totalColumns')
+ , displayTds
+ , rowHeaders = this.instance.getSetting('rowHeaders')
+ , displayThs = rowHeaders.length
+ , TR
+ , TD
+ , TH
+ , adjusted = false
+ , workspaceWidth;
+
+ this.instance.wtViewport.resetSettings();
+
+ var noPartial = false;
+ if (this.verticalRenderReverse) {
+ if (offsetRow === totalRows - this.rowFilter.fixedCount - 1) {
+ noPartial = true;
+ }
+ else {
+ this.instance.update('offsetRow', offsetRow + 1); //if we are scrolling reverse
+ this.rowFilter.readSettings(this.instance);
+ }
+ }
+
+ //draw TBODY
+ if (totalColumns > 0) {
+ source_r = this.rowFilter.visibleToSource(r);
+
+ var first = true;
+
+ while (source_r < totalRows && source_r >= 0) {
+ if (r >= this.tbodyChildrenLength || (this.verticalRenderReverse && r >= this.rowFilter.fixedCount)) {
+ TR = document.createElement('TR');
+ for (c = 0; c < displayThs; c++) {
+ TR.appendChild(document.createElement('TH'));
+ }
+ if (this.verticalRenderReverse && r >= this.rowFilter.fixedCount) {
+ this.TBODY.insertBefore(TR, this.TBODY.childNodes[this.rowFilter.fixedCount] || this.TBODY.firstChild);
+ }
+ else {
+ this.TBODY.appendChild(TR);
+ }
+ this.tbodyChildrenLength++;
+ }
+ else if (r === 0) {
+ TR = this.TBODY.firstChild;
+ }
+ else {
+ TR = TR.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
+ }
+
+ //TH
+ TH = TR.firstChild;
+ for (c = 0; c < displayThs; c++) {
+
+ //If the number of row headers increased we need to replace TD with TH
+ if (TH.nodeName == 'TD') {
+ TD = TH;
+ TH = document.createElement('TH');
+ TR.insertBefore(TH, TD);
+ TR.removeChild(TD);
+ }
+
+ rowHeaders[c](source_r, TH); //actually TH
+ TH = TH.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
+ }
+
+ if (first) {
+// if (r === 0) {
+ first = false;
+
+ this.adjustAvailableNodes();
+ adjusted = true;
+ displayTds = this.columnStrategy.cellCount;
+
+ //TD
+ this.adjustColumns(TR, displayTds + displayThs);
+
+ workspaceWidth = this.instance.wtViewport.getWorkspaceWidth();
+ this.columnStrategy.stretch();
+ for (c = 0; c < displayTds; c++) {
+ this.COLGROUP.childNodes[c + displayThs].style.width = this.columnStrategy.getSize(c) + 'px';
+ }
+ }
+ else {
+ //TD
+ this.adjustColumns(TR, displayTds + displayThs);
+ }
+
+ for (c = 0; c < displayTds; c++) {
+ source_c = this.columnFilter.visibleToSource(c);
+ if (c === 0) {
+ TD = TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(source_c)];
+ }
+ else {
+ TD = TD.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
+ }
+
+ //If the number of headers has been reduced, we need to replace excess TH with TD
+ if (TD.nodeName == 'TH') {
+ TH = TD;
+ TD = document.createElement('TD');
+ TR.insertBefore(TD, TH);
+ TR.removeChild(TH);
+ }
+
+ TD.className = '';
+ TD.removeAttribute('style');
+ this.instance.getSetting('cellRenderer', source_r, source_c, TD);
+ }
+
+ offsetRow = this.instance.getSetting('offsetRow'); //refresh the value
+
+ //after last column is rendered, check if last cell is fully displayed
+ if (this.verticalRenderReverse && noPartial) {
+ if (-this.wtDom.outerHeight(TR.firstChild) < this.rowStrategy.remainingSize) {
+ this.TBODY.removeChild(TR);
+ this.instance.update('offsetRow', offsetRow + 1);
+ this.tbodyChildrenLength--;
+ this.rowFilter.readSettings(this.instance);
+ break;
+
+ }
+ else {
+ this.rowStrategy.add(r, TD);
+ }
+ }
+ else {
+ this.rowStrategy.add(r, TD);
+
+ if (this.rowStrategy.isLastIncomplete()) {
+ break;
+ }
+ }
+
+ if (this.verticalRenderReverse && r >= this.rowFilter.fixedCount) {
+ if (offsetRow === 0) {
+ break;
+ }
+ this.instance.update('offsetRow', offsetRow - 1);
+ this.rowFilter.readSettings(this.instance);
+ }
+ else {
+ r++;
+ }
+
+ source_r = this.rowFilter.visibleToSource(r);
+ }
+ }
+
+ if (!adjusted) {
+ this.adjustAvailableNodes();
+ }
+
+ r = this.rowStrategy.countVisible();
+ while (this.tbodyChildrenLength > r) {
+ this.TBODY.removeChild(this.TBODY.lastChild);
+ this.tbodyChildrenLength--;
+ }
+
+ this.instance.wtScrollbars.refresh();
+
+ if (workspaceWidth !== this.instance.wtViewport.getWorkspaceWidth()) {
+ //workspace width changed though to shown/hidden vertical scrollbar. Let's reapply stretching
+ this.columnStrategy.stretch();
+ for (c = 0; c < this.columnStrategy.cellCount; c++) {
+ this.COLGROUP.childNodes[c + displayThs].style.width = this.columnStrategy.getSize(c) + 'px';
+ }
+ }
+
+ this.verticalRenderReverse = false;
+};
+
+WalkontableTable.prototype.refreshPositions = function (selectionsOnly) {
+ this.refreshHiderDimensions();
+ this.refreshSelections(selectionsOnly);
+};
+
+WalkontableTable.prototype.refreshSelections = function (selectionsOnly) {
+ var vr
+ , r
+ , vc
+ , c
+ , s
+ , slen
+ , classNames = []
+ , visibleRows = this.rowStrategy.countVisible()
+ , visibleColumns = this.columnStrategy.countVisible();
+
+ this.oldCellCache = this.currentCellCache;
+ this.currentCellCache = new WalkontableClassNameCache();
+
+ if (this.instance.selections) {
+ for (r in this.instance.selections) {
+ if (this.instance.selections.hasOwnProperty(r)) {
+ this.instance.selections[r].draw();
+ if (this.instance.selections[r].settings.className) {
+ classNames.push(this.instance.selections[r].settings.className);
+ }
+ if (this.instance.selections[r].settings.highlightRowClassName) {
+ classNames.push(this.instance.selections[r].settings.highlightRowClassName);
+ }
+ if (this.instance.selections[r].settings.highlightColumnClassName) {
+ classNames.push(this.instance.selections[r].settings.highlightColumnClassName);
+ }
+ }
+ }
+ }
+
+ slen = classNames.length;
+
+ for (vr = 0; vr < visibleRows; vr++) {
+ for (vc = 0; vc < visibleColumns; vc++) {
+ r = this.rowFilter.visibleToSource(vr);
+ c = this.columnFilter.visibleToSource(vc);
+ for (s = 0; s < slen; s++) {
+ if (this.currentCellCache.test(vr, vc, classNames[s])) {
+ this.wtDom.addClass(this.getCell([r, c]), classNames[s]);
+ }
+ else if (selectionsOnly && this.oldCellCache.test(vr, vc, classNames[s])) {
+ this.wtDom.removeClass(this.getCell([r, c]), classNames[s]);
+ }
+ }
+ }
+ }
+};
+
+/* this function is not used currently (was used in _doDraw)
+ WalkontableTable.prototype.isCellVisible = function (r, c) {
+ var out = 0;
+
+ if (this.isRowInViewport(r)) {
+ if (this.getLastVisibleRow() === c && this.rowStrategy.remainingSize > 0) {
+ out |= FLAG_PARTIALLY_VISIBLE_VERTICAL;
+ }
+ else {
+ out |= FLAG_VISIBLE_VERTICAL;
+ }
+ }
+ else {
+ out |= FLAG_NOT_VISIBLE_VERTICAL;
+ }
+
+ if (this.isColumnInViewport(c)) {
+ if (this.getLastVisibleColumn() === c && this.columnStrategy.remainingSize > 0) {
+ out |= FLAG_PARTIALLY_VISIBLE_HORIZONTAL;
+ }
+ else {
+ out |= FLAG_VISIBLE_HORIZONTAL;
+ }
+ }
+ else {
+ out |= FLAG_NOT_VISIBLE_HORIZONTAL;
+ }
+
+ return out;
+ };*/
+
+/**
+ * getCell
+ * @param {Array} coords
+ * @return {Object} HTMLElement on success or {Number} one of the exit codes on error:
+ * -1 row before viewport
+ * -2 row after viewport
+ * -3 column before viewport
+ * -4 column after viewport
+ *
+ */
+WalkontableTable.prototype.getCell = function (coords) {
+ if (this.isRowBeforeViewport(coords[0])) {
+ return -1; //row before viewport
+ }
+ else if (this.isRowAfterViewport(coords[0])) {
+ return -2; //row after viewport
+ }
+ else {
+ if (this.isColumnBeforeViewport(coords[1])) {
+ return -3; //column before viewport
+ }
+ else if (this.isColumnAfterViewport(coords[1])) {
+ return -4; //column after viewport
+ }
+ else {
+ return this.TBODY.childNodes[this.rowFilter.sourceToVisible(coords[0])].childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(coords[1])];
+ }
+ }
+};
+
+WalkontableTable.prototype.getCoords = function (TD) {
+ return [
+ this.rowFilter.visibleToSource(this.wtDom.prevSiblings(TD.parentNode).length),
+ this.columnFilter.visibleRowHeadedColumnToSourceColumn(TD.cellIndex)
+ ];
+};
+
+//returns -1 if no row is visible
+WalkontableTable.prototype.getLastVisibleRow = function () {
+ return this.rowFilter.visibleToSource(this.rowStrategy.cellCount - 1);
+};
+
+//returns -1 if no column is visible
+WalkontableTable.prototype.getLastVisibleColumn = function () {
+ return this.columnFilter.visibleToSource(this.columnStrategy.cellCount - 1);
+};
+
+WalkontableTable.prototype.isRowBeforeViewport = function (r) {
+ return (this.rowFilter.sourceToVisible(r) < this.rowFilter.fixedCount && r >= this.rowFilter.fixedCount);
+};
+
+WalkontableTable.prototype.isRowAfterViewport = function (r) {
+ return (r > this.getLastVisibleRow());
+};
+
+WalkontableTable.prototype.isColumnBeforeViewport = function (c) {
+ return (this.columnFilter.sourceToVisible(c) < this.columnFilter.fixedCount && c >= this.columnFilter.fixedCount);
+};
+
+WalkontableTable.prototype.isColumnAfterViewport = function (c) {
+ return (c > this.getLastVisibleColumn());
+};
+
+WalkontableTable.prototype.isRowInViewport = function (r) {
+ return (!this.isRowBeforeViewport(r) && !this.isRowAfterViewport(r));
+};
+
+WalkontableTable.prototype.isColumnInViewport = function (c) {
+ return (!this.isColumnBeforeViewport(c) && !this.isColumnAfterViewport(c));
+};
+
+WalkontableTable.prototype.isLastRowFullyVisible = function () {
+ return (this.getLastVisibleRow() === this.instance.getSetting('totalRows') - 1 && !this.rowStrategy.isLastIncomplete());
+};
+
+WalkontableTable.prototype.isLastColumnFullyVisible = function () {
+ return (this.getLastVisibleColumn() === this.instance.getSetting('totalColumns') - 1 && !this.columnStrategy.isLastIncomplete());
+};
+
+function WalkontableViewport(instance) {
+ this.instance = instance;
+ this.resetSettings();
+}
+
+/*WalkontableViewport.prototype.isInSightVertical = function () {
+ //is table outside viewport bottom edge
+ if (tableTop > windowHeight + scrollTop) {
+ return -1;
+ }
+
+ //is table outside viewport top edge
+ else if (scrollTop > tableTop + tableFakeHeight) {
+ return -2;
+ }
+
+ //table is in viewport but how much exactly?
+ else {
+
+ }
+};*/
+
+//used by scrollbar
+WalkontableViewport.prototype.getWorkspaceHeight = function (proposedHeight) {
+ var height = this.instance.getSetting('height');
+
+ if (height === Infinity || height === void 0 || height === null || height < 1) {
+ if (this.instance.wtScrollbars.vertical instanceof WalkontableScrollbarNative) {
+ height = this.instance.wtScrollbars.vertical.availableSize();
+ }
+ else {
+ height = Infinity;
+ }
+ }
+
+ if (height !== Infinity) {
+ if (proposedHeight >= height) {
+ height -= this.instance.getSetting('scrollbarHeight');
+ }
+ else if (this.instance.wtScrollbars.horizontal.visible) {
+ height -= this.instance.getSetting('scrollbarHeight');
+ }
+ }
+
+ return height;
+};
+
+WalkontableViewport.prototype.getWorkspaceWidth = function (proposedWidth) {
+ var width = this.instance.getSetting('width');
+
+ if (width === Infinity || width === void 0 || width === null || width < 1) {
+ if (this.instance.wtScrollbars.horizontal instanceof WalkontableScrollbarNative) {
+ width = this.instance.wtScrollbars.horizontal.availableSize();
+ }
+ else {
+ width = Infinity;
+ }
+ }
+
+ if (width !== Infinity) {
+ if (proposedWidth >= width) {
+ width -= this.instance.getSetting('scrollbarWidth');
+ }
+ else if (this.instance.wtScrollbars.vertical.visible) {
+ width -= this.instance.getSetting('scrollbarWidth');
+ }
+ }
+ return width;
+};
+
+WalkontableViewport.prototype.getWorkspaceActualHeight = function () {
+ return this.instance.wtDom.outerHeight(this.instance.wtTable.TABLE);
+};
+
+WalkontableViewport.prototype.getWorkspaceActualWidth = function () {
+ return this.instance.wtDom.outerWidth(this.instance.wtTable.TABLE) || this.instance.wtDom.outerWidth(this.instance.wtTable.TBODY) || this.instance.wtDom.outerWidth(this.instance.wtTable.THEAD); //IE8 reports 0 as
offsetWidth;
+};
+
+WalkontableViewport.prototype.getViewportHeight = function (proposedHeight) {
+ var containerHeight = this.getWorkspaceHeight(proposedHeight);
+
+ if (containerHeight === Infinity) {
+ return containerHeight;
+ }
+
+ if (isNaN(this.columnHeaderHeight)) {
+ var cellOffset = this.instance.wtDom.offset(this.instance.wtTable.TBODY)
+ , tableOffset = this.instance.wtTable.tableOffset;
+ this.columnHeaderHeight = cellOffset.top - tableOffset.top;
+ }
+
+ if (this.columnHeaderHeight > 0) {
+ return containerHeight - this.columnHeaderHeight;
+ }
+ else {
+ return containerHeight;
+ }
+};
+
+WalkontableViewport.prototype.getViewportWidth = function (proposedWidth) {
+ var containerWidth = this.getWorkspaceWidth(proposedWidth);
+
+ if (containerWidth === Infinity) {
+ return containerWidth;
+ }
+
+ if (isNaN(this.rowHeaderWidth)) {
+ var TR = this.instance.wtTable.TBODY ? this.instance.wtTable.TBODY.firstChild : null;
+ if (TR) {
+ var TD = TR.firstChild;
+ this.rowHeaderWidth = 0;
+ while (TD && TD.nodeName === 'TH') {
+ this.rowHeaderWidth += this.instance.wtDom.outerWidth(TD);
+ TD = TD.nextSibling;
+ }
+ }
+ }
+
+ if (this.rowHeaderWidth > 0) {
+ return containerWidth - this.rowHeaderWidth;
+ }
+ else {
+ return containerWidth;
+ }
+};
+
+WalkontableViewport.prototype.resetSettings = function () {
+ this.rowHeaderWidth = NaN;
+ this.columnHeaderHeight = NaN;
+};
+function WalkontableWheel(instance) {
+ if (instance.getSetting('scrollbarModelV') === 'native' || instance.getSetting('scrollbarModelH') === 'native') {
+ return;
+ }
+
+ $(instance.wtTable.TABLE).on('mousewheel', function (event, delta, deltaX, deltaY) {
+ if (!deltaX && !deltaY && delta) { //we are in IE8, see https://github.com/brandonaaron/jquery-mousewheel/issues/53
+ deltaY = delta;
+ }
+
+ if (deltaY > 0 && instance.getSetting('offsetRow') === 0) {
+ return; //attempt to scroll up when it's already showing first row
+ }
+ else if (deltaY < 0 && instance.wtTable.isLastRowFullyVisible()) {
+ return; //attempt to scroll down when it's already showing last row
+ }
+ else if (deltaX < 0 && instance.getSetting('offsetColumn') === 0) {
+ return; //attempt to scroll left when it's already showing first column
+ }
+ else if (deltaX > 0 && instance.wtTable.isLastColumnFullyVisible()) {
+ return; //attempt to scroll right when it's already showing last column
+ }
+
+ //now we are sure we really want to scroll
+ clearTimeout(instance.wheelTimeout);
+ instance.wheelTimeout = setTimeout(function () { //timeout is needed because with fast-wheel scrolling mousewheel event comes dozen times per second
+ if (deltaY) {
+ //ceil is needed because jquery-mousewheel reports fractional mousewheel deltas on touchpad scroll
+ //see http://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers
+ if (instance.wtScrollbars.vertical.visible) { // if we see scrollbar
+ instance.scrollVertical(-Math.ceil(deltaY)).draw();
+ }
+ }
+ else if (deltaX) {
+ if (instance.wtScrollbars.horizontal.visible) { // if we see scrollbar
+ instance.scrollHorizontal(Math.ceil(deltaX)).draw();
+ }
+ }
+ }, 0);
+
+ event.preventDefault();
+ });
+}
+/**
+ * Dragdealer JS v0.9.5 - patched by Walkontable at lines 66, 309-310, 339-340
+ * http://code.ovidiu.ch/dragdealer-js
+ *
+ * Copyright (c) 2010, Ovidiu Chereches
+ * MIT License
+ * http://legal.ovidiu.ch/licenses/MIT
+ */
+
+/* Cursor */
+
+var Cursor =
+{
+ x: 0, y: 0,
+ init: function()
+ {
+ this.setEvent('mouse');
+ this.setEvent('touch');
+ },
+ setEvent: function(type)
+ {
+ var moveHandler = document['on' + type + 'move'] || function(){};
+ document['on' + type + 'move'] = function(e)
+ {
+ moveHandler(e);
+ Cursor.refresh(e);
+ }
+ },
+ refresh: function(e)
+ {
+ if(!e)
+ {
+ e = window.event;
+ }
+ if(e.type == 'mousemove')
+ {
+ this.set(e);
+ }
+ else if(e.touches)
+ {
+ this.set(e.touches[0]);
+ }
+ },
+ set: function(e)
+ {
+ if(e.pageX || e.pageY)
+ {
+ this.x = e.pageX;
+ this.y = e.pageY;
+ }
+ else if(e.clientX || e.clientY)
+ {
+ this.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
+ this.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
+ }
+ }
+};
+Cursor.init();
+
+/* Position */
+
+var Position =
+{
+ get: function(obj)
+ {
+ var curtop = 0, curleft = 0; //Walkontable patch. Original (var curleft = curtop = 0;) created curtop in global scope
+ if(obj.offsetParent)
+ {
+ do
+ {
+ curleft += obj.offsetLeft;
+ curtop += obj.offsetTop;
+ }
+ while((obj = obj.offsetParent));
+ }
+ return [curleft, curtop];
+ }
+};
+
+/* Dragdealer */
+
+var Dragdealer = function(wrapper, options)
+{
+ if(typeof(wrapper) == 'string')
+ {
+ wrapper = document.getElementById(wrapper);
+ }
+ if(!wrapper)
+ {
+ return;
+ }
+ var handle = wrapper.getElementsByTagName('div')[0];
+ if(!handle || handle.className.search(/(^|\s)handle(\s|$)/) == -1)
+ {
+ return;
+ }
+ this.init(wrapper, handle, options || {});
+ this.setup();
+};
+Dragdealer.prototype =
+{
+ init: function(wrapper, handle, options)
+ {
+ this.wrapper = wrapper;
+ this.handle = handle;
+ this.options = options;
+
+ this.disabled = this.getOption('disabled', false);
+ this.horizontal = this.getOption('horizontal', true);
+ this.vertical = this.getOption('vertical', false);
+ this.slide = this.getOption('slide', true);
+ this.steps = this.getOption('steps', 0);
+ this.snap = this.getOption('snap', false);
+ this.loose = this.getOption('loose', false);
+ this.speed = this.getOption('speed', 10) / 100;
+ this.xPrecision = this.getOption('xPrecision', 0);
+ this.yPrecision = this.getOption('yPrecision', 0);
+
+ this.callback = options.callback || null;
+ this.animationCallback = options.animationCallback || null;
+
+ this.bounds = {
+ left: options.left || 0, right: -(options.right || 0),
+ top: options.top || 0, bottom: -(options.bottom || 0),
+ x0: 0, x1: 0, xRange: 0,
+ y0: 0, y1: 0, yRange: 0
+ };
+ this.value = {
+ prev: [-1, -1],
+ current: [options.x || 0, options.y || 0],
+ target: [options.x || 0, options.y || 0]
+ };
+ this.offset = {
+ wrapper: [0, 0],
+ mouse: [0, 0],
+ prev: [-999999, -999999],
+ current: [0, 0],
+ target: [0, 0]
+ };
+ this.change = [0, 0];
+
+ this.activity = false;
+ this.dragging = false;
+ this.tapping = false;
+ },
+ getOption: function(name, defaultValue)
+ {
+ return this.options[name] !== undefined ? this.options[name] : defaultValue;
+ },
+ setup: function()
+ {
+ this.setWrapperOffset();
+ this.setBoundsPadding();
+ this.setBounds();
+ this.setSteps();
+
+ this.addListeners();
+ },
+ setWrapperOffset: function()
+ {
+ this.offset.wrapper = Position.get(this.wrapper);
+ },
+ setBoundsPadding: function()
+ {
+ if(!this.bounds.left && !this.bounds.right)
+ {
+ this.bounds.left = Position.get(this.handle)[0] - this.offset.wrapper[0];
+ this.bounds.right = -this.bounds.left;
+ }
+ if(!this.bounds.top && !this.bounds.bottom)
+ {
+ this.bounds.top = Position.get(this.handle)[1] - this.offset.wrapper[1];
+ this.bounds.bottom = -this.bounds.top;
+ }
+ },
+ setBounds: function()
+ {
+ this.bounds.x0 = this.bounds.left;
+ this.bounds.x1 = this.wrapper.offsetWidth + this.bounds.right;
+ this.bounds.xRange = (this.bounds.x1 - this.bounds.x0) - this.handle.offsetWidth;
+
+ this.bounds.y0 = this.bounds.top;
+ this.bounds.y1 = this.wrapper.offsetHeight + this.bounds.bottom;
+ this.bounds.yRange = (this.bounds.y1 - this.bounds.y0) - this.handle.offsetHeight;
+
+ this.bounds.xStep = 1 / (this.xPrecision || Math.max(this.wrapper.offsetWidth, this.handle.offsetWidth));
+ this.bounds.yStep = 1 / (this.yPrecision || Math.max(this.wrapper.offsetHeight, this.handle.offsetHeight));
+ },
+ setSteps: function()
+ {
+ if(this.steps > 1)
+ {
+ this.stepRatios = [];
+ for(var i = 0; i <= this.steps - 1; i++)
+ {
+ this.stepRatios[i] = i / (this.steps - 1);
+ }
+ }
+ },
+ addListeners: function()
+ {
+ var self = this;
+
+ this.wrapper.onselectstart = function()
+ {
+ return false;
+ }
+ this.handle.onmousedown = this.handle.ontouchstart = function(e)
+ {
+ self.handleDownHandler(e);
+ };
+ this.wrapper.onmousedown = this.wrapper.ontouchstart = function(e)
+ {
+ self.wrapperDownHandler(e);
+ };
+ var mouseUpHandler = document.onmouseup || function(){};
+ document.onmouseup = function(e)
+ {
+ mouseUpHandler(e);
+ self.documentUpHandler(e);
+ };
+ var touchEndHandler = document.ontouchend || function(){};
+ document.ontouchend = function(e)
+ {
+ touchEndHandler(e);
+ self.documentUpHandler(e);
+ };
+ var resizeHandler = window.onresize || function(){};
+ window.onresize = function(e)
+ {
+ resizeHandler(e);
+ self.documentResizeHandler(e);
+ };
+ this.wrapper.onmousemove = function(e)
+ {
+ self.activity = true;
+ }
+ this.wrapper.onclick = function(e)
+ {
+ return !self.activity;
+ }
+
+ this.interval = setInterval(function(){ self.animate() }, 25);
+ self.animate(false, true);
+ },
+ handleDownHandler: function(e)
+ {
+ this.activity = false;
+ Cursor.refresh(e);
+
+ this.preventDefaults(e, true);
+ this.startDrag();
+ this.cancelEvent(e);
+ },
+ wrapperDownHandler: function(e)
+ {
+ Cursor.refresh(e);
+
+ this.preventDefaults(e, true);
+ this.startTap();
+ },
+ documentUpHandler: function(e)
+ {
+ this.stopDrag();
+ this.stopTap();
+ //this.cancelEvent(e);
+ },
+ documentResizeHandler: function(e)
+ {
+ this.setWrapperOffset();
+ this.setBounds();
+
+ this.update();
+ },
+ enable: function()
+ {
+ this.disabled = false;
+ this.handle.className = this.handle.className.replace(/\s?disabled/g, '');
+ },
+ disable: function()
+ {
+ this.disabled = true;
+ this.handle.className += ' disabled';
+ },
+ setStep: function(x, y, snap)
+ {
+ this.setValue(
+ this.steps && x > 1 ? (x - 1) / (this.steps - 1) : 0,
+ this.steps && y > 1 ? (y - 1) / (this.steps - 1) : 0,
+ snap
+ );
+ },
+ setValue: function(x, y, snap)
+ {
+ this.setTargetValue([x, y || 0]);
+ if(snap)
+ {
+ this.groupCopy(this.value.current, this.value.target);
+ }
+ },
+ startTap: function(target)
+ {
+ if(this.disabled)
+ {
+ return;
+ }
+ this.tapping = true;
+
+ this.setWrapperOffset();
+ this.setBounds();
+
+ if(target === undefined)
+ {
+ target = [
+ Cursor.x - this.offset.wrapper[0] - (this.handle.offsetWidth / 2),
+ Cursor.y - this.offset.wrapper[1] - (this.handle.offsetHeight / 2)
+ ];
+ }
+ this.setTargetOffset(target);
+ },
+ stopTap: function()
+ {
+ if(this.disabled || !this.tapping)
+ {
+ return;
+ }
+ this.tapping = false;
+
+ this.setTargetValue(this.value.current);
+ this.result();
+ },
+ startDrag: function()
+ {
+ if(this.disabled)
+ {
+ return;
+ }
+
+ this.setWrapperOffset();
+ this.setBounds();
+
+ this.offset.mouse = [
+ Cursor.x - Position.get(this.handle)[0],
+ Cursor.y - Position.get(this.handle)[1]
+ ];
+
+ this.dragging = true;
+ },
+ stopDrag: function()
+ {
+ if(this.disabled || !this.dragging)
+ {
+ return;
+ }
+ this.dragging = false;
+
+ var target = this.groupClone(this.value.current);
+ if(this.slide)
+ {
+ var ratioChange = this.change;
+ target[0] += ratioChange[0] * 4;
+ target[1] += ratioChange[1] * 4;
+ }
+ this.setTargetValue(target);
+ this.result();
+ },
+ feedback: function()
+ {
+ var value = this.value.current;
+ if(this.snap && this.steps > 1)
+ {
+ value = this.getClosestSteps(value);
+ }
+ if(!this.groupCompare(value, this.value.prev))
+ {
+ if(typeof(this.animationCallback) == 'function')
+ {
+ this.animationCallback(value[0], value[1]);
+ }
+ this.groupCopy(this.value.prev, value);
+ }
+ },
+ result: function()
+ {
+ if(typeof(this.callback) == 'function')
+ {
+ this.callback(this.value.target[0], this.value.target[1]);
+ }
+ },
+ animate: function(direct, first)
+ {
+ if(direct && !this.dragging)
+ {
+ return;
+ }
+ if(this.dragging)
+ {
+ var prevTarget = this.groupClone(this.value.target);
+
+ var offset = [
+ Cursor.x - this.offset.wrapper[0] - this.offset.mouse[0],
+ Cursor.y - this.offset.wrapper[1] - this.offset.mouse[1]
+ ];
+ this.setTargetOffset(offset, this.loose);
+
+ this.change = [
+ this.value.target[0] - prevTarget[0],
+ this.value.target[1] - prevTarget[1]
+ ];
+ }
+ if(this.dragging || first)
+ {
+ this.groupCopy(this.value.current, this.value.target);
+ }
+ if(this.dragging || this.glide() || first)
+ {
+ this.update();
+ this.feedback();
+ }
+ },
+ glide: function()
+ {
+ var diff = [
+ this.value.target[0] - this.value.current[0],
+ this.value.target[1] - this.value.current[1]
+ ];
+ if(!diff[0] && !diff[1])
+ {
+ return false;
+ }
+ if(Math.abs(diff[0]) > this.bounds.xStep || Math.abs(diff[1]) > this.bounds.yStep)
+ {
+ this.value.current[0] += diff[0] * this.speed;
+ this.value.current[1] += diff[1] * this.speed;
+ }
+ else
+ {
+ this.groupCopy(this.value.current, this.value.target);
+ }
+ return true;
+ },
+ update: function()
+ {
+ if(!this.snap)
+ {
+ this.offset.current = this.getOffsetsByRatios(this.value.current);
+ }
+ else
+ {
+ this.offset.current = this.getOffsetsByRatios(
+ this.getClosestSteps(this.value.current)
+ );
+ }
+ this.show();
+ },
+ show: function()
+ {
+ if(!this.groupCompare(this.offset.current, this.offset.prev))
+ {
+ if(this.horizontal)
+ {
+ this.handle.style.left = String(this.offset.current[0]) + 'px';
+ }
+ if(this.vertical)
+ {
+ this.handle.style.top = String(this.offset.current[1]) + 'px';
+ }
+ this.groupCopy(this.offset.prev, this.offset.current);
+ }
+ },
+ setTargetValue: function(value, loose)
+ {
+ var target = loose ? this.getLooseValue(value) : this.getProperValue(value);
+
+ this.groupCopy(this.value.target, target);
+ this.offset.target = this.getOffsetsByRatios(target);
+ },
+ setTargetOffset: function(offset, loose)
+ {
+ var value = this.getRatiosByOffsets(offset);
+ var target = loose ? this.getLooseValue(value) : this.getProperValue(value);
+
+ this.groupCopy(this.value.target, target);
+ this.offset.target = this.getOffsetsByRatios(target);
+ },
+ getLooseValue: function(value)
+ {
+ var proper = this.getProperValue(value);
+ return [
+ proper[0] + ((value[0] - proper[0]) / 4),
+ proper[1] + ((value[1] - proper[1]) / 4)
+ ];
+ },
+ getProperValue: function(value)
+ {
+ var proper = this.groupClone(value);
+
+ proper[0] = Math.max(proper[0], 0);
+ proper[1] = Math.max(proper[1], 0);
+ proper[0] = Math.min(proper[0], 1);
+ proper[1] = Math.min(proper[1], 1);
+
+ if((!this.dragging && !this.tapping) || this.snap)
+ {
+ if(this.steps > 1)
+ {
+ proper = this.getClosestSteps(proper);
+ }
+ }
+ return proper;
+ },
+ getRatiosByOffsets: function(group)
+ {
+ return [
+ this.getRatioByOffset(group[0], this.bounds.xRange, this.bounds.x0),
+ this.getRatioByOffset(group[1], this.bounds.yRange, this.bounds.y0)
+ ];
+ },
+ getRatioByOffset: function(offset, range, padding)
+ {
+ return range ? (offset - padding) / range : 0;
+ },
+ getOffsetsByRatios: function(group)
+ {
+ return [
+ this.getOffsetByRatio(group[0], this.bounds.xRange, this.bounds.x0),
+ this.getOffsetByRatio(group[1], this.bounds.yRange, this.bounds.y0)
+ ];
+ },
+ getOffsetByRatio: function(ratio, range, padding)
+ {
+ return Math.round(ratio * range) + padding;
+ },
+ getClosestSteps: function(group)
+ {
+ return [
+ this.getClosestStep(group[0]),
+ this.getClosestStep(group[1])
+ ];
+ },
+ getClosestStep: function(value)
+ {
+ var k = 0;
+ var min = 1;
+ for(var i = 0; i <= this.steps - 1; i++)
+ {
+ if(Math.abs(this.stepRatios[i] - value) < min)
+ {
+ min = Math.abs(this.stepRatios[i] - value);
+ k = i;
+ }
+ }
+ return this.stepRatios[k];
+ },
+ groupCompare: function(a, b)
+ {
+ return a[0] == b[0] && a[1] == b[1];
+ },
+ groupCopy: function(a, b)
+ {
+ a[0] = b[0];
+ a[1] = b[1];
+ },
+ groupClone: function(a)
+ {
+ return [a[0], a[1]];
+ },
+ preventDefaults: function(e, selection)
+ {
+ if(!e)
+ {
+ e = window.event;
+ }
+ if(e.preventDefault)
+ {
+ e.preventDefault();
+ }
+ e.returnValue = false;
+
+ if(selection && document.selection)
+ {
+ document.selection.empty();
+ }
+ },
+ cancelEvent: function(e)
+ {
+ if(!e)
+ {
+ e = window.event;
+ }
+ if(e.stopPropagation)
+ {
+ e.stopPropagation();
+ }
+ e.cancelBubble = true;
+ }
+};
+
+/**
+ * jQuery.browser shim that makes Walkontable working with jQuery 1.9+
+ */
+if (!jQuery.browser) {
+ (function () {
+ var matched, browser;
+
+ /*
+ * Copyright 2011, John Resig
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ */
+ jQuery.uaMatch = function (ua) {
+ ua = ua.toLowerCase();
+
+ var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
+ /(webkit)[ \/]([\w.]+)/.exec(ua) ||
+ /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
+ /(msie) ([\w.]+)/.exec(ua) ||
+ ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
+ [];
+
+ return {
+ browser: match[ 1 ] || "",
+ version: match[ 2 ] || "0"
+ };
+ };
+
+ matched = jQuery.uaMatch(navigator.userAgent);
+ browser = {};
+
+ if (matched.browser) {
+ browser[ matched.browser ] = true;
+ browser.version = matched.version;
+ }
+
+ // Chrome is Webkit, but Webkit is also Safari.
+ if (browser.chrome) {
+ browser.webkit = true;
+ }
+ else if (browser.webkit) {
+ browser.safari = true;
+ }
+
+ jQuery.browser = browser;
+
+ })();
+}
+/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
+ * Licensed under the MIT License (LICENSE.txt).
+ *
+ * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
+ * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
+ * Thanks to: Seamus Leahy for adding deltaX and deltaY
+ *
+ * Version: 3.1.3
+ *
+ * Requires: 1.2.2+
+ */
+
+(function (factory) {
+ if ( typeof define === 'function' && define.amd ) {
+ // AMD. Register as an anonymous module.
+ define(['jquery'], factory);
+ } else if (typeof exports === 'object') {
+ // Node/CommonJS style for Browserify
+ module.exports = factory;
+ } else {
+ // Browser globals
+ factory(jQuery);
+ }
+}(function ($) {
+
+ var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'];
+ var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
+ var lowestDelta, lowestDeltaXY;
+
+ if ( $.event.fixHooks ) {
+ for ( var i = toFix.length; i; ) {
+ $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
+ }
+ }
+
+ $.event.special.mousewheel = {
+ setup: function() {
+ if ( this.addEventListener ) {
+ for ( var i = toBind.length; i; ) {
+ this.addEventListener( toBind[--i], handler, false );
+ }
+ } else {
+ this.onmousewheel = handler;
+ }
+ },
+
+ teardown: function() {
+ if ( this.removeEventListener ) {
+ for ( var i = toBind.length; i; ) {
+ this.removeEventListener( toBind[--i], handler, false );
+ }
+ } else {
+ this.onmousewheel = null;
+ }
+ }
+ };
+
+ $.fn.extend({
+ mousewheel: function(fn) {
+ return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
+ },
+
+ unmousewheel: function(fn) {
+ return this.unbind("mousewheel", fn);
+ }
+ });
+
+
+ function handler(event) {
+ var orgEvent = event || window.event,
+ args = [].slice.call(arguments, 1),
+ delta = 0,
+ deltaX = 0,
+ deltaY = 0,
+ absDelta = 0,
+ absDeltaXY = 0,
+ fn;
+ event = $.event.fix(orgEvent);
+ event.type = "mousewheel";
+
+ // Old school scrollwheel delta
+ if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; }
+ if ( orgEvent.detail ) { delta = orgEvent.detail * -1; }
+
+ // New school wheel delta (wheel event)
+ if ( orgEvent.deltaY ) {
+ deltaY = orgEvent.deltaY * -1;
+ delta = deltaY;
+ }
+ if ( orgEvent.deltaX ) {
+ deltaX = orgEvent.deltaX;
+ delta = deltaX * -1;
+ }
+
+ // Webkit
+ if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; }
+ if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; }
+
+ // Look for lowest delta to normalize the delta values
+ absDelta = Math.abs(delta);
+ if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; }
+ absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX));
+ if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; }
+
+ // Get a whole value for the deltas
+ fn = delta > 0 ? 'floor' : 'ceil';
+ delta = Math[fn](delta / lowestDelta);
+ deltaX = Math[fn](deltaX / lowestDeltaXY);
+ deltaY = Math[fn](deltaY / lowestDeltaXY);
+
+ // Add event and delta to the front of the arguments
+ args.unshift(event, delta, deltaX, deltaY);
+
+ return ($.event.dispatch || $.event.handle).apply(this, args);
+ }
+
+}));
+
+})(jQuery, window, Handsontable);
\ No newline at end of file
diff --git a/.svn/pristine/08/08389bd2533ec3a07475fbda783a4bf5cb8d7b54.svn-base b/.svn/pristine/08/08389bd2533ec3a07475fbda783a4bf5cb8d7b54.svn-base
new file mode 100644
index 0000000..42b913a
--- /dev/null
+++ b/.svn/pristine/08/08389bd2533ec3a07475fbda783a4bf5cb8d7b54.svn-base
@@ -0,0 +1,58 @@
+.combo {
+ display: inline-block;
+ white-space: nowrap;
+ margin: 0;
+ padding: 0;
+ border-width: 1px;
+ border-style: solid;
+ overflow: hidden;
+ vertical-align: middle;
+}
+.combo .combo-text {
+ font-size: 12px;
+ border: 0px;
+ line-height: 20px;
+ height: 20px;
+ margin: 0;
+ padding: 0px 2px;
+ *margin-top: -1px;
+ *height: 18px;
+ *line-height: 18px;
+ _height: 18px;
+ _line-height: 18px;
+ vertical-align: baseline;
+}
+.combo-arrow {
+ width: 18px;
+ height: 20px;
+ overflow: hidden;
+ display: inline-block;
+ vertical-align: top;
+ cursor: pointer;
+ opacity: 0.6;
+ filter: alpha(opacity=60);
+}
+.combo-arrow-hover {
+ opacity: 1.0;
+ filter: alpha(opacity=100);
+}
+.combo-panel {
+ overflow: auto;
+}
+.combo-arrow {
+ background: url('images/combo_arrow.png') no-repeat center center;
+}
+.combo,
+.combo-panel {
+ background-color: #ffffff;
+}
+.combo {
+ border-color: #95B8E7;
+ background-color: #ffffff;
+}
+.combo-arrow {
+ background-color: #E0ECFF;
+}
+.combo-arrow-hover {
+ background-color: #eaf2ff;
+}
diff --git a/.svn/pristine/08/08b9bcf4b9018a9be82577231f6d3333078589af.svn-base b/.svn/pristine/08/08b9bcf4b9018a9be82577231f6d3333078589af.svn-base
new file mode 100644
index 0000000..50a0512
--- /dev/null
+++ b/.svn/pristine/08/08b9bcf4b9018a9be82577231f6d3333078589af.svn-base
@@ -0,0 +1,21778 @@
+/**
+ * @license AngularJS v1.2.19
+ * (c) 2010-2014 Google, Inc. http://angularjs.org
+ * License: MIT
+ */
+(function(window, document, undefined) {'use strict';
+
+/**
+ * @description
+ *
+ * This object provides a utility for producing rich Error messages within
+ * Angular. It can be called as follows:
+ *
+ * var exampleMinErr = minErr('example');
+ * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
+ *
+ * The above creates an instance of minErr in the example namespace. The
+ * resulting error will have a namespaced error code of example.one. The
+ * resulting error will replace {0} with the value of foo, and {1} with the
+ * value of bar. The object is not restricted in the number of arguments it can
+ * take.
+ *
+ * If fewer arguments are specified than necessary for interpolation, the extra
+ * interpolation markers will be preserved in the final string.
+ *
+ * Since data will be parsed statically during a build step, some restrictions
+ * are applied with respect to how minErr instances are created and called.
+ * Instances should have names of the form namespaceMinErr for a minErr created
+ * using minErr('namespace') . Error codes, namespaces and template strings
+ * should all be static strings, not variables or general expressions.
+ *
+ * @param {string} module The namespace to use for the new minErr instance.
+ * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
+ */
+
+function minErr(module) {
+ return function () {
+ var code = arguments[0],
+ prefix = '[' + (module ? module + ':' : '') + code + '] ',
+ template = arguments[1],
+ templateArgs = arguments,
+ stringify = function (obj) {
+ if (typeof obj === 'function') {
+ return obj.toString().replace(/ \{[\s\S]*$/, '');
+ } else if (typeof obj === 'undefined') {
+ return 'undefined';
+ } else if (typeof obj !== 'string') {
+ return JSON.stringify(obj);
+ }
+ return obj;
+ },
+ message, i;
+
+ message = prefix + template.replace(/\{\d+\}/g, function (match) {
+ var index = +match.slice(1, -1), arg;
+
+ if (index + 2 < templateArgs.length) {
+ arg = templateArgs[index + 2];
+ if (typeof arg === 'function') {
+ return arg.toString().replace(/ ?\{[\s\S]*$/, '');
+ } else if (typeof arg === 'undefined') {
+ return 'undefined';
+ } else if (typeof arg !== 'string') {
+ return toJson(arg);
+ }
+ return arg;
+ }
+ return match;
+ });
+
+ message = message + '\nhttp://errors.angularjs.org/1.2.19/' +
+ (module ? module + '/' : '') + code;
+ for (i = 2; i < arguments.length; i++) {
+ message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' +
+ encodeURIComponent(stringify(arguments[i]));
+ }
+
+ return new Error(message);
+ };
+}
+
+/* We need to tell jshint what variables are being exported */
+/* global
+ -angular,
+ -msie,
+ -jqLite,
+ -jQuery,
+ -slice,
+ -push,
+ -toString,
+ -ngMinErr,
+ -angularModule,
+ -nodeName_,
+ -uid,
+ -VALIDITY_STATE_PROPERTY,
+
+ -lowercase,
+ -uppercase,
+ -manualLowercase,
+ -manualUppercase,
+ -nodeName_,
+ -isArrayLike,
+ -forEach,
+ -sortedKeys,
+ -forEachSorted,
+ -reverseParams,
+ -nextUid,
+ -setHashKey,
+ -extend,
+ -int,
+ -inherit,
+ -noop,
+ -identity,
+ -valueFn,
+ -isUndefined,
+ -isDefined,
+ -isObject,
+ -isString,
+ -isNumber,
+ -isDate,
+ -isArray,
+ -isFunction,
+ -isRegExp,
+ -isWindow,
+ -isScope,
+ -isFile,
+ -isBlob,
+ -isBoolean,
+ -trim,
+ -isElement,
+ -makeMap,
+ -map,
+ -size,
+ -includes,
+ -indexOf,
+ -arrayRemove,
+ -isLeafNode,
+ -copy,
+ -shallowCopy,
+ -equals,
+ -csp,
+ -concat,
+ -sliceArgs,
+ -bind,
+ -toJsonReplacer,
+ -toJson,
+ -fromJson,
+ -toBoolean,
+ -startingTag,
+ -tryDecodeURIComponent,
+ -parseKeyValue,
+ -toKeyValue,
+ -encodeUriSegment,
+ -encodeUriQuery,
+ -angularInit,
+ -bootstrap,
+ -snake_case,
+ -bindJQuery,
+ -assertArg,
+ -assertArgFn,
+ -assertNotHasOwnProperty,
+ -getter,
+ -getBlockElements,
+ -hasOwnProperty,
+
+*/
+
+////////////////////////////////////
+
+/**
+ * @ngdoc module
+ * @name ng
+ * @module ng
+ * @description
+ *
+ * # ng (core module)
+ * The ng module is loaded by default when an AngularJS application is started. The module itself
+ * contains the essential components for an AngularJS application to function. The table below
+ * lists a high level breakdown of each of the services/factories, filters, directives and testing
+ * components available within this core module.
+ *
+ *
+ */
+
+// The name of a form control's ValidityState property.
+// This is used so that it's possible for internal tests to create mock ValidityStates.
+var VALIDITY_STATE_PROPERTY = 'validity';
+
+/**
+ * @ngdoc function
+ * @name angular.lowercase
+ * @module ng
+ * @kind function
+ *
+ * @description Converts the specified string to lowercase.
+ * @param {string} string String to be converted to lowercase.
+ * @returns {string} Lowercased string.
+ */
+var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
+var hasOwnProperty = Object.prototype.hasOwnProperty;
+
+/**
+ * @ngdoc function
+ * @name angular.uppercase
+ * @module ng
+ * @kind function
+ *
+ * @description Converts the specified string to uppercase.
+ * @param {string} string String to be converted to uppercase.
+ * @returns {string} Uppercased string.
+ */
+var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
+
+
+var manualLowercase = function(s) {
+ /* jshint bitwise: false */
+ return isString(s)
+ ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
+ : s;
+};
+var manualUppercase = function(s) {
+ /* jshint bitwise: false */
+ return isString(s)
+ ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
+ : s;
+};
+
+
+// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
+// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
+// with correct but slower alternatives.
+if ('i' !== 'I'.toLowerCase()) {
+ lowercase = manualLowercase;
+ uppercase = manualUppercase;
+}
+
+
+var /** holds major version number for IE or NaN for real browsers */
+ msie,
+ jqLite, // delay binding since jQuery could be loaded after us.
+ jQuery, // delay binding
+ slice = [].slice,
+ push = [].push,
+ toString = Object.prototype.toString,
+ ngMinErr = minErr('ng'),
+
+ /** @name angular */
+ angular = window.angular || (window.angular = {}),
+ angularModule,
+ nodeName_,
+ uid = ['0', '0', '0'];
+
+/**
+ * IE 11 changed the format of the UserAgent string.
+ * See http://msdn.microsoft.com/en-us/library/ms537503.aspx
+ */
+msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
+if (isNaN(msie)) {
+ msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
+}
+
+
+/**
+ * @private
+ * @param {*} obj
+ * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
+ * String ...)
+ */
+function isArrayLike(obj) {
+ if (obj == null || isWindow(obj)) {
+ return false;
+ }
+
+ var length = obj.length;
+
+ if (obj.nodeType === 1 && length) {
+ return true;
+ }
+
+ return isString(obj) || isArray(obj) || length === 0 ||
+ typeof length === 'number' && length > 0 && (length - 1) in obj;
+}
+
+/**
+ * @ngdoc function
+ * @name angular.forEach
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
+ * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
+ * is the value of an object property or an array element and `key` is the object property key or
+ * array element index. Specifying a `context` for the function is optional.
+ *
+ * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
+ * using the `hasOwnProperty` method.
+ *
+ ```js
+ var values = {name: 'misko', gender: 'male'};
+ var log = [];
+ angular.forEach(values, function(value, key) {
+ this.push(key + ': ' + value);
+ }, log);
+ expect(log).toEqual(['name: misko', 'gender: male']);
+ ```
+ *
+ * @param {Object|Array} obj Object to iterate over.
+ * @param {Function} iterator Iterator function.
+ * @param {Object=} context Object to become context (`this`) for the iterator function.
+ * @returns {Object|Array} Reference to `obj`.
+ */
+function forEach(obj, iterator, context) {
+ var key;
+ if (obj) {
+ if (isFunction(obj)) {
+ for (key in obj) {
+ // Need to check if hasOwnProperty exists,
+ // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
+ if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
+ iterator.call(context, obj[key], key);
+ }
+ }
+ } else if (obj.forEach && obj.forEach !== forEach) {
+ obj.forEach(iterator, context);
+ } else if (isArrayLike(obj)) {
+ for (key = 0; key < obj.length; key++)
+ iterator.call(context, obj[key], key);
+ } else {
+ for (key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ iterator.call(context, obj[key], key);
+ }
+ }
+ }
+ }
+ return obj;
+}
+
+function sortedKeys(obj) {
+ var keys = [];
+ for (var key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ keys.push(key);
+ }
+ }
+ return keys.sort();
+}
+
+function forEachSorted(obj, iterator, context) {
+ var keys = sortedKeys(obj);
+ for ( var i = 0; i < keys.length; i++) {
+ iterator.call(context, obj[keys[i]], keys[i]);
+ }
+ return keys;
+}
+
+
+/**
+ * when using forEach the params are value, key, but it is often useful to have key, value.
+ * @param {function(string, *)} iteratorFn
+ * @returns {function(*, string)}
+ */
+function reverseParams(iteratorFn) {
+ return function(value, key) { iteratorFn(key, value); };
+}
+
+/**
+ * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
+ * characters such as '012ABC'. The reason why we are not using simply a number counter is that
+ * the number string gets longer over time, and it can also overflow, where as the nextId
+ * will grow much slower, it is a string, and it will never overflow.
+ *
+ * @returns {string} an unique alpha-numeric string
+ */
+function nextUid() {
+ var index = uid.length;
+ var digit;
+
+ while(index) {
+ index--;
+ digit = uid[index].charCodeAt(0);
+ if (digit == 57 /*'9'*/) {
+ uid[index] = 'A';
+ return uid.join('');
+ }
+ if (digit == 90 /*'Z'*/) {
+ uid[index] = '0';
+ } else {
+ uid[index] = String.fromCharCode(digit + 1);
+ return uid.join('');
+ }
+ }
+ uid.unshift('0');
+ return uid.join('');
+}
+
+
+/**
+ * Set or clear the hashkey for an object.
+ * @param obj object
+ * @param h the hashkey (!truthy to delete the hashkey)
+ */
+function setHashKey(obj, h) {
+ if (h) {
+ obj.$$hashKey = h;
+ }
+ else {
+ delete obj.$$hashKey;
+ }
+}
+
+/**
+ * @ngdoc function
+ * @name angular.extend
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Extends the destination object `dst` by copying all of the properties from the `src` object(s)
+ * to `dst`. You can specify multiple `src` objects.
+ *
+ * @param {Object} dst Destination object.
+ * @param {...Object} src Source object(s).
+ * @returns {Object} Reference to `dst`.
+ */
+function extend(dst) {
+ var h = dst.$$hashKey;
+ forEach(arguments, function(obj) {
+ if (obj !== dst) {
+ forEach(obj, function(value, key) {
+ dst[key] = value;
+ });
+ }
+ });
+
+ setHashKey(dst,h);
+ return dst;
+}
+
+function int(str) {
+ return parseInt(str, 10);
+}
+
+
+function inherit(parent, extra) {
+ return extend(new (extend(function() {}, {prototype:parent}))(), extra);
+}
+
+/**
+ * @ngdoc function
+ * @name angular.noop
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * A function that performs no operations. This function can be useful when writing code in the
+ * functional style.
+ ```js
+ function foo(callback) {
+ var result = calculateResult();
+ (callback || angular.noop)(result);
+ }
+ ```
+ */
+function noop() {}
+noop.$inject = [];
+
+
+/**
+ * @ngdoc function
+ * @name angular.identity
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * A function that returns its first argument. This function is useful when writing code in the
+ * functional style.
+ *
+ ```js
+ function transformer(transformationFn, value) {
+ return (transformationFn || angular.identity)(value);
+ };
+ ```
+ */
+function identity($) {return $;}
+identity.$inject = [];
+
+
+function valueFn(value) {return function() {return value;};}
+
+/**
+ * @ngdoc function
+ * @name angular.isUndefined
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is undefined.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is undefined.
+ */
+function isUndefined(value){return typeof value === 'undefined';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isDefined
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is defined.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is defined.
+ */
+function isDefined(value){return typeof value !== 'undefined';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isObject
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
+ * considered to be objects. Note that JavaScript arrays are objects.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is an `Object` but not `null`.
+ */
+function isObject(value){return value != null && typeof value === 'object';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isString
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is a `String`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `String`.
+ */
+function isString(value){return typeof value === 'string';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isNumber
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is a `Number`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `Number`.
+ */
+function isNumber(value){return typeof value === 'number';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isDate
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a value is a date.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `Date`.
+ */
+function isDate(value) {
+ return toString.call(value) === '[object Date]';
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isArray
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is an `Array`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is an `Array`.
+ */
+var isArray = (function() {
+ if (!isFunction(Array.isArray)) {
+ return function(value) {
+ return toString.call(value) === '[object Array]';
+ };
+ }
+ return Array.isArray;
+})();
+
+/**
+ * @ngdoc function
+ * @name angular.isFunction
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is a `Function`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `Function`.
+ */
+function isFunction(value){return typeof value === 'function';}
+
+
+/**
+ * Determines if a value is a regular expression object.
+ *
+ * @private
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `RegExp`.
+ */
+function isRegExp(value) {
+ return toString.call(value) === '[object RegExp]';
+}
+
+
+/**
+ * Checks if `obj` is a window object.
+ *
+ * @private
+ * @param {*} obj Object to check
+ * @returns {boolean} True if `obj` is a window obj.
+ */
+function isWindow(obj) {
+ return obj && obj.document && obj.location && obj.alert && obj.setInterval;
+}
+
+
+function isScope(obj) {
+ return obj && obj.$evalAsync && obj.$watch;
+}
+
+
+function isFile(obj) {
+ return toString.call(obj) === '[object File]';
+}
+
+
+function isBlob(obj) {
+ return toString.call(obj) === '[object Blob]';
+}
+
+
+function isBoolean(value) {
+ return typeof value === 'boolean';
+}
+
+
+var trim = (function() {
+ // native trim is way faster: http://jsperf.com/angular-trim-test
+ // but IE doesn't have it... :-(
+ // TODO: we should move this into IE/ES5 polyfill
+ if (!String.prototype.trim) {
+ return function(value) {
+ return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
+ };
+ }
+ return function(value) {
+ return isString(value) ? value.trim() : value;
+ };
+})();
+
+
+/**
+ * @ngdoc function
+ * @name angular.isElement
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is a DOM element (or wrapped jQuery element).
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
+ */
+function isElement(node) {
+ return !!(node &&
+ (node.nodeName // we are a direct element
+ || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
+}
+
+/**
+ * @param str 'key1,key2,...'
+ * @returns {object} in the form of {key1:true, key2:true, ...}
+ */
+function makeMap(str) {
+ var obj = {}, items = str.split(","), i;
+ for ( i = 0; i < items.length; i++ )
+ obj[ items[i] ] = true;
+ return obj;
+}
+
+
+if (msie < 9) {
+ nodeName_ = function(element) {
+ element = element.nodeName ? element : element[0];
+ return (element.scopeName && element.scopeName != 'HTML')
+ ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
+ };
+} else {
+ nodeName_ = function(element) {
+ return element.nodeName ? element.nodeName : element[0].nodeName;
+ };
+}
+
+
+function map(obj, iterator, context) {
+ var results = [];
+ forEach(obj, function(value, index, list) {
+ results.push(iterator.call(context, value, index, list));
+ });
+ return results;
+}
+
+
+/**
+ * @description
+ * Determines the number of elements in an array, the number of properties an object has, or
+ * the length of a string.
+ *
+ * Note: This function is used to augment the Object type in Angular expressions. See
+ * {@link angular.Object} for more information about Angular arrays.
+ *
+ * @param {Object|Array|string} obj Object, array, or string to inspect.
+ * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
+ * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
+ */
+function size(obj, ownPropsOnly) {
+ var count = 0, key;
+
+ if (isArray(obj) || isString(obj)) {
+ return obj.length;
+ } else if (isObject(obj)) {
+ for (key in obj)
+ if (!ownPropsOnly || obj.hasOwnProperty(key))
+ count++;
+ }
+
+ return count;
+}
+
+
+function includes(array, obj) {
+ return indexOf(array, obj) != -1;
+}
+
+function indexOf(array, obj) {
+ if (array.indexOf) return array.indexOf(obj);
+
+ for (var i = 0; i < array.length; i++) {
+ if (obj === array[i]) return i;
+ }
+ return -1;
+}
+
+function arrayRemove(array, value) {
+ var index = indexOf(array, value);
+ if (index >=0)
+ array.splice(index, 1);
+ return value;
+}
+
+function isLeafNode (node) {
+ if (node) {
+ switch (node.nodeName) {
+ case "OPTION":
+ case "PRE":
+ case "TITLE":
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * @ngdoc function
+ * @name angular.copy
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Creates a deep copy of `source`, which should be an object or an array.
+ *
+ * * If no destination is supplied, a copy of the object or array is created.
+ * * If a destination is provided, all of its elements (for array) or properties (for objects)
+ * are deleted and then all elements/properties from the source are copied to it.
+ * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
+ * * If `source` is identical to 'destination' an exception will be thrown.
+ *
+ * @param {*} source The source that will be used to make a copy.
+ * Can be any type, including primitives, `null`, and `undefined`.
+ * @param {(Object|Array)=} destination Destination into which the source is copied. If
+ * provided, must be of the same type as `source`.
+ * @returns {*} The copy or updated `destination`, if `destination` was specified.
+ *
+ * @example
+
+
+
+
+
form = {{user | json}}
+
master = {{master | json}}
+
+
+
+
+
+ */
+function copy(source, destination, stackSource, stackDest) {
+ if (isWindow(source) || isScope(source)) {
+ throw ngMinErr('cpws',
+ "Can't copy! Making copies of Window or Scope instances is not supported.");
+ }
+
+ if (!destination) {
+ destination = source;
+ if (source) {
+ if (isArray(source)) {
+ destination = copy(source, [], stackSource, stackDest);
+ } else if (isDate(source)) {
+ destination = new Date(source.getTime());
+ } else if (isRegExp(source)) {
+ destination = new RegExp(source.source);
+ } else if (isObject(source)) {
+ destination = copy(source, {}, stackSource, stackDest);
+ }
+ }
+ } else {
+ if (source === destination) throw ngMinErr('cpi',
+ "Can't copy! Source and destination are identical.");
+
+ stackSource = stackSource || [];
+ stackDest = stackDest || [];
+
+ if (isObject(source)) {
+ var index = indexOf(stackSource, source);
+ if (index !== -1) return stackDest[index];
+
+ stackSource.push(source);
+ stackDest.push(destination);
+ }
+
+ var result;
+ if (isArray(source)) {
+ destination.length = 0;
+ for ( var i = 0; i < source.length; i++) {
+ result = copy(source[i], null, stackSource, stackDest);
+ if (isObject(source[i])) {
+ stackSource.push(source[i]);
+ stackDest.push(result);
+ }
+ destination.push(result);
+ }
+ } else {
+ var h = destination.$$hashKey;
+ forEach(destination, function(value, key) {
+ delete destination[key];
+ });
+ for ( var key in source) {
+ result = copy(source[key], null, stackSource, stackDest);
+ if (isObject(source[key])) {
+ stackSource.push(source[key]);
+ stackDest.push(result);
+ }
+ destination[key] = result;
+ }
+ setHashKey(destination,h);
+ }
+
+ }
+ return destination;
+}
+
+/**
+ * Creates a shallow copy of an object, an array or a primitive
+ */
+function shallowCopy(src, dst) {
+ if (isArray(src)) {
+ dst = dst || [];
+
+ for ( var i = 0; i < src.length; i++) {
+ dst[i] = src[i];
+ }
+ } else if (isObject(src)) {
+ dst = dst || {};
+
+ for (var key in src) {
+ if (hasOwnProperty.call(src, key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
+ dst[key] = src[key];
+ }
+ }
+ }
+
+ return dst || src;
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.equals
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if two objects or two values are equivalent. Supports value types, regular
+ * expressions, arrays and objects.
+ *
+ * Two objects or values are considered equivalent if at least one of the following is true:
+ *
+ * * Both objects or values pass `===` comparison.
+ * * Both objects or values are of the same type and all of their properties are equal by
+ * comparing them with `angular.equals`.
+ * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
+ * * Both values represent the same regular expression (In JavaScript,
+ * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
+ * representation matches).
+ *
+ * During a property comparison, properties of `function` type and properties with names
+ * that begin with `$` are ignored.
+ *
+ * Scope and DOMWindow objects are being compared only by identify (`===`).
+ *
+ * @param {*} o1 Object or value to compare.
+ * @param {*} o2 Object or value to compare.
+ * @returns {boolean} True if arguments are equal.
+ */
+function equals(o1, o2) {
+ if (o1 === o2) return true;
+ if (o1 === null || o2 === null) return false;
+ if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
+ var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
+ if (t1 == t2) {
+ if (t1 == 'object') {
+ if (isArray(o1)) {
+ if (!isArray(o2)) return false;
+ if ((length = o1.length) == o2.length) {
+ for(key=0; key 2 ? sliceArgs(arguments, 2) : [];
+ if (isFunction(fn) && !(fn instanceof RegExp)) {
+ return curryArgs.length
+ ? function() {
+ return arguments.length
+ ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
+ : fn.apply(self, curryArgs);
+ }
+ : function() {
+ return arguments.length
+ ? fn.apply(self, arguments)
+ : fn.call(self);
+ };
+ } else {
+ // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
+ return fn;
+ }
+}
+
+
+function toJsonReplacer(key, value) {
+ var val = value;
+
+ if (typeof key === 'string' && key.charAt(0) === '$') {
+ val = undefined;
+ } else if (isWindow(value)) {
+ val = '$WINDOW';
+ } else if (value && document === value) {
+ val = '$DOCUMENT';
+ } else if (isScope(value)) {
+ val = '$SCOPE';
+ }
+
+ return val;
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.toJson
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Serializes input into a JSON-formatted string. Properties with leading $ characters will be
+ * stripped since angular uses this notation internally.
+ *
+ * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
+ * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
+ * @returns {string|undefined} JSON-ified string representing `obj`.
+ */
+function toJson(obj, pretty) {
+ if (typeof obj === 'undefined') return undefined;
+ return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.fromJson
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Deserializes a JSON string.
+ *
+ * @param {string} json JSON string to deserialize.
+ * @returns {Object|Array|string|number} Deserialized thingy.
+ */
+function fromJson(json) {
+ return isString(json)
+ ? JSON.parse(json)
+ : json;
+}
+
+
+function toBoolean(value) {
+ if (typeof value === 'function') {
+ value = true;
+ } else if (value && value.length !== 0) {
+ var v = lowercase("" + value);
+ value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
+ } else {
+ value = false;
+ }
+ return value;
+}
+
+/**
+ * @returns {string} Returns the string representation of the element.
+ */
+function startingTag(element) {
+ element = jqLite(element).clone();
+ try {
+ // turns out IE does not let you set .html() on elements which
+ // are not allowed to have children. So we just ignore it.
+ element.empty();
+ } catch(e) {}
+ // As Per DOM Standards
+ var TEXT_NODE = 3;
+ var elemHtml = jqLite('
').append(element).html();
+ try {
+ return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
+ elemHtml.
+ match(/^(<[^>]+>)/)[1].
+ replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
+ } catch(e) {
+ return lowercase(elemHtml);
+ }
+
+}
+
+
+/////////////////////////////////////////////////
+
+/**
+ * Tries to decode the URI component without throwing an exception.
+ *
+ * @private
+ * @param str value potential URI component to check.
+ * @returns {boolean} True if `value` can be decoded
+ * with the decodeURIComponent function.
+ */
+function tryDecodeURIComponent(value) {
+ try {
+ return decodeURIComponent(value);
+ } catch(e) {
+ // Ignore any invalid uri component
+ }
+}
+
+
+/**
+ * Parses an escaped url query string into key-value pairs.
+ * @returns {Object.}
+ */
+function parseKeyValue(/**string*/keyValue) {
+ var obj = {}, key_value, key;
+ forEach((keyValue || "").split('&'), function(keyValue) {
+ if ( keyValue ) {
+ key_value = keyValue.split('=');
+ key = tryDecodeURIComponent(key_value[0]);
+ if ( isDefined(key) ) {
+ var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
+ if (!obj[key]) {
+ obj[key] = val;
+ } else if(isArray(obj[key])) {
+ obj[key].push(val);
+ } else {
+ obj[key] = [obj[key],val];
+ }
+ }
+ }
+ });
+ return obj;
+}
+
+function toKeyValue(obj) {
+ var parts = [];
+ forEach(obj, function(value, key) {
+ if (isArray(value)) {
+ forEach(value, function(arrayValue) {
+ parts.push(encodeUriQuery(key, true) +
+ (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
+ });
+ } else {
+ parts.push(encodeUriQuery(key, true) +
+ (value === true ? '' : '=' + encodeUriQuery(value, true)));
+ }
+ });
+ return parts.length ? parts.join('&') : '';
+}
+
+
+/**
+ * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
+ * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
+ * segments:
+ * segment = *pchar
+ * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
+ * pct-encoded = "%" HEXDIG HEXDIG
+ * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
+ * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
+ * / "*" / "+" / "," / ";" / "="
+ */
+function encodeUriSegment(val) {
+ return encodeUriQuery(val, true).
+ replace(/%26/gi, '&').
+ replace(/%3D/gi, '=').
+ replace(/%2B/gi, '+');
+}
+
+
+/**
+ * This method is intended for encoding *key* or *value* parts of query component. We need a custom
+ * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
+ * encoded per http://tools.ietf.org/html/rfc3986:
+ * query = *( pchar / "/" / "?" )
+ * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
+ * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
+ * pct-encoded = "%" HEXDIG HEXDIG
+ * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
+ * / "*" / "+" / "," / ";" / "="
+ */
+function encodeUriQuery(val, pctEncodeSpaces) {
+ return encodeURIComponent(val).
+ replace(/%40/gi, '@').
+ replace(/%3A/gi, ':').
+ replace(/%24/g, '$').
+ replace(/%2C/gi, ',').
+ replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
+}
+
+
+/**
+ * @ngdoc directive
+ * @name ngApp
+ * @module ng
+ *
+ * @element ANY
+ * @param {angular.Module} ngApp an optional application
+ * {@link angular.module module} name to load.
+ *
+ * @description
+ *
+ * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
+ * designates the **root element** of the application and is typically placed near the root element
+ * of the page - e.g. on the `` or `` tags.
+ *
+ * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
+ * found in the document will be used to define the root element to auto-bootstrap as an
+ * application. To run multiple applications in an HTML document you must manually bootstrap them using
+ * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
+ *
+ * You can specify an **AngularJS module** to be used as the root module for the application. This
+ * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and
+ * should contain the application code needed or have dependencies on other modules that will
+ * contain the code. See {@link angular.module} for more information.
+ *
+ * In the example below if the `ngApp` directive were not placed on the `html` element then the
+ * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
+ * would not be resolved to `3`.
+ *
+ * `ngApp` is the easiest, and most common, way to bootstrap an application.
+ *
+
+
+
+ I can add: {{a}} + {{b}} = {{ a+b }}
+
+
+
+ angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
+ $scope.a = 1;
+ $scope.b = 2;
+ });
+
+
+ *
+ */
+function angularInit(element, bootstrap) {
+ var elements = [element],
+ appElement,
+ module,
+ names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
+ NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
+
+ function append(element) {
+ element && elements.push(element);
+ }
+
+ forEach(names, function(name) {
+ names[name] = true;
+ append(document.getElementById(name));
+ name = name.replace(':', '\\:');
+ if (element.querySelectorAll) {
+ forEach(element.querySelectorAll('.' + name), append);
+ forEach(element.querySelectorAll('.' + name + '\\:'), append);
+ forEach(element.querySelectorAll('[' + name + ']'), append);
+ }
+ });
+
+ forEach(elements, function(element) {
+ if (!appElement) {
+ var className = ' ' + element.className + ' ';
+ var match = NG_APP_CLASS_REGEXP.exec(className);
+ if (match) {
+ appElement = element;
+ module = (match[2] || '').replace(/\s+/g, ',');
+ } else {
+ forEach(element.attributes, function(attr) {
+ if (!appElement && names[attr.name]) {
+ appElement = element;
+ module = attr.value;
+ }
+ });
+ }
+ }
+ });
+ if (appElement) {
+ bootstrap(appElement, module ? [module] : []);
+ }
+}
+
+/**
+ * @ngdoc function
+ * @name angular.bootstrap
+ * @module ng
+ * @description
+ * Use this function to manually start up angular application.
+ *
+ * See: {@link guide/bootstrap Bootstrap}
+ *
+ * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
+ * They must use {@link ng.directive:ngApp ngApp}.
+ *
+ * Angular will detect if it has been loaded into the browser more than once and only allow the
+ * first loaded script to be bootstrapped and will report a warning to the browser console for
+ * each of the subsequent scripts. This prevents strange results in applications, where otherwise
+ * multiple instances of Angular try to work on the DOM.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
{{heading}}
+ *
+ *
+ *
{{fill}}
+ *
+ *
+ *
+ *
+ *
+ * var app = angular.module('multi-bootstrap', [])
+ *
+ * .controller('BrokenTable', function($scope) {
+ * $scope.headings = ['One', 'Two', 'Three'];
+ * $scope.fillings = [[1, 2, 3], ['A', 'B', 'C'], [7, 8, 9]];
+ * });
+ *
+ *
+ * it('should only insert one table cell for each item in $scope.fillings', function() {
+ * expect(element.all(by.css('td')).count())
+ * .toBe(9);
+ * });
+ *
+ *
+ *
+ * @param {DOMElement} element DOM element which is the root of angular application.
+ * @param {Array=} modules an array of modules to load into the application.
+ * Each item in the array should be the name of a predefined module or a (DI annotated)
+ * function that will be invoked by the injector as a run block.
+ * See: {@link angular.module modules}
+ * @returns {auto.$injector} Returns the newly created injector for this app.
+ */
+function bootstrap(element, modules) {
+ var doBootstrap = function() {
+ element = jqLite(element);
+
+ if (element.injector()) {
+ var tag = (element[0] === document) ? 'document' : startingTag(element);
+ throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag);
+ }
+
+ modules = modules || [];
+ modules.unshift(['$provide', function($provide) {
+ $provide.value('$rootElement', element);
+ }]);
+ modules.unshift('ng');
+ var injector = createInjector(modules);
+ injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate',
+ function(scope, element, compile, injector, animate) {
+ scope.$apply(function() {
+ element.data('$injector', injector);
+ compile(element)(scope);
+ });
+ }]
+ );
+ return injector;
+ };
+
+ var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
+
+ if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
+ return doBootstrap();
+ }
+
+ window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
+ angular.resumeBootstrap = function(extraModules) {
+ forEach(extraModules, function(module) {
+ modules.push(module);
+ });
+ doBootstrap();
+ };
+}
+
+var SNAKE_CASE_REGEXP = /[A-Z]/g;
+function snake_case(name, separator) {
+ separator = separator || '_';
+ return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
+ return (pos ? separator : '') + letter.toLowerCase();
+ });
+}
+
+function bindJQuery() {
+ // bind to jQuery if present;
+ jQuery = window.jQuery;
+ // Use jQuery if it exists with proper functionality, otherwise default to us.
+ // Angular 1.2+ requires jQuery 1.7.1+ for on()/off() support.
+ if (jQuery && jQuery.fn.on) {
+ jqLite = jQuery;
+ extend(jQuery.fn, {
+ scope: JQLitePrototype.scope,
+ isolateScope: JQLitePrototype.isolateScope,
+ controller: JQLitePrototype.controller,
+ injector: JQLitePrototype.injector,
+ inheritedData: JQLitePrototype.inheritedData
+ });
+ // Method signature:
+ // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments)
+ jqLitePatchJQueryRemove('remove', true, true, false);
+ jqLitePatchJQueryRemove('empty', false, false, false);
+ jqLitePatchJQueryRemove('html', false, false, true);
+ } else {
+ jqLite = JQLite;
+ }
+ angular.element = jqLite;
+}
+
+/**
+ * throw error if the argument is falsy.
+ */
+function assertArg(arg, name, reason) {
+ if (!arg) {
+ throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
+ }
+ return arg;
+}
+
+function assertArgFn(arg, name, acceptArrayAnnotation) {
+ if (acceptArrayAnnotation && isArray(arg)) {
+ arg = arg[arg.length - 1];
+ }
+
+ assertArg(isFunction(arg), name, 'not a function, got ' +
+ (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
+ return arg;
+}
+
+/**
+ * throw error if the name given is hasOwnProperty
+ * @param {String} name the name to test
+ * @param {String} context the context in which the name is used, such as module or directive
+ */
+function assertNotHasOwnProperty(name, context) {
+ if (name === 'hasOwnProperty') {
+ throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
+ }
+}
+
+/**
+ * Return the value accessible from the object by path. Any undefined traversals are ignored
+ * @param {Object} obj starting object
+ * @param {String} path path to traverse
+ * @param {boolean} [bindFnToScope=true]
+ * @returns {Object} value as accessible by path
+ */
+//TODO(misko): this function needs to be removed
+function getter(obj, path, bindFnToScope) {
+ if (!path) return obj;
+ var keys = path.split('.');
+ var key;
+ var lastInstance = obj;
+ var len = keys.length;
+
+ for (var i = 0; i < len; i++) {
+ key = keys[i];
+ if (obj) {
+ obj = (lastInstance = obj)[key];
+ }
+ }
+ if (!bindFnToScope && isFunction(obj)) {
+ return bind(lastInstance, obj);
+ }
+ return obj;
+}
+
+/**
+ * Return the DOM siblings between the first and last node in the given array.
+ * @param {Array} array like object
+ * @returns {DOMElement} object containing the elements
+ */
+function getBlockElements(nodes) {
+ var startNode = nodes[0],
+ endNode = nodes[nodes.length - 1];
+ if (startNode === endNode) {
+ return jqLite(startNode);
+ }
+
+ var element = startNode;
+ var elements = [element];
+
+ do {
+ element = element.nextSibling;
+ if (!element) break;
+ elements.push(element);
+ } while (element !== endNode);
+
+ return jqLite(elements);
+}
+
+/**
+ * @ngdoc type
+ * @name angular.Module
+ * @module ng
+ * @description
+ *
+ * Interface for configuring angular {@link angular.module modules}.
+ */
+
+function setupModuleLoader(window) {
+
+ var $injectorMinErr = minErr('$injector');
+ var ngMinErr = minErr('ng');
+
+ function ensure(obj, name, factory) {
+ return obj[name] || (obj[name] = factory());
+ }
+
+ var angular = ensure(window, 'angular', Object);
+
+ // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
+ angular.$$minErr = angular.$$minErr || minErr;
+
+ return ensure(angular, 'module', function() {
+ /** @type {Object.} */
+ var modules = {};
+
+ /**
+ * @ngdoc function
+ * @name angular.module
+ * @module ng
+ * @description
+ *
+ * The `angular.module` is a global place for creating, registering and retrieving Angular
+ * modules.
+ * All modules (angular core or 3rd party) that should be available to an application must be
+ * registered using this mechanism.
+ *
+ * When passed two or more arguments, a new module is created. If passed only one argument, an
+ * existing module (the name passed as the first argument to `module`) is retrieved.
+ *
+ *
+ * # Module
+ *
+ * A module is a collection of services, directives, controllers, filters, and configuration information.
+ * `angular.module` is used to configure the {@link auto.$injector $injector}.
+ *
+ * ```js
+ * // Create a new module
+ * var myModule = angular.module('myModule', []);
+ *
+ * // register a new service
+ * myModule.value('appName', 'MyCoolApp');
+ *
+ * // configure existing services inside initialization blocks.
+ * myModule.config(['$locationProvider', function($locationProvider) {
+ * // Configure existing providers
+ * $locationProvider.hashPrefix('!');
+ * }]);
+ * ```
+ *
+ * Then you can create an injector and load your modules like this:
+ *
+ * ```js
+ * var injector = angular.injector(['ng', 'myModule'])
+ * ```
+ *
+ * However it's more likely that you'll just use
+ * {@link ng.directive:ngApp ngApp} or
+ * {@link angular.bootstrap} to simplify this process for you.
+ *
+ * @param {!string} name The name of the module to create or retrieve.
+ * @param {!Array.=} requires If specified then new module is being created. If
+ * unspecified then the module is being retrieved for further configuration.
+ * @param {Function=} configFn Optional configuration function for the module. Same as
+ * {@link angular.Module#config Module#config()}.
+ * @returns {module} new module with the {@link angular.Module} api.
+ */
+ return function module(name, requires, configFn) {
+ var assertNotHasOwnProperty = function(name, context) {
+ if (name === 'hasOwnProperty') {
+ throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
+ }
+ };
+
+ assertNotHasOwnProperty(name, 'module');
+ if (requires && modules.hasOwnProperty(name)) {
+ modules[name] = null;
+ }
+ return ensure(modules, name, function() {
+ if (!requires) {
+ throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
+ "the module name or forgot to load it. If registering a module ensure that you " +
+ "specify the dependencies as the second argument.", name);
+ }
+
+ /** @type {!Array.>} */
+ var invokeQueue = [];
+
+ /** @type {!Array.} */
+ var runBlocks = [];
+
+ var config = invokeLater('$injector', 'invoke');
+
+ /** @type {angular.Module} */
+ var moduleInstance = {
+ // Private state
+ _invokeQueue: invokeQueue,
+ _runBlocks: runBlocks,
+
+ /**
+ * @ngdoc property
+ * @name angular.Module#requires
+ * @module ng
+ * @returns {Array.} List of module names which must be loaded before this module.
+ * @description
+ * Holds the list of modules which the injector will load before the current module is
+ * loaded.
+ */
+ requires: requires,
+
+ /**
+ * @ngdoc property
+ * @name angular.Module#name
+ * @module ng
+ * @returns {string} Name of the module.
+ * @description
+ */
+ name: name,
+
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#provider
+ * @module ng
+ * @param {string} name service name
+ * @param {Function} providerType Construction function for creating new instance of the
+ * service.
+ * @description
+ * See {@link auto.$provide#provider $provide.provider()}.
+ */
+ provider: invokeLater('$provide', 'provider'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#factory
+ * @module ng
+ * @param {string} name service name
+ * @param {Function} providerFunction Function for creating new instance of the service.
+ * @description
+ * See {@link auto.$provide#factory $provide.factory()}.
+ */
+ factory: invokeLater('$provide', 'factory'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#service
+ * @module ng
+ * @param {string} name service name
+ * @param {Function} constructor A constructor function that will be instantiated.
+ * @description
+ * See {@link auto.$provide#service $provide.service()}.
+ */
+ service: invokeLater('$provide', 'service'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#value
+ * @module ng
+ * @param {string} name service name
+ * @param {*} object Service instance object.
+ * @description
+ * See {@link auto.$provide#value $provide.value()}.
+ */
+ value: invokeLater('$provide', 'value'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#constant
+ * @module ng
+ * @param {string} name constant name
+ * @param {*} object Constant value.
+ * @description
+ * Because the constant are fixed, they get applied before other provide methods.
+ * See {@link auto.$provide#constant $provide.constant()}.
+ */
+ constant: invokeLater('$provide', 'constant', 'unshift'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#animation
+ * @module ng
+ * @param {string} name animation name
+ * @param {Function} animationFactory Factory function for creating new instance of an
+ * animation.
+ * @description
+ *
+ * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
+ *
+ *
+ * Defines an animation hook that can be later used with
+ * {@link ngAnimate.$animate $animate} service and directives that use this service.
+ *
+ * ```js
+ * module.animation('.animation-name', function($inject1, $inject2) {
+ * return {
+ * eventName : function(element, done) {
+ * //code to run the animation
+ * //once complete, then run done()
+ * return function cancellationFunction(element) {
+ * //code to cancel the animation
+ * }
+ * }
+ * }
+ * })
+ * ```
+ *
+ * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and
+ * {@link ngAnimate ngAnimate module} for more information.
+ */
+ animation: invokeLater('$animateProvider', 'register'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#filter
+ * @module ng
+ * @param {string} name Filter name.
+ * @param {Function} filterFactory Factory function for creating new instance of filter.
+ * @description
+ * See {@link ng.$filterProvider#register $filterProvider.register()}.
+ */
+ filter: invokeLater('$filterProvider', 'register'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#controller
+ * @module ng
+ * @param {string|Object} name Controller name, or an object map of controllers where the
+ * keys are the names and the values are the constructors.
+ * @param {Function} constructor Controller constructor function.
+ * @description
+ * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
+ */
+ controller: invokeLater('$controllerProvider', 'register'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#directive
+ * @module ng
+ * @param {string|Object} name Directive name, or an object map of directives where the
+ * keys are the names and the values are the factories.
+ * @param {Function} directiveFactory Factory function for creating new instance of
+ * directives.
+ * @description
+ * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
+ */
+ directive: invokeLater('$compileProvider', 'directive'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#config
+ * @module ng
+ * @param {Function} configFn Execute this function on module load. Useful for service
+ * configuration.
+ * @description
+ * Use this method to register work which needs to be performed on module loading.
+ * For more about how to configure services, see
+ * {@link providers#providers_provider-recipe Provider Recipe}.
+ */
+ config: config,
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#run
+ * @module ng
+ * @param {Function} initializationFn Execute this function after injector creation.
+ * Useful for application initialization.
+ * @description
+ * Use this method to register work which should be performed when the injector is done
+ * loading all modules.
+ */
+ run: function(block) {
+ runBlocks.push(block);
+ return this;
+ }
+ };
+
+ if (configFn) {
+ config(configFn);
+ }
+
+ return moduleInstance;
+
+ /**
+ * @param {string} provider
+ * @param {string} method
+ * @param {String=} insertMethod
+ * @returns {angular.Module}
+ */
+ function invokeLater(provider, method, insertMethod) {
+ return function() {
+ invokeQueue[insertMethod || 'push']([provider, method, arguments]);
+ return moduleInstance;
+ };
+ }
+ });
+ };
+ });
+
+}
+
+/* global
+ angularModule: true,
+ version: true,
+
+ $LocaleProvider,
+ $CompileProvider,
+
+ htmlAnchorDirective,
+ inputDirective,
+ inputDirective,
+ formDirective,
+ scriptDirective,
+ selectDirective,
+ styleDirective,
+ optionDirective,
+ ngBindDirective,
+ ngBindHtmlDirective,
+ ngBindTemplateDirective,
+ ngClassDirective,
+ ngClassEvenDirective,
+ ngClassOddDirective,
+ ngCspDirective,
+ ngCloakDirective,
+ ngControllerDirective,
+ ngFormDirective,
+ ngHideDirective,
+ ngIfDirective,
+ ngIncludeDirective,
+ ngIncludeFillContentDirective,
+ ngInitDirective,
+ ngNonBindableDirective,
+ ngPluralizeDirective,
+ ngRepeatDirective,
+ ngShowDirective,
+ ngStyleDirective,
+ ngSwitchDirective,
+ ngSwitchWhenDirective,
+ ngSwitchDefaultDirective,
+ ngOptionsDirective,
+ ngTranscludeDirective,
+ ngModelDirective,
+ ngListDirective,
+ ngChangeDirective,
+ requiredDirective,
+ requiredDirective,
+ ngValueDirective,
+ ngAttributeAliasDirectives,
+ ngEventDirectives,
+
+ $AnchorScrollProvider,
+ $AnimateProvider,
+ $BrowserProvider,
+ $CacheFactoryProvider,
+ $ControllerProvider,
+ $DocumentProvider,
+ $ExceptionHandlerProvider,
+ $FilterProvider,
+ $InterpolateProvider,
+ $IntervalProvider,
+ $HttpProvider,
+ $HttpBackendProvider,
+ $LocationProvider,
+ $LogProvider,
+ $ParseProvider,
+ $RootScopeProvider,
+ $QProvider,
+ $$SanitizeUriProvider,
+ $SceProvider,
+ $SceDelegateProvider,
+ $SnifferProvider,
+ $TemplateCacheProvider,
+ $TimeoutProvider,
+ $$RAFProvider,
+ $$AsyncCallbackProvider,
+ $WindowProvider
+*/
+
+
+/**
+ * @ngdoc object
+ * @name angular.version
+ * @module ng
+ * @description
+ * An object that contains information about the current AngularJS version. This object has the
+ * following properties:
+ *
+ * - `full` – `{string}` – Full version string, such as "0.9.18".
+ * - `major` – `{number}` – Major version number, such as "0".
+ * - `minor` – `{number}` – Minor version number, such as "9".
+ * - `dot` – `{number}` – Dot version number, such as "18".
+ * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
+ */
+var version = {
+ full: '1.2.19', // all of these placeholder strings will be replaced by grunt's
+ major: 1, // package task
+ minor: 2,
+ dot: 19,
+ codeName: 'precognitive-flashbacks'
+};
+
+
+function publishExternalAPI(angular){
+ extend(angular, {
+ 'bootstrap': bootstrap,
+ 'copy': copy,
+ 'extend': extend,
+ 'equals': equals,
+ 'element': jqLite,
+ 'forEach': forEach,
+ 'injector': createInjector,
+ 'noop':noop,
+ 'bind':bind,
+ 'toJson': toJson,
+ 'fromJson': fromJson,
+ 'identity':identity,
+ 'isUndefined': isUndefined,
+ 'isDefined': isDefined,
+ 'isString': isString,
+ 'isFunction': isFunction,
+ 'isObject': isObject,
+ 'isNumber': isNumber,
+ 'isElement': isElement,
+ 'isArray': isArray,
+ 'version': version,
+ 'isDate': isDate,
+ 'lowercase': lowercase,
+ 'uppercase': uppercase,
+ 'callbacks': {counter: 0},
+ '$$minErr': minErr,
+ '$$csp': csp
+ });
+
+ angularModule = setupModuleLoader(window);
+ try {
+ angularModule('ngLocale');
+ } catch (e) {
+ angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
+ }
+
+ angularModule('ng', ['ngLocale'], ['$provide',
+ function ngModule($provide) {
+ // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
+ $provide.provider({
+ $$sanitizeUri: $$SanitizeUriProvider
+ });
+ $provide.provider('$compile', $CompileProvider).
+ directive({
+ a: htmlAnchorDirective,
+ input: inputDirective,
+ textarea: inputDirective,
+ form: formDirective,
+ script: scriptDirective,
+ select: selectDirective,
+ style: styleDirective,
+ option: optionDirective,
+ ngBind: ngBindDirective,
+ ngBindHtml: ngBindHtmlDirective,
+ ngBindTemplate: ngBindTemplateDirective,
+ ngClass: ngClassDirective,
+ ngClassEven: ngClassEvenDirective,
+ ngClassOdd: ngClassOddDirective,
+ ngCloak: ngCloakDirective,
+ ngController: ngControllerDirective,
+ ngForm: ngFormDirective,
+ ngHide: ngHideDirective,
+ ngIf: ngIfDirective,
+ ngInclude: ngIncludeDirective,
+ ngInit: ngInitDirective,
+ ngNonBindable: ngNonBindableDirective,
+ ngPluralize: ngPluralizeDirective,
+ ngRepeat: ngRepeatDirective,
+ ngShow: ngShowDirective,
+ ngStyle: ngStyleDirective,
+ ngSwitch: ngSwitchDirective,
+ ngSwitchWhen: ngSwitchWhenDirective,
+ ngSwitchDefault: ngSwitchDefaultDirective,
+ ngOptions: ngOptionsDirective,
+ ngTransclude: ngTranscludeDirective,
+ ngModel: ngModelDirective,
+ ngList: ngListDirective,
+ ngChange: ngChangeDirective,
+ required: requiredDirective,
+ ngRequired: requiredDirective,
+ ngValue: ngValueDirective
+ }).
+ directive({
+ ngInclude: ngIncludeFillContentDirective
+ }).
+ directive(ngAttributeAliasDirectives).
+ directive(ngEventDirectives);
+ $provide.provider({
+ $anchorScroll: $AnchorScrollProvider,
+ $animate: $AnimateProvider,
+ $browser: $BrowserProvider,
+ $cacheFactory: $CacheFactoryProvider,
+ $controller: $ControllerProvider,
+ $document: $DocumentProvider,
+ $exceptionHandler: $ExceptionHandlerProvider,
+ $filter: $FilterProvider,
+ $interpolate: $InterpolateProvider,
+ $interval: $IntervalProvider,
+ $http: $HttpProvider,
+ $httpBackend: $HttpBackendProvider,
+ $location: $LocationProvider,
+ $log: $LogProvider,
+ $parse: $ParseProvider,
+ $rootScope: $RootScopeProvider,
+ $q: $QProvider,
+ $sce: $SceProvider,
+ $sceDelegate: $SceDelegateProvider,
+ $sniffer: $SnifferProvider,
+ $templateCache: $TemplateCacheProvider,
+ $timeout: $TimeoutProvider,
+ $window: $WindowProvider,
+ $$rAF: $$RAFProvider,
+ $$asyncCallback : $$AsyncCallbackProvider
+ });
+ }
+ ]);
+}
+
+/* global
+
+ -JQLitePrototype,
+ -addEventListenerFn,
+ -removeEventListenerFn,
+ -BOOLEAN_ATTR
+*/
+
+//////////////////////////////////
+//JQLite
+//////////////////////////////////
+
+/**
+ * @ngdoc function
+ * @name angular.element
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
+ *
+ * If jQuery is available, `angular.element` is an alias for the
+ * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
+ * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
+ *
+ *
jqLite is a tiny, API-compatible subset of jQuery that allows
+ * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
+ * commonly needed functionality with the goal of having a very small footprint.
+ *
+ * To use jQuery, simply load it before `DOMContentLoaded` event fired.
+ *
+ *
**Note:** all element references in Angular are always wrapped with jQuery or
+ * jqLite; they are never raw DOM references.
+ *
+ * ## Angular's jqLite
+ * jqLite provides only the following jQuery methods:
+ *
+ * - [`addClass()`](http://api.jquery.com/addClass/)
+ * - [`after()`](http://api.jquery.com/after/)
+ * - [`append()`](http://api.jquery.com/append/)
+ * - [`attr()`](http://api.jquery.com/attr/)
+ * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
+ * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
+ * - [`clone()`](http://api.jquery.com/clone/)
+ * - [`contents()`](http://api.jquery.com/contents/)
+ * - [`css()`](http://api.jquery.com/css/)
+ * - [`data()`](http://api.jquery.com/data/)
+ * - [`empty()`](http://api.jquery.com/empty/)
+ * - [`eq()`](http://api.jquery.com/eq/)
+ * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
+ * - [`hasClass()`](http://api.jquery.com/hasClass/)
+ * - [`html()`](http://api.jquery.com/html/)
+ * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
+ * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
+ * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
+ * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
+ * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
+ * - [`prepend()`](http://api.jquery.com/prepend/)
+ * - [`prop()`](http://api.jquery.com/prop/)
+ * - [`ready()`](http://api.jquery.com/ready/)
+ * - [`remove()`](http://api.jquery.com/remove/)
+ * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
+ * - [`removeClass()`](http://api.jquery.com/removeClass/)
+ * - [`removeData()`](http://api.jquery.com/removeData/)
+ * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
+ * - [`text()`](http://api.jquery.com/text/)
+ * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
+ * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
+ * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
+ * - [`val()`](http://api.jquery.com/val/)
+ * - [`wrap()`](http://api.jquery.com/wrap/)
+ *
+ * ## jQuery/jqLite Extras
+ * Angular also provides the following additional methods and events to both jQuery and jqLite:
+ *
+ * ### Events
+ * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
+ * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
+ * element before it is removed.
+ *
+ * ### Methods
+ * - `controller(name)` - retrieves the controller of the current element or its parent. By default
+ * retrieves controller associated with the `ngController` directive. If `name` is provided as
+ * camelCase directive name, then the controller for this directive will be retrieved (e.g.
+ * `'ngModel'`).
+ * - `injector()` - retrieves the injector of the current element or its parent.
+ * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
+ * element or its parent.
+ * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
+ * current element. This getter should be used only on elements that contain a directive which starts a new isolate
+ * scope. Calling `scope()` on this element always returns the original non-isolate scope.
+ * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
+ * parent element is reached.
+ *
+ * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
+ * @returns {Object} jQuery object.
+ */
+
+JQLite.expando = 'ng339';
+
+var jqCache = JQLite.cache = {},
+ jqId = 1,
+ addEventListenerFn = (window.document.addEventListener
+ ? function(element, type, fn) {element.addEventListener(type, fn, false);}
+ : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
+ removeEventListenerFn = (window.document.removeEventListener
+ ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
+ : function(element, type, fn) {element.detachEvent('on' + type, fn); });
+
+/*
+ * !!! This is an undocumented "private" function !!!
+ */
+var jqData = JQLite._data = function(node) {
+ //jQuery always returns an object on cache miss
+ return this.cache[node[this.expando]] || {};
+};
+
+function jqNextId() { return ++jqId; }
+
+
+var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
+var MOZ_HACK_REGEXP = /^moz([A-Z])/;
+var jqLiteMinErr = minErr('jqLite');
+
+/**
+ * Converts snake_case to camelCase.
+ * Also there is special case for Moz prefix starting with upper case letter.
+ * @param name Name to normalize
+ */
+function camelCase(name) {
+ return name.
+ replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
+ return offset ? letter.toUpperCase() : letter;
+ }).
+ replace(MOZ_HACK_REGEXP, 'Moz$1');
+}
+
+/////////////////////////////////////////////
+// jQuery mutation patch
+//
+// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
+// $destroy event on all DOM nodes being removed.
+//
+/////////////////////////////////////////////
+
+function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) {
+ var originalJqFn = jQuery.fn[name];
+ originalJqFn = originalJqFn.$original || originalJqFn;
+ removePatch.$original = originalJqFn;
+ jQuery.fn[name] = removePatch;
+
+ function removePatch(param) {
+ // jshint -W040
+ var list = filterElems && param ? [this.filter(param)] : [this],
+ fireEvent = dispatchThis,
+ set, setIndex, setLength,
+ element, childIndex, childLength, children;
+
+ if (!getterIfNoArguments || param != null) {
+ while(list.length) {
+ set = list.shift();
+ for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
+ element = jqLite(set[setIndex]);
+ if (fireEvent) {
+ element.triggerHandler('$destroy');
+ } else {
+ fireEvent = !fireEvent;
+ }
+ for(childIndex = 0, childLength = (children = element.children()).length;
+ childIndex < childLength;
+ childIndex++) {
+ list.push(jQuery(children[childIndex]));
+ }
+ }
+ }
+ }
+ return originalJqFn.apply(this, arguments);
+ }
+}
+
+var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
+var HTML_REGEXP = /<|?\w+;/;
+var TAG_NAME_REGEXP = /<([\w:]+)/;
+var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
+
+var wrapMap = {
+ 'option': [1, ''],
+
+ 'thead': [1, '
', '
'],
+ 'col': [2, '
', '
'],
+ 'tr': [2, '
', '
'],
+ 'td': [3, '
', '
'],
+ '_default': [0, "", ""]
+};
+
+wrapMap.optgroup = wrapMap.option;
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+function jqLiteIsTextNode(html) {
+ return !HTML_REGEXP.test(html);
+}
+
+function jqLiteBuildFragment(html, context) {
+ var elem, tmp, tag, wrap,
+ fragment = context.createDocumentFragment(),
+ nodes = [], i, j, jj;
+
+ if (jqLiteIsTextNode(html)) {
+ // Convert non-html into a text node
+ nodes.push(context.createTextNode(html));
+ } else {
+ tmp = fragment.appendChild(context.createElement('div'));
+ // Convert html into DOM nodes
+ tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
+ wrap = wrapMap[tag] || wrapMap._default;
+ tmp.innerHTML = '
' +
+ wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1>$2>") + wrap[2];
+ tmp.removeChild(tmp.firstChild);
+
+ // Descend through wrappers to the right content
+ i = wrap[0];
+ while (i--) {
+ tmp = tmp.lastChild;
+ }
+
+ for (j=0, jj=tmp.childNodes.length; j -1);
+}
+
+function jqLiteRemoveClass(element, cssClasses) {
+ if (cssClasses && element.setAttribute) {
+ forEach(cssClasses.split(' '), function(cssClass) {
+ element.setAttribute('class', trim(
+ (" " + (element.getAttribute('class') || '') + " ")
+ .replace(/[\n\t]/g, " ")
+ .replace(" " + trim(cssClass) + " ", " "))
+ );
+ });
+ }
+}
+
+function jqLiteAddClass(element, cssClasses) {
+ if (cssClasses && element.setAttribute) {
+ var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
+ .replace(/[\n\t]/g, " ");
+
+ forEach(cssClasses.split(' '), function(cssClass) {
+ cssClass = trim(cssClass);
+ if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
+ existingClasses += cssClass + ' ';
+ }
+ });
+
+ element.setAttribute('class', trim(existingClasses));
+ }
+}
+
+function jqLiteAddNodes(root, elements) {
+ if (elements) {
+ elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
+ ? elements
+ : [ elements ];
+ for(var i=0; i < elements.length; i++) {
+ root.push(elements[i]);
+ }
+ }
+}
+
+function jqLiteController(element, name) {
+ return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
+}
+
+function jqLiteInheritedData(element, name, value) {
+ element = jqLite(element);
+
+ // if element is the document object work with the html element instead
+ // this makes $(document).scope() possible
+ if(element[0].nodeType == 9) {
+ element = element.find('html');
+ }
+ var names = isArray(name) ? name : [name];
+
+ while (element.length) {
+ var node = element[0];
+ for (var i = 0, ii = names.length; i < ii; i++) {
+ if ((value = element.data(names[i])) !== undefined) return value;
+ }
+
+ // If dealing with a document fragment node with a host element, and no parent, use the host
+ // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
+ // to lookup parent controllers.
+ element = jqLite(node.parentNode || (node.nodeType === 11 && node.host));
+ }
+}
+
+function jqLiteEmpty(element) {
+ for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
+ jqLiteDealoc(childNodes[i]);
+ }
+ while (element.firstChild) {
+ element.removeChild(element.firstChild);
+ }
+}
+
+//////////////////////////////////////////
+// Functions which are declared directly.
+//////////////////////////////////////////
+var JQLitePrototype = JQLite.prototype = {
+ ready: function(fn) {
+ var fired = false;
+
+ function trigger() {
+ if (fired) return;
+ fired = true;
+ fn();
+ }
+
+ // check if document already is loaded
+ if (document.readyState === 'complete'){
+ setTimeout(trigger);
+ } else {
+ this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
+ // we can not use jqLite since we are not done loading and jQuery could be loaded later.
+ // jshint -W064
+ JQLite(window).on('load', trigger); // fallback to window.onload for others
+ // jshint +W064
+ }
+ },
+ toString: function() {
+ var value = [];
+ forEach(this, function(e){ value.push('' + e);});
+ return '[' + value.join(', ') + ']';
+ },
+
+ eq: function(index) {
+ return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
+ },
+
+ length: 0,
+ push: push,
+ sort: [].sort,
+ splice: [].splice
+};
+
+//////////////////////////////////////////
+// Functions iterating getter/setters.
+// these functions return self on setter and
+// value on get.
+//////////////////////////////////////////
+var BOOLEAN_ATTR = {};
+forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
+ BOOLEAN_ATTR[lowercase(value)] = value;
+});
+var BOOLEAN_ELEMENTS = {};
+forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
+ BOOLEAN_ELEMENTS[uppercase(value)] = true;
+});
+
+function getBooleanAttrName(element, name) {
+ // check dom last since we will most likely fail on name
+ var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
+
+ // booleanAttr is here twice to minimize DOM access
+ return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
+}
+
+forEach({
+ data: jqLiteData,
+ inheritedData: jqLiteInheritedData,
+
+ scope: function(element) {
+ // Can't use jqLiteData here directly so we stay compatible with jQuery!
+ return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
+ },
+
+ isolateScope: function(element) {
+ // Can't use jqLiteData here directly so we stay compatible with jQuery!
+ return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate');
+ },
+
+ controller: jqLiteController,
+
+ injector: function(element) {
+ return jqLiteInheritedData(element, '$injector');
+ },
+
+ removeAttr: function(element,name) {
+ element.removeAttribute(name);
+ },
+
+ hasClass: jqLiteHasClass,
+
+ css: function(element, name, value) {
+ name = camelCase(name);
+
+ if (isDefined(value)) {
+ element.style[name] = value;
+ } else {
+ var val;
+
+ if (msie <= 8) {
+ // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
+ val = element.currentStyle && element.currentStyle[name];
+ if (val === '') val = 'auto';
+ }
+
+ val = val || element.style[name];
+
+ if (msie <= 8) {
+ // jquery weirdness :-/
+ val = (val === '') ? undefined : val;
+ }
+
+ return val;
+ }
+ },
+
+ attr: function(element, name, value){
+ var lowercasedName = lowercase(name);
+ if (BOOLEAN_ATTR[lowercasedName]) {
+ if (isDefined(value)) {
+ if (!!value) {
+ element[name] = true;
+ element.setAttribute(name, lowercasedName);
+ } else {
+ element[name] = false;
+ element.removeAttribute(lowercasedName);
+ }
+ } else {
+ return (element[name] ||
+ (element.attributes.getNamedItem(name)|| noop).specified)
+ ? lowercasedName
+ : undefined;
+ }
+ } else if (isDefined(value)) {
+ element.setAttribute(name, value);
+ } else if (element.getAttribute) {
+ // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
+ // some elements (e.g. Document) don't have get attribute, so return undefined
+ var ret = element.getAttribute(name, 2);
+ // normalize non-existing attributes to undefined (as jQuery)
+ return ret === null ? undefined : ret;
+ }
+ },
+
+ prop: function(element, name, value) {
+ if (isDefined(value)) {
+ element[name] = value;
+ } else {
+ return element[name];
+ }
+ },
+
+ text: (function() {
+ var NODE_TYPE_TEXT_PROPERTY = [];
+ if (msie < 9) {
+ NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/
+ NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/
+ } else {
+ NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/
+ NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/
+ }
+ getText.$dv = '';
+ return getText;
+
+ function getText(element, value) {
+ var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType];
+ if (isUndefined(value)) {
+ return textProp ? element[textProp] : '';
+ }
+ element[textProp] = value;
+ }
+ })(),
+
+ val: function(element, value) {
+ if (isUndefined(value)) {
+ if (nodeName_(element) === 'SELECT' && element.multiple) {
+ var result = [];
+ forEach(element.options, function (option) {
+ if (option.selected) {
+ result.push(option.value || option.text);
+ }
+ });
+ return result.length === 0 ? null : result;
+ }
+ return element.value;
+ }
+ element.value = value;
+ },
+
+ html: function(element, value) {
+ if (isUndefined(value)) {
+ return element.innerHTML;
+ }
+ for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
+ jqLiteDealoc(childNodes[i]);
+ }
+ element.innerHTML = value;
+ },
+
+ empty: jqLiteEmpty
+}, function(fn, name){
+ /**
+ * Properties: writes return selection, reads return first value
+ */
+ JQLite.prototype[name] = function(arg1, arg2) {
+ var i, key;
+ var nodeCount = this.length;
+
+ // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
+ // in a way that survives minification.
+ // jqLiteEmpty takes no arguments but is a setter.
+ if (fn !== jqLiteEmpty &&
+ (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
+ if (isObject(arg1)) {
+
+ // we are a write, but the object properties are the key/values
+ for (i = 0; i < nodeCount; i++) {
+ if (fn === jqLiteData) {
+ // data() takes the whole object in jQuery
+ fn(this[i], arg1);
+ } else {
+ for (key in arg1) {
+ fn(this[i], key, arg1[key]);
+ }
+ }
+ }
+ // return self for chaining
+ return this;
+ } else {
+ // we are a read, so read the first child.
+ // TODO: do we still need this?
+ var value = fn.$dv;
+ // Only if we have $dv do we iterate over all, otherwise it is just the first element.
+ var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
+ for (var j = 0; j < jj; j++) {
+ var nodeValue = fn(this[j], arg1, arg2);
+ value = value ? value + nodeValue : nodeValue;
+ }
+ return value;
+ }
+ } else {
+ // we are a write, so apply to all children
+ for (i = 0; i < nodeCount; i++) {
+ fn(this[i], arg1, arg2);
+ }
+ // return self for chaining
+ return this;
+ }
+ };
+});
+
+function createEventHandler(element, events) {
+ var eventHandler = function (event, type) {
+ if (!event.preventDefault) {
+ event.preventDefault = function() {
+ event.returnValue = false; //ie
+ };
+ }
+
+ if (!event.stopPropagation) {
+ event.stopPropagation = function() {
+ event.cancelBubble = true; //ie
+ };
+ }
+
+ if (!event.target) {
+ event.target = event.srcElement || document;
+ }
+
+ if (isUndefined(event.defaultPrevented)) {
+ var prevent = event.preventDefault;
+ event.preventDefault = function() {
+ event.defaultPrevented = true;
+ prevent.call(event);
+ };
+ event.defaultPrevented = false;
+ }
+
+ event.isDefaultPrevented = function() {
+ return event.defaultPrevented || event.returnValue === false;
+ };
+
+ // Copy event handlers in case event handlers array is modified during execution.
+ var eventHandlersCopy = shallowCopy(events[type || event.type] || []);
+
+ forEach(eventHandlersCopy, function(fn) {
+ fn.call(element, event);
+ });
+
+ // Remove monkey-patched methods (IE),
+ // as they would cause memory leaks in IE8.
+ if (msie <= 8) {
+ // IE7/8 does not allow to delete property on native object
+ event.preventDefault = null;
+ event.stopPropagation = null;
+ event.isDefaultPrevented = null;
+ } else {
+ // It shouldn't affect normal browsers (native methods are defined on prototype).
+ delete event.preventDefault;
+ delete event.stopPropagation;
+ delete event.isDefaultPrevented;
+ }
+ };
+ eventHandler.elem = element;
+ return eventHandler;
+}
+
+//////////////////////////////////////////
+// Functions iterating traversal.
+// These functions chain results into a single
+// selector.
+//////////////////////////////////////////
+forEach({
+ removeData: jqLiteRemoveData,
+
+ dealoc: jqLiteDealoc,
+
+ on: function onFn(element, type, fn, unsupported){
+ if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
+
+ var events = jqLiteExpandoStore(element, 'events'),
+ handle = jqLiteExpandoStore(element, 'handle');
+
+ if (!events) jqLiteExpandoStore(element, 'events', events = {});
+ if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
+
+ forEach(type.split(' '), function(type){
+ var eventFns = events[type];
+
+ if (!eventFns) {
+ if (type == 'mouseenter' || type == 'mouseleave') {
+ var contains = document.body.contains || document.body.compareDocumentPosition ?
+ function( a, b ) {
+ // jshint bitwise: false
+ 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;
+ };
+
+ events[type] = [];
+
+ // Refer to jQuery's implementation of mouseenter & mouseleave
+ // Read about mouseenter and mouseleave:
+ // http://www.quirksmode.org/js/events_mouse.html#link8
+ var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"};
+
+ onFn(element, eventmap[type], function(event) {
+ var target = this, related = event.relatedTarget;
+ // 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 && !contains(target, related)) ){
+ handle(event, type);
+ }
+ });
+
+ } else {
+ addEventListenerFn(element, type, handle);
+ events[type] = [];
+ }
+ eventFns = events[type];
+ }
+ eventFns.push(fn);
+ });
+ },
+
+ off: jqLiteOff,
+
+ one: function(element, type, fn) {
+ element = jqLite(element);
+
+ //add the listener twice so that when it is called
+ //you can remove the original function and still be
+ //able to call element.off(ev, fn) normally
+ element.on(type, function onFn() {
+ element.off(type, fn);
+ element.off(type, onFn);
+ });
+ element.on(type, fn);
+ },
+
+ replaceWith: function(element, replaceNode) {
+ var index, parent = element.parentNode;
+ jqLiteDealoc(element);
+ forEach(new JQLite(replaceNode), function(node){
+ if (index) {
+ parent.insertBefore(node, index.nextSibling);
+ } else {
+ parent.replaceChild(node, element);
+ }
+ index = node;
+ });
+ },
+
+ children: function(element) {
+ var children = [];
+ forEach(element.childNodes, function(element){
+ if (element.nodeType === 1)
+ children.push(element);
+ });
+ return children;
+ },
+
+ contents: function(element) {
+ return element.contentDocument || element.childNodes || [];
+ },
+
+ append: function(element, node) {
+ forEach(new JQLite(node), function(child){
+ if (element.nodeType === 1 || element.nodeType === 11) {
+ element.appendChild(child);
+ }
+ });
+ },
+
+ prepend: function(element, node) {
+ if (element.nodeType === 1) {
+ var index = element.firstChild;
+ forEach(new JQLite(node), function(child){
+ element.insertBefore(child, index);
+ });
+ }
+ },
+
+ wrap: function(element, wrapNode) {
+ wrapNode = jqLite(wrapNode)[0];
+ var parent = element.parentNode;
+ if (parent) {
+ parent.replaceChild(wrapNode, element);
+ }
+ wrapNode.appendChild(element);
+ },
+
+ remove: function(element) {
+ jqLiteDealoc(element);
+ var parent = element.parentNode;
+ if (parent) parent.removeChild(element);
+ },
+
+ after: function(element, newElement) {
+ var index = element, parent = element.parentNode;
+ forEach(new JQLite(newElement), function(node){
+ parent.insertBefore(node, index.nextSibling);
+ index = node;
+ });
+ },
+
+ addClass: jqLiteAddClass,
+ removeClass: jqLiteRemoveClass,
+
+ toggleClass: function(element, selector, condition) {
+ if (selector) {
+ forEach(selector.split(' '), function(className){
+ var classCondition = condition;
+ if (isUndefined(classCondition)) {
+ classCondition = !jqLiteHasClass(element, className);
+ }
+ (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
+ });
+ }
+ },
+
+ parent: function(element) {
+ var parent = element.parentNode;
+ return parent && parent.nodeType !== 11 ? parent : null;
+ },
+
+ next: function(element) {
+ if (element.nextElementSibling) {
+ return element.nextElementSibling;
+ }
+
+ // IE8 doesn't have nextElementSibling
+ var elm = element.nextSibling;
+ while (elm != null && elm.nodeType !== 1) {
+ elm = elm.nextSibling;
+ }
+ return elm;
+ },
+
+ find: function(element, selector) {
+ if (element.getElementsByTagName) {
+ return element.getElementsByTagName(selector);
+ } else {
+ return [];
+ }
+ },
+
+ clone: jqLiteClone,
+
+ triggerHandler: function(element, eventName, eventData) {
+ var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName];
+
+ eventData = eventData || [];
+
+ var event = [{
+ preventDefault: noop,
+ stopPropagation: noop
+ }];
+
+ forEach(eventFns, function(fn) {
+ fn.apply(element, event.concat(eventData));
+ });
+ }
+}, function(fn, name){
+ /**
+ * chaining functions
+ */
+ JQLite.prototype[name] = function(arg1, arg2, arg3) {
+ var value;
+ for(var i=0; i < this.length; i++) {
+ if (isUndefined(value)) {
+ value = fn(this[i], arg1, arg2, arg3);
+ if (isDefined(value)) {
+ // any function which returns a value needs to be wrapped
+ value = jqLite(value);
+ }
+ } else {
+ jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
+ }
+ }
+ return isDefined(value) ? value : this;
+ };
+
+ // bind legacy bind/unbind to on/off
+ JQLite.prototype.bind = JQLite.prototype.on;
+ JQLite.prototype.unbind = JQLite.prototype.off;
+});
+
+/**
+ * Computes a hash of an 'obj'.
+ * Hash of a:
+ * string is string
+ * number is number as string
+ * object is either result of calling $$hashKey function on the object or uniquely generated id,
+ * that is also assigned to the $$hashKey property of the object.
+ *
+ * @param obj
+ * @returns {string} hash string such that the same input will have the same hash string.
+ * The resulting string key is in 'type:hashKey' format.
+ */
+function hashKey(obj, nextUidFn) {
+ var objType = typeof obj,
+ key;
+
+ if (objType == 'function' || (objType == 'object' && obj !== null)) {
+ if (typeof (key = obj.$$hashKey) == 'function') {
+ // must invoke on object to keep the right this
+ key = obj.$$hashKey();
+ } else if (key === undefined) {
+ key = obj.$$hashKey = (nextUidFn || nextUid)();
+ }
+ } else {
+ key = obj;
+ }
+
+ return objType + ':' + key;
+}
+
+/**
+ * HashMap which can use objects as keys
+ */
+function HashMap(array, isolatedUid) {
+ if (isolatedUid) {
+ var uid = 0;
+ this.nextUid = function() {
+ return ++uid;
+ };
+ }
+ forEach(array, this.put, this);
+}
+HashMap.prototype = {
+ /**
+ * Store key value pair
+ * @param key key to store can be any type
+ * @param value value to store can be any type
+ */
+ put: function(key, value) {
+ this[hashKey(key, this.nextUid)] = value;
+ },
+
+ /**
+ * @param key
+ * @returns {Object} the value for the key
+ */
+ get: function(key) {
+ return this[hashKey(key, this.nextUid)];
+ },
+
+ /**
+ * Remove the key/value pair
+ * @param key
+ */
+ remove: function(key) {
+ var value = this[key = hashKey(key, this.nextUid)];
+ delete this[key];
+ return value;
+ }
+};
+
+/**
+ * @ngdoc function
+ * @module ng
+ * @name angular.injector
+ * @kind function
+ *
+ * @description
+ * Creates an injector function that can be used for retrieving services as well as for
+ * dependency injection (see {@link guide/di dependency injection}).
+ *
+
+ * @param {Array.} modules A list of module functions or their aliases. See
+ * {@link angular.module}. The `ng` module must be explicitly added.
+ * @returns {function()} Injector function. See {@link auto.$injector $injector}.
+ *
+ * @example
+ * Typical usage
+ * ```js
+ * // create an injector
+ * var $injector = angular.injector(['ng']);
+ *
+ * // use the injector to kick off your application
+ * // use the type inference to auto inject arguments, or use implicit injection
+ * $injector.invoke(function($rootScope, $compile, $document){
+ * $compile($document)($rootScope);
+ * $rootScope.$digest();
+ * });
+ * ```
+ *
+ * Sometimes you want to get access to the injector of a currently running Angular app
+ * from outside Angular. Perhaps, you want to inject and compile some markup after the
+ * application has been bootstrapped. You can do this using the extra `injector()` added
+ * to JQuery/jqLite elements. See {@link angular.element}.
+ *
+ * *This is fairly rare but could be the case if a third party library is injecting the
+ * markup.*
+ *
+ * In the following example a new block of HTML containing a `ng-controller`
+ * directive is added to the end of the document body by JQuery. We then compile and link
+ * it into the current AngularJS scope.
+ *
+ * ```js
+ * var $div = $('
{{content.label}}
');
+ * $(document.body).append($div);
+ *
+ * angular.element(document).injector().invoke(function($compile) {
+ * var scope = angular.element($div).scope();
+ * $compile($div)(scope);
+ * });
+ * ```
+ */
+
+
+/**
+ * @ngdoc module
+ * @name auto
+ * @description
+ *
+ * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
+ */
+
+var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
+var FN_ARG_SPLIT = /,/;
+var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
+var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
+var $injectorMinErr = minErr('$injector');
+function annotate(fn) {
+ var $inject,
+ fnText,
+ argDecl,
+ last;
+
+ if (typeof fn === 'function') {
+ if (!($inject = fn.$inject)) {
+ $inject = [];
+ if (fn.length) {
+ fnText = fn.toString().replace(STRIP_COMMENTS, '');
+ argDecl = fnText.match(FN_ARGS);
+ forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
+ arg.replace(FN_ARG, function(all, underscore, name){
+ $inject.push(name);
+ });
+ });
+ }
+ fn.$inject = $inject;
+ }
+ } else if (isArray(fn)) {
+ last = fn.length - 1;
+ assertArgFn(fn[last], 'fn');
+ $inject = fn.slice(0, last);
+ } else {
+ assertArgFn(fn, 'fn', true);
+ }
+ return $inject;
+}
+
+///////////////////////////////////////
+
+/**
+ * @ngdoc service
+ * @name $injector
+ * @kind function
+ *
+ * @description
+ *
+ * `$injector` is used to retrieve object instances as defined by
+ * {@link auto.$provide provider}, instantiate types, invoke methods,
+ * and load modules.
+ *
+ * The following always holds true:
+ *
+ * ```js
+ * var $injector = angular.injector();
+ * expect($injector.get('$injector')).toBe($injector);
+ * expect($injector.invoke(function($injector){
+ * return $injector;
+ * }).toBe($injector);
+ * ```
+ *
+ * # Injection Function Annotation
+ *
+ * JavaScript does not have annotations, and annotations are needed for dependency injection. The
+ * following are all valid ways of annotating function with injection arguments and are equivalent.
+ *
+ * ```js
+ * // inferred (only works if code not minified/obfuscated)
+ * $injector.invoke(function(serviceA){});
+ *
+ * // annotated
+ * function explicit(serviceA) {};
+ * explicit.$inject = ['serviceA'];
+ * $injector.invoke(explicit);
+ *
+ * // inline
+ * $injector.invoke(['serviceA', function(serviceA){}]);
+ * ```
+ *
+ * ## Inference
+ *
+ * In JavaScript calling `toString()` on a function returns the function definition. The definition
+ * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
+ * minification, and obfuscation tools since these tools change the argument names.
+ *
+ * ## `$inject` Annotation
+ * By adding an `$inject` property onto a function the injection parameters can be specified.
+ *
+ * ## Inline
+ * As an array of injection names, where the last item in the array is the function to call.
+ */
+
+/**
+ * @ngdoc method
+ * @name $injector#get
+ *
+ * @description
+ * Return an instance of the service.
+ *
+ * @param {string} name The name of the instance to retrieve.
+ * @return {*} The instance.
+ */
+
+/**
+ * @ngdoc method
+ * @name $injector#invoke
+ *
+ * @description
+ * Invoke the method and supply the method arguments from the `$injector`.
+ *
+ * @param {!Function} fn The function to invoke. Function parameters are injected according to the
+ * {@link guide/di $inject Annotation} rules.
+ * @param {Object=} self The `this` for the invoked method.
+ * @param {Object=} locals Optional object. If preset then any argument names are read from this
+ * object first, before the `$injector` is consulted.
+ * @returns {*} the value returned by the invoked `fn` function.
+ */
+
+/**
+ * @ngdoc method
+ * @name $injector#has
+ *
+ * @description
+ * Allows the user to query if the particular service exists.
+ *
+ * @param {string} Name of the service to query.
+ * @returns {boolean} returns true if injector has given service.
+ */
+
+/**
+ * @ngdoc method
+ * @name $injector#instantiate
+ * @description
+ * Create a new instance of JS type. The method takes a constructor function, invokes the new
+ * operator, and supplies all of the arguments to the constructor function as specified by the
+ * constructor annotation.
+ *
+ * @param {Function} Type Annotated constructor function.
+ * @param {Object=} locals Optional object. If preset then any argument names are read from this
+ * object first, before the `$injector` is consulted.
+ * @returns {Object} new instance of `Type`.
+ */
+
+/**
+ * @ngdoc method
+ * @name $injector#annotate
+ *
+ * @description
+ * Returns an array of service names which the function is requesting for injection. This API is
+ * used by the injector to determine which services need to be injected into the function when the
+ * function is invoked. There are three ways in which the function can be annotated with the needed
+ * dependencies.
+ *
+ * # Argument names
+ *
+ * The simplest form is to extract the dependencies from the arguments of the function. This is done
+ * by converting the function into a string using `toString()` method and extracting the argument
+ * names.
+ * ```js
+ * // Given
+ * function MyController($scope, $route) {
+ * // ...
+ * }
+ *
+ * // Then
+ * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
+ * ```
+ *
+ * This method does not work with code minification / obfuscation. For this reason the following
+ * annotation strategies are supported.
+ *
+ * # The `$inject` property
+ *
+ * If a function has an `$inject` property and its value is an array of strings, then the strings
+ * represent names of services to be injected into the function.
+ * ```js
+ * // Given
+ * var MyController = function(obfuscatedScope, obfuscatedRoute) {
+ * // ...
+ * }
+ * // Define function dependencies
+ * MyController['$inject'] = ['$scope', '$route'];
+ *
+ * // Then
+ * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
+ * ```
+ *
+ * # The array notation
+ *
+ * It is often desirable to inline Injected functions and that's when setting the `$inject` property
+ * is very inconvenient. In these situations using the array notation to specify the dependencies in
+ * a way that survives minification is a better choice:
+ *
+ * ```js
+ * // We wish to write this (not minification / obfuscation safe)
+ * injector.invoke(function($compile, $rootScope) {
+ * // ...
+ * });
+ *
+ * // We are forced to write break inlining
+ * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
+ * // ...
+ * };
+ * tmpFn.$inject = ['$compile', '$rootScope'];
+ * injector.invoke(tmpFn);
+ *
+ * // To better support inline function the inline annotation is supported
+ * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
+ * // ...
+ * }]);
+ *
+ * // Therefore
+ * expect(injector.annotate(
+ * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
+ * ).toEqual(['$compile', '$rootScope']);
+ * ```
+ *
+ * @param {Function|Array.} fn Function for which dependent service names need to
+ * be retrieved as described above.
+ *
+ * @returns {Array.} The names of the services which the function requires.
+ */
+
+
+
+
+/**
+ * @ngdoc service
+ * @name $provide
+ *
+ * @description
+ *
+ * The {@link auto.$provide $provide} service has a number of methods for registering components
+ * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
+ * {@link angular.Module}.
+ *
+ * An Angular **service** is a singleton object created by a **service factory**. These **service
+ * factories** are functions which, in turn, are created by a **service provider**.
+ * The **service providers** are constructor functions. When instantiated they must contain a
+ * property called `$get`, which holds the **service factory** function.
+ *
+ * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
+ * correct **service provider**, instantiating it and then calling its `$get` **service factory**
+ * function to get the instance of the **service**.
+ *
+ * Often services have no configuration options and there is no need to add methods to the service
+ * provider. The provider will be no more than a constructor function with a `$get` property. For
+ * these cases the {@link auto.$provide $provide} service has additional helper methods to register
+ * services without specifying a provider.
+ *
+ * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
+ * {@link auto.$injector $injector}
+ * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
+ * providers and services.
+ * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
+ * services, not providers.
+ * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
+ * that will be wrapped in a **service provider** object, whose `$get` property will contain the
+ * given factory function.
+ * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
+ * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
+ * a new object using the given constructor function.
+ *
+ * See the individual methods for more information and examples.
+ */
+
+/**
+ * @ngdoc method
+ * @name $provide#provider
+ * @description
+ *
+ * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
+ * are constructor functions, whose instances are responsible for "providing" a factory for a
+ * service.
+ *
+ * Service provider names start with the name of the service they provide followed by `Provider`.
+ * For example, the {@link ng.$log $log} service has a provider called
+ * {@link ng.$logProvider $logProvider}.
+ *
+ * Service provider objects can have additional methods which allow configuration of the provider
+ * and its service. Importantly, you can configure what kind of service is created by the `$get`
+ * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
+ * method {@link ng.$logProvider#debugEnabled debugEnabled}
+ * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
+ * console or not.
+ *
+ * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
+ 'Provider'` key.
+ * @param {(Object|function())} provider If the provider is:
+ *
+ * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
+ * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
+ * - `Constructor`: a new instance of the provider will be created using
+ * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
+ *
+ * @returns {Object} registered provider instance
+
+ * @example
+ *
+ * The following example shows how to create a simple event tracking service and register it using
+ * {@link auto.$provide#provider $provide.provider()}.
+ *
+ * ```js
+ * // Define the eventTracker provider
+ * function EventTrackerProvider() {
+ * var trackingUrl = '/track';
+ *
+ * // A provider method for configuring where the tracked events should been saved
+ * this.setTrackingUrl = function(url) {
+ * trackingUrl = url;
+ * };
+ *
+ * // The service factory function
+ * this.$get = ['$http', function($http) {
+ * var trackedEvents = {};
+ * return {
+ * // Call this to track an event
+ * event: function(event) {
+ * var count = trackedEvents[event] || 0;
+ * count += 1;
+ * trackedEvents[event] = count;
+ * return count;
+ * },
+ * // Call this to save the tracked events to the trackingUrl
+ * save: function() {
+ * $http.post(trackingUrl, trackedEvents);
+ * }
+ * };
+ * }];
+ * }
+ *
+ * describe('eventTracker', function() {
+ * var postSpy;
+ *
+ * beforeEach(module(function($provide) {
+ * // Register the eventTracker provider
+ * $provide.provider('eventTracker', EventTrackerProvider);
+ * }));
+ *
+ * beforeEach(module(function(eventTrackerProvider) {
+ * // Configure eventTracker provider
+ * eventTrackerProvider.setTrackingUrl('/custom-track');
+ * }));
+ *
+ * it('tracks events', inject(function(eventTracker) {
+ * expect(eventTracker.event('login')).toEqual(1);
+ * expect(eventTracker.event('login')).toEqual(2);
+ * }));
+ *
+ * it('saves to the tracking url', inject(function(eventTracker, $http) {
+ * postSpy = spyOn($http, 'post');
+ * eventTracker.event('login');
+ * eventTracker.save();
+ * expect(postSpy).toHaveBeenCalled();
+ * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
+ * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
+ * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
+ * }));
+ * });
+ * ```
+ */
+
+/**
+ * @ngdoc method
+ * @name $provide#factory
+ * @description
+ *
+ * Register a **service factory**, which will be called to return the service instance.
+ * This is short for registering a service where its provider consists of only a `$get` property,
+ * which is the given service factory function.
+ * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
+ * configure your service in a provider.
+ *
+ * @param {string} name The name of the instance.
+ * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
+ * for `$provide.provider(name, {$get: $getFn})`.
+ * @returns {Object} registered provider instance
+ *
+ * @example
+ * Here is an example of registering a service
+ * ```js
+ * $provide.factory('ping', ['$http', function($http) {
+ * return function ping() {
+ * return $http.send('/ping');
+ * };
+ * }]);
+ * ```
+ * You would then inject and use this service like this:
+ * ```js
+ * someModule.controller('Ctrl', ['ping', function(ping) {
+ * ping();
+ * }]);
+ * ```
+ */
+
+
+/**
+ * @ngdoc method
+ * @name $provide#service
+ * @description
+ *
+ * Register a **service constructor**, which will be invoked with `new` to create the service
+ * instance.
+ * This is short for registering a service where its provider's `$get` property is the service
+ * constructor function that will be used to instantiate the service instance.
+ *
+ * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
+ * as a type/class.
+ *
+ * @param {string} name The name of the instance.
+ * @param {Function} constructor A class (constructor function) that will be instantiated.
+ * @returns {Object} registered provider instance
+ *
+ * @example
+ * Here is an example of registering a service using
+ * {@link auto.$provide#service $provide.service(class)}.
+ * ```js
+ * var Ping = function($http) {
+ * this.$http = $http;
+ * };
+ *
+ * Ping.$inject = ['$http'];
+ *
+ * Ping.prototype.send = function() {
+ * return this.$http.get('/ping');
+ * };
+ * $provide.service('ping', Ping);
+ * ```
+ * You would then inject and use this service like this:
+ * ```js
+ * someModule.controller('Ctrl', ['ping', function(ping) {
+ * ping.send();
+ * }]);
+ * ```
+ */
+
+
+/**
+ * @ngdoc method
+ * @name $provide#value
+ * @description
+ *
+ * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
+ * number, an array, an object or a function. This is short for registering a service where its
+ * provider's `$get` property is a factory function that takes no arguments and returns the **value
+ * service**.
+ *
+ * Value services are similar to constant services, except that they cannot be injected into a
+ * module configuration function (see {@link angular.Module#config}) but they can be overridden by
+ * an Angular
+ * {@link auto.$provide#decorator decorator}.
+ *
+ * @param {string} name The name of the instance.
+ * @param {*} value The value.
+ * @returns {Object} registered provider instance
+ *
+ * @example
+ * Here are some examples of creating value services.
+ * ```js
+ * $provide.value('ADMIN_USER', 'admin');
+ *
+ * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
+ *
+ * $provide.value('halfOf', function(value) {
+ * return value / 2;
+ * });
+ * ```
+ */
+
+
+/**
+ * @ngdoc method
+ * @name $provide#constant
+ * @description
+ *
+ * Register a **constant service**, such as a string, a number, an array, an object or a function,
+ * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
+ * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
+ * be overridden by an Angular {@link auto.$provide#decorator decorator}.
+ *
+ * @param {string} name The name of the constant.
+ * @param {*} value The constant value.
+ * @returns {Object} registered instance
+ *
+ * @example
+ * Here a some examples of creating constants:
+ * ```js
+ * $provide.constant('SHARD_HEIGHT', 306);
+ *
+ * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
+ *
+ * $provide.constant('double', function(value) {
+ * return value * 2;
+ * });
+ * ```
+ */
+
+
+/**
+ * @ngdoc method
+ * @name $provide#decorator
+ * @description
+ *
+ * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
+ * intercepts the creation of a service, allowing it to override or modify the behaviour of the
+ * service. The object returned by the decorator may be the original service, or a new service
+ * object which replaces or wraps and delegates to the original service.
+ *
+ * @param {string} name The name of the service to decorate.
+ * @param {function()} decorator This function will be invoked when the service needs to be
+ * instantiated and should return the decorated service instance. The function is called using
+ * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
+ * Local injection arguments:
+ *
+ * * `$delegate` - The original service instance, which can be monkey patched, configured,
+ * decorated or delegated to.
+ *
+ * @example
+ * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
+ * calls to {@link ng.$log#error $log.warn()}.
+ * ```js
+ * $provide.decorator('$log', ['$delegate', function($delegate) {
+ * $delegate.warn = $delegate.error;
+ * return $delegate;
+ * }]);
+ * ```
+ */
+
+
+function createInjector(modulesToLoad) {
+ var INSTANTIATING = {},
+ providerSuffix = 'Provider',
+ path = [],
+ loadedModules = new HashMap([], true),
+ providerCache = {
+ $provide: {
+ provider: supportObject(provider),
+ factory: supportObject(factory),
+ service: supportObject(service),
+ value: supportObject(value),
+ constant: supportObject(constant),
+ decorator: decorator
+ }
+ },
+ providerInjector = (providerCache.$injector =
+ createInternalInjector(providerCache, function() {
+ throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
+ })),
+ instanceCache = {},
+ instanceInjector = (instanceCache.$injector =
+ createInternalInjector(instanceCache, function(servicename) {
+ var provider = providerInjector.get(servicename + providerSuffix);
+ return instanceInjector.invoke(provider.$get, provider);
+ }));
+
+
+ forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
+
+ return instanceInjector;
+
+ ////////////////////////////////////
+ // $provider
+ ////////////////////////////////////
+
+ function supportObject(delegate) {
+ return function(key, value) {
+ if (isObject(key)) {
+ forEach(key, reverseParams(delegate));
+ } else {
+ return delegate(key, value);
+ }
+ };
+ }
+
+ function provider(name, provider_) {
+ assertNotHasOwnProperty(name, 'service');
+ if (isFunction(provider_) || isArray(provider_)) {
+ provider_ = providerInjector.instantiate(provider_);
+ }
+ if (!provider_.$get) {
+ throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
+ }
+ return providerCache[name + providerSuffix] = provider_;
+ }
+
+ function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
+
+ function service(name, constructor) {
+ return factory(name, ['$injector', function($injector) {
+ return $injector.instantiate(constructor);
+ }]);
+ }
+
+ function value(name, val) { return factory(name, valueFn(val)); }
+
+ function constant(name, value) {
+ assertNotHasOwnProperty(name, 'constant');
+ providerCache[name] = value;
+ instanceCache[name] = value;
+ }
+
+ function decorator(serviceName, decorFn) {
+ var origProvider = providerInjector.get(serviceName + providerSuffix),
+ orig$get = origProvider.$get;
+
+ origProvider.$get = function() {
+ var origInstance = instanceInjector.invoke(orig$get, origProvider);
+ return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
+ };
+ }
+
+ ////////////////////////////////////
+ // Module Loading
+ ////////////////////////////////////
+ function loadModules(modulesToLoad){
+ var runBlocks = [], moduleFn, invokeQueue, i, ii;
+ forEach(modulesToLoad, function(module) {
+ if (loadedModules.get(module)) return;
+ loadedModules.put(module, true);
+
+ try {
+ if (isString(module)) {
+ moduleFn = angularModule(module);
+ runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
+
+ for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
+ var invokeArgs = invokeQueue[i],
+ provider = providerInjector.get(invokeArgs[0]);
+
+ provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
+ }
+ } else if (isFunction(module)) {
+ runBlocks.push(providerInjector.invoke(module));
+ } else if (isArray(module)) {
+ runBlocks.push(providerInjector.invoke(module));
+ } else {
+ assertArgFn(module, 'module');
+ }
+ } catch (e) {
+ if (isArray(module)) {
+ module = module[module.length - 1];
+ }
+ if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
+ // Safari & FF's stack traces don't contain error.message content
+ // unlike those of Chrome and IE
+ // So if stack doesn't contain message, we create a new string that contains both.
+ // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
+ /* jshint -W022 */
+ e = e.message + '\n' + e.stack;
+ }
+ throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
+ module, e.stack || e.message || e);
+ }
+ });
+ return runBlocks;
+ }
+
+ ////////////////////////////////////
+ // internal Injector
+ ////////////////////////////////////
+
+ function createInternalInjector(cache, factory) {
+
+ function getService(serviceName) {
+ if (cache.hasOwnProperty(serviceName)) {
+ if (cache[serviceName] === INSTANTIATING) {
+ throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
+ serviceName + ' <- ' + path.join(' <- '));
+ }
+ return cache[serviceName];
+ } else {
+ try {
+ path.unshift(serviceName);
+ cache[serviceName] = INSTANTIATING;
+ return cache[serviceName] = factory(serviceName);
+ } catch (err) {
+ if (cache[serviceName] === INSTANTIATING) {
+ delete cache[serviceName];
+ }
+ throw err;
+ } finally {
+ path.shift();
+ }
+ }
+ }
+
+ function invoke(fn, self, locals){
+ var args = [],
+ $inject = annotate(fn),
+ length, i,
+ key;
+
+ for(i = 0, length = $inject.length; i < length; i++) {
+ key = $inject[i];
+ if (typeof key !== 'string') {
+ throw $injectorMinErr('itkn',
+ 'Incorrect injection token! Expected service name as string, got {0}', key);
+ }
+ args.push(
+ locals && locals.hasOwnProperty(key)
+ ? locals[key]
+ : getService(key)
+ );
+ }
+ if (isArray(fn)) {
+ fn = fn[length];
+ }
+
+ // http://jsperf.com/angularjs-invoke-apply-vs-switch
+ // #5388
+ return fn.apply(self, args);
+ }
+
+ function instantiate(Type, locals) {
+ var Constructor = function() {},
+ instance, returnedValue;
+
+ // Check if Type is annotated and use just the given function at n-1 as parameter
+ // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
+ Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
+ instance = new Constructor();
+ returnedValue = invoke(Type, instance, locals);
+
+ return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
+ }
+
+ return {
+ invoke: invoke,
+ instantiate: instantiate,
+ get: getService,
+ annotate: annotate,
+ has: function(name) {
+ return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
+ }
+ };
+ }
+}
+
+/**
+ * @ngdoc service
+ * @name $anchorScroll
+ * @kind function
+ * @requires $window
+ * @requires $location
+ * @requires $rootScope
+ *
+ * @description
+ * When called, it checks current value of `$location.hash()` and scrolls to the related element,
+ * according to rules specified in
+ * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
+ *
+ * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor.
+ * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
+ *
+ * @example
+
+
+
+
+
+ function ScrollCtrl($scope, $location, $anchorScroll) {
+ $scope.gotoBottom = function (){
+ // set the location.hash to the id of
+ // the element you wish to scroll to.
+ $location.hash('bottom');
+
+ // call $anchorScroll()
+ $anchorScroll();
+ };
+ }
+
+
+ #scrollArea {
+ height: 350px;
+ overflow: auto;
+ }
+
+ #bottom {
+ display: block;
+ margin-top: 2000px;
+ }
+
+
+ */
+function $AnchorScrollProvider() {
+
+ var autoScrollingEnabled = true;
+
+ this.disableAutoScrolling = function() {
+ autoScrollingEnabled = false;
+ };
+
+ this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
+ var document = $window.document;
+
+ // helper function to get first anchor from a NodeList
+ // can't use filter.filter, as it accepts only instances of Array
+ // and IE can't convert NodeList to an array using [].slice
+ // TODO(vojta): use filter if we change it to accept lists as well
+ function getFirstAnchor(list) {
+ var result = null;
+ forEach(list, function(element) {
+ if (!result && lowercase(element.nodeName) === 'a') result = element;
+ });
+ return result;
+ }
+
+ function scroll() {
+ var hash = $location.hash(), elm;
+
+ // empty hash, scroll to the top of the page
+ if (!hash) $window.scrollTo(0, 0);
+
+ // element with given id
+ else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
+
+ // first anchor with given name :-D
+ else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
+
+ // no element and hash == 'top', scroll to the top of the page
+ else if (hash === 'top') $window.scrollTo(0, 0);
+ }
+
+ // does not scroll when user clicks on anchor link that is currently on
+ // (no url change, no $location.hash() change), browser native does scroll
+ if (autoScrollingEnabled) {
+ $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
+ function autoScrollWatchAction() {
+ $rootScope.$evalAsync(scroll);
+ });
+ }
+
+ return scroll;
+ }];
+}
+
+var $animateMinErr = minErr('$animate');
+
+/**
+ * @ngdoc provider
+ * @name $animateProvider
+ *
+ * @description
+ * Default implementation of $animate that doesn't perform any animations, instead just
+ * synchronously performs DOM
+ * updates and calls done() callbacks.
+ *
+ * In order to enable animations the ngAnimate module has to be loaded.
+ *
+ * To see the functional implementation check out src/ngAnimate/animate.js
+ */
+var $AnimateProvider = ['$provide', function($provide) {
+
+
+ this.$$selectors = {};
+
+
+ /**
+ * @ngdoc method
+ * @name $animateProvider#register
+ *
+ * @description
+ * Registers a new injectable animation factory function. The factory function produces the
+ * animation object which contains callback functions for each event that is expected to be
+ * animated.
+ *
+ * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
+ * must be called once the element animation is complete. If a function is returned then the
+ * animation service will use this function to cancel the animation whenever a cancel event is
+ * triggered.
+ *
+ *
+ * ```js
+ * return {
+ * eventFn : function(element, done) {
+ * //code to run the animation
+ * //once complete, then run done()
+ * return function cancellationFunction() {
+ * //code to cancel the animation
+ * }
+ * }
+ * }
+ * ```
+ *
+ * @param {string} name The name of the animation.
+ * @param {Function} factory The factory function that will be executed to return the animation
+ * object.
+ */
+ this.register = function(name, factory) {
+ var key = name + '-animation';
+ if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
+ "Expecting class selector starting with '.' got '{0}'.", name);
+ this.$$selectors[name.substr(1)] = key;
+ $provide.factory(key, factory);
+ };
+
+ /**
+ * @ngdoc method
+ * @name $animateProvider#classNameFilter
+ *
+ * @description
+ * Sets and/or returns the CSS class regular expression that is checked when performing
+ * an animation. Upon bootstrap the classNameFilter value is not set at all and will
+ * therefore enable $animate to attempt to perform an animation on any element.
+ * When setting the classNameFilter value, animations will only be performed on elements
+ * that successfully match the filter expression. This in turn can boost performance
+ * for low-powered devices as well as applications containing a lot of structural operations.
+ * @param {RegExp=} expression The className expression which will be checked against all animations
+ * @return {RegExp} The current CSS className expression value. If null then there is no expression value
+ */
+ this.classNameFilter = function(expression) {
+ if(arguments.length === 1) {
+ this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
+ }
+ return this.$$classNameFilter;
+ };
+
+ this.$get = ['$timeout', '$$asyncCallback', function($timeout, $$asyncCallback) {
+
+ function async(fn) {
+ fn && $$asyncCallback(fn);
+ }
+
+ /**
+ *
+ * @ngdoc service
+ * @name $animate
+ * @description The $animate service provides rudimentary DOM manipulation functions to
+ * insert, remove and move elements within the DOM, as well as adding and removing classes.
+ * This service is the core service used by the ngAnimate $animator service which provides
+ * high-level animation hooks for CSS and JavaScript.
+ *
+ * $animate is available in the AngularJS core, however, the ngAnimate module must be included
+ * to enable full out animation support. Otherwise, $animate will only perform simple DOM
+ * manipulation operations.
+ *
+ * To learn more about enabling animation support, click here to visit the {@link ngAnimate
+ * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
+ * page}.
+ */
+ return {
+
+ /**
+ *
+ * @ngdoc method
+ * @name $animate#enter
+ * @kind function
+ * @description Inserts the element into the DOM either after the `after` element or within
+ * the `parent` element. Once complete, the done() callback will be fired (if provided).
+ * @param {DOMElement} element the element which will be inserted into the DOM
+ * @param {DOMElement} parent the parent element which will append the element as
+ * a child (if the after element is not present)
+ * @param {DOMElement} after the sibling element which will append the element
+ * after itself
+ * @param {Function=} done callback function that will be called after the element has been
+ * inserted into the DOM
+ */
+ enter : function(element, parent, after, done) {
+ if (after) {
+ after.after(element);
+ } else {
+ if (!parent || !parent[0]) {
+ parent = after.parent();
+ }
+ parent.append(element);
+ }
+ async(done);
+ },
+
+ /**
+ *
+ * @ngdoc method
+ * @name $animate#leave
+ * @kind function
+ * @description Removes the element from the DOM. Once complete, the done() callback will be
+ * fired (if provided).
+ * @param {DOMElement} element the element which will be removed from the DOM
+ * @param {Function=} done callback function that will be called after the element has been
+ * removed from the DOM
+ */
+ leave : function(element, done) {
+ element.remove();
+ async(done);
+ },
+
+ /**
+ *
+ * @ngdoc method
+ * @name $animate#move
+ * @kind function
+ * @description Moves the position of the provided element within the DOM to be placed
+ * either after the `after` element or inside of the `parent` element. Once complete, the
+ * done() callback will be fired (if provided).
+ *
+ * @param {DOMElement} element the element which will be moved around within the
+ * DOM
+ * @param {DOMElement} parent the parent element where the element will be
+ * inserted into (if the after element is not present)
+ * @param {DOMElement} after the sibling element where the element will be
+ * positioned next to
+ * @param {Function=} done the callback function (if provided) that will be fired after the
+ * element has been moved to its new position
+ */
+ move : function(element, parent, after, done) {
+ // Do not remove element before insert. Removing will cause data associated with the
+ // element to be dropped. Insert will implicitly do the remove.
+ this.enter(element, parent, after, done);
+ },
+
+ /**
+ *
+ * @ngdoc method
+ * @name $animate#addClass
+ * @kind function
+ * @description Adds the provided className CSS class value to the provided element. Once
+ * complete, the done() callback will be fired (if provided).
+ * @param {DOMElement} element the element which will have the className value
+ * added to it
+ * @param {string} className the CSS class which will be added to the element
+ * @param {Function=} done the callback function (if provided) that will be fired after the
+ * className value has been added to the element
+ */
+ addClass : function(element, className, done) {
+ className = isString(className) ?
+ className :
+ isArray(className) ? className.join(' ') : '';
+ forEach(element, function (element) {
+ jqLiteAddClass(element, className);
+ });
+ async(done);
+ },
+
+ /**
+ *
+ * @ngdoc method
+ * @name $animate#removeClass
+ * @kind function
+ * @description Removes the provided className CSS class value from the provided element.
+ * Once complete, the done() callback will be fired (if provided).
+ * @param {DOMElement} element the element which will have the className value
+ * removed from it
+ * @param {string} className the CSS class which will be removed from the element
+ * @param {Function=} done the callback function (if provided) that will be fired after the
+ * className value has been removed from the element
+ */
+ removeClass : function(element, className, done) {
+ className = isString(className) ?
+ className :
+ isArray(className) ? className.join(' ') : '';
+ forEach(element, function (element) {
+ jqLiteRemoveClass(element, className);
+ });
+ async(done);
+ },
+
+ /**
+ *
+ * @ngdoc method
+ * @name $animate#setClass
+ * @kind function
+ * @description Adds and/or removes the given CSS classes to and from the element.
+ * Once complete, the done() callback will be fired (if provided).
+ * @param {DOMElement} element the element which will have its CSS classes changed
+ * removed from it
+ * @param {string} add the CSS classes which will be added to the element
+ * @param {string} remove the CSS class which will be removed from the element
+ * @param {Function=} done the callback function (if provided) that will be fired after the
+ * CSS classes have been set on the element
+ */
+ setClass : function(element, add, remove, done) {
+ forEach(element, function (element) {
+ jqLiteAddClass(element, add);
+ jqLiteRemoveClass(element, remove);
+ });
+ async(done);
+ },
+
+ enabled : noop
+ };
+ }];
+}];
+
+function $$AsyncCallbackProvider(){
+ this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
+ return $$rAF.supported
+ ? function(fn) { return $$rAF(fn); }
+ : function(fn) {
+ return $timeout(fn, 0, false);
+ };
+ }];
+}
+
+/**
+ * ! This is a private undocumented service !
+ *
+ * @name $browser
+ * @requires $log
+ * @description
+ * This object has two goals:
+ *
+ * - hide all the global state in the browser caused by the window object
+ * - abstract away all the browser specific features and inconsistencies
+ *
+ * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
+ * service, which can be used for convenient testing of the application without the interaction with
+ * the real browser apis.
+ */
+/**
+ * @param {object} window The global window object.
+ * @param {object} document jQuery wrapped document.
+ * @param {function()} XHR XMLHttpRequest constructor.
+ * @param {object} $log console.log or an object with the same interface.
+ * @param {object} $sniffer $sniffer service
+ */
+function Browser(window, document, $log, $sniffer) {
+ var self = this,
+ rawDocument = document[0],
+ location = window.location,
+ history = window.history,
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ pendingDeferIds = {};
+
+ self.isMock = false;
+
+ var outstandingRequestCount = 0;
+ var outstandingRequestCallbacks = [];
+
+ // TODO(vojta): remove this temporary api
+ self.$$completeOutstandingRequest = completeOutstandingRequest;
+ self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
+
+ /**
+ * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
+ * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
+ */
+ function completeOutstandingRequest(fn) {
+ try {
+ fn.apply(null, sliceArgs(arguments, 1));
+ } finally {
+ outstandingRequestCount--;
+ if (outstandingRequestCount === 0) {
+ while(outstandingRequestCallbacks.length) {
+ try {
+ outstandingRequestCallbacks.pop()();
+ } catch (e) {
+ $log.error(e);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * @private
+ * Note: this method is used only by scenario runner
+ * TODO(vojta): prefix this method with $$ ?
+ * @param {function()} callback Function that will be called when no outstanding request
+ */
+ self.notifyWhenNoOutstandingRequests = function(callback) {
+ // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
+ // at some deterministic time in respect to the test runner's actions. Leaving things up to the
+ // regular poller would result in flaky tests.
+ forEach(pollFns, function(pollFn){ pollFn(); });
+
+ if (outstandingRequestCount === 0) {
+ callback();
+ } else {
+ outstandingRequestCallbacks.push(callback);
+ }
+ };
+
+ //////////////////////////////////////////////////////////////
+ // Poll Watcher API
+ //////////////////////////////////////////////////////////////
+ var pollFns = [],
+ pollTimeout;
+
+ /**
+ * @name $browser#addPollFn
+ *
+ * @param {function()} fn Poll function to add
+ *
+ * @description
+ * Adds a function to the list of functions that poller periodically executes,
+ * and starts polling if not started yet.
+ *
+ * @returns {function()} the added function
+ */
+ self.addPollFn = function(fn) {
+ if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
+ pollFns.push(fn);
+ return fn;
+ };
+
+ /**
+ * @param {number} interval How often should browser call poll functions (ms)
+ * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
+ *
+ * @description
+ * Configures the poller to run in the specified intervals, using the specified
+ * setTimeout fn and kicks it off.
+ */
+ function startPoller(interval, setTimeout) {
+ (function check() {
+ forEach(pollFns, function(pollFn){ pollFn(); });
+ pollTimeout = setTimeout(check, interval);
+ })();
+ }
+
+ //////////////////////////////////////////////////////////////
+ // URL API
+ //////////////////////////////////////////////////////////////
+
+ var lastBrowserUrl = location.href,
+ baseElement = document.find('base'),
+ newLocation = null;
+
+ /**
+ * @name $browser#url
+ *
+ * @description
+ * GETTER:
+ * Without any argument, this method just returns current value of location.href.
+ *
+ * SETTER:
+ * With at least one argument, this method sets url to new value.
+ * If html5 history api supported, pushState/replaceState is used, otherwise
+ * location.href/location.replace is used.
+ * Returns its own instance to allow chaining
+ *
+ * NOTE: this api is intended for use only by the $location service. Please use the
+ * {@link ng.$location $location service} to change url.
+ *
+ * @param {string} url New url (when used as setter)
+ * @param {boolean=} replace Should new url replace current history record ?
+ */
+ self.url = function(url, replace) {
+ // Android Browser BFCache causes location, history reference to become stale.
+ if (location !== window.location) location = window.location;
+ if (history !== window.history) history = window.history;
+
+ // setter
+ if (url) {
+ if (lastBrowserUrl == url) return;
+ lastBrowserUrl = url;
+ if ($sniffer.history) {
+ if (replace) history.replaceState(null, '', url);
+ else {
+ history.pushState(null, '', url);
+ // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
+ baseElement.attr('href', baseElement.attr('href'));
+ }
+ } else {
+ newLocation = url;
+ if (replace) {
+ location.replace(url);
+ } else {
+ location.href = url;
+ }
+ }
+ return self;
+ // getter
+ } else {
+ // - newLocation is a workaround for an IE7-9 issue with location.replace and location.href
+ // methods not updating location.href synchronously.
+ // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
+ return newLocation || location.href.replace(/%27/g,"'");
+ }
+ };
+
+ var urlChangeListeners = [],
+ urlChangeInit = false;
+
+ function fireUrlChange() {
+ newLocation = null;
+ if (lastBrowserUrl == self.url()) return;
+
+ lastBrowserUrl = self.url();
+ forEach(urlChangeListeners, function(listener) {
+ listener(self.url());
+ });
+ }
+
+ /**
+ * @name $browser#onUrlChange
+ *
+ * @description
+ * Register callback function that will be called, when url changes.
+ *
+ * It's only called when the url is changed from outside of angular:
+ * - user types different url into address bar
+ * - user clicks on history (forward/back) button
+ * - user clicks on a link
+ *
+ * It's not called when url is changed by $browser.url() method
+ *
+ * The listener gets called with new url as parameter.
+ *
+ * NOTE: this api is intended for use only by the $location service. Please use the
+ * {@link ng.$location $location service} to monitor url changes in angular apps.
+ *
+ * @param {function(string)} listener Listener function to be called when url changes.
+ * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
+ */
+ self.onUrlChange = function(callback) {
+ // TODO(vojta): refactor to use node's syntax for events
+ if (!urlChangeInit) {
+ // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
+ // don't fire popstate when user change the address bar and don't fire hashchange when url
+ // changed by push/replaceState
+
+ // html5 history api - popstate event
+ if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange);
+ // hashchange event
+ if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange);
+ // polling
+ else self.addPollFn(fireUrlChange);
+
+ urlChangeInit = true;
+ }
+
+ urlChangeListeners.push(callback);
+ return callback;
+ };
+
+ //////////////////////////////////////////////////////////////
+ // Misc API
+ //////////////////////////////////////////////////////////////
+
+ /**
+ * @name $browser#baseHref
+ *
+ * @description
+ * Returns current
+ * (always relative - without domain)
+ *
+ * @returns {string} The current base href
+ */
+ self.baseHref = function() {
+ var href = baseElement.attr('href');
+ return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
+ };
+
+ //////////////////////////////////////////////////////////////
+ // Cookies API
+ //////////////////////////////////////////////////////////////
+ var lastCookies = {};
+ var lastCookieString = '';
+ var cookiePath = self.baseHref();
+
+ /**
+ * @name $browser#cookies
+ *
+ * @param {string=} name Cookie name
+ * @param {string=} value Cookie value
+ *
+ * @description
+ * The cookies method provides a 'private' low level access to browser cookies.
+ * It is not meant to be used directly, use the $cookie service instead.
+ *
+ * The return values vary depending on the arguments that the method was called with as follows:
+ *
+ * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
+ * it
+ * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
+ * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
+ * way)
+ *
+ * @returns {Object} Hash of all cookies (if called without any parameter)
+ */
+ self.cookies = function(name, value) {
+ /* global escape: false, unescape: false */
+ var cookieLength, cookieArray, cookie, i, index;
+
+ if (name) {
+ if (value === undefined) {
+ rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
+ ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
+ } else {
+ if (isString(value)) {
+ cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
+ ';path=' + cookiePath).length + 1;
+
+ // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
+ // - 300 cookies
+ // - 20 cookies per unique domain
+ // - 4096 bytes per cookie
+ if (cookieLength > 4096) {
+ $log.warn("Cookie '"+ name +
+ "' possibly not set or overflowed because it was too large ("+
+ cookieLength + " > 4096 bytes)!");
+ }
+ }
+ }
+ } else {
+ if (rawDocument.cookie !== lastCookieString) {
+ lastCookieString = rawDocument.cookie;
+ cookieArray = lastCookieString.split("; ");
+ lastCookies = {};
+
+ for (i = 0; i < cookieArray.length; i++) {
+ cookie = cookieArray[i];
+ index = cookie.indexOf('=');
+ if (index > 0) { //ignore nameless cookies
+ name = unescape(cookie.substring(0, index));
+ // the first value that is seen for a cookie is the most
+ // specific one. values for the same cookie name that
+ // follow are for less specific paths.
+ if (lastCookies[name] === undefined) {
+ lastCookies[name] = unescape(cookie.substring(index + 1));
+ }
+ }
+ }
+ }
+ return lastCookies;
+ }
+ };
+
+
+ /**
+ * @name $browser#defer
+ * @param {function()} fn A function, who's execution should be deferred.
+ * @param {number=} [delay=0] of milliseconds to defer the function execution.
+ * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
+ *
+ * @description
+ * Executes a fn asynchronously via `setTimeout(fn, delay)`.
+ *
+ * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
+ * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
+ * via `$browser.defer.flush()`.
+ *
+ */
+ self.defer = function(fn, delay) {
+ var timeoutId;
+ outstandingRequestCount++;
+ timeoutId = setTimeout(function() {
+ delete pendingDeferIds[timeoutId];
+ completeOutstandingRequest(fn);
+ }, delay || 0);
+ pendingDeferIds[timeoutId] = true;
+ return timeoutId;
+ };
+
+
+ /**
+ * @name $browser#defer.cancel
+ *
+ * @description
+ * Cancels a deferred task identified with `deferId`.
+ *
+ * @param {*} deferId Token returned by the `$browser.defer` function.
+ * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
+ * canceled.
+ */
+ self.defer.cancel = function(deferId) {
+ if (pendingDeferIds[deferId]) {
+ delete pendingDeferIds[deferId];
+ clearTimeout(deferId);
+ completeOutstandingRequest(noop);
+ return true;
+ }
+ return false;
+ };
+
+}
+
+function $BrowserProvider(){
+ this.$get = ['$window', '$log', '$sniffer', '$document',
+ function( $window, $log, $sniffer, $document){
+ return new Browser($window, $document, $log, $sniffer);
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name $cacheFactory
+ *
+ * @description
+ * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
+ * them.
+ *
+ * ```js
+ *
+ * var cache = $cacheFactory('cacheId');
+ * expect($cacheFactory.get('cacheId')).toBe(cache);
+ * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
+ *
+ * cache.put("key", "value");
+ * cache.put("another key", "another value");
+ *
+ * // We've specified no options on creation
+ * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
+ *
+ * ```
+ *
+ *
+ * @param {string} cacheId Name or id of the newly created cache.
+ * @param {object=} options Options object that specifies the cache behavior. Properties:
+ *
+ * - `{number=}` `capacity` — turns the cache into LRU cache.
+ *
+ * @returns {object} Newly created cache object with the following set of methods:
+ *
+ * - `{object}` `info()` — Returns id, size, and options of cache.
+ * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
+ * it.
+ * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
+ * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
+ * - `{void}` `removeAll()` — Removes all cached values.
+ * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
+ *
+ * @example
+
+
+
+
+
+
+
+
Cached Values
+
+
+ :
+
+
+
+
Cache Info
+
+
+ :
+
+
+
+
+
+ angular.module('cacheExampleApp', []).
+ controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
+ $scope.keys = [];
+ $scope.cache = $cacheFactory('cacheId');
+ $scope.put = function(key, value) {
+ $scope.cache.put(key, value);
+ $scope.keys.push(key);
+ };
+ }]);
+
+
+ p {
+ margin: 10px 0 3px;
+ }
+
+
+ */
+function $CacheFactoryProvider() {
+
+ this.$get = function() {
+ var caches = {};
+
+ function cacheFactory(cacheId, options) {
+ if (cacheId in caches) {
+ throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
+ }
+
+ var size = 0,
+ stats = extend({}, options, {id: cacheId}),
+ data = {},
+ capacity = (options && options.capacity) || Number.MAX_VALUE,
+ lruHash = {},
+ freshEnd = null,
+ staleEnd = null;
+
+ /**
+ * @ngdoc type
+ * @name $cacheFactory.Cache
+ *
+ * @description
+ * A cache object used to store and retrieve data, primarily used by
+ * {@link $http $http} and the {@link ng.directive:script script} directive to cache
+ * templates and other data.
+ *
+ * ```js
+ * angular.module('superCache')
+ * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
+ * return $cacheFactory('super-cache');
+ * }]);
+ * ```
+ *
+ * Example test:
+ *
+ * ```js
+ * it('should behave like a cache', inject(function(superCache) {
+ * superCache.put('key', 'value');
+ * superCache.put('another key', 'another value');
+ *
+ * expect(superCache.info()).toEqual({
+ * id: 'super-cache',
+ * size: 2
+ * });
+ *
+ * superCache.remove('another key');
+ * expect(superCache.get('another key')).toBeUndefined();
+ *
+ * superCache.removeAll();
+ * expect(superCache.info()).toEqual({
+ * id: 'super-cache',
+ * size: 0
+ * });
+ * }));
+ * ```
+ */
+ return caches[cacheId] = {
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory.Cache#put
+ * @kind function
+ *
+ * @description
+ * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
+ * retrieved later, and incrementing the size of the cache if the key was not already
+ * present in the cache. If behaving like an LRU cache, it will also remove stale
+ * entries from the set.
+ *
+ * It will not insert undefined values into the cache.
+ *
+ * @param {string} key the key under which the cached data is stored.
+ * @param {*} value the value to store alongside the key. If it is undefined, the key
+ * will not be stored.
+ * @returns {*} the value stored.
+ */
+ put: function(key, value) {
+ if (capacity < Number.MAX_VALUE) {
+ var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
+
+ refresh(lruEntry);
+ }
+
+ if (isUndefined(value)) return;
+ if (!(key in data)) size++;
+ data[key] = value;
+
+ if (size > capacity) {
+ this.remove(staleEnd.key);
+ }
+
+ return value;
+ },
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory.Cache#get
+ * @kind function
+ *
+ * @description
+ * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
+ *
+ * @param {string} key the key of the data to be retrieved
+ * @returns {*} the value stored.
+ */
+ get: function(key) {
+ if (capacity < Number.MAX_VALUE) {
+ var lruEntry = lruHash[key];
+
+ if (!lruEntry) return;
+
+ refresh(lruEntry);
+ }
+
+ return data[key];
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory.Cache#remove
+ * @kind function
+ *
+ * @description
+ * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
+ *
+ * @param {string} key the key of the entry to be removed
+ */
+ remove: function(key) {
+ if (capacity < Number.MAX_VALUE) {
+ var lruEntry = lruHash[key];
+
+ if (!lruEntry) return;
+
+ if (lruEntry == freshEnd) freshEnd = lruEntry.p;
+ if (lruEntry == staleEnd) staleEnd = lruEntry.n;
+ link(lruEntry.n,lruEntry.p);
+
+ delete lruHash[key];
+ }
+
+ delete data[key];
+ size--;
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory.Cache#removeAll
+ * @kind function
+ *
+ * @description
+ * Clears the cache object of any entries.
+ */
+ removeAll: function() {
+ data = {};
+ size = 0;
+ lruHash = {};
+ freshEnd = staleEnd = null;
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory.Cache#destroy
+ * @kind function
+ *
+ * @description
+ * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
+ * removing it from the {@link $cacheFactory $cacheFactory} set.
+ */
+ destroy: function() {
+ data = null;
+ stats = null;
+ lruHash = null;
+ delete caches[cacheId];
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory.Cache#info
+ * @kind function
+ *
+ * @description
+ * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
+ *
+ * @returns {object} an object with the following properties:
+ *
+ *
**id**: the id of the cache instance
+ *
**size**: the number of entries kept in the cache instance
+ *
**...**: any additional properties from the options object when creating the
+ * cache.
+ *
+ */
+ info: function() {
+ return extend({}, stats, {size: size});
+ }
+ };
+
+
+ /**
+ * makes the `entry` the freshEnd of the LRU linked list
+ */
+ function refresh(entry) {
+ if (entry != freshEnd) {
+ if (!staleEnd) {
+ staleEnd = entry;
+ } else if (staleEnd == entry) {
+ staleEnd = entry.n;
+ }
+
+ link(entry.n, entry.p);
+ link(entry, freshEnd);
+ freshEnd = entry;
+ freshEnd.n = null;
+ }
+ }
+
+
+ /**
+ * bidirectionally links two entries of the LRU linked list
+ */
+ function link(nextEntry, prevEntry) {
+ if (nextEntry != prevEntry) {
+ if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
+ if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
+ }
+ }
+ }
+
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory#info
+ *
+ * @description
+ * Get information about all the caches that have been created
+ *
+ * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
+ */
+ cacheFactory.info = function() {
+ var info = {};
+ forEach(caches, function(cache, cacheId) {
+ info[cacheId] = cache.info();
+ });
+ return info;
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory#get
+ *
+ * @description
+ * Get access to a cache object by the `cacheId` used when it was created.
+ *
+ * @param {string} cacheId Name or id of a cache to access.
+ * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
+ */
+ cacheFactory.get = function(cacheId) {
+ return caches[cacheId];
+ };
+
+
+ return cacheFactory;
+ };
+}
+
+/**
+ * @ngdoc service
+ * @name $templateCache
+ *
+ * @description
+ * The first time a template is used, it is loaded in the template cache for quick retrieval. You
+ * can load templates directly into the cache in a `script` tag, or by consuming the
+ * `$templateCache` service directly.
+ *
+ * Adding via the `script` tag:
+ *
+ * ```html
+ *
+ * ```
+ *
+ * **Note:** the `script` tag containing the template does not need to be included in the `head` of
+ * the document, but it must be below the `ng-app` definition.
+ *
+ * Adding via the $templateCache service:
+ *
+ * ```js
+ * var myApp = angular.module('myApp', []);
+ * myApp.run(function($templateCache) {
+ * $templateCache.put('templateId.html', 'This is the content of the template');
+ * });
+ * ```
+ *
+ * To retrieve the template later, simply use it in your HTML:
+ * ```html
+ *
+ * ```
+ *
+ * or get it via Javascript:
+ * ```js
+ * $templateCache.get('templateId.html')
+ * ```
+ *
+ * See {@link ng.$cacheFactory $cacheFactory}.
+ *
+ */
+function $TemplateCacheProvider() {
+ this.$get = ['$cacheFactory', function($cacheFactory) {
+ return $cacheFactory('templates');
+ }];
+}
+
+/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
+ *
+ * DOM-related variables:
+ *
+ * - "node" - DOM Node
+ * - "element" - DOM Element or Node
+ * - "$node" or "$element" - jqLite-wrapped node or element
+ *
+ *
+ * Compiler related stuff:
+ *
+ * - "linkFn" - linking fn of a single directive
+ * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
+ * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
+ * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
+ */
+
+
+/**
+ * @ngdoc service
+ * @name $compile
+ * @kind function
+ *
+ * @description
+ * Compiles an HTML string or DOM into a template and produces a template function, which
+ * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
+ *
+ * The compilation is a process of walking the DOM tree and matching DOM elements to
+ * {@link ng.$compileProvider#directive directives}.
+ *
+ *
+ * **Note:** This document is an in-depth reference of all directive options.
+ * For a gentle introduction to directives with examples of common use cases,
+ * see the {@link guide/directive directive guide}.
+ *
+ *
+ * ## Comprehensive Directive API
+ *
+ * There are many different options for a directive.
+ *
+ * The difference resides in the return value of the factory function.
+ * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
+ * or just the `postLink` function (all other properties will have the default values).
+ *
+ *
+ * **Best Practice:** It's recommended to use the "directive definition object" form.
+ *
+ * **Note:** Any unspecified options will use the default value. You can see the default values below.
+ *
+ *
+ * Therefore the above can be simplified as:
+ *
+ * ```js
+ * var myModule = angular.module(...);
+ *
+ * myModule.directive('directiveName', function factory(injectables) {
+ * var directiveDefinitionObject = {
+ * link: function postLink(scope, iElement, iAttrs) { ... }
+ * };
+ * return directiveDefinitionObject;
+ * // or
+ * // return function postLink(scope, iElement, iAttrs) { ... }
+ * });
+ * ```
+ *
+ *
+ *
+ * ### Directive Definition Object
+ *
+ * The directive definition object provides instructions to the {@link ng.$compile
+ * compiler}. The attributes are:
+ *
+ * #### `priority`
+ * When there are multiple directives defined on a single DOM element, sometimes it
+ * is necessary to specify the order in which the directives are applied. The `priority` is used
+ * to sort the directives before their `compile` functions get called. Priority is defined as a
+ * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
+ * are also run in priority order, but post-link functions are run in reverse order. The order
+ * of directives with the same priority is undefined. The default priority is `0`.
+ *
+ * #### `terminal`
+ * If set to true then the current `priority` will be the last set of directives
+ * which will execute (any directives at the current priority will still execute
+ * as the order of execution on same `priority` is undefined).
+ *
+ * #### `scope`
+ * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
+ * same element request a new scope, only one new scope is created. The new scope rule does not
+ * apply for the root of the template since the root of the template always gets a new scope.
+ *
+ * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
+ * normal scope in that it does not prototypically inherit from the parent scope. This is useful
+ * when creating reusable components, which should not accidentally read or modify data in the
+ * parent scope.
+ *
+ * The 'isolate' scope takes an object hash which defines a set of local scope properties
+ * derived from the parent scope. These local properties are useful for aliasing values for
+ * templates. Locals definition is a hash of local scope property to its source:
+ *
+ * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
+ * always a string since DOM attributes are strings. If no `attr` name is specified then the
+ * attribute name is assumed to be the same as the local name.
+ * Given `` and widget definition
+ * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
+ * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
+ * `localName` property on the widget scope. The `name` is read from the parent scope (not
+ * component scope).
+ *
+ * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
+ * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
+ * name is specified then the attribute name is assumed to be the same as the local name.
+ * Given `` and widget definition of
+ * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
+ * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
+ * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
+ * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
+ * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
+ *
+ * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
+ * If no `attr` name is specified then the attribute name is assumed to be the same as the
+ * local name. Given `` and widget definition of
+ * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
+ * a function wrapper for the `count = count + value` expression. Often it's desirable to
+ * pass data from the isolated scope via an expression and to the parent scope, this can be
+ * done by passing a map of local variable names and values into the expression wrapper fn.
+ * For example, if the expression is `increment(amount)` then we can specify the amount value
+ * by calling the `localFn` as `localFn({amount: 22})`.
+ *
+ *
+ *
+ * #### `controller`
+ * Controller constructor function. The controller is instantiated before the
+ * pre-linking phase and it is shared with other directives (see
+ * `require` attribute). This allows the directives to communicate with each other and augment
+ * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
+ *
+ * * `$scope` - Current scope associated with the element
+ * * `$element` - Current element
+ * * `$attrs` - Current attributes object for the element
+ * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope.
+ * The scope can be overridden by an optional first argument.
+ * `function([scope], cloneLinkingFn)`.
+ *
+ *
+ * #### `require`
+ * Require another directive and inject its controller as the fourth argument to the linking function. The
+ * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
+ * injected argument will be an array in corresponding order. If no such directive can be
+ * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
+ *
+ * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
+ * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
+ * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found.
+ * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the
+ * `link` fn if not found.
+ *
+ *
+ * #### `controllerAs`
+ * Controller alias at the directive scope. An alias for the controller so it
+ * can be referenced at the directive template. The directive needs to define a scope for this
+ * configuration to be used. Useful in the case when directive is used as component.
+ *
+ *
+ * #### `restrict`
+ * String of subset of `EACM` which restricts the directive to a specific directive
+ * declaration style. If omitted, the default (attributes only) is used.
+ *
+ * * `E` - Element name: ``
+ * * `A` - Attribute (default): ``
+ * * `C` - Class: ``
+ * * `M` - Comment: ``
+ *
+ *
+ * #### `template`
+ * replace the current element with the contents of the HTML. The replacement process
+ * migrates all of the attributes / classes from the old element to the new one. See the
+ * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
+ * Directives Guide} for an example.
+ *
+ * You can specify `template` as a string representing the template or as a function which takes
+ * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and
+ * returns a string value representing the template.
+ *
+ *
+ * #### `templateUrl`
+ * Same as `template` but the template is loaded from the specified URL. Because
+ * the template loading is asynchronous the compilation/linking is suspended until the template
+ * is loaded.
+ *
+ * You can specify `templateUrl` as a string representing the URL or as a function which takes two
+ * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
+ * a string value representing the url. In either case, the template URL is passed through {@link
+ * api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
+ *
+ *
+ * #### `replace` ([*DEPRECATED*!], will be removed in next major release)
+ * specify where the template should be inserted. Defaults to `false`.
+ *
+ * * `true` - the template will replace the current element.
+ * * `false` - the template will replace the contents of the current element.
+ *
+ *
+ * #### `transclude`
+ * compile the content of the element and make it available to the directive.
+ * Typically used with {@link ng.directive:ngTransclude
+ * ngTransclude}. The advantage of transclusion is that the linking function receives a
+ * transclusion function which is pre-bound to the correct scope. In a typical setup the widget
+ * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
+ * scope. This makes it possible for the widget to have private state, and the transclusion to
+ * be bound to the parent (pre-`isolate`) scope.
+ *
+ * * `true` - transclude the content of the directive.
+ * * `'element'` - transclude the whole element including any directives defined at lower priority.
+ *
+ *
+ * #### `compile`
+ *
+ * ```js
+ * function compile(tElement, tAttrs, transclude) { ... }
+ * ```
+ *
+ * The compile function deals with transforming the template DOM. Since most directives do not do
+ * template transformation, it is not used often. The compile function takes the following arguments:
+ *
+ * * `tElement` - template element - The element where the directive has been declared. It is
+ * safe to do template transformation on the element and child elements only.
+ *
+ * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
+ * between all directive compile functions.
+ *
+ * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
+ *
+ *
+ * **Note:** The template instance and the link instance may be different objects if the template has
+ * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
+ * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
+ * should be done in a linking function rather than in a compile function.
+ *
+
+ *
+ * **Note:** The compile function cannot handle directives that recursively use themselves in their
+ * own templates or compile functions. Compiling these directives results in an infinite loop and a
+ * stack overflow errors.
+ *
+ * This can be avoided by manually using $compile in the postLink function to imperatively compile
+ * a directive's template instead of relying on automatic template compilation via `template` or
+ * `templateUrl` declaration or manual compilation inside the compile function.
+ *
+ *
+ *
+ * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
+ * e.g. does not know about the right outer scope. Please use the transclude function that is passed
+ * to the link function instead.
+ *
+
+ * A compile function can have a return value which can be either a function or an object.
+ *
+ * * returning a (post-link) function - is equivalent to registering the linking function via the
+ * `link` property of the config object when the compile function is empty.
+ *
+ * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
+ * control when a linking function should be called during the linking phase. See info about
+ * pre-linking and post-linking functions below.
+ *
+ *
+ * #### `link`
+ * This property is used only if the `compile` property is not defined.
+ *
+ * ```js
+ * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
+ * ```
+ *
+ * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
+ * executed after the template has been cloned. This is where most of the directive logic will be
+ * put.
+ *
+ * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
+ * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
+ *
+ * * `iElement` - instance element - The element where the directive is to be used. It is safe to
+ * manipulate the children of the element only in `postLink` function since the children have
+ * already been linked.
+ *
+ * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
+ * between all directive linking functions.
+ *
+ * * `controller` - a controller instance - A controller instance if at least one directive on the
+ * element defines a controller. The controller is shared among all the directives, which allows
+ * the directives to use the controllers as a communication channel.
+ *
+ * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
+ * The scope can be overridden by an optional first argument. This is the same as the `$transclude`
+ * parameter of directive controllers.
+ * `function([scope], cloneLinkingFn)`.
+ *
+ *
+ * #### Pre-linking function
+ *
+ * Executed before the child elements are linked. Not safe to do DOM transformation since the
+ * compiler linking function will fail to locate the correct elements for linking.
+ *
+ * #### Post-linking function
+ *
+ * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
+ *
+ *
+ * ### Attributes
+ *
+ * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
+ * `link()` or `compile()` functions. It has a variety of uses.
+ *
+ * accessing *Normalized attribute names:*
+ * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
+ * the attributes object allows for normalized access to
+ * the attributes.
+ *
+ * * *Directive inter-communication:* All directives share the same instance of the attributes
+ * object which allows the directives to use the attributes object as inter directive
+ * communication.
+ *
+ * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
+ * allowing other directives to read the interpolated value.
+ *
+ * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
+ * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
+ * the only way to easily get the actual value because during the linking phase the interpolation
+ * hasn't been evaluated yet and so the value is at this time set to `undefined`.
+ *
+ * ```js
+ * function linkingFn(scope, elm, attrs, ctrl) {
+ * // get the attribute value
+ * console.log(attrs.ngModel);
+ *
+ * // change the attribute
+ * attrs.$set('ngModel', 'new value');
+ *
+ * // observe changes to interpolated attribute
+ * attrs.$observe('ngModel', function(value) {
+ * console.log('ngModel has changed value to ' + value);
+ * });
+ * }
+ * ```
+ *
+ * Below is an example using `$compileProvider`.
+ *
+ *
+ * **Note**: Typically directives are registered with `module.directive`. The example below is
+ * to illustrate how `$compile` works.
+ *
+ *
+
+
+
+
+
+
+
+
+
+
+ it('should auto compile', function() {
+ var textarea = $('textarea');
+ var output = $('div[compile]');
+ // The initial state reads 'Hello Angular'.
+ expect(output.getText()).toBe('Hello Angular');
+ textarea.clear();
+ textarea.sendKeys('{{name}}!');
+ expect(output.getText()).toBe('Angular!');
+ });
+
+
+
+ *
+ *
+ * @param {string|DOMElement} element Element or HTML string to compile into a template function.
+ * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives.
+ * @param {number} maxPriority only apply directives lower than given priority (Only effects the
+ * root element(s), not their children)
+ * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template
+ * (a DOM element/tree) to a scope. Where:
+ *
+ * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
+ * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
+ * `template` and call the `cloneAttachFn` function allowing the caller to attach the
+ * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
+ * called as: `cloneAttachFn(clonedElement, scope)` where:
+ *
+ * * `clonedElement` - is a clone of the original `element` passed into the compiler.
+ * * `scope` - is the current scope with which the linking function is working with.
+ *
+ * Calling the linking function returns the element of the template. It is either the original
+ * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
+ *
+ * After linking the view is not updated until after a call to $digest which typically is done by
+ * Angular automatically.
+ *
+ * If you need access to the bound view, there are two ways to do it:
+ *
+ * - If you are not asking the linking function to clone the template, create the DOM element(s)
+ * before you send them to the compiler and keep this reference around.
+ * ```js
+ * var element = $compile('
{{total}}
')(scope);
+ * ```
+ *
+ * - if on the other hand, you need the element to be cloned, the view reference from the original
+ * example would not point to the clone, but rather to the original template that was cloned. In
+ * this case, you can access the clone via the cloneAttachFn:
+ * ```js
+ * var templateElement = angular.element('
{{total}}
'),
+ * scope = ....;
+ *
+ * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
+ * //attach the clone to DOM document at the right place
+ * });
+ *
+ * //now we have reference to the cloned DOM via `clonedElement`
+ * ```
+ *
+ *
+ * For information on how the compiler works, see the
+ * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
+ */
+
+var $compileMinErr = minErr('$compile');
+
+/**
+ * @ngdoc provider
+ * @name $compileProvider
+ * @kind function
+ *
+ * @description
+ */
+$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
+function $CompileProvider($provide, $$sanitizeUriProvider) {
+ var hasDirectives = {},
+ Suffix = 'Directive',
+ COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w_\-]+)\s+(.*)$/,
+ CLASS_DIRECTIVE_REGEXP = /(([\d\w_\-]+)(?:\:([^;]+))?;?)/;
+
+ // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
+ // The assumption is that future DOM event attribute names will begin with
+ // 'on' and be composed of only English letters.
+ var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
+
+ /**
+ * @ngdoc method
+ * @name $compileProvider#directive
+ * @kind function
+ *
+ * @description
+ * Register a new directive with the compiler.
+ *
+ * @param {string|Object} name Name of the directive in camel-case (i.e. ngBind which
+ * will match as ng-bind), or an object map of directives where the keys are the
+ * names and the values are the factories.
+ * @param {Function|Array} directiveFactory An injectable directive factory function. See
+ * {@link guide/directive} for more info.
+ * @returns {ng.$compileProvider} Self for chaining.
+ */
+ this.directive = function registerDirective(name, directiveFactory) {
+ assertNotHasOwnProperty(name, 'directive');
+ if (isString(name)) {
+ assertArg(directiveFactory, 'directiveFactory');
+ if (!hasDirectives.hasOwnProperty(name)) {
+ hasDirectives[name] = [];
+ $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
+ function($injector, $exceptionHandler) {
+ var directives = [];
+ forEach(hasDirectives[name], function(directiveFactory, index) {
+ try {
+ var directive = $injector.invoke(directiveFactory);
+ if (isFunction(directive)) {
+ directive = { compile: valueFn(directive) };
+ } else if (!directive.compile && directive.link) {
+ directive.compile = valueFn(directive.link);
+ }
+ directive.priority = directive.priority || 0;
+ directive.index = index;
+ directive.name = directive.name || name;
+ directive.require = directive.require || (directive.controller && directive.name);
+ directive.restrict = directive.restrict || 'A';
+ directives.push(directive);
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ });
+ return directives;
+ }]);
+ }
+ hasDirectives[name].push(directiveFactory);
+ } else {
+ forEach(name, reverseParams(registerDirective));
+ }
+ return this;
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $compileProvider#aHrefSanitizationWhitelist
+ * @kind function
+ *
+ * @description
+ * Retrieves or overrides the default regular expression that is used for whitelisting of safe
+ * urls during a[href] sanitization.
+ *
+ * The sanitization is a security measure aimed at prevent XSS attacks via html links.
+ *
+ * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
+ * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
+ * regular expression. If a match is found, the original url is written into the dom. Otherwise,
+ * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
+ *
+ * @param {RegExp=} regexp New regexp to whitelist urls with.
+ * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
+ * chaining otherwise.
+ */
+ this.aHrefSanitizationWhitelist = function(regexp) {
+ if (isDefined(regexp)) {
+ $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
+ return this;
+ } else {
+ return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
+ }
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $compileProvider#imgSrcSanitizationWhitelist
+ * @kind function
+ *
+ * @description
+ * Retrieves or overrides the default regular expression that is used for whitelisting of safe
+ * urls during img[src] sanitization.
+ *
+ * The sanitization is a security measure aimed at prevent XSS attacks via html links.
+ *
+ * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
+ * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
+ * regular expression. If a match is found, the original url is written into the dom. Otherwise,
+ * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
+ *
+ * @param {RegExp=} regexp New regexp to whitelist urls with.
+ * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
+ * chaining otherwise.
+ */
+ this.imgSrcSanitizationWhitelist = function(regexp) {
+ if (isDefined(regexp)) {
+ $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
+ return this;
+ } else {
+ return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
+ }
+ };
+
+ this.$get = [
+ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
+ '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
+ function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
+ $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
+
+ var Attributes = function(element, attr) {
+ this.$$element = element;
+ this.$attr = attr || {};
+ };
+
+ Attributes.prototype = {
+ $normalize: directiveNormalize,
+
+
+ /**
+ * @ngdoc method
+ * @name $compile.directive.Attributes#$addClass
+ * @kind function
+ *
+ * @description
+ * Adds the CSS class value specified by the classVal parameter to the element. If animations
+ * are enabled then an animation will be triggered for the class addition.
+ *
+ * @param {string} classVal The className value that will be added to the element
+ */
+ $addClass : function(classVal) {
+ if(classVal && classVal.length > 0) {
+ $animate.addClass(this.$$element, classVal);
+ }
+ },
+
+ /**
+ * @ngdoc method
+ * @name $compile.directive.Attributes#$removeClass
+ * @kind function
+ *
+ * @description
+ * Removes the CSS class value specified by the classVal parameter from the element. If
+ * animations are enabled then an animation will be triggered for the class removal.
+ *
+ * @param {string} classVal The className value that will be removed from the element
+ */
+ $removeClass : function(classVal) {
+ if(classVal && classVal.length > 0) {
+ $animate.removeClass(this.$$element, classVal);
+ }
+ },
+
+ /**
+ * @ngdoc method
+ * @name $compile.directive.Attributes#$updateClass
+ * @kind function
+ *
+ * @description
+ * Adds and removes the appropriate CSS class values to the element based on the difference
+ * between the new and old CSS class values (specified as newClasses and oldClasses).
+ *
+ * @param {string} newClasses The current CSS className value
+ * @param {string} oldClasses The former CSS className value
+ */
+ $updateClass : function(newClasses, oldClasses) {
+ var toAdd = tokenDifference(newClasses, oldClasses);
+ var toRemove = tokenDifference(oldClasses, newClasses);
+
+ if(toAdd.length === 0) {
+ $animate.removeClass(this.$$element, toRemove);
+ } else if(toRemove.length === 0) {
+ $animate.addClass(this.$$element, toAdd);
+ } else {
+ $animate.setClass(this.$$element, toAdd, toRemove);
+ }
+ },
+
+ /**
+ * Set a normalized attribute on the element in a way such that all directives
+ * can share the attribute. This function properly handles boolean attributes.
+ * @param {string} key Normalized key. (ie ngAttribute)
+ * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
+ * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
+ * Defaults to true.
+ * @param {string=} attrName Optional none normalized name. Defaults to key.
+ */
+ $set: function(key, value, writeAttr, attrName) {
+ // TODO: decide whether or not to throw an error if "class"
+ //is set through this function since it may cause $updateClass to
+ //become unstable.
+
+ var booleanKey = getBooleanAttrName(this.$$element[0], key),
+ normalizedVal,
+ nodeName;
+
+ if (booleanKey) {
+ this.$$element.prop(key, value);
+ attrName = booleanKey;
+ }
+
+ this[key] = value;
+
+ // translate normalized key to actual key
+ if (attrName) {
+ this.$attr[key] = attrName;
+ } else {
+ attrName = this.$attr[key];
+ if (!attrName) {
+ this.$attr[key] = attrName = snake_case(key, '-');
+ }
+ }
+
+ nodeName = nodeName_(this.$$element);
+
+ // sanitize a[href] and img[src] values
+ if ((nodeName === 'A' && key === 'href') ||
+ (nodeName === 'IMG' && key === 'src')) {
+ this[key] = value = $$sanitizeUri(value, key === 'src');
+ }
+
+ if (writeAttr !== false) {
+ if (value === null || value === undefined) {
+ this.$$element.removeAttr(attrName);
+ } else {
+ this.$$element.attr(attrName, value);
+ }
+ }
+
+ // fire observers
+ var $$observers = this.$$observers;
+ $$observers && forEach($$observers[key], function(fn) {
+ try {
+ fn(value);
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ });
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $compile.directive.Attributes#$observe
+ * @kind function
+ *
+ * @description
+ * Observes an interpolated attribute.
+ *
+ * The observer function will be invoked once during the next `$digest` following
+ * compilation. The observer is then invoked whenever the interpolated value
+ * changes.
+ *
+ * @param {string} key Normalized key. (ie ngAttribute) .
+ * @param {function(interpolatedValue)} fn Function that will be called whenever
+ the interpolated value of the attribute changes.
+ * See the {@link guide/directive#Attributes Directives} guide for more info.
+ * @returns {function()} the `fn` parameter.
+ */
+ $observe: function(key, fn) {
+ var attrs = this,
+ $$observers = (attrs.$$observers || (attrs.$$observers = {})),
+ listeners = ($$observers[key] || ($$observers[key] = []));
+
+ listeners.push(fn);
+ $rootScope.$evalAsync(function() {
+ if (!listeners.$$inter) {
+ // no one registered attribute interpolation function, so lets call it manually
+ fn(attrs[key]);
+ }
+ });
+ return fn;
+ }
+ };
+
+ var startSymbol = $interpolate.startSymbol(),
+ endSymbol = $interpolate.endSymbol(),
+ denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
+ ? identity
+ : function denormalizeTemplate(template) {
+ return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
+ },
+ NG_ATTR_BINDING = /^ngAttr[A-Z]/;
+
+
+ return compile;
+
+ //================================
+
+ function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
+ previousCompileContext) {
+ if (!($compileNodes instanceof jqLite)) {
+ // jquery always rewraps, whereas we need to preserve the original selector so that we can
+ // modify it.
+ $compileNodes = jqLite($compileNodes);
+ }
+ // We can not compile top level text elements since text nodes can be merged and we will
+ // not be able to attach scope data to them, so we will wrap them in
+ forEach($compileNodes, function(node, index){
+ if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
+ $compileNodes[index] = node = jqLite(node).wrap('').parent()[0];
+ }
+ });
+ var compositeLinkFn =
+ compileNodes($compileNodes, transcludeFn, $compileNodes,
+ maxPriority, ignoreDirective, previousCompileContext);
+ safeAddClass($compileNodes, 'ng-scope');
+ return function publicLinkFn(scope, cloneConnectFn, transcludeControllers, parentBoundTranscludeFn){
+ assertArg(scope, 'scope');
+ // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
+ // and sometimes changes the structure of the DOM.
+ var $linkNode = cloneConnectFn
+ ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
+ : $compileNodes;
+
+ forEach(transcludeControllers, function(instance, name) {
+ $linkNode.data('$' + name + 'Controller', instance);
+ });
+
+ // Attach scope only to non-text nodes.
+ for(var i = 0, ii = $linkNode.length; i
+ addDirective(directives,
+ directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
+
+ // iterate over the attributes
+ for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
+ j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
+ var attrStartName = false;
+ var attrEndName = false;
+
+ attr = nAttrs[j];
+ if (!msie || msie >= 8 || attr.specified) {
+ name = attr.name;
+ value = trim(attr.value);
+
+ // support ngAttr attribute binding
+ ngAttrName = directiveNormalize(name);
+ if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
+ name = snake_case(ngAttrName.substr(6), '-');
+ }
+
+ var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
+ if (ngAttrName === directiveNName + 'Start') {
+ attrStartName = name;
+ attrEndName = name.substr(0, name.length - 5) + 'end';
+ name = name.substr(0, name.length - 6);
+ }
+
+ nName = directiveNormalize(name.toLowerCase());
+ attrsMap[nName] = name;
+ if (isNgAttr || !attrs.hasOwnProperty(nName)) {
+ attrs[nName] = value;
+ if (getBooleanAttrName(node, nName)) {
+ attrs[nName] = true; // presence means true
+ }
+ }
+ addAttrInterpolateDirective(node, directives, value, nName);
+ addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
+ attrEndName);
+ }
+ }
+
+ // use class as directive
+ className = node.className;
+ if (isString(className) && className !== '') {
+ while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
+ nName = directiveNormalize(match[2]);
+ if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
+ attrs[nName] = trim(match[3]);
+ }
+ className = className.substr(match.index + match[0].length);
+ }
+ }
+ break;
+ case 3: /* Text Node */
+ addTextInterpolateDirective(directives, node.nodeValue);
+ break;
+ case 8: /* Comment */
+ try {
+ match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
+ if (match) {
+ nName = directiveNormalize(match[1]);
+ if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
+ attrs[nName] = trim(match[2]);
+ }
+ }
+ } catch (e) {
+ // turns out that under some circumstances IE9 throws errors when one attempts to read
+ // comment's node value.
+ // Just ignore it and continue. (Can't seem to reproduce in test case.)
+ }
+ break;
+ }
+
+ directives.sort(byPriority);
+ return directives;
+ }
+
+ /**
+ * Given a node with an directive-start it collects all of the siblings until it finds
+ * directive-end.
+ * @param node
+ * @param attrStart
+ * @param attrEnd
+ * @returns {*}
+ */
+ function groupScan(node, attrStart, attrEnd) {
+ var nodes = [];
+ var depth = 0;
+ if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
+ var startNode = node;
+ do {
+ if (!node) {
+ throw $compileMinErr('uterdir',
+ "Unterminated attribute, found '{0}' but no matching '{1}' found.",
+ attrStart, attrEnd);
+ }
+ if (node.nodeType == 1 /** Element **/) {
+ if (node.hasAttribute(attrStart)) depth++;
+ if (node.hasAttribute(attrEnd)) depth--;
+ }
+ nodes.push(node);
+ node = node.nextSibling;
+ } while (depth > 0);
+ } else {
+ nodes.push(node);
+ }
+
+ return jqLite(nodes);
+ }
+
+ /**
+ * Wrapper for linking function which converts normal linking function into a grouped
+ * linking function.
+ * @param linkFn
+ * @param attrStart
+ * @param attrEnd
+ * @returns {Function}
+ */
+ function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
+ return function(scope, element, attrs, controllers, transcludeFn) {
+ element = groupScan(element[0], attrStart, attrEnd);
+ return linkFn(scope, element, attrs, controllers, transcludeFn);
+ };
+ }
+
+ /**
+ * Once the directives have been collected, their compile functions are executed. This method
+ * is responsible for inlining directive templates as well as terminating the application
+ * of the directives if the terminal directive has been reached.
+ *
+ * @param {Array} directives Array of collected directives to execute their compile function.
+ * this needs to be pre-sorted by priority order.
+ * @param {Node} compileNode The raw DOM node to apply the compile functions to
+ * @param {Object} templateAttrs The shared attribute function
+ * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
+ * scope argument is auto-generated to the new
+ * child of the transcluded parent scope.
+ * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
+ * argument has the root jqLite array so that we can replace nodes
+ * on it.
+ * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
+ * compiling the transclusion.
+ * @param {Array.} preLinkFns
+ * @param {Array.} postLinkFns
+ * @param {Object} previousCompileContext Context used for previous compilation of the current
+ * node
+ * @returns {Function} linkFn
+ */
+ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
+ jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
+ previousCompileContext) {
+ previousCompileContext = previousCompileContext || {};
+
+ var terminalPriority = -Number.MAX_VALUE,
+ newScopeDirective,
+ controllerDirectives = previousCompileContext.controllerDirectives,
+ newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
+ templateDirective = previousCompileContext.templateDirective,
+ nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
+ hasTranscludeDirective = false,
+ hasTemplate = false,
+ hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
+ $compileNode = templateAttrs.$$element = jqLite(compileNode),
+ directive,
+ directiveName,
+ $template,
+ replaceDirective = originalReplaceDirective,
+ childTranscludeFn = transcludeFn,
+ linkFn,
+ directiveValue;
+
+ // executes all directives on the current element
+ for(var i = 0, ii = directives.length; i < ii; i++) {
+ directive = directives[i];
+ var attrStart = directive.$$start;
+ var attrEnd = directive.$$end;
+
+ // collect multiblock sections
+ if (attrStart) {
+ $compileNode = groupScan(compileNode, attrStart, attrEnd);
+ }
+ $template = undefined;
+
+ if (terminalPriority > directive.priority) {
+ break; // prevent further processing of directives
+ }
+
+ if (directiveValue = directive.scope) {
+ newScopeDirective = newScopeDirective || directive;
+
+ // skip the check for directives with async templates, we'll check the derived sync
+ // directive when the template arrives
+ if (!directive.templateUrl) {
+ assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
+ $compileNode);
+ if (isObject(directiveValue)) {
+ newIsolateScopeDirective = directive;
+ }
+ }
+ }
+
+ directiveName = directive.name;
+
+ if (!directive.templateUrl && directive.controller) {
+ directiveValue = directive.controller;
+ controllerDirectives = controllerDirectives || {};
+ assertNoDuplicate("'" + directiveName + "' controller",
+ controllerDirectives[directiveName], directive, $compileNode);
+ controllerDirectives[directiveName] = directive;
+ }
+
+ if (directiveValue = directive.transclude) {
+ hasTranscludeDirective = true;
+
+ // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
+ // This option should only be used by directives that know how to safely handle element transclusion,
+ // where the transcluded nodes are added or replaced after linking.
+ if (!directive.$$tlb) {
+ assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
+ nonTlbTranscludeDirective = directive;
+ }
+
+ if (directiveValue == 'element') {
+ hasElementTranscludeDirective = true;
+ terminalPriority = directive.priority;
+ $template = groupScan(compileNode, attrStart, attrEnd);
+ $compileNode = templateAttrs.$$element =
+ jqLite(document.createComment(' ' + directiveName + ': ' +
+ templateAttrs[directiveName] + ' '));
+ compileNode = $compileNode[0];
+ replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode);
+
+ childTranscludeFn = compile($template, transcludeFn, terminalPriority,
+ replaceDirective && replaceDirective.name, {
+ // Don't pass in:
+ // - controllerDirectives - otherwise we'll create duplicates controllers
+ // - newIsolateScopeDirective or templateDirective - combining templates with
+ // element transclusion doesn't make sense.
+ //
+ // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
+ // on the same element more than once.
+ nonTlbTranscludeDirective: nonTlbTranscludeDirective
+ });
+ } else {
+ $template = jqLite(jqLiteClone(compileNode)).contents();
+ $compileNode.empty(); // clear contents
+ childTranscludeFn = compile($template, transcludeFn);
+ }
+ }
+
+ if (directive.template) {
+ hasTemplate = true;
+ assertNoDuplicate('template', templateDirective, directive, $compileNode);
+ templateDirective = directive;
+
+ directiveValue = (isFunction(directive.template))
+ ? directive.template($compileNode, templateAttrs)
+ : directive.template;
+
+ directiveValue = denormalizeTemplate(directiveValue);
+
+ if (directive.replace) {
+ replaceDirective = directive;
+ if (jqLiteIsTextNode(directiveValue)) {
+ $template = [];
+ } else {
+ $template = jqLite(trim(directiveValue));
+ }
+ compileNode = $template[0];
+
+ if ($template.length != 1 || compileNode.nodeType !== 1) {
+ throw $compileMinErr('tplrt',
+ "Template for directive '{0}' must have exactly one root element. {1}",
+ directiveName, '');
+ }
+
+ replaceWith(jqCollection, $compileNode, compileNode);
+
+ var newTemplateAttrs = {$attr: {}};
+
+ // combine directives from the original node and from the template:
+ // - take the array of directives for this element
+ // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
+ // - collect directives from the template and sort them by priority
+ // - combine directives as: processed + template + unprocessed
+ var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
+ var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
+
+ if (newIsolateScopeDirective) {
+ markDirectivesAsIsolate(templateDirectives);
+ }
+ directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
+ mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
+
+ ii = directives.length;
+ } else {
+ $compileNode.html(directiveValue);
+ }
+ }
+
+ if (directive.templateUrl) {
+ hasTemplate = true;
+ assertNoDuplicate('template', templateDirective, directive, $compileNode);
+ templateDirective = directive;
+
+ if (directive.replace) {
+ replaceDirective = directive;
+ }
+
+ nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
+ templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
+ controllerDirectives: controllerDirectives,
+ newIsolateScopeDirective: newIsolateScopeDirective,
+ templateDirective: templateDirective,
+ nonTlbTranscludeDirective: nonTlbTranscludeDirective
+ });
+ ii = directives.length;
+ } else if (directive.compile) {
+ try {
+ linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
+ if (isFunction(linkFn)) {
+ addLinkFns(null, linkFn, attrStart, attrEnd);
+ } else if (linkFn) {
+ addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
+ }
+ } catch (e) {
+ $exceptionHandler(e, startingTag($compileNode));
+ }
+ }
+
+ if (directive.terminal) {
+ nodeLinkFn.terminal = true;
+ terminalPriority = Math.max(terminalPriority, directive.priority);
+ }
+
+ }
+
+ nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
+ nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
+ nodeLinkFn.templateOnThisElement = hasTemplate;
+ nodeLinkFn.transclude = childTranscludeFn;
+
+ previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
+
+ // might be normal or delayed nodeLinkFn depending on if templateUrl is present
+ return nodeLinkFn;
+
+ ////////////////////
+
+ function addLinkFns(pre, post, attrStart, attrEnd) {
+ if (pre) {
+ if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
+ pre.require = directive.require;
+ pre.directiveName = directiveName;
+ if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
+ pre = cloneAndAnnotateFn(pre, {isolateScope: true});
+ }
+ preLinkFns.push(pre);
+ }
+ if (post) {
+ if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
+ post.require = directive.require;
+ post.directiveName = directiveName;
+ if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
+ post = cloneAndAnnotateFn(post, {isolateScope: true});
+ }
+ postLinkFns.push(post);
+ }
+ }
+
+
+ function getControllers(directiveName, require, $element, elementControllers) {
+ var value, retrievalMethod = 'data', optional = false;
+ if (isString(require)) {
+ while((value = require.charAt(0)) == '^' || value == '?') {
+ require = require.substr(1);
+ if (value == '^') {
+ retrievalMethod = 'inheritedData';
+ }
+ optional = optional || value == '?';
+ }
+ value = null;
+
+ if (elementControllers && retrievalMethod === 'data') {
+ value = elementControllers[require];
+ }
+ value = value || $element[retrievalMethod]('$' + require + 'Controller');
+
+ if (!value && !optional) {
+ throw $compileMinErr('ctreq',
+ "Controller '{0}', required by directive '{1}', can't be found!",
+ require, directiveName);
+ }
+ return value;
+ } else if (isArray(require)) {
+ value = [];
+ forEach(require, function(require) {
+ value.push(getControllers(directiveName, require, $element, elementControllers));
+ });
+ }
+ return value;
+ }
+
+
+ function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
+ var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn;
+
+ if (compileNode === linkNode) {
+ attrs = templateAttrs;
+ } else {
+ attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
+ }
+ $element = attrs.$$element;
+
+ if (newIsolateScopeDirective) {
+ var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
+ var $linkNode = jqLite(linkNode);
+
+ isolateScope = scope.$new(true);
+
+ if (templateDirective && (templateDirective === newIsolateScopeDirective ||
+ templateDirective === newIsolateScopeDirective.$$originalDirective)) {
+ $linkNode.data('$isolateScope', isolateScope) ;
+ } else {
+ $linkNode.data('$isolateScopeNoTemplate', isolateScope);
+ }
+
+
+
+ safeAddClass($linkNode, 'ng-isolate-scope');
+
+ forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
+ var match = definition.match(LOCAL_REGEXP) || [],
+ attrName = match[3] || scopeName,
+ optional = (match[2] == '?'),
+ mode = match[1], // @, =, or &
+ lastValue,
+ parentGet, parentSet, compare;
+
+ isolateScope.$$isolateBindings[scopeName] = mode + attrName;
+
+ switch (mode) {
+
+ case '@':
+ attrs.$observe(attrName, function(value) {
+ isolateScope[scopeName] = value;
+ });
+ attrs.$$observers[attrName].$$scope = scope;
+ if( attrs[attrName] ) {
+ // If the attribute has been provided then we trigger an interpolation to ensure
+ // the value is there for use in the link fn
+ isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
+ }
+ break;
+
+ case '=':
+ if (optional && !attrs[attrName]) {
+ return;
+ }
+ parentGet = $parse(attrs[attrName]);
+ if (parentGet.literal) {
+ compare = equals;
+ } else {
+ compare = function(a,b) { return a === b; };
+ }
+ parentSet = parentGet.assign || function() {
+ // reset the change, or we will throw this exception on every $digest
+ lastValue = isolateScope[scopeName] = parentGet(scope);
+ throw $compileMinErr('nonassign',
+ "Expression '{0}' used with directive '{1}' is non-assignable!",
+ attrs[attrName], newIsolateScopeDirective.name);
+ };
+ lastValue = isolateScope[scopeName] = parentGet(scope);
+ isolateScope.$watch(function parentValueWatch() {
+ var parentValue = parentGet(scope);
+ if (!compare(parentValue, isolateScope[scopeName])) {
+ // we are out of sync and need to copy
+ if (!compare(parentValue, lastValue)) {
+ // parent changed and it has precedence
+ isolateScope[scopeName] = parentValue;
+ } else {
+ // if the parent can be assigned then do so
+ parentSet(scope, parentValue = isolateScope[scopeName]);
+ }
+ }
+ return lastValue = parentValue;
+ }, null, parentGet.literal);
+ break;
+
+ case '&':
+ parentGet = $parse(attrs[attrName]);
+ isolateScope[scopeName] = function(locals) {
+ return parentGet(scope, locals);
+ };
+ break;
+
+ default:
+ throw $compileMinErr('iscp',
+ "Invalid isolate scope definition for directive '{0}'." +
+ " Definition: {... {1}: '{2}' ...}",
+ newIsolateScopeDirective.name, scopeName, definition);
+ }
+ });
+ }
+ transcludeFn = boundTranscludeFn && controllersBoundTransclude;
+ if (controllerDirectives) {
+ forEach(controllerDirectives, function(directive) {
+ var locals = {
+ $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
+ $element: $element,
+ $attrs: attrs,
+ $transclude: transcludeFn
+ }, controllerInstance;
+
+ controller = directive.controller;
+ if (controller == '@') {
+ controller = attrs[directive.name];
+ }
+
+ controllerInstance = $controller(controller, locals);
+ // For directives with element transclusion the element is a comment,
+ // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
+ // clean up (http://bugs.jquery.com/ticket/8335).
+ // Instead, we save the controllers for the element in a local hash and attach to .data
+ // later, once we have the actual element.
+ elementControllers[directive.name] = controllerInstance;
+ if (!hasElementTranscludeDirective) {
+ $element.data('$' + directive.name + 'Controller', controllerInstance);
+ }
+
+ if (directive.controllerAs) {
+ locals.$scope[directive.controllerAs] = controllerInstance;
+ }
+ });
+ }
+
+ // PRELINKING
+ for(i = 0, ii = preLinkFns.length; i < ii; i++) {
+ try {
+ linkFn = preLinkFns[i];
+ linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
+ linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn);
+ } catch (e) {
+ $exceptionHandler(e, startingTag($element));
+ }
+ }
+
+ // RECURSION
+ // We only pass the isolate scope, if the isolate directive has a template,
+ // otherwise the child elements do not belong to the isolate directive.
+ var scopeToChild = scope;
+ if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
+ scopeToChild = isolateScope;
+ }
+ childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
+
+ // POSTLINKING
+ for(i = postLinkFns.length - 1; i >= 0; i--) {
+ try {
+ linkFn = postLinkFns[i];
+ linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
+ linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn);
+ } catch (e) {
+ $exceptionHandler(e, startingTag($element));
+ }
+ }
+
+ // This is the function that is injected as `$transclude`.
+ function controllersBoundTransclude(scope, cloneAttachFn) {
+ var transcludeControllers;
+
+ // no scope passed
+ if (arguments.length < 2) {
+ cloneAttachFn = scope;
+ scope = undefined;
+ }
+
+ if (hasElementTranscludeDirective) {
+ transcludeControllers = elementControllers;
+ }
+
+ return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers);
+ }
+ }
+ }
+
+ function markDirectivesAsIsolate(directives) {
+ // mark all directives as needing isolate scope.
+ for (var j = 0, jj = directives.length; j < jj; j++) {
+ directives[j] = inherit(directives[j], {$$isolateScope: true});
+ }
+ }
+
+ /**
+ * looks up the directive and decorates it with exception handling and proper parameters. We
+ * call this the boundDirective.
+ *
+ * @param {string} name name of the directive to look up.
+ * @param {string} location The directive must be found in specific format.
+ * String containing any of theses characters:
+ *
+ * * `E`: element name
+ * * `A': attribute
+ * * `C`: class
+ * * `M`: comment
+ * @returns {boolean} true if directive was added.
+ */
+ function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
+ endAttrName) {
+ if (name === ignoreDirective) return null;
+ var match = null;
+ if (hasDirectives.hasOwnProperty(name)) {
+ for(var directive, directives = $injector.get(name + Suffix),
+ i = 0, ii = directives.length; i directive.priority) &&
+ directive.restrict.indexOf(location) != -1) {
+ if (startAttrName) {
+ directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
+ }
+ tDirectives.push(directive);
+ match = directive;
+ }
+ } catch(e) { $exceptionHandler(e); }
+ }
+ }
+ return match;
+ }
+
+
+ /**
+ * When the element is replaced with HTML template then the new attributes
+ * on the template need to be merged with the existing attributes in the DOM.
+ * The desired effect is to have both of the attributes present.
+ *
+ * @param {object} dst destination attributes (original DOM)
+ * @param {object} src source attributes (from the directive template)
+ */
+ function mergeTemplateAttributes(dst, src) {
+ var srcAttr = src.$attr,
+ dstAttr = dst.$attr,
+ $element = dst.$$element;
+
+ // reapply the old attributes to the new element
+ forEach(dst, function(value, key) {
+ if (key.charAt(0) != '$') {
+ if (src[key] && src[key] !== value) {
+ value += (key === 'style' ? ';' : ' ') + src[key];
+ }
+ dst.$set(key, value, true, srcAttr[key]);
+ }
+ });
+
+ // copy the new attributes on the old attrs object
+ forEach(src, function(value, key) {
+ if (key == 'class') {
+ safeAddClass($element, value);
+ dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
+ } else if (key == 'style') {
+ $element.attr('style', $element.attr('style') + ';' + value);
+ dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
+ // `dst` will never contain hasOwnProperty as DOM parser won't let it.
+ // You will get an "InvalidCharacterError: DOM Exception 5" error if you
+ // have an attribute like "has-own-property" or "data-has-own-property", etc.
+ } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
+ dst[key] = value;
+ dstAttr[key] = srcAttr[key];
+ }
+ });
+ }
+
+
+ function compileTemplateUrl(directives, $compileNode, tAttrs,
+ $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
+ var linkQueue = [],
+ afterTemplateNodeLinkFn,
+ afterTemplateChildLinkFn,
+ beforeTemplateCompileNode = $compileNode[0],
+ origAsyncDirective = directives.shift(),
+ // The fact that we have to copy and patch the directive seems wrong!
+ derivedSyncDirective = extend({}, origAsyncDirective, {
+ templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
+ }),
+ templateUrl = (isFunction(origAsyncDirective.templateUrl))
+ ? origAsyncDirective.templateUrl($compileNode, tAttrs)
+ : origAsyncDirective.templateUrl;
+
+ $compileNode.empty();
+
+ $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
+ success(function(content) {
+ var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
+
+ content = denormalizeTemplate(content);
+
+ if (origAsyncDirective.replace) {
+ if (jqLiteIsTextNode(content)) {
+ $template = [];
+ } else {
+ $template = jqLite(trim(content));
+ }
+ compileNode = $template[0];
+
+ if ($template.length != 1 || compileNode.nodeType !== 1) {
+ throw $compileMinErr('tplrt',
+ "Template for directive '{0}' must have exactly one root element. {1}",
+ origAsyncDirective.name, templateUrl);
+ }
+
+ tempTemplateAttrs = {$attr: {}};
+ replaceWith($rootElement, $compileNode, compileNode);
+ var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
+
+ if (isObject(origAsyncDirective.scope)) {
+ markDirectivesAsIsolate(templateDirectives);
+ }
+ directives = templateDirectives.concat(directives);
+ mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
+ } else {
+ compileNode = beforeTemplateCompileNode;
+ $compileNode.html(content);
+ }
+
+ directives.unshift(derivedSyncDirective);
+
+ afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
+ childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
+ previousCompileContext);
+ forEach($rootElement, function(node, i) {
+ if (node == compileNode) {
+ $rootElement[i] = $compileNode[0];
+ }
+ });
+ afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
+
+ while(linkQueue.length) {
+ var scope = linkQueue.shift(),
+ beforeTemplateLinkNode = linkQueue.shift(),
+ linkRootElement = linkQueue.shift(),
+ boundTranscludeFn = linkQueue.shift(),
+ linkNode = $compileNode[0];
+
+ if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
+ var oldClasses = beforeTemplateLinkNode.className;
+
+ if (!(previousCompileContext.hasElementTranscludeDirective &&
+ origAsyncDirective.replace)) {
+ // it was cloned therefore we have to clone as well.
+ linkNode = jqLiteClone(compileNode);
+ }
+
+ replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
+
+ // Copy in CSS classes from original node
+ safeAddClass(jqLite(linkNode), oldClasses);
+ }
+ if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
+ childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
+ } else {
+ childBoundTranscludeFn = boundTranscludeFn;
+ }
+ afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
+ childBoundTranscludeFn);
+ }
+ linkQueue = null;
+ }).
+ error(function(response, code, headers, config) {
+ throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
+ });
+
+ return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
+ var childBoundTranscludeFn = boundTranscludeFn;
+ if (linkQueue) {
+ linkQueue.push(scope);
+ linkQueue.push(node);
+ linkQueue.push(rootElement);
+ linkQueue.push(childBoundTranscludeFn);
+ } else {
+ if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
+ childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
+ }
+ afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
+ }
+ };
+ }
+
+
+ /**
+ * Sorting function for bound directives.
+ */
+ function byPriority(a, b) {
+ var diff = b.priority - a.priority;
+ if (diff !== 0) return diff;
+ if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
+ return a.index - b.index;
+ }
+
+
+ function assertNoDuplicate(what, previousDirective, directive, element) {
+ if (previousDirective) {
+ throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
+ previousDirective.name, directive.name, what, startingTag(element));
+ }
+ }
+
+
+ function addTextInterpolateDirective(directives, text) {
+ var interpolateFn = $interpolate(text, true);
+ if (interpolateFn) {
+ directives.push({
+ priority: 0,
+ compile: function textInterpolateCompileFn(templateNode) {
+ // when transcluding a template that has bindings in the root
+ // then we don't have a parent and should do this in the linkFn
+ var parent = templateNode.parent(), hasCompileParent = parent.length;
+ if (hasCompileParent) safeAddClass(templateNode.parent(), 'ng-binding');
+
+ return function textInterpolateLinkFn(scope, node) {
+ var parent = node.parent(),
+ bindings = parent.data('$binding') || [];
+ bindings.push(interpolateFn);
+ parent.data('$binding', bindings);
+ if (!hasCompileParent) safeAddClass(parent, 'ng-binding');
+ scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
+ node[0].nodeValue = value;
+ });
+ };
+ }
+ });
+ }
+ }
+
+
+ function getTrustedContext(node, attrNormalizedName) {
+ if (attrNormalizedName == "srcdoc") {
+ return $sce.HTML;
+ }
+ var tag = nodeName_(node);
+ // maction[xlink:href] can source SVG. It's not limited to .
+ if (attrNormalizedName == "xlinkHref" ||
+ (tag == "FORM" && attrNormalizedName == "action") ||
+ (tag != "IMG" && (attrNormalizedName == "src" ||
+ attrNormalizedName == "ngSrc"))) {
+ return $sce.RESOURCE_URL;
+ }
+ }
+
+
+ function addAttrInterpolateDirective(node, directives, value, name) {
+ var interpolateFn = $interpolate(value, true);
+
+ // no interpolation found -> ignore
+ if (!interpolateFn) return;
+
+
+ if (name === "multiple" && nodeName_(node) === "SELECT") {
+ throw $compileMinErr("selmulti",
+ "Binding to the 'multiple' attribute is not supported. Element: {0}",
+ startingTag(node));
+ }
+
+ directives.push({
+ priority: 100,
+ compile: function() {
+ return {
+ pre: function attrInterpolatePreLinkFn(scope, element, attr) {
+ var $$observers = (attr.$$observers || (attr.$$observers = {}));
+
+ if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
+ throw $compileMinErr('nodomevents',
+ "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
+ "ng- versions (such as ng-click instead of onclick) instead.");
+ }
+
+ // we need to interpolate again, in case the attribute value has been updated
+ // (e.g. by another directive's compile function)
+ interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
+
+ // if attribute was updated so that there is no interpolation going on we don't want to
+ // register any observers
+ if (!interpolateFn) return;
+
+ // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the
+ // actual attr value
+ attr[name] = interpolateFn(scope);
+ ($$observers[name] || ($$observers[name] = [])).$$inter = true;
+ (attr.$$observers && attr.$$observers[name].$$scope || scope).
+ $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
+ //special case for class attribute addition + removal
+ //so that class changes can tap into the animation
+ //hooks provided by the $animate service. Be sure to
+ //skip animations when the first digest occurs (when
+ //both the new and the old values are the same) since
+ //the CSS classes are the non-interpolated values
+ if(name === 'class' && newValue != oldValue) {
+ attr.$updateClass(newValue, oldValue);
+ } else {
+ attr.$set(name, newValue);
+ }
+ });
+ }
+ };
+ }
+ });
+ }
+
+
+ /**
+ * This is a special jqLite.replaceWith, which can replace items which
+ * have no parents, provided that the containing jqLite collection is provided.
+ *
+ * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
+ * in the root of the tree.
+ * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
+ * the shell, but replace its DOM node reference.
+ * @param {Node} newNode The new DOM node.
+ */
+ function replaceWith($rootElement, elementsToRemove, newNode) {
+ var firstElementToRemove = elementsToRemove[0],
+ removeCount = elementsToRemove.length,
+ parent = firstElementToRemove.parentNode,
+ i, ii;
+
+ if ($rootElement) {
+ for(i = 0, ii = $rootElement.length; i < ii; i++) {
+ if ($rootElement[i] == firstElementToRemove) {
+ $rootElement[i++] = newNode;
+ for (var j = i, j2 = j + removeCount - 1,
+ jj = $rootElement.length;
+ j < jj; j++, j2++) {
+ if (j2 < jj) {
+ $rootElement[j] = $rootElement[j2];
+ } else {
+ delete $rootElement[j];
+ }
+ }
+ $rootElement.length -= removeCount - 1;
+ break;
+ }
+ }
+ }
+
+ if (parent) {
+ parent.replaceChild(newNode, firstElementToRemove);
+ }
+ var fragment = document.createDocumentFragment();
+ fragment.appendChild(firstElementToRemove);
+ newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
+ for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
+ var element = elementsToRemove[k];
+ jqLite(element).remove(); // must do this way to clean up expando
+ fragment.appendChild(element);
+ delete elementsToRemove[k];
+ }
+
+ elementsToRemove[0] = newNode;
+ elementsToRemove.length = 1;
+ }
+
+
+ function cloneAndAnnotateFn(fn, annotation) {
+ return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
+ }
+ }];
+}
+
+var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
+/**
+ * Converts all accepted directives format into proper directive name.
+ * All of these will become 'myDirective':
+ * my:Directive
+ * my-directive
+ * x-my-directive
+ * data-my:directive
+ *
+ * Also there is special case for Moz prefix starting with upper case letter.
+ * @param name Name to normalize
+ */
+function directiveNormalize(name) {
+ return camelCase(name.replace(PREFIX_REGEXP, ''));
+}
+
+/**
+ * @ngdoc type
+ * @name $compile.directive.Attributes
+ *
+ * @description
+ * A shared object between directive compile / linking functions which contains normalized DOM
+ * element attributes. The values reflect current binding state `{{ }}`. The normalization is
+ * needed since all of these are treated as equivalent in Angular:
+ *
+ * ```
+ *
+ * ```
+ */
+
+/**
+ * @ngdoc property
+ * @name $compile.directive.Attributes#$attr
+ * @returns {object} A map of DOM element attribute names to the normalized name. This is
+ * needed to do reverse lookup from normalized name back to actual name.
+ */
+
+
+/**
+ * @ngdoc method
+ * @name $compile.directive.Attributes#$set
+ * @kind function
+ *
+ * @description
+ * Set DOM element attribute value.
+ *
+ *
+ * @param {string} name Normalized element attribute name of the property to modify. The name is
+ * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
+ * property to the original name.
+ * @param {string} value Value to set the attribute to. The value can be an interpolated string.
+ */
+
+
+
+/**
+ * Closure compiler type information
+ */
+
+function nodesetLinkingFn(
+ /* angular.Scope */ scope,
+ /* NodeList */ nodeList,
+ /* Element */ rootElement,
+ /* function(Function) */ boundTranscludeFn
+){}
+
+function directiveLinkingFn(
+ /* nodesetLinkingFn */ nodesetLinkingFn,
+ /* angular.Scope */ scope,
+ /* Node */ node,
+ /* Element */ rootElement,
+ /* function(Function) */ boundTranscludeFn
+){}
+
+function tokenDifference(str1, str2) {
+ var values = '',
+ tokens1 = str1.split(/\s+/),
+ tokens2 = str2.split(/\s+/);
+
+ outer:
+ for(var i = 0; i < tokens1.length; i++) {
+ var token = tokens1[i];
+ for(var j = 0; j < tokens2.length; j++) {
+ if(token == tokens2[j]) continue outer;
+ }
+ values += (values.length > 0 ? ' ' : '') + token;
+ }
+ return values;
+}
+
+/**
+ * @ngdoc provider
+ * @name $controllerProvider
+ * @description
+ * The {@link ng.$controller $controller service} is used by Angular to create new
+ * controllers.
+ *
+ * This provider allows controller registration via the
+ * {@link ng.$controllerProvider#register register} method.
+ */
+function $ControllerProvider() {
+ var controllers = {},
+ CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
+
+
+ /**
+ * @ngdoc method
+ * @name $controllerProvider#register
+ * @param {string|Object} name Controller name, or an object map of controllers where the keys are
+ * the names and the values are the constructors.
+ * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
+ * annotations in the array notation).
+ */
+ this.register = function(name, constructor) {
+ assertNotHasOwnProperty(name, 'controller');
+ if (isObject(name)) {
+ extend(controllers, name);
+ } else {
+ controllers[name] = constructor;
+ }
+ };
+
+
+ this.$get = ['$injector', '$window', function($injector, $window) {
+
+ /**
+ * @ngdoc service
+ * @name $controller
+ * @requires $injector
+ *
+ * @param {Function|string} constructor If called with a function then it's considered to be the
+ * controller constructor function. Otherwise it's considered to be a string which is used
+ * to retrieve the controller constructor using the following steps:
+ *
+ * * check if a controller with given name is registered via `$controllerProvider`
+ * * check if evaluating the string on the current scope returns a constructor
+ * * check `window[constructor]` on the global `window` object
+ *
+ * @param {Object} locals Injection locals for Controller.
+ * @return {Object} Instance of given controller.
+ *
+ * @description
+ * `$controller` service is responsible for instantiating controllers.
+ *
+ * It's just a simple call to {@link auto.$injector $injector}, but extracted into
+ * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
+ */
+ return function(expression, locals) {
+ var instance, match, constructor, identifier;
+
+ if(isString(expression)) {
+ match = expression.match(CNTRL_REG),
+ constructor = match[1],
+ identifier = match[3];
+ expression = controllers.hasOwnProperty(constructor)
+ ? controllers[constructor]
+ : getter(locals.$scope, constructor, true) || getter($window, constructor, true);
+
+ assertArgFn(expression, constructor, true);
+ }
+
+ instance = $injector.instantiate(expression, locals);
+
+ if (identifier) {
+ if (!(locals && typeof locals.$scope === 'object')) {
+ throw minErr('$controller')('noscp',
+ "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
+ constructor || expression.name, identifier);
+ }
+
+ locals.$scope[identifier] = instance;
+ }
+
+ return instance;
+ };
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name $document
+ * @requires $window
+ *
+ * @description
+ * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
+ *
+ * @example
+
+
+
+
$document title:
+
window.document title:
+
+
+
+ function MainCtrl($scope, $document) {
+ $scope.title = $document[0].title;
+ $scope.windowTitle = angular.element(window.document)[0].title;
+ }
+
+
+ */
+function $DocumentProvider(){
+ this.$get = ['$window', function(window){
+ return jqLite(window.document);
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name $exceptionHandler
+ * @requires ng.$log
+ *
+ * @description
+ * Any uncaught exception in angular expressions is delegated to this service.
+ * The default implementation simply delegates to `$log.error` which logs it into
+ * the browser console.
+ *
+ * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
+ * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
+ *
+ * ## Example:
+ *
+ * ```js
+ * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
+ * return function (exception, cause) {
+ * exception.message += ' (caused by "' + cause + '")';
+ * throw exception;
+ * };
+ * });
+ * ```
+ *
+ * This example will override the normal action of `$exceptionHandler`, to make angular
+ * exceptions fail hard when they happen, instead of just logging to the console.
+ *
+ * @param {Error} exception Exception associated with the error.
+ * @param {string=} cause optional information about the context in which
+ * the error was thrown.
+ *
+ */
+function $ExceptionHandlerProvider() {
+ this.$get = ['$log', function($log) {
+ return function(exception, cause) {
+ $log.error.apply($log, arguments);
+ };
+ }];
+}
+
+/**
+ * Parse headers into key value object
+ *
+ * @param {string} headers Raw headers as a string
+ * @returns {Object} Parsed headers as key value object
+ */
+function parseHeaders(headers) {
+ var parsed = {}, key, val, i;
+
+ if (!headers) return parsed;
+
+ forEach(headers.split('\n'), function(line) {
+ i = line.indexOf(':');
+ key = lowercase(trim(line.substr(0, i)));
+ val = trim(line.substr(i + 1));
+
+ if (key) {
+ if (parsed[key]) {
+ parsed[key] += ', ' + val;
+ } else {
+ parsed[key] = val;
+ }
+ }
+ });
+
+ return parsed;
+}
+
+
+/**
+ * Returns a function that provides access to parsed headers.
+ *
+ * Headers are lazy parsed when first requested.
+ * @see parseHeaders
+ *
+ * @param {(string|Object)} headers Headers to provide access to.
+ * @returns {function(string=)} Returns a getter function which if called with:
+ *
+ * - if called with single an argument returns a single header value or null
+ * - if called with no arguments returns an object containing all headers.
+ */
+function headersGetter(headers) {
+ var headersObj = isObject(headers) ? headers : undefined;
+
+ return function(name) {
+ if (!headersObj) headersObj = parseHeaders(headers);
+
+ if (name) {
+ return headersObj[lowercase(name)] || null;
+ }
+
+ return headersObj;
+ };
+}
+
+
+/**
+ * Chain all given functions
+ *
+ * This function is used for both request and response transforming
+ *
+ * @param {*} data Data to transform.
+ * @param {function(string=)} headers Http headers getter fn.
+ * @param {(Function|Array.)} fns Function or an array of functions.
+ * @returns {*} Transformed data.
+ */
+function transformData(data, headers, fns) {
+ if (isFunction(fns))
+ return fns(data, headers);
+
+ forEach(fns, function(fn) {
+ data = fn(data, headers);
+ });
+
+ return data;
+}
+
+
+function isSuccess(status) {
+ return 200 <= status && status < 300;
+}
+
+
+function $HttpProvider() {
+ var JSON_START = /^\s*(\[|\{[^\{])/,
+ JSON_END = /[\}\]]\s*$/,
+ PROTECTION_PREFIX = /^\)\]\}',?\n/,
+ CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
+
+ var defaults = this.defaults = {
+ // transform incoming response data
+ transformResponse: [function(data) {
+ if (isString(data)) {
+ // strip json vulnerability protection prefix
+ data = data.replace(PROTECTION_PREFIX, '');
+ if (JSON_START.test(data) && JSON_END.test(data))
+ data = fromJson(data);
+ }
+ return data;
+ }],
+
+ // transform outgoing request data
+ transformRequest: [function(d) {
+ return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
+ }],
+
+ // default headers
+ headers: {
+ common: {
+ 'Accept': 'application/json, text/plain, */*'
+ },
+ post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
+ put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
+ patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
+ },
+
+ xsrfCookieName: 'XSRF-TOKEN',
+ xsrfHeaderName: 'X-XSRF-TOKEN'
+ };
+
+ /**
+ * Are ordered by request, i.e. they are applied in the same order as the
+ * array, on request, but reverse order, on response.
+ */
+ var interceptorFactories = this.interceptors = [];
+
+ /**
+ * For historical reasons, response interceptors are ordered by the order in which
+ * they are applied to the response. (This is the opposite of interceptorFactories)
+ */
+ var responseInterceptorFactories = this.responseInterceptors = [];
+
+ this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
+ function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
+
+ var defaultCache = $cacheFactory('$http');
+
+ /**
+ * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
+ * The reversal is needed so that we can build up the interception chain around the
+ * server request.
+ */
+ var reversedInterceptors = [];
+
+ forEach(interceptorFactories, function(interceptorFactory) {
+ reversedInterceptors.unshift(isString(interceptorFactory)
+ ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
+ });
+
+ forEach(responseInterceptorFactories, function(interceptorFactory, index) {
+ var responseFn = isString(interceptorFactory)
+ ? $injector.get(interceptorFactory)
+ : $injector.invoke(interceptorFactory);
+
+ /**
+ * Response interceptors go before "around" interceptors (no real reason, just
+ * had to pick one.) But they are already reversed, so we can't use unshift, hence
+ * the splice.
+ */
+ reversedInterceptors.splice(index, 0, {
+ response: function(response) {
+ return responseFn($q.when(response));
+ },
+ responseError: function(response) {
+ return responseFn($q.reject(response));
+ }
+ });
+ });
+
+
+ /**
+ * @ngdoc service
+ * @kind function
+ * @name $http
+ * @requires ng.$httpBackend
+ * @requires $cacheFactory
+ * @requires $rootScope
+ * @requires $q
+ * @requires $injector
+ *
+ * @description
+ * The `$http` service is a core Angular service that facilitates communication with the remote
+ * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
+ * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
+ *
+ * For unit testing applications that use `$http` service, see
+ * {@link ngMock.$httpBackend $httpBackend mock}.
+ *
+ * For a higher level of abstraction, please check out the {@link ngResource.$resource
+ * $resource} service.
+ *
+ * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
+ * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
+ * it is important to familiarize yourself with these APIs and the guarantees they provide.
+ *
+ *
+ * # General usage
+ * The `$http` service is a function which takes a single argument — a configuration object —
+ * that is used to generate an HTTP request and returns a {@link ng.$q promise}
+ * with two $http specific methods: `success` and `error`.
+ *
+ * ```js
+ * $http({method: 'GET', url: '/someUrl'}).
+ * success(function(data, status, headers, config) {
+ * // this callback will be called asynchronously
+ * // when the response is available
+ * }).
+ * error(function(data, status, headers, config) {
+ * // called asynchronously if an error occurs
+ * // or server returns response with an error status.
+ * });
+ * ```
+ *
+ * Since the returned value of calling the $http function is a `promise`, you can also use
+ * the `then` method to register callbacks, and these callbacks will receive a single argument –
+ * an object representing the response. See the API signature and type info below for more
+ * details.
+ *
+ * A response status code between 200 and 299 is considered a success status and
+ * will result in the success callback being called. Note that if the response is a redirect,
+ * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
+ * called for such responses.
+ *
+ * # Writing Unit Tests that use $http
+ * When unit testing (using {@link ngMock ngMock}), it is necessary to call
+ * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
+ * request using trained responses.
+ *
+ * ```
+ * $httpBackend.expectGET(...);
+ * $http.get(...);
+ * $httpBackend.flush();
+ * ```
+ *
+ * # Shortcut methods
+ *
+ * Shortcut methods are also available. All shortcut methods require passing in the URL, and
+ * request data must be passed in for POST/PUT requests.
+ *
+ * ```js
+ * $http.get('/someUrl').success(successCallback);
+ * $http.post('/someUrl', data).success(successCallback);
+ * ```
+ *
+ * Complete list of shortcut methods:
+ *
+ * - {@link ng.$http#get $http.get}
+ * - {@link ng.$http#head $http.head}
+ * - {@link ng.$http#post $http.post}
+ * - {@link ng.$http#put $http.put}
+ * - {@link ng.$http#delete $http.delete}
+ * - {@link ng.$http#jsonp $http.jsonp}
+ *
+ *
+ * # Setting HTTP Headers
+ *
+ * The $http service will automatically add certain HTTP headers to all requests. These defaults
+ * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
+ * object, which currently contains this default configuration:
+ *
+ * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
+ * - `Accept: application/json, text/plain, * / *`
+ * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
+ * - `Content-Type: application/json`
+ * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
+ * - `Content-Type: application/json`
+ *
+ * To add or overwrite these defaults, simply add or remove a property from these configuration
+ * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
+ * with the lowercased HTTP method name as the key, e.g.
+ * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
+ *
+ * The defaults can also be set at runtime via the `$http.defaults` object in the same
+ * fashion. For example:
+ *
+ * ```
+ * module.run(function($http) {
+ * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
+ * });
+ * ```
+ *
+ * In addition, you can supply a `headers` property in the config object passed when
+ * calling `$http(config)`, which overrides the defaults without changing them globally.
+ *
+ *
+ * # Transforming Requests and Responses
+ *
+ * Both requests and responses can be transformed using transform functions. By default, Angular
+ * applies these transformations:
+ *
+ * Request transformations:
+ *
+ * - If the `data` property of the request configuration object contains an object, serialize it
+ * into JSON format.
+ *
+ * Response transformations:
+ *
+ * - If XSRF prefix is detected, strip it (see Security Considerations section below).
+ * - If JSON response is detected, deserialize it using a JSON parser.
+ *
+ * To globally augment or override the default transforms, modify the
+ * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse`
+ * properties. These properties are by default an array of transform functions, which allows you
+ * to `push` or `unshift` a new transformation function into the transformation chain. You can
+ * also decide to completely override any default transformations by assigning your
+ * transformation functions to these properties directly without the array wrapper. These defaults
+ * are again available on the $http factory at run-time, which may be useful if you have run-time
+ * services you wish to be involved in your transformations.
+ *
+ * Similarly, to locally override the request/response transforms, augment the
+ * `transformRequest` and/or `transformResponse` properties of the configuration object passed
+ * into `$http`.
+ *
+ *
+ * # Caching
+ *
+ * To enable caching, set the request configuration `cache` property to `true` (to use default
+ * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
+ * When the cache is enabled, `$http` stores the response from the server in the specified
+ * cache. The next time the same request is made, the response is served from the cache without
+ * sending a request to the server.
+ *
+ * Note that even if the response is served from cache, delivery of the data is asynchronous in
+ * the same way that real requests are.
+ *
+ * If there are multiple GET requests for the same URL that should be cached using the same
+ * cache, but the cache is not populated yet, only one request to the server will be made and
+ * the remaining requests will be fulfilled using the response from the first request.
+ *
+ * You can change the default cache to a new object (built with
+ * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
+ * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set
+ * their `cache` property to `true` will now use this cache object.
+ *
+ * If you set the default cache to `false` then only requests that specify their own custom
+ * cache object will be cached.
+ *
+ * # Interceptors
+ *
+ * Before you start creating interceptors, be sure to understand the
+ * {@link ng.$q $q and deferred/promise APIs}.
+ *
+ * For purposes of global error handling, authentication, or any kind of synchronous or
+ * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
+ * able to intercept requests before they are handed to the server and
+ * responses before they are handed over to the application code that
+ * initiated these requests. The interceptors leverage the {@link ng.$q
+ * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
+ *
+ * The interceptors are service factories that are registered with the `$httpProvider` by
+ * adding them to the `$httpProvider.interceptors` array. The factory is called and
+ * injected with dependencies (if specified) and returns the interceptor.
+ *
+ * There are two kinds of interceptors (and two kinds of rejection interceptors):
+ *
+ * * `request`: interceptors get called with a http `config` object. The function is free to
+ * modify the `config` object or create a new one. The function needs to return the `config`
+ * object directly, or a promise containing the `config` or a new `config` object.
+ * * `requestError`: interceptor gets called when a previous interceptor threw an error or
+ * resolved with a rejection.
+ * * `response`: interceptors get called with http `response` object. The function is free to
+ * modify the `response` object or create a new one. The function needs to return the `response`
+ * object directly, or as a promise containing the `response` or a new `response` object.
+ * * `responseError`: interceptor gets called when a previous interceptor threw an error or
+ * resolved with a rejection.
+ *
+ *
+ * ```js
+ * // register the interceptor as a service
+ * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
+ * return {
+ * // optional method
+ * 'request': function(config) {
+ * // do something on success
+ * return config;
+ * },
+ *
+ * // optional method
+ * 'requestError': function(rejection) {
+ * // do something on error
+ * if (canRecover(rejection)) {
+ * return responseOrNewPromise
+ * }
+ * return $q.reject(rejection);
+ * },
+ *
+ *
+ *
+ * // optional method
+ * 'response': function(response) {
+ * // do something on success
+ * return response;
+ * },
+ *
+ * // optional method
+ * 'responseError': function(rejection) {
+ * // do something on error
+ * if (canRecover(rejection)) {
+ * return responseOrNewPromise
+ * }
+ * return $q.reject(rejection);
+ * }
+ * };
+ * });
+ *
+ * $httpProvider.interceptors.push('myHttpInterceptor');
+ *
+ *
+ * // alternatively, register the interceptor via an anonymous factory
+ * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
+ * return {
+ * 'request': function(config) {
+ * // same as above
+ * },
+ *
+ * 'response': function(response) {
+ * // same as above
+ * }
+ * };
+ * });
+ * ```
+ *
+ * # Response interceptors (DEPRECATED)
+ *
+ * Before you start creating interceptors, be sure to understand the
+ * {@link ng.$q $q and deferred/promise APIs}.
+ *
+ * For purposes of global error handling, authentication or any kind of synchronous or
+ * asynchronous preprocessing of received responses, it is desirable to be able to intercept
+ * responses for http requests before they are handed over to the application code that
+ * initiated these requests. The response interceptors leverage the {@link ng.$q
+ * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
+ *
+ * The interceptors are service factories that are registered with the $httpProvider by
+ * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
+ * injected with dependencies (if specified) and returns the interceptor — a function that
+ * takes a {@link ng.$q promise} and returns the original or a new promise.
+ *
+ * ```js
+ * // register the interceptor as a service
+ * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
+ * return function(promise) {
+ * return promise.then(function(response) {
+ * // do something on success
+ * return response;
+ * }, function(response) {
+ * // do something on error
+ * if (canRecover(response)) {
+ * return responseOrNewPromise
+ * }
+ * return $q.reject(response);
+ * });
+ * }
+ * });
+ *
+ * $httpProvider.responseInterceptors.push('myHttpInterceptor');
+ *
+ *
+ * // register the interceptor via an anonymous factory
+ * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
+ * return function(promise) {
+ * // same as above
+ * }
+ * });
+ * ```
+ *
+ *
+ * # Security Considerations
+ *
+ * When designing web applications, consider security threats from:
+ *
+ * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
+ * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
+ *
+ * Both server and the client must cooperate in order to eliminate these threats. Angular comes
+ * pre-configured with strategies that address these issues, but for this to work backend server
+ * cooperation is required.
+ *
+ * ## JSON Vulnerability Protection
+ *
+ * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
+ * allows third party website to turn your JSON resource URL into
+ * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
+ * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
+ * Angular will automatically strip the prefix before processing it as JSON.
+ *
+ * For example if your server needs to return:
+ * ```js
+ * ['one','two']
+ * ```
+ *
+ * which is vulnerable to attack, your server can return:
+ * ```js
+ * )]}',
+ * ['one','two']
+ * ```
+ *
+ * Angular will strip the prefix, before processing the JSON.
+ *
+ *
+ * ## Cross Site Request Forgery (XSRF) Protection
+ *
+ * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
+ * an unauthorized site can gain your user's private data. Angular provides a mechanism
+ * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
+ * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
+ * JavaScript that runs on your domain could read the cookie, your server can be assured that
+ * the XHR came from JavaScript running on your domain. The header will not be set for
+ * cross-domain requests.
+ *
+ * To take advantage of this, your server needs to set a token in a JavaScript readable session
+ * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
+ * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
+ * that only JavaScript running on your domain could have sent the request. The token must be
+ * unique for each user and must be verifiable by the server (to prevent the JavaScript from
+ * making up its own tokens). We recommend that the token is a digest of your site's
+ * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
+ * for added security.
+ *
+ * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
+ * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
+ * or the per-request config object.
+ *
+ *
+ * @param {object} config Object describing the request to be made and how it should be
+ * processed. The object has following properties:
+ *
+ * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
+ * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
+ * - **params** – `{Object.}` – Map of strings or objects which will be turned
+ * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
+ * JSONified.
+ * - **data** – `{string|Object}` – Data to be sent as the request message data.
+ * - **headers** – `{Object}` – Map of strings or functions which return strings representing
+ * HTTP headers to send to the server. If the return value of a function is null, the
+ * header will not be sent.
+ * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
+ * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
+ * - **transformRequest** –
+ * `{function(data, headersGetter)|Array.}` –
+ * transform function or an array of such functions. The transform function takes the http
+ * request body and headers and returns its transformed (typically serialized) version.
+ * - **transformResponse** –
+ * `{function(data, headersGetter)|Array.}` –
+ * transform function or an array of such functions. The transform function takes the http
+ * response body and headers and returns its transformed (typically deserialized) version.
+ * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
+ * GET request, otherwise if a cache instance built with
+ * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
+ * caching.
+ * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
+ * that should abort the request when resolved.
+ * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
+ * XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5
+ * for more information.
+ * - **responseType** - `{string}` - see
+ * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
+ *
+ * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
+ * standard `then` method and two http specific methods: `success` and `error`. The `then`
+ * method takes two arguments a success and an error callback which will be called with a
+ * response object. The `success` and `error` methods take a single argument - a function that
+ * will be called when the request succeeds or fails respectively. The arguments passed into
+ * these functions are destructured representation of the response object passed into the
+ * `then` method. The response object has these properties:
+ *
+ * - **data** – `{string|Object}` – The response body transformed with the transform
+ * functions.
+ * - **status** – `{number}` – HTTP status code of the response.
+ * - **headers** – `{function([headerName])}` – Header getter function.
+ * - **config** – `{Object}` – The configuration object that was used to generate the request.
+ * - **statusText** – `{string}` – HTTP status text of the response.
+ *
+ * @property {Array.
+ *
+ * @param {function()} fn A function that should be called repeatedly.
+ * @param {number} delay Number of milliseconds between each function call.
+ * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
+ * indefinitely.
+ * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
+ * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
+ * @returns {promise} A promise which will be notified on each iteration.
+ *
+ * @example
+ *
+ *
+ *
+ *
+ *
+ *
+ * Date format:
+ * Current time is:
+ *
+ * Blood 1 : {{blood_1}}
+ * Blood 2 : {{blood_2}}
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+ function interval(fn, delay, count, invokeApply) {
+ var setInterval = $window.setInterval,
+ clearInterval = $window.clearInterval,
+ deferred = $q.defer(),
+ promise = deferred.promise,
+ iteration = 0,
+ skipApply = (isDefined(invokeApply) && !invokeApply);
+
+ count = isDefined(count) ? count : 0;
+
+ promise.then(null, null, fn);
+
+ promise.$$intervalId = setInterval(function tick() {
+ deferred.notify(iteration++);
+
+ if (count > 0 && iteration >= count) {
+ deferred.resolve(iteration);
+ clearInterval(promise.$$intervalId);
+ delete intervals[promise.$$intervalId];
+ }
+
+ if (!skipApply) $rootScope.$apply();
+
+ }, delay);
+
+ intervals[promise.$$intervalId] = deferred;
+
+ return promise;
+ }
+
+
+ /**
+ * @ngdoc method
+ * @name $interval#cancel
+ *
+ * @description
+ * Cancels a task associated with the `promise`.
+ *
+ * @param {promise} promise returned by the `$interval` function.
+ * @returns {boolean} Returns `true` if the task was successfully canceled.
+ */
+ interval.cancel = function(promise) {
+ if (promise && promise.$$intervalId in intervals) {
+ intervals[promise.$$intervalId].reject('canceled');
+ $window.clearInterval(promise.$$intervalId);
+ delete intervals[promise.$$intervalId];
+ return true;
+ }
+ return false;
+ };
+
+ return interval;
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name $locale
+ *
+ * @description
+ * $locale service provides localization rules for various Angular components. As of right now the
+ * only public api is:
+ *
+ * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
+ */
+function $LocaleProvider(){
+ this.$get = function() {
+ return {
+ id: 'en-us',
+
+ NUMBER_FORMATS: {
+ DECIMAL_SEP: '.',
+ GROUP_SEP: ',',
+ PATTERNS: [
+ { // Decimal Pattern
+ minInt: 1,
+ minFrac: 0,
+ maxFrac: 3,
+ posPre: '',
+ posSuf: '',
+ negPre: '-',
+ negSuf: '',
+ gSize: 3,
+ lgSize: 3
+ },{ //Currency Pattern
+ minInt: 1,
+ minFrac: 2,
+ maxFrac: 2,
+ posPre: '\u00A4',
+ posSuf: '',
+ negPre: '(\u00A4',
+ negSuf: ')',
+ gSize: 3,
+ lgSize: 3
+ }
+ ],
+ CURRENCY_SYM: '$'
+ },
+
+ DATETIME_FORMATS: {
+ MONTH:
+ 'January,February,March,April,May,June,July,August,September,October,November,December'
+ .split(','),
+ SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
+ DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
+ SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
+ AMPMS: ['AM','PM'],
+ medium: 'MMM d, y h:mm:ss a',
+ short: 'M/d/yy h:mm a',
+ fullDate: 'EEEE, MMMM d, y',
+ longDate: 'MMMM d, y',
+ mediumDate: 'MMM d, y',
+ shortDate: 'M/d/yy',
+ mediumTime: 'h:mm:ss a',
+ shortTime: 'h:mm a'
+ },
+
+ pluralCat: function(num) {
+ if (num === 1) {
+ return 'one';
+ }
+ return 'other';
+ }
+ };
+ };
+}
+
+var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
+ DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
+var $locationMinErr = minErr('$location');
+
+
+/**
+ * Encode path using encodeUriSegment, ignoring forward slashes
+ *
+ * @param {string} path Path to encode
+ * @returns {string}
+ */
+function encodePath(path) {
+ var segments = path.split('/'),
+ i = segments.length;
+
+ while (i--) {
+ segments[i] = encodeUriSegment(segments[i]);
+ }
+
+ return segments.join('/');
+}
+
+function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
+ var parsedUrl = urlResolve(absoluteUrl, appBase);
+
+ locationObj.$$protocol = parsedUrl.protocol;
+ locationObj.$$host = parsedUrl.hostname;
+ locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
+}
+
+
+function parseAppUrl(relativeUrl, locationObj, appBase) {
+ var prefixed = (relativeUrl.charAt(0) !== '/');
+ if (prefixed) {
+ relativeUrl = '/' + relativeUrl;
+ }
+ var match = urlResolve(relativeUrl, appBase);
+ locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
+ match.pathname.substring(1) : match.pathname);
+ locationObj.$$search = parseKeyValue(match.search);
+ locationObj.$$hash = decodeURIComponent(match.hash);
+
+ // make sure path starts with '/';
+ if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
+ locationObj.$$path = '/' + locationObj.$$path;
+ }
+}
+
+
+/**
+ *
+ * @param {string} begin
+ * @param {string} whole
+ * @returns {string} returns text from whole after begin or undefined if it does not begin with
+ * expected string.
+ */
+function beginsWith(begin, whole) {
+ if (whole.indexOf(begin) === 0) {
+ return whole.substr(begin.length);
+ }
+}
+
+
+function stripHash(url) {
+ var index = url.indexOf('#');
+ return index == -1 ? url : url.substr(0, index);
+}
+
+
+function stripFile(url) {
+ return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
+}
+
+/* return the server only (scheme://host:port) */
+function serverBase(url) {
+ return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
+}
+
+
+/**
+ * LocationHtml5Url represents an url
+ * This object is exposed as $location service when HTML5 mode is enabled and supported
+ *
+ * @constructor
+ * @param {string} appBase application base URL
+ * @param {string} basePrefix url path prefix
+ */
+function LocationHtml5Url(appBase, basePrefix) {
+ this.$$html5 = true;
+ basePrefix = basePrefix || '';
+ var appBaseNoFile = stripFile(appBase);
+ parseAbsoluteUrl(appBase, this, appBase);
+
+
+ /**
+ * Parse given html5 (regular) url string into properties
+ * @param {string} newAbsoluteUrl HTML5 url
+ * @private
+ */
+ this.$$parse = function(url) {
+ var pathUrl = beginsWith(appBaseNoFile, url);
+ if (!isString(pathUrl)) {
+ throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
+ appBaseNoFile);
+ }
+
+ parseAppUrl(pathUrl, this, appBase);
+
+ if (!this.$$path) {
+ this.$$path = '/';
+ }
+
+ this.$$compose();
+ };
+
+ /**
+ * Compose url and update `absUrl` property
+ * @private
+ */
+ this.$$compose = function() {
+ var search = toKeyValue(this.$$search),
+ hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
+
+ this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
+ this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
+ };
+
+ this.$$rewrite = function(url) {
+ var appUrl, prevAppUrl;
+
+ if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
+ prevAppUrl = appUrl;
+ if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
+ return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
+ } else {
+ return appBase + prevAppUrl;
+ }
+ } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
+ return appBaseNoFile + appUrl;
+ } else if (appBaseNoFile == url + '/') {
+ return appBaseNoFile;
+ }
+ };
+}
+
+
+/**
+ * LocationHashbangUrl represents url
+ * This object is exposed as $location service when developer doesn't opt into html5 mode.
+ * It also serves as the base class for html5 mode fallback on legacy browsers.
+ *
+ * @constructor
+ * @param {string} appBase application base URL
+ * @param {string} hashPrefix hashbang prefix
+ */
+function LocationHashbangUrl(appBase, hashPrefix) {
+ var appBaseNoFile = stripFile(appBase);
+
+ parseAbsoluteUrl(appBase, this, appBase);
+
+
+ /**
+ * Parse given hashbang url into properties
+ * @param {string} url Hashbang url
+ * @private
+ */
+ this.$$parse = function(url) {
+ var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
+ var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
+ ? beginsWith(hashPrefix, withoutBaseUrl)
+ : (this.$$html5)
+ ? withoutBaseUrl
+ : '';
+
+ if (!isString(withoutHashUrl)) {
+ throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
+ hashPrefix);
+ }
+ parseAppUrl(withoutHashUrl, this, appBase);
+
+ this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
+
+ this.$$compose();
+
+ /*
+ * In Windows, on an anchor node on documents loaded from
+ * the filesystem, the browser will return a pathname
+ * prefixed with the drive name ('/C:/path') when a
+ * pathname without a drive is set:
+ * * a.setAttribute('href', '/foo')
+ * * a.pathname === '/C:/foo' //true
+ *
+ * Inside of Angular, we're always using pathnames that
+ * do not include drive names for routing.
+ */
+ function removeWindowsDriveName (path, url, base) {
+ /*
+ Matches paths for file protocol on windows,
+ such as /C:/foo/bar, and captures only /foo/bar.
+ */
+ var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
+
+ var firstPathSegmentMatch;
+
+ //Get the relative path from the input URL.
+ if (url.indexOf(base) === 0) {
+ url = url.replace(base, '');
+ }
+
+ // The input URL intentionally contains a first path segment that ends with a colon.
+ if (windowsFilePathExp.exec(url)) {
+ return path;
+ }
+
+ firstPathSegmentMatch = windowsFilePathExp.exec(path);
+ return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
+ }
+ };
+
+ /**
+ * Compose hashbang url and update `absUrl` property
+ * @private
+ */
+ this.$$compose = function() {
+ var search = toKeyValue(this.$$search),
+ hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
+
+ this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
+ this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
+ };
+
+ this.$$rewrite = function(url) {
+ if(stripHash(appBase) == stripHash(url)) {
+ return url;
+ }
+ };
+}
+
+
+/**
+ * LocationHashbangUrl represents url
+ * This object is exposed as $location service when html5 history api is enabled but the browser
+ * does not support it.
+ *
+ * @constructor
+ * @param {string} appBase application base URL
+ * @param {string} hashPrefix hashbang prefix
+ */
+function LocationHashbangInHtml5Url(appBase, hashPrefix) {
+ this.$$html5 = true;
+ LocationHashbangUrl.apply(this, arguments);
+
+ var appBaseNoFile = stripFile(appBase);
+
+ this.$$rewrite = function(url) {
+ var appUrl;
+
+ if ( appBase == stripHash(url) ) {
+ return url;
+ } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
+ return appBase + hashPrefix + appUrl;
+ } else if ( appBaseNoFile === url + '/') {
+ return appBaseNoFile;
+ }
+ };
+
+ this.$$compose = function() {
+ var search = toKeyValue(this.$$search),
+ hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
+
+ this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
+ // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
+ this.$$absUrl = appBase + hashPrefix + this.$$url;
+ };
+
+}
+
+
+LocationHashbangInHtml5Url.prototype =
+ LocationHashbangUrl.prototype =
+ LocationHtml5Url.prototype = {
+
+ /**
+ * Are we in html5 mode?
+ * @private
+ */
+ $$html5: false,
+
+ /**
+ * Has any change been replacing ?
+ * @private
+ */
+ $$replace: false,
+
+ /**
+ * @ngdoc method
+ * @name $location#absUrl
+ *
+ * @description
+ * This method is getter only.
+ *
+ * Return full url representation with all segments encoded according to rules specified in
+ * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
+ *
+ * @return {string} full url
+ */
+ absUrl: locationGetter('$$absUrl'),
+
+ /**
+ * @ngdoc method
+ * @name $location#url
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
+ *
+ * Change path, search and hash, when called with parameter and return `$location`.
+ *
+ * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
+ * @param {string=} replace The path that will be changed
+ * @return {string} url
+ */
+ url: function(url, replace) {
+ if (isUndefined(url))
+ return this.$$url;
+
+ var match = PATH_MATCH.exec(url);
+ if (match[1]) this.path(decodeURIComponent(match[1]));
+ if (match[2] || match[1]) this.search(match[3] || '');
+ this.hash(match[5] || '', replace);
+
+ return this;
+ },
+
+ /**
+ * @ngdoc method
+ * @name $location#protocol
+ *
+ * @description
+ * This method is getter only.
+ *
+ * Return protocol of current url.
+ *
+ * @return {string} protocol of current url
+ */
+ protocol: locationGetter('$$protocol'),
+
+ /**
+ * @ngdoc method
+ * @name $location#host
+ *
+ * @description
+ * This method is getter only.
+ *
+ * Return host of current url.
+ *
+ * @return {string} host of current url.
+ */
+ host: locationGetter('$$host'),
+
+ /**
+ * @ngdoc method
+ * @name $location#port
+ *
+ * @description
+ * This method is getter only.
+ *
+ * Return port of current url.
+ *
+ * @return {Number} port
+ */
+ port: locationGetter('$$port'),
+
+ /**
+ * @ngdoc method
+ * @name $location#path
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return path of current url when called without any parameter.
+ *
+ * Change path when called with parameter and return `$location`.
+ *
+ * Note: Path should always begin with forward slash (/), this method will add the forward slash
+ * if it is missing.
+ *
+ * @param {string=} path New path
+ * @return {string} path
+ */
+ path: locationGetterSetter('$$path', function(path) {
+ return path.charAt(0) == '/' ? path : '/' + path;
+ }),
+
+ /**
+ * @ngdoc method
+ * @name $location#search
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return search part (as object) of current url when called without any parameter.
+ *
+ * Change search part when called with parameter and return `$location`.
+ *
+ *
+ * ```js
+ * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
+ * var searchObject = $location.search();
+ * // => {foo: 'bar', baz: 'xoxo'}
+ *
+ *
+ * // set foo to 'yipee'
+ * $location.search('foo', 'yipee');
+ * // => $location
+ * ```
+ *
+ * @param {string|Object.|Object.>} search New search params - string or
+ * hash object.
+ *
+ * When called with a single argument the method acts as a setter, setting the `search` component
+ * of `$location` to the specified value.
+ *
+ * If the argument is a hash object containing an array of values, these values will be encoded
+ * as duplicate search parameters in the url.
+ *
+ * @param {(string|Array)=} paramValue If `search` is a string, then `paramValue` will
+ * override only a single search property.
+ *
+ * If `paramValue` is an array, it will override the property of the `search` component of
+ * `$location` specified via the first argument.
+ *
+ * If `paramValue` is `null`, the property specified via the first argument will be deleted.
+ *
+ * @return {Object} If called with no arguments returns the parsed `search` object. If called with
+ * one or more arguments returns `$location` object itself.
+ */
+ search: function(search, paramValue) {
+ switch (arguments.length) {
+ case 0:
+ return this.$$search;
+ case 1:
+ if (isString(search)) {
+ this.$$search = parseKeyValue(search);
+ } else if (isObject(search)) {
+ this.$$search = search;
+ } else {
+ throw $locationMinErr('isrcharg',
+ 'The first argument of the `$location#search()` call must be a string or an object.');
+ }
+ break;
+ default:
+ if (isUndefined(paramValue) || paramValue === null) {
+ delete this.$$search[search];
+ } else {
+ this.$$search[search] = paramValue;
+ }
+ }
+
+ this.$$compose();
+ return this;
+ },
+
+ /**
+ * @ngdoc method
+ * @name $location#hash
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return hash fragment when called without any parameter.
+ *
+ * Change hash fragment when called with parameter and return `$location`.
+ *
+ * @param {string=} hash New hash fragment
+ * @return {string} hash
+ */
+ hash: locationGetterSetter('$$hash', identity),
+
+ /**
+ * @ngdoc method
+ * @name $location#replace
+ *
+ * @description
+ * If called, all changes to $location during current `$digest` will be replacing current history
+ * record, instead of adding new one.
+ */
+ replace: function() {
+ this.$$replace = true;
+ return this;
+ }
+};
+
+function locationGetter(property) {
+ return function() {
+ return this[property];
+ };
+}
+
+
+function locationGetterSetter(property, preprocess) {
+ return function(value) {
+ if (isUndefined(value))
+ return this[property];
+
+ this[property] = preprocess(value);
+ this.$$compose();
+
+ return this;
+ };
+}
+
+
+/**
+ * @ngdoc service
+ * @name $location
+ *
+ * @requires $rootElement
+ *
+ * @description
+ * The $location service parses the URL in the browser address bar (based on the
+ * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
+ * available to your application. Changes to the URL in the address bar are reflected into
+ * $location service and changes to $location are reflected into the browser address bar.
+ *
+ * **The $location service:**
+ *
+ * - Exposes the current URL in the browser address bar, so you can
+ * - Watch and observe the URL.
+ * - Change the URL.
+ * - Synchronizes the URL with the browser when the user
+ * - Changes the address bar.
+ * - Clicks the back or forward button (or clicks a History link).
+ * - Clicks on a link.
+ * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
+ *
+ * For more information see {@link guide/$location Developer Guide: Using $location}
+ */
+
+/**
+ * @ngdoc provider
+ * @name $locationProvider
+ * @description
+ * Use the `$locationProvider` to configure how the application deep linking paths are stored.
+ */
+function $LocationProvider(){
+ var hashPrefix = '',
+ html5Mode = false;
+
+ /**
+ * @ngdoc method
+ * @name $locationProvider#hashPrefix
+ * @description
+ * @param {string=} prefix Prefix for hash part (containing path and search)
+ * @returns {*} current value if used as getter or itself (chaining) if used as setter
+ */
+ this.hashPrefix = function(prefix) {
+ if (isDefined(prefix)) {
+ hashPrefix = prefix;
+ return this;
+ } else {
+ return hashPrefix;
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name $locationProvider#html5Mode
+ * @description
+ * @param {boolean=} mode Use HTML5 strategy if available.
+ * @returns {*} current value if used as getter or itself (chaining) if used as setter
+ */
+ this.html5Mode = function(mode) {
+ if (isDefined(mode)) {
+ html5Mode = mode;
+ return this;
+ } else {
+ return html5Mode;
+ }
+ };
+
+ /**
+ * @ngdoc event
+ * @name $location#$locationChangeStart
+ * @eventType broadcast on root scope
+ * @description
+ * Broadcasted before a URL will change. This change can be prevented by calling
+ * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
+ * details about event object. Upon successful change
+ * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired.
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {string} newUrl New URL
+ * @param {string=} oldUrl URL that was before it was changed.
+ */
+
+ /**
+ * @ngdoc event
+ * @name $location#$locationChangeSuccess
+ * @eventType broadcast on root scope
+ * @description
+ * Broadcasted after a URL was changed.
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {string} newUrl New URL
+ * @param {string=} oldUrl URL that was before it was changed.
+ */
+
+ this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
+ function( $rootScope, $browser, $sniffer, $rootElement) {
+ var $location,
+ LocationMode,
+ baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
+ initialUrl = $browser.url(),
+ appBase;
+
+ if (html5Mode) {
+ appBase = serverBase(initialUrl) + (baseHref || '/');
+ LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
+ } else {
+ appBase = stripHash(initialUrl);
+ LocationMode = LocationHashbangUrl;
+ }
+ $location = new LocationMode(appBase, '#' + hashPrefix);
+ $location.$$parse($location.$$rewrite(initialUrl));
+
+ $rootElement.on('click', function(event) {
+ // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
+ // currently we open nice url link and redirect then
+
+ if (event.ctrlKey || event.metaKey || event.which == 2) return;
+
+ var elm = jqLite(event.target);
+
+ // traverse the DOM up to find first A tag
+ while (lowercase(elm[0].nodeName) !== 'a') {
+ // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
+ if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
+ }
+
+ var absHref = elm.prop('href');
+
+ if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
+ // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
+ // an animation.
+ absHref = urlResolve(absHref.animVal).href;
+ }
+
+ // Make relative links work in HTML5 mode for legacy browsers (or at least IE8 & 9)
+ // The href should be a regular url e.g. /link/somewhere or link/somewhere or ../somewhere or
+ // somewhere#anchor or http://example.com/somewhere
+ if (LocationMode === LocationHashbangInHtml5Url) {
+ // get the actual href attribute - see
+ // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
+ var href = elm.attr('href') || elm.attr('xlink:href');
+
+ if (href.indexOf('://') < 0) { // Ignore absolute URLs
+ var prefix = '#' + hashPrefix;
+ if (href[0] == '/') {
+ // absolute path - replace old path
+ absHref = appBase + prefix + href;
+ } else if (href[0] == '#') {
+ // local anchor
+ absHref = appBase + prefix + ($location.path() || '/') + href;
+ } else {
+ // relative path - join with current path
+ var stack = $location.path().split("/"),
+ parts = href.split("/");
+ for (var i=0; i html5 url
+ if ($location.absUrl() != initialUrl) {
+ $browser.url($location.absUrl(), true);
+ }
+
+ // update $location when $browser url changes
+ $browser.onUrlChange(function(newUrl) {
+ if ($location.absUrl() != newUrl) {
+ $rootScope.$evalAsync(function() {
+ var oldUrl = $location.absUrl();
+
+ $location.$$parse(newUrl);
+ if ($rootScope.$broadcast('$locationChangeStart', newUrl,
+ oldUrl).defaultPrevented) {
+ $location.$$parse(oldUrl);
+ $browser.url(oldUrl);
+ } else {
+ afterLocationChange(oldUrl);
+ }
+ });
+ if (!$rootScope.$$phase) $rootScope.$digest();
+ }
+ });
+
+ // update browser
+ var changeCounter = 0;
+ $rootScope.$watch(function $locationWatch() {
+ var oldUrl = $browser.url();
+ var currentReplace = $location.$$replace;
+
+ if (!changeCounter || oldUrl != $location.absUrl()) {
+ changeCounter++;
+ $rootScope.$evalAsync(function() {
+ if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
+ defaultPrevented) {
+ $location.$$parse(oldUrl);
+ } else {
+ $browser.url($location.absUrl(), currentReplace);
+ afterLocationChange(oldUrl);
+ }
+ });
+ }
+ $location.$$replace = false;
+
+ return changeCounter;
+ });
+
+ return $location;
+
+ function afterLocationChange(oldUrl) {
+ $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
+ }
+}];
+}
+
+/**
+ * @ngdoc service
+ * @name $log
+ * @requires $window
+ *
+ * @description
+ * Simple service for logging. Default implementation safely writes the message
+ * into the browser's console (if present).
+ *
+ * The main purpose of this service is to simplify debugging and troubleshooting.
+ *
+ * The default is to log `debug` messages. You can use
+ * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
+ *
+ * @example
+
+
+ function LogCtrl($scope, $log) {
+ $scope.$log = $log;
+ $scope.message = 'Hello World!';
+ }
+
+
+
+
Reload this page with open console, enter text and hit the log button...
+ Message:
+
+
+
+
+
+
+
+
+ */
+
+/**
+ * @ngdoc provider
+ * @name $logProvider
+ * @description
+ * Use the `$logProvider` to configure how the application logs messages
+ */
+function $LogProvider(){
+ var debug = true,
+ self = this;
+
+ /**
+ * @ngdoc property
+ * @name $logProvider#debugEnabled
+ * @description
+ * @param {boolean=} flag enable or disable debug level messages
+ * @returns {*} current value if used as getter or itself (chaining) if used as setter
+ */
+ this.debugEnabled = function(flag) {
+ if (isDefined(flag)) {
+ debug = flag;
+ return this;
+ } else {
+ return debug;
+ }
+ };
+
+ this.$get = ['$window', function($window){
+ return {
+ /**
+ * @ngdoc method
+ * @name $log#log
+ *
+ * @description
+ * Write a log message
+ */
+ log: consoleLog('log'),
+
+ /**
+ * @ngdoc method
+ * @name $log#info
+ *
+ * @description
+ * Write an information message
+ */
+ info: consoleLog('info'),
+
+ /**
+ * @ngdoc method
+ * @name $log#warn
+ *
+ * @description
+ * Write a warning message
+ */
+ warn: consoleLog('warn'),
+
+ /**
+ * @ngdoc method
+ * @name $log#error
+ *
+ * @description
+ * Write an error message
+ */
+ error: consoleLog('error'),
+
+ /**
+ * @ngdoc method
+ * @name $log#debug
+ *
+ * @description
+ * Write a debug message
+ */
+ debug: (function () {
+ var fn = consoleLog('debug');
+
+ return function() {
+ if (debug) {
+ fn.apply(self, arguments);
+ }
+ };
+ }())
+ };
+
+ function formatError(arg) {
+ if (arg instanceof Error) {
+ if (arg.stack) {
+ arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
+ ? 'Error: ' + arg.message + '\n' + arg.stack
+ : arg.stack;
+ } else if (arg.sourceURL) {
+ arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
+ }
+ }
+ return arg;
+ }
+
+ function consoleLog(type) {
+ var console = $window.console || {},
+ logFn = console[type] || console.log || noop,
+ hasApply = false;
+
+ // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
+ // The reason behind this is that console.log has type "object" in IE8...
+ try {
+ hasApply = !!logFn.apply;
+ } catch (e) {}
+
+ if (hasApply) {
+ return function() {
+ var args = [];
+ forEach(arguments, function(arg) {
+ args.push(formatError(arg));
+ });
+ return logFn.apply(console, args);
+ };
+ }
+
+ // we are IE which either doesn't have window.console => this is noop and we do nothing,
+ // or we are IE where console.log doesn't have apply so we log at least first 2 args
+ return function(arg1, arg2) {
+ logFn(arg1, arg2 == null ? '' : arg2);
+ };
+ }
+ }];
+}
+
+var $parseMinErr = minErr('$parse');
+var promiseWarningCache = {};
+var promiseWarning;
+
+// Sandboxing Angular Expressions
+// ------------------------------
+// Angular expressions are generally considered safe because these expressions only have direct
+// access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
+// obtaining a reference to native JS functions such as the Function constructor.
+//
+// As an example, consider the following Angular expression:
+//
+// {}.toString.constructor('alert("evil JS code")')
+//
+// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
+// against the expression language, but not to prevent exploits that were enabled by exposing
+// sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good
+// practice and therefore we are not even trying to protect against interaction with an object
+// explicitly exposed in this way.
+//
+// In general, it is not possible to access a Window object from an angular expression unless a
+// window or some DOM object that has a reference to window is published onto a Scope.
+// Similarly we prevent invocations of function known to be dangerous, as well as assignments to
+// native objects.
+
+
+function ensureSafeMemberName(name, fullExpression) {
+ if (name === "__defineGetter__" || name === "__defineSetter__"
+ || name === "__lookupGetter__" || name === "__lookupSetter__"
+ || name === "__proto__") {
+ throw $parseMinErr('isecfld',
+ 'Attempting to access a disallowed field in Angular expressions! '
+ +'Expression: {0}', fullExpression);
+ }
+ return name;
+}
+
+function ensureSafeObject(obj, fullExpression) {
+ // nifty check if obj is Function that is fast and works across iframes and other contexts
+ if (obj) {
+ if (obj.constructor === obj) {
+ throw $parseMinErr('isecfn',
+ 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ } else if (// isWindow(obj)
+ obj.document && obj.location && obj.alert && obj.setInterval) {
+ throw $parseMinErr('isecwindow',
+ 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ } else if (// isElement(obj)
+ obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
+ throw $parseMinErr('isecdom',
+ 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ } else if (// block Object so that we can't get hold of dangerous Object.* methods
+ obj === Object) {
+ throw $parseMinErr('isecobj',
+ 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ }
+ }
+ return obj;
+}
+
+var CALL = Function.prototype.call;
+var APPLY = Function.prototype.apply;
+var BIND = Function.prototype.bind;
+
+function ensureSafeFunction(obj, fullExpression) {
+ if (obj) {
+ if (obj.constructor === obj) {
+ throw $parseMinErr('isecfn',
+ 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ } else if (obj === CALL || obj === APPLY || (BIND && obj === BIND)) {
+ throw $parseMinErr('isecff',
+ 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ }
+ }
+}
+
+var OPERATORS = {
+ /* jshint bitwise : false */
+ 'null':function(){return null;},
+ 'true':function(){return true;},
+ 'false':function(){return false;},
+ undefined:noop,
+ '+':function(self, locals, a,b){
+ a=a(self, locals); b=b(self, locals);
+ if (isDefined(a)) {
+ if (isDefined(b)) {
+ return a + b;
+ }
+ return a;
+ }
+ return isDefined(b)?b:undefined;},
+ '-':function(self, locals, a,b){
+ a=a(self, locals); b=b(self, locals);
+ return (isDefined(a)?a:0)-(isDefined(b)?b:0);
+ },
+ '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
+ '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
+ '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
+ '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
+ '=':noop,
+ '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
+ '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
+ '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
+ '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
+ '<':function(self, locals, a,b){return a(self, locals)':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
+ '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
+ '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
+ '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
+ '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
+ '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
+// '|':function(self, locals, a,b){return a|b;},
+ '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
+ '!':function(self, locals, a){return !a(self, locals);}
+};
+/* jshint bitwise: true */
+var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
+
+
+/////////////////////////////////////////
+
+
+/**
+ * @constructor
+ */
+var Lexer = function (options) {
+ this.options = options;
+};
+
+Lexer.prototype = {
+ constructor: Lexer,
+
+ lex: function (text) {
+ this.text = text;
+
+ this.index = 0;
+ this.ch = undefined;
+ this.lastCh = ':'; // can start regexp
+
+ this.tokens = [];
+
+ while (this.index < this.text.length) {
+ this.ch = this.text.charAt(this.index);
+ if (this.is('"\'')) {
+ this.readString(this.ch);
+ } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
+ this.readNumber();
+ } else if (this.isIdent(this.ch)) {
+ this.readIdent();
+ } else if (this.is('(){}[].,;:?')) {
+ this.tokens.push({
+ index: this.index,
+ text: this.ch
+ });
+ this.index++;
+ } else if (this.isWhitespace(this.ch)) {
+ this.index++;
+ continue;
+ } else {
+ var ch2 = this.ch + this.peek();
+ var ch3 = ch2 + this.peek(2);
+ var fn = OPERATORS[this.ch];
+ var fn2 = OPERATORS[ch2];
+ var fn3 = OPERATORS[ch3];
+ if (fn3) {
+ this.tokens.push({index: this.index, text: ch3, fn: fn3});
+ this.index += 3;
+ } else if (fn2) {
+ this.tokens.push({index: this.index, text: ch2, fn: fn2});
+ this.index += 2;
+ } else if (fn) {
+ this.tokens.push({
+ index: this.index,
+ text: this.ch,
+ fn: fn
+ });
+ this.index += 1;
+ } else {
+ this.throwError('Unexpected next character ', this.index, this.index + 1);
+ }
+ }
+ this.lastCh = this.ch;
+ }
+ return this.tokens;
+ },
+
+ is: function(chars) {
+ return chars.indexOf(this.ch) !== -1;
+ },
+
+ was: function(chars) {
+ return chars.indexOf(this.lastCh) !== -1;
+ },
+
+ peek: function(i) {
+ var num = i || 1;
+ return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
+ },
+
+ isNumber: function(ch) {
+ return ('0' <= ch && ch <= '9');
+ },
+
+ isWhitespace: function(ch) {
+ // IE treats non-breaking space as \u00A0
+ return (ch === ' ' || ch === '\r' || ch === '\t' ||
+ ch === '\n' || ch === '\v' || ch === '\u00A0');
+ },
+
+ isIdent: function(ch) {
+ return ('a' <= ch && ch <= 'z' ||
+ 'A' <= ch && ch <= 'Z' ||
+ '_' === ch || ch === '$');
+ },
+
+ isExpOperator: function(ch) {
+ return (ch === '-' || ch === '+' || this.isNumber(ch));
+ },
+
+ throwError: function(error, start, end) {
+ end = end || this.index;
+ var colStr = (isDefined(start)
+ ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
+ : ' ' + end);
+ throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
+ error, colStr, this.text);
+ },
+
+ readNumber: function() {
+ var number = '';
+ var start = this.index;
+ while (this.index < this.text.length) {
+ var ch = lowercase(this.text.charAt(this.index));
+ if (ch == '.' || this.isNumber(ch)) {
+ number += ch;
+ } else {
+ var peekCh = this.peek();
+ if (ch == 'e' && this.isExpOperator(peekCh)) {
+ number += ch;
+ } else if (this.isExpOperator(ch) &&
+ peekCh && this.isNumber(peekCh) &&
+ number.charAt(number.length - 1) == 'e') {
+ number += ch;
+ } else if (this.isExpOperator(ch) &&
+ (!peekCh || !this.isNumber(peekCh)) &&
+ number.charAt(number.length - 1) == 'e') {
+ this.throwError('Invalid exponent');
+ } else {
+ break;
+ }
+ }
+ this.index++;
+ }
+ number = 1 * number;
+ this.tokens.push({
+ index: start,
+ text: number,
+ literal: true,
+ constant: true,
+ fn: function() { return number; }
+ });
+ },
+
+ readIdent: function() {
+ var parser = this;
+
+ var ident = '';
+ var start = this.index;
+
+ var lastDot, peekIndex, methodName, ch;
+
+ while (this.index < this.text.length) {
+ ch = this.text.charAt(this.index);
+ if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
+ if (ch === '.') lastDot = this.index;
+ ident += ch;
+ } else {
+ break;
+ }
+ this.index++;
+ }
+
+ //check if this is not a method invocation and if it is back out to last dot
+ if (lastDot) {
+ peekIndex = this.index;
+ while (peekIndex < this.text.length) {
+ ch = this.text.charAt(peekIndex);
+ if (ch === '(') {
+ methodName = ident.substr(lastDot - start + 1);
+ ident = ident.substr(0, lastDot - start);
+ this.index = peekIndex;
+ break;
+ }
+ if (this.isWhitespace(ch)) {
+ peekIndex++;
+ } else {
+ break;
+ }
+ }
+ }
+
+
+ var token = {
+ index: start,
+ text: ident
+ };
+
+ // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
+ if (OPERATORS.hasOwnProperty(ident)) {
+ token.fn = OPERATORS[ident];
+ token.literal = true;
+ token.constant = true;
+ } else {
+ var getter = getterFn(ident, this.options, this.text);
+ token.fn = extend(function(self, locals) {
+ return (getter(self, locals));
+ }, {
+ assign: function(self, value) {
+ return setter(self, ident, value, parser.text, parser.options);
+ }
+ });
+ }
+
+ this.tokens.push(token);
+
+ if (methodName) {
+ this.tokens.push({
+ index:lastDot,
+ text: '.'
+ });
+ this.tokens.push({
+ index: lastDot + 1,
+ text: methodName
+ });
+ }
+ },
+
+ readString: function(quote) {
+ var start = this.index;
+ this.index++;
+ var string = '';
+ var rawString = quote;
+ var escape = false;
+ while (this.index < this.text.length) {
+ var ch = this.text.charAt(this.index);
+ rawString += ch;
+ if (escape) {
+ if (ch === 'u') {
+ var hex = this.text.substring(this.index + 1, this.index + 5);
+ if (!hex.match(/[\da-f]{4}/i))
+ this.throwError('Invalid unicode escape [\\u' + hex + ']');
+ this.index += 4;
+ string += String.fromCharCode(parseInt(hex, 16));
+ } else {
+ var rep = ESCAPE[ch];
+ if (rep) {
+ string += rep;
+ } else {
+ string += ch;
+ }
+ }
+ escape = false;
+ } else if (ch === '\\') {
+ escape = true;
+ } else if (ch === quote) {
+ this.index++;
+ this.tokens.push({
+ index: start,
+ text: rawString,
+ string: string,
+ literal: true,
+ constant: true,
+ fn: function() { return string; }
+ });
+ return;
+ } else {
+ string += ch;
+ }
+ this.index++;
+ }
+ this.throwError('Unterminated quote', start);
+ }
+};
+
+
+/**
+ * @constructor
+ */
+var Parser = function (lexer, $filter, options) {
+ this.lexer = lexer;
+ this.$filter = $filter;
+ this.options = options;
+};
+
+Parser.ZERO = extend(function () {
+ return 0;
+}, {
+ constant: true
+});
+
+Parser.prototype = {
+ constructor: Parser,
+
+ parse: function (text) {
+ this.text = text;
+
+ this.tokens = this.lexer.lex(text);
+
+ var value = this.statements();
+
+ if (this.tokens.length !== 0) {
+ this.throwError('is an unexpected token', this.tokens[0]);
+ }
+
+ value.literal = !!value.literal;
+ value.constant = !!value.constant;
+
+ return value;
+ },
+
+ primary: function () {
+ var primary;
+ if (this.expect('(')) {
+ primary = this.filterChain();
+ this.consume(')');
+ } else if (this.expect('[')) {
+ primary = this.arrayDeclaration();
+ } else if (this.expect('{')) {
+ primary = this.object();
+ } else {
+ var token = this.expect();
+ primary = token.fn;
+ if (!primary) {
+ this.throwError('not a primary expression', token);
+ }
+ primary.literal = !!token.literal;
+ primary.constant = !!token.constant;
+ }
+
+ var next, context;
+ while ((next = this.expect('(', '[', '.'))) {
+ if (next.text === '(') {
+ primary = this.functionCall(primary, context);
+ context = null;
+ } else if (next.text === '[') {
+ context = primary;
+ primary = this.objectIndex(primary);
+ } else if (next.text === '.') {
+ context = primary;
+ primary = this.fieldAccess(primary);
+ } else {
+ this.throwError('IMPOSSIBLE');
+ }
+ }
+ return primary;
+ },
+
+ throwError: function(msg, token) {
+ throw $parseMinErr('syntax',
+ 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
+ token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
+ },
+
+ peekToken: function() {
+ if (this.tokens.length === 0)
+ throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
+ return this.tokens[0];
+ },
+
+ peek: function(e1, e2, e3, e4) {
+ if (this.tokens.length > 0) {
+ var token = this.tokens[0];
+ var t = token.text;
+ if (t === e1 || t === e2 || t === e3 || t === e4 ||
+ (!e1 && !e2 && !e3 && !e4)) {
+ return token;
+ }
+ }
+ return false;
+ },
+
+ expect: function(e1, e2, e3, e4){
+ var token = this.peek(e1, e2, e3, e4);
+ if (token) {
+ this.tokens.shift();
+ return token;
+ }
+ return false;
+ },
+
+ consume: function(e1){
+ if (!this.expect(e1)) {
+ this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
+ }
+ },
+
+ unaryFn: function(fn, right) {
+ return extend(function(self, locals) {
+ return fn(self, locals, right);
+ }, {
+ constant:right.constant
+ });
+ },
+
+ ternaryFn: function(left, middle, right){
+ return extend(function(self, locals){
+ return left(self, locals) ? middle(self, locals) : right(self, locals);
+ }, {
+ constant: left.constant && middle.constant && right.constant
+ });
+ },
+
+ binaryFn: function(left, fn, right) {
+ return extend(function(self, locals) {
+ return fn(self, locals, left, right);
+ }, {
+ constant:left.constant && right.constant
+ });
+ },
+
+ statements: function() {
+ var statements = [];
+ while (true) {
+ if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
+ statements.push(this.filterChain());
+ if (!this.expect(';')) {
+ // optimize for the common case where there is only one statement.
+ // TODO(size): maybe we should not support multiple statements?
+ return (statements.length === 1)
+ ? statements[0]
+ : function(self, locals) {
+ var value;
+ for (var i = 0; i < statements.length; i++) {
+ var statement = statements[i];
+ if (statement) {
+ value = statement(self, locals);
+ }
+ }
+ return value;
+ };
+ }
+ }
+ },
+
+ filterChain: function() {
+ var left = this.expression();
+ var token;
+ while (true) {
+ if ((token = this.expect('|'))) {
+ left = this.binaryFn(left, token.fn, this.filter());
+ } else {
+ return left;
+ }
+ }
+ },
+
+ filter: function() {
+ var token = this.expect();
+ var fn = this.$filter(token.text);
+ var argsFn = [];
+ while (true) {
+ if ((token = this.expect(':'))) {
+ argsFn.push(this.expression());
+ } else {
+ var fnInvoke = function(self, locals, input) {
+ var args = [input];
+ for (var i = 0; i < argsFn.length; i++) {
+ args.push(argsFn[i](self, locals));
+ }
+ return fn.apply(self, args);
+ };
+ return function() {
+ return fnInvoke;
+ };
+ }
+ }
+ },
+
+ expression: function() {
+ return this.assignment();
+ },
+
+ assignment: function() {
+ var left = this.ternary();
+ var right;
+ var token;
+ if ((token = this.expect('='))) {
+ if (!left.assign) {
+ this.throwError('implies assignment but [' +
+ this.text.substring(0, token.index) + '] can not be assigned to', token);
+ }
+ right = this.ternary();
+ return function(scope, locals) {
+ return left.assign(scope, right(scope, locals), locals);
+ };
+ }
+ return left;
+ },
+
+ ternary: function() {
+ var left = this.logicalOR();
+ var middle;
+ var token;
+ if ((token = this.expect('?'))) {
+ middle = this.ternary();
+ if ((token = this.expect(':'))) {
+ return this.ternaryFn(left, middle, this.ternary());
+ } else {
+ this.throwError('expected :', token);
+ }
+ } else {
+ return left;
+ }
+ },
+
+ logicalOR: function() {
+ var left = this.logicalAND();
+ var token;
+ while (true) {
+ if ((token = this.expect('||'))) {
+ left = this.binaryFn(left, token.fn, this.logicalAND());
+ } else {
+ return left;
+ }
+ }
+ },
+
+ logicalAND: function() {
+ var left = this.equality();
+ var token;
+ if ((token = this.expect('&&'))) {
+ left = this.binaryFn(left, token.fn, this.logicalAND());
+ }
+ return left;
+ },
+
+ equality: function() {
+ var left = this.relational();
+ var token;
+ if ((token = this.expect('==','!=','===','!=='))) {
+ left = this.binaryFn(left, token.fn, this.equality());
+ }
+ return left;
+ },
+
+ relational: function() {
+ var left = this.additive();
+ var token;
+ if ((token = this.expect('<', '>', '<=', '>='))) {
+ left = this.binaryFn(left, token.fn, this.relational());
+ }
+ return left;
+ },
+
+ additive: function() {
+ var left = this.multiplicative();
+ var token;
+ while ((token = this.expect('+','-'))) {
+ left = this.binaryFn(left, token.fn, this.multiplicative());
+ }
+ return left;
+ },
+
+ multiplicative: function() {
+ var left = this.unary();
+ var token;
+ while ((token = this.expect('*','/','%'))) {
+ left = this.binaryFn(left, token.fn, this.unary());
+ }
+ return left;
+ },
+
+ unary: function() {
+ var token;
+ if (this.expect('+')) {
+ return this.primary();
+ } else if ((token = this.expect('-'))) {
+ return this.binaryFn(Parser.ZERO, token.fn, this.unary());
+ } else if ((token = this.expect('!'))) {
+ return this.unaryFn(token.fn, this.unary());
+ } else {
+ return this.primary();
+ }
+ },
+
+ fieldAccess: function(object) {
+ var parser = this;
+ var field = this.expect().text;
+ var getter = getterFn(field, this.options, this.text);
+
+ return extend(function(scope, locals, self) {
+ return getter(self || object(scope, locals));
+ }, {
+ assign: function(scope, value, locals) {
+ return setter(object(scope, locals), field, value, parser.text, parser.options);
+ }
+ });
+ },
+
+ objectIndex: function(obj) {
+ var parser = this;
+
+ var indexFn = this.expression();
+ this.consume(']');
+
+ return extend(function(self, locals) {
+ var o = obj(self, locals),
+ i = indexFn(self, locals),
+ v, p;
+
+ ensureSafeMemberName(i, parser.text);
+ if (!o) return undefined;
+ v = ensureSafeObject(o[i], parser.text);
+ if (v && v.then && parser.options.unwrapPromises) {
+ p = v;
+ if (!('$$v' in v)) {
+ p.$$v = undefined;
+ p.then(function(val) { p.$$v = val; });
+ }
+ v = v.$$v;
+ }
+ return v;
+ }, {
+ assign: function(self, value, locals) {
+ var key = indexFn(self, locals);
+ // prevent overwriting of Function.constructor which would break ensureSafeObject check
+ var safe = ensureSafeObject(obj(self, locals), parser.text);
+ return safe[key] = value;
+ }
+ });
+ },
+
+ functionCall: function(fn, contextGetter) {
+ var argsFn = [];
+ if (this.peekToken().text !== ')') {
+ do {
+ argsFn.push(this.expression());
+ } while (this.expect(','));
+ }
+ this.consume(')');
+
+ var parser = this;
+
+ return function(scope, locals) {
+ var args = [];
+ var context = contextGetter ? contextGetter(scope, locals) : scope;
+
+ for (var i = 0; i < argsFn.length; i++) {
+ args.push(argsFn[i](scope, locals));
+ }
+ var fnPtr = fn(scope, locals, context) || noop;
+
+ ensureSafeObject(context, parser.text);
+ ensureSafeFunction(fnPtr, parser.text);
+
+ // IE stupidity! (IE doesn't have apply for some native functions)
+ var v = fnPtr.apply
+ ? fnPtr.apply(context, args)
+ : fnPtr(args[0], args[1], args[2], args[3], args[4]);
+
+ return ensureSafeObject(v, parser.text);
+ };
+ },
+
+ // This is used with json array declaration
+ arrayDeclaration: function () {
+ var elementFns = [];
+ var allConstant = true;
+ if (this.peekToken().text !== ']') {
+ do {
+ if (this.peek(']')) {
+ // Support trailing commas per ES5.1.
+ break;
+ }
+ var elementFn = this.expression();
+ elementFns.push(elementFn);
+ if (!elementFn.constant) {
+ allConstant = false;
+ }
+ } while (this.expect(','));
+ }
+ this.consume(']');
+
+ return extend(function(self, locals) {
+ var array = [];
+ for (var i = 0; i < elementFns.length; i++) {
+ array.push(elementFns[i](self, locals));
+ }
+ return array;
+ }, {
+ literal: true,
+ constant: allConstant
+ });
+ },
+
+ object: function () {
+ var keyValues = [];
+ var allConstant = true;
+ if (this.peekToken().text !== '}') {
+ do {
+ if (this.peek('}')) {
+ // Support trailing commas per ES5.1.
+ break;
+ }
+ var token = this.expect(),
+ key = token.string || token.text;
+ this.consume(':');
+ var value = this.expression();
+ keyValues.push({key: key, value: value});
+ if (!value.constant) {
+ allConstant = false;
+ }
+ } while (this.expect(','));
+ }
+ this.consume('}');
+
+ return extend(function(self, locals) {
+ var object = {};
+ for (var i = 0; i < keyValues.length; i++) {
+ var keyValue = keyValues[i];
+ object[keyValue.key] = keyValue.value(self, locals);
+ }
+ return object;
+ }, {
+ literal: true,
+ constant: allConstant
+ });
+ }
+};
+
+
+//////////////////////////////////////////////////
+// Parser helper functions
+//////////////////////////////////////////////////
+
+function setter(obj, path, setValue, fullExp, options) {
+ //needed?
+ options = options || {};
+
+ var element = path.split('.'), key;
+ for (var i = 0; element.length > 1; i++) {
+ key = ensureSafeMemberName(element.shift(), fullExp);
+ var propertyObj = obj[key];
+ if (!propertyObj) {
+ propertyObj = {};
+ obj[key] = propertyObj;
+ }
+ obj = propertyObj;
+ if (obj.then && options.unwrapPromises) {
+ promiseWarning(fullExp);
+ if (!("$$v" in obj)) {
+ (function(promise) {
+ promise.then(function(val) { promise.$$v = val; }); }
+ )(obj);
+ }
+ if (obj.$$v === undefined) {
+ obj.$$v = {};
+ }
+ obj = obj.$$v;
+ }
+ }
+ key = ensureSafeMemberName(element.shift(), fullExp);
+ ensureSafeObject(obj, fullExp);
+ ensureSafeObject(obj[key], fullExp);
+ obj[key] = setValue;
+ return setValue;
+}
+
+var getterFnCache = {};
+
+/**
+ * Implementation of the "Black Hole" variant from:
+ * - http://jsperf.com/angularjs-parse-getter/4
+ * - http://jsperf.com/path-evaluation-simplified/7
+ */
+function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
+ ensureSafeMemberName(key0, fullExp);
+ ensureSafeMemberName(key1, fullExp);
+ ensureSafeMemberName(key2, fullExp);
+ ensureSafeMemberName(key3, fullExp);
+ ensureSafeMemberName(key4, fullExp);
+
+ return !options.unwrapPromises
+ ? function cspSafeGetter(scope, locals) {
+ var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
+
+ if (pathVal == null) return pathVal;
+ pathVal = pathVal[key0];
+
+ if (!key1) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key1];
+
+ if (!key2) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key2];
+
+ if (!key3) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key3];
+
+ if (!key4) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key4];
+
+ return pathVal;
+ }
+ : function cspSafePromiseEnabledGetter(scope, locals) {
+ var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
+ promise;
+
+ if (pathVal == null) return pathVal;
+
+ pathVal = pathVal[key0];
+ if (pathVal && pathVal.then) {
+ promiseWarning(fullExp);
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+
+ if (!key1) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key1];
+ if (pathVal && pathVal.then) {
+ promiseWarning(fullExp);
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+
+ if (!key2) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key2];
+ if (pathVal && pathVal.then) {
+ promiseWarning(fullExp);
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+
+ if (!key3) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key3];
+ if (pathVal && pathVal.then) {
+ promiseWarning(fullExp);
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+
+ if (!key4) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key4];
+ if (pathVal && pathVal.then) {
+ promiseWarning(fullExp);
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+ return pathVal;
+ };
+}
+
+function simpleGetterFn1(key0, fullExp) {
+ ensureSafeMemberName(key0, fullExp);
+
+ return function simpleGetterFn1(scope, locals) {
+ if (scope == null) return undefined;
+ return ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
+ };
+}
+
+function simpleGetterFn2(key0, key1, fullExp) {
+ ensureSafeMemberName(key0, fullExp);
+ ensureSafeMemberName(key1, fullExp);
+
+ return function simpleGetterFn2(scope, locals) {
+ if (scope == null) return undefined;
+ scope = ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
+ return scope == null ? undefined : scope[key1];
+ };
+}
+
+function getterFn(path, options, fullExp) {
+ // Check whether the cache has this getter already.
+ // We can use hasOwnProperty directly on the cache because we ensure,
+ // see below, that the cache never stores a path called 'hasOwnProperty'
+ if (getterFnCache.hasOwnProperty(path)) {
+ return getterFnCache[path];
+ }
+
+ var pathKeys = path.split('.'),
+ pathKeysLength = pathKeys.length,
+ fn;
+
+ // When we have only 1 or 2 tokens, use optimized special case closures.
+ // http://jsperf.com/angularjs-parse-getter/6
+ if (!options.unwrapPromises && pathKeysLength === 1) {
+ fn = simpleGetterFn1(pathKeys[0], fullExp);
+ } else if (!options.unwrapPromises && pathKeysLength === 2) {
+ fn = simpleGetterFn2(pathKeys[0], pathKeys[1], fullExp);
+ } else if (options.csp) {
+ if (pathKeysLength < 6) {
+ fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
+ options);
+ } else {
+ fn = function(scope, locals) {
+ var i = 0, val;
+ do {
+ val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
+ pathKeys[i++], fullExp, options)(scope, locals);
+
+ locals = undefined; // clear after first iteration
+ scope = val;
+ } while (i < pathKeysLength);
+ return val;
+ };
+ }
+ } else {
+ var code = 'var p;\n';
+ forEach(pathKeys, function(key, index) {
+ ensureSafeMemberName(key, fullExp);
+ code += 'if(s == null) return undefined;\n' +
+ 's='+ (index
+ // we simply dereference 's' on any .dot notation
+ ? 's'
+ // but if we are first then we check locals first, and if so read it first
+ : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
+ (options.unwrapPromises
+ ? 'if (s && s.then) {\n' +
+ ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' +
+ ' if (!("$$v" in s)) {\n' +
+ ' p=s;\n' +
+ ' p.$$v = undefined;\n' +
+ ' p.then(function(v) {p.$$v=v;});\n' +
+ '}\n' +
+ ' s=s.$$v\n' +
+ '}\n'
+ : '');
+ });
+ code += 'return s;';
+
+ /* jshint -W054 */
+ var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning
+ /* jshint +W054 */
+ evaledFnGetter.toString = valueFn(code);
+ fn = options.unwrapPromises ? function(scope, locals) {
+ return evaledFnGetter(scope, locals, promiseWarning);
+ } : evaledFnGetter;
+ }
+
+ // Only cache the value if it's not going to mess up the cache object
+ // This is more performant that using Object.prototype.hasOwnProperty.call
+ if (path !== 'hasOwnProperty') {
+ getterFnCache[path] = fn;
+ }
+ return fn;
+}
+
+///////////////////////////////////
+
+/**
+ * @ngdoc service
+ * @name $parse
+ * @kind function
+ *
+ * @description
+ *
+ * Converts Angular {@link guide/expression expression} into a function.
+ *
+ * ```js
+ * var getter = $parse('user.name');
+ * var setter = getter.assign;
+ * var context = {user:{name:'angular'}};
+ * var locals = {user:{name:'local'}};
+ *
+ * expect(getter(context)).toEqual('angular');
+ * setter(context, 'newValue');
+ * expect(context.user.name).toEqual('newValue');
+ * expect(getter(context, locals)).toEqual('local');
+ * ```
+ *
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ *
+ * The returned function also has the following properties:
+ * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
+ * literal.
+ * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
+ * constant literals.
+ * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
+ * set to a function to change its value on the given context.
+ *
+ */
+
+
+/**
+ * @ngdoc provider
+ * @name $parseProvider
+ * @kind function
+ *
+ * @description
+ * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
+ * service.
+ */
+function $ParseProvider() {
+ var cache = {};
+
+ var $parseOptions = {
+ csp: false,
+ unwrapPromises: false,
+ logPromiseWarnings: true
+ };
+
+
+ /**
+ * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
+ *
+ * @ngdoc method
+ * @name $parseProvider#unwrapPromises
+ * @description
+ *
+ * **This feature is deprecated, see deprecation notes below for more info**
+ *
+ * If set to true (default is false), $parse will unwrap promises automatically when a promise is
+ * found at any part of the expression. In other words, if set to true, the expression will always
+ * result in a non-promise value.
+ *
+ * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled,
+ * the fulfillment value is used in place of the promise while evaluating the expression.
+ *
+ * **Deprecation notice**
+ *
+ * This is a feature that didn't prove to be wildly useful or popular, primarily because of the
+ * dichotomy between data access in templates (accessed as raw values) and controller code
+ * (accessed as promises).
+ *
+ * In most code we ended up resolving promises manually in controllers anyway and thus unifying
+ * the model access there.
+ *
+ * Other downsides of automatic promise unwrapping:
+ *
+ * - when building components it's often desirable to receive the raw promises
+ * - adds complexity and slows down expression evaluation
+ * - makes expression code pre-generation unattractive due to the amount of code that needs to be
+ * generated
+ * - makes IDE auto-completion and tool support hard
+ *
+ * **Warning Logs**
+ *
+ * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a
+ * promise (to reduce the noise, each expression is logged only once). To disable this logging use
+ * `$parseProvider.logPromiseWarnings(false)` api.
+ *
+ *
+ * @param {boolean=} value New value.
+ * @returns {boolean|self} Returns the current setting when used as getter and self if used as
+ * setter.
+ */
+ this.unwrapPromises = function(value) {
+ if (isDefined(value)) {
+ $parseOptions.unwrapPromises = !!value;
+ return this;
+ } else {
+ return $parseOptions.unwrapPromises;
+ }
+ };
+
+
+ /**
+ * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
+ *
+ * @ngdoc method
+ * @name $parseProvider#logPromiseWarnings
+ * @description
+ *
+ * Controls whether Angular should log a warning on any encounter of a promise in an expression.
+ *
+ * The default is set to `true`.
+ *
+ * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well.
+ *
+ * @param {boolean=} value New value.
+ * @returns {boolean|self} Returns the current setting when used as getter and self if used as
+ * setter.
+ */
+ this.logPromiseWarnings = function(value) {
+ if (isDefined(value)) {
+ $parseOptions.logPromiseWarnings = value;
+ return this;
+ } else {
+ return $parseOptions.logPromiseWarnings;
+ }
+ };
+
+
+ this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) {
+ $parseOptions.csp = $sniffer.csp;
+
+ promiseWarning = function promiseWarningFn(fullExp) {
+ if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return;
+ promiseWarningCache[fullExp] = true;
+ $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' +
+ 'Automatic unwrapping of promises in Angular expressions is deprecated.');
+ };
+
+ return function(exp) {
+ var parsedExpression;
+
+ switch (typeof exp) {
+ case 'string':
+
+ if (cache.hasOwnProperty(exp)) {
+ return cache[exp];
+ }
+
+ var lexer = new Lexer($parseOptions);
+ var parser = new Parser(lexer, $filter, $parseOptions);
+ parsedExpression = parser.parse(exp);
+
+ if (exp !== 'hasOwnProperty') {
+ // Only cache the value if it's not going to mess up the cache object
+ // This is more performant that using Object.prototype.hasOwnProperty.call
+ cache[exp] = parsedExpression;
+ }
+
+ return parsedExpression;
+
+ case 'function':
+ return exp;
+
+ default:
+ return noop;
+ }
+ };
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name $q
+ * @requires $rootScope
+ *
+ * @description
+ * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
+ *
+ * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
+ * interface for interacting with an object that represents the result of an action that is
+ * performed asynchronously, and may or may not be finished at any given point in time.
+ *
+ * From the perspective of dealing with error handling, deferred and promise APIs are to
+ * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
+ *
+ * ```js
+ * // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet`
+ * // are available in the current lexical scope (they could have been injected or passed in).
+ *
+ * function asyncGreet(name) {
+ * var deferred = $q.defer();
+ *
+ * setTimeout(function() {
+ * deferred.notify('About to greet ' + name + '.');
+ *
+ * if (okToGreet(name)) {
+ * deferred.resolve('Hello, ' + name + '!');
+ * } else {
+ * deferred.reject('Greeting ' + name + ' is not allowed.');
+ * }
+ * }, 1000);
+ *
+ * return deferred.promise;
+ * }
+ *
+ * var promise = asyncGreet('Robin Hood');
+ * promise.then(function(greeting) {
+ * alert('Success: ' + greeting);
+ * }, function(reason) {
+ * alert('Failed: ' + reason);
+ * }, function(update) {
+ * alert('Got notification: ' + update);
+ * });
+ * ```
+ *
+ * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
+ * comes in the way of guarantees that promise and deferred APIs make, see
+ * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
+ *
+ * Additionally the promise api allows for composition that is very hard to do with the
+ * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
+ * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
+ * section on serial or parallel joining of promises.
+ *
+ *
+ * # The Deferred API
+ *
+ * A new instance of deferred is constructed by calling `$q.defer()`.
+ *
+ * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
+ * that can be used for signaling the successful or unsuccessful completion, as well as the status
+ * of the task.
+ *
+ * **Methods**
+ *
+ * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
+ * constructed via `$q.reject`, the promise will be rejected instead.
+ * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
+ * resolving it with a rejection constructed via `$q.reject`.
+ * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
+ * multiple times before the promise is either resolved or rejected.
+ *
+ * **Properties**
+ *
+ * - promise – `{Promise}` – promise object associated with this deferred.
+ *
+ *
+ * # The Promise API
+ *
+ * A new promise instance is created when a deferred instance is created and can be retrieved by
+ * calling `deferred.promise`.
+ *
+ * The purpose of the promise object is to allow for interested parties to get access to the result
+ * of the deferred task when it completes.
+ *
+ * **Methods**
+ *
+ * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
+ * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
+ * as soon as the result is available. The callbacks are called with a single argument: the result
+ * or rejection reason. Additionally, the notify callback may be called zero or more times to
+ * provide a progress indication, before the promise is resolved or rejected.
+ *
+ * This method *returns a new promise* which is resolved or rejected via the return value of the
+ * `successCallback`, `errorCallback`. It also notifies via the return value of the
+ * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
+ * method.
+ *
+ * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
+ *
+ * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
+ * but to do so without modifying the final value. This is useful to release resources or do some
+ * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
+ * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
+ * more information.
+ *
+ * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
+ * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
+ * make your code IE8 and Android 2.x compatible.
+ *
+ * # Chaining promises
+ *
+ * Because calling the `then` method of a promise returns a new derived promise, it is easily
+ * possible to create a chain of promises:
+ *
+ * ```js
+ * promiseB = promiseA.then(function(result) {
+ * return result + 1;
+ * });
+ *
+ * // promiseB will be resolved immediately after promiseA is resolved and its value
+ * // will be the result of promiseA incremented by 1
+ * ```
+ *
+ * It is possible to create chains of any length and since a promise can be resolved with another
+ * promise (which will defer its resolution further), it is possible to pause/defer resolution of
+ * the promises at any point in the chain. This makes it possible to implement powerful APIs like
+ * $http's response interceptors.
+ *
+ *
+ * # Differences between Kris Kowal's Q and $q
+ *
+ * There are two main differences:
+ *
+ * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
+ * mechanism in angular, which means faster propagation of resolution or rejection into your
+ * models and avoiding unnecessary browser repaints, which would result in flickering UI.
+ * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
+ * all the important functionality needed for common async tasks.
+ *
+ * # Testing
+ *
+ * ```js
+ * it('should simulate promise', inject(function($q, $rootScope) {
+ * var deferred = $q.defer();
+ * var promise = deferred.promise;
+ * var resolvedValue;
+ *
+ * promise.then(function(value) { resolvedValue = value; });
+ * expect(resolvedValue).toBeUndefined();
+ *
+ * // Simulate resolving of promise
+ * deferred.resolve(123);
+ * // Note that the 'then' function does not get called synchronously.
+ * // This is because we want the promise API to always be async, whether or not
+ * // it got called synchronously or asynchronously.
+ * expect(resolvedValue).toBeUndefined();
+ *
+ * // Propagate promise resolution to 'then' functions using $apply().
+ * $rootScope.$apply();
+ * expect(resolvedValue).toEqual(123);
+ * }));
+ * ```
+ */
+function $QProvider() {
+
+ this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
+ return qFactory(function(callback) {
+ $rootScope.$evalAsync(callback);
+ }, $exceptionHandler);
+ }];
+}
+
+
+/**
+ * Constructs a promise manager.
+ *
+ * @param {function(Function)} nextTick Function for executing functions in the next turn.
+ * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
+ * debugging purposes.
+ * @returns {object} Promise manager.
+ */
+function qFactory(nextTick, exceptionHandler) {
+
+ /**
+ * @ngdoc method
+ * @name $q#defer
+ * @kind function
+ *
+ * @description
+ * Creates a `Deferred` object which represents a task which will finish in the future.
+ *
+ * @returns {Deferred} Returns a new instance of deferred.
+ */
+ var defer = function() {
+ var pending = [],
+ value, deferred;
+
+ deferred = {
+
+ resolve: function(val) {
+ if (pending) {
+ var callbacks = pending;
+ pending = undefined;
+ value = ref(val);
+
+ if (callbacks.length) {
+ nextTick(function() {
+ var callback;
+ for (var i = 0, ii = callbacks.length; i < ii; i++) {
+ callback = callbacks[i];
+ value.then(callback[0], callback[1], callback[2]);
+ }
+ });
+ }
+ }
+ },
+
+
+ reject: function(reason) {
+ deferred.resolve(createInternalRejectedPromise(reason));
+ },
+
+
+ notify: function(progress) {
+ if (pending) {
+ var callbacks = pending;
+
+ if (pending.length) {
+ nextTick(function() {
+ var callback;
+ for (var i = 0, ii = callbacks.length; i < ii; i++) {
+ callback = callbacks[i];
+ callback[2](progress);
+ }
+ });
+ }
+ }
+ },
+
+
+ promise: {
+ then: function(callback, errback, progressback) {
+ var result = defer();
+
+ var wrappedCallback = function(value) {
+ try {
+ result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
+ } catch(e) {
+ result.reject(e);
+ exceptionHandler(e);
+ }
+ };
+
+ var wrappedErrback = function(reason) {
+ try {
+ result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
+ } catch(e) {
+ result.reject(e);
+ exceptionHandler(e);
+ }
+ };
+
+ var wrappedProgressback = function(progress) {
+ try {
+ result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
+ } catch(e) {
+ exceptionHandler(e);
+ }
+ };
+
+ if (pending) {
+ pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
+ } else {
+ value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
+ }
+
+ return result.promise;
+ },
+
+ "catch": function(callback) {
+ return this.then(null, callback);
+ },
+
+ "finally": function(callback) {
+
+ function makePromise(value, resolved) {
+ var result = defer();
+ if (resolved) {
+ result.resolve(value);
+ } else {
+ result.reject(value);
+ }
+ return result.promise;
+ }
+
+ function handleCallback(value, isResolved) {
+ var callbackOutput = null;
+ try {
+ callbackOutput = (callback ||defaultCallback)();
+ } catch(e) {
+ return makePromise(e, false);
+ }
+ if (callbackOutput && isFunction(callbackOutput.then)) {
+ return callbackOutput.then(function() {
+ return makePromise(value, isResolved);
+ }, function(error) {
+ return makePromise(error, false);
+ });
+ } else {
+ return makePromise(value, isResolved);
+ }
+ }
+
+ return this.then(function(value) {
+ return handleCallback(value, true);
+ }, function(error) {
+ return handleCallback(error, false);
+ });
+ }
+ }
+ };
+
+ return deferred;
+ };
+
+
+ var ref = function(value) {
+ if (value && isFunction(value.then)) return value;
+ return {
+ then: function(callback) {
+ var result = defer();
+ nextTick(function() {
+ result.resolve(callback(value));
+ });
+ return result.promise;
+ }
+ };
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $q#reject
+ * @kind function
+ *
+ * @description
+ * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
+ * used to forward rejection in a chain of promises. If you are dealing with the last promise in
+ * a promise chain, you don't need to worry about it.
+ *
+ * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
+ * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
+ * a promise error callback and you want to forward the error to the promise derived from the
+ * current promise, you have to "rethrow" the error by returning a rejection constructed via
+ * `reject`.
+ *
+ * ```js
+ * promiseB = promiseA.then(function(result) {
+ * // success: do something and resolve promiseB
+ * // with the old or a new result
+ * return result;
+ * }, function(reason) {
+ * // error: handle the error if possible and
+ * // resolve promiseB with newPromiseOrValue,
+ * // otherwise forward the rejection to promiseB
+ * if (canHandle(reason)) {
+ * // handle the error and recover
+ * return newPromiseOrValue;
+ * }
+ * return $q.reject(reason);
+ * });
+ * ```
+ *
+ * @param {*} reason Constant, message, exception or an object representing the rejection reason.
+ * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
+ */
+ var reject = function(reason) {
+ var result = defer();
+ result.reject(reason);
+ return result.promise;
+ };
+
+ var createInternalRejectedPromise = function(reason) {
+ return {
+ then: function(callback, errback) {
+ var result = defer();
+ nextTick(function() {
+ try {
+ result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
+ } catch(e) {
+ result.reject(e);
+ exceptionHandler(e);
+ }
+ });
+ return result.promise;
+ }
+ };
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $q#when
+ * @kind function
+ *
+ * @description
+ * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
+ * This is useful when you are dealing with an object that might or might not be a promise, or if
+ * the promise comes from a source that can't be trusted.
+ *
+ * @param {*} value Value or a promise
+ * @returns {Promise} Returns a promise of the passed value or promise
+ */
+ var when = function(value, callback, errback, progressback) {
+ var result = defer(),
+ done;
+
+ var wrappedCallback = function(value) {
+ try {
+ return (isFunction(callback) ? callback : defaultCallback)(value);
+ } catch (e) {
+ exceptionHandler(e);
+ return reject(e);
+ }
+ };
+
+ var wrappedErrback = function(reason) {
+ try {
+ return (isFunction(errback) ? errback : defaultErrback)(reason);
+ } catch (e) {
+ exceptionHandler(e);
+ return reject(e);
+ }
+ };
+
+ var wrappedProgressback = function(progress) {
+ try {
+ return (isFunction(progressback) ? progressback : defaultCallback)(progress);
+ } catch (e) {
+ exceptionHandler(e);
+ }
+ };
+
+ nextTick(function() {
+ ref(value).then(function(value) {
+ if (done) return;
+ done = true;
+ result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
+ }, function(reason) {
+ if (done) return;
+ done = true;
+ result.resolve(wrappedErrback(reason));
+ }, function(progress) {
+ if (done) return;
+ result.notify(wrappedProgressback(progress));
+ });
+ });
+
+ return result.promise;
+ };
+
+
+ function defaultCallback(value) {
+ return value;
+ }
+
+
+ function defaultErrback(reason) {
+ return reject(reason);
+ }
+
+
+ /**
+ * @ngdoc method
+ * @name $q#all
+ * @kind function
+ *
+ * @description
+ * Combines multiple promises into a single promise that is resolved when all of the input
+ * promises are resolved.
+ *
+ * @param {Array.|Object.} promises An array or hash of promises.
+ * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
+ * each value corresponding to the promise at the same index/key in the `promises` array/hash.
+ * If any of the promises is resolved with a rejection, this resulting promise will be rejected
+ * with the same rejection value.
+ */
+ function all(promises) {
+ var deferred = defer(),
+ counter = 0,
+ results = isArray(promises) ? [] : {};
+
+ forEach(promises, function(promise, key) {
+ counter++;
+ ref(promise).then(function(value) {
+ if (results.hasOwnProperty(key)) return;
+ results[key] = value;
+ if (!(--counter)) deferred.resolve(results);
+ }, function(reason) {
+ if (results.hasOwnProperty(key)) return;
+ deferred.reject(reason);
+ });
+ });
+
+ if (counter === 0) {
+ deferred.resolve(results);
+ }
+
+ return deferred.promise;
+ }
+
+ return {
+ defer: defer,
+ reject: reject,
+ when: when,
+ all: all
+ };
+}
+
+function $$RAFProvider(){ //rAF
+ this.$get = ['$window', '$timeout', function($window, $timeout) {
+ var requestAnimationFrame = $window.requestAnimationFrame ||
+ $window.webkitRequestAnimationFrame ||
+ $window.mozRequestAnimationFrame;
+
+ var cancelAnimationFrame = $window.cancelAnimationFrame ||
+ $window.webkitCancelAnimationFrame ||
+ $window.mozCancelAnimationFrame ||
+ $window.webkitCancelRequestAnimationFrame;
+
+ var rafSupported = !!requestAnimationFrame;
+ var raf = rafSupported
+ ? function(fn) {
+ var id = requestAnimationFrame(fn);
+ return function() {
+ cancelAnimationFrame(id);
+ };
+ }
+ : function(fn) {
+ var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
+ return function() {
+ $timeout.cancel(timer);
+ };
+ };
+
+ raf.supported = rafSupported;
+
+ return raf;
+ }];
+}
+
+/**
+ * DESIGN NOTES
+ *
+ * The design decisions behind the scope are heavily favored for speed and memory consumption.
+ *
+ * The typical use of scope is to watch the expressions, which most of the time return the same
+ * value as last time so we optimize the operation.
+ *
+ * Closures construction is expensive in terms of speed as well as memory:
+ * - No closures, instead use prototypical inheritance for API
+ * - Internal state needs to be stored on scope directly, which means that private state is
+ * exposed as $$____ properties
+ *
+ * Loop operations are optimized by using while(count--) { ... }
+ * - this means that in order to keep the same order of execution as addition we have to add
+ * items to the array at the beginning (unshift) instead of at the end (push)
+ *
+ * Child scopes are created and removed often
+ * - Using an array would be slow since inserts in middle are expensive so we use linked list
+ *
+ * There are few watches then a lot of observers. This is why you don't want the observer to be
+ * implemented in the same way as watch. Watch requires return of initialization function which
+ * are expensive to construct.
+ */
+
+
+/**
+ * @ngdoc provider
+ * @name $rootScopeProvider
+ * @description
+ *
+ * Provider for the $rootScope service.
+ */
+
+/**
+ * @ngdoc method
+ * @name $rootScopeProvider#digestTtl
+ * @description
+ *
+ * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
+ * assuming that the model is unstable.
+ *
+ * The current default is 10 iterations.
+ *
+ * In complex applications it's possible that the dependencies between `$watch`s will result in
+ * several digest iterations. However if an application needs more than the default 10 digest
+ * iterations for its model to stabilize then you should investigate what is causing the model to
+ * continuously change during the digest.
+ *
+ * Increasing the TTL could have performance implications, so you should not change it without
+ * proper justification.
+ *
+ * @param {number} limit The number of digest iterations.
+ */
+
+
+/**
+ * @ngdoc service
+ * @name $rootScope
+ * @description
+ *
+ * Every application has a single root {@link ng.$rootScope.Scope scope}.
+ * All other scopes are descendant scopes of the root scope. Scopes provide separation
+ * between the model and the view, via a mechanism for watching the model for changes.
+ * They also provide an event emission/broadcast and subscription facility. See the
+ * {@link guide/scope developer guide on scopes}.
+ */
+function $RootScopeProvider(){
+ var TTL = 10;
+ var $rootScopeMinErr = minErr('$rootScope');
+ var lastDirtyWatch = null;
+
+ this.digestTtl = function(value) {
+ if (arguments.length) {
+ TTL = value;
+ }
+ return TTL;
+ };
+
+ this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
+ function( $injector, $exceptionHandler, $parse, $browser) {
+
+ /**
+ * @ngdoc type
+ * @name $rootScope.Scope
+ *
+ * @description
+ * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
+ * {@link auto.$injector $injector}. Child scopes are created using the
+ * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
+ * compiled HTML template is executed.)
+ *
+ * Here is a simple scope snippet to show how you can interact with the scope.
+ * ```html
+ *
+ * ```
+ *
+ * # Inheritance
+ * A scope can inherit from a parent scope, as in this example:
+ * ```js
+ var parent = $rootScope;
+ var child = parent.$new();
+
+ parent.salutation = "Hello";
+ child.name = "World";
+ expect(child.salutation).toEqual('Hello');
+
+ child.salutation = "Welcome";
+ expect(child.salutation).toEqual('Welcome');
+ expect(parent.salutation).toEqual('Hello');
+ * ```
+ *
+ *
+ * @param {Object.=} providers Map of service factory which need to be
+ * provided for the current scope. Defaults to {@link ng}.
+ * @param {Object.=} instanceCache Provides pre-instantiated services which should
+ * append/override services provided by `providers`. This is handy
+ * when unit-testing and having the need to override a default
+ * service.
+ * @returns {Object} Newly created scope.
+ *
+ */
+ function Scope() {
+ this.$id = nextUid();
+ this.$$phase = this.$parent = this.$$watchers =
+ this.$$nextSibling = this.$$prevSibling =
+ this.$$childHead = this.$$childTail = null;
+ this['this'] = this.$root = this;
+ this.$$destroyed = false;
+ this.$$asyncQueue = [];
+ this.$$postDigestQueue = [];
+ this.$$listeners = {};
+ this.$$listenerCount = {};
+ this.$$isolateBindings = {};
+ }
+
+ /**
+ * @ngdoc property
+ * @name $rootScope.Scope#$id
+ * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
+ * debugging.
+ */
+
+
+ Scope.prototype = {
+ constructor: Scope,
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$new
+ * @kind function
+ *
+ * @description
+ * Creates a new child {@link ng.$rootScope.Scope scope}.
+ *
+ * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
+ * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the
+ * scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
+ *
+ * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
+ * desired for the scope and its child scopes to be permanently detached from the parent and
+ * thus stop participating in model change detection and listener notification by invoking.
+ *
+ * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
+ * parent scope. The scope is isolated, as it can not see parent scope properties.
+ * When creating widgets, it is useful for the widget to not accidentally read parent
+ * state.
+ *
+ * @returns {Object} The newly created child scope.
+ *
+ */
+ $new: function(isolate) {
+ var ChildScope,
+ child;
+
+ if (isolate) {
+ child = new Scope();
+ child.$root = this.$root;
+ // ensure that there is just one async queue per $rootScope and its children
+ child.$$asyncQueue = this.$$asyncQueue;
+ child.$$postDigestQueue = this.$$postDigestQueue;
+ } else {
+ // Only create a child scope class if somebody asks for one,
+ // but cache it to allow the VM to optimize lookups.
+ if (!this.$$childScopeClass) {
+ this.$$childScopeClass = function() {
+ this.$$watchers = this.$$nextSibling =
+ this.$$childHead = this.$$childTail = null;
+ this.$$listeners = {};
+ this.$$listenerCount = {};
+ this.$id = nextUid();
+ this.$$childScopeClass = null;
+ };
+ this.$$childScopeClass.prototype = this;
+ }
+ child = new this.$$childScopeClass();
+ }
+ child['this'] = child;
+ child.$parent = this;
+ child.$$prevSibling = this.$$childTail;
+ if (this.$$childHead) {
+ this.$$childTail.$$nextSibling = child;
+ this.$$childTail = child;
+ } else {
+ this.$$childHead = this.$$childTail = child;
+ }
+ return child;
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$watch
+ * @kind function
+ *
+ * @description
+ * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
+ *
+ * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
+ * $digest()} and should return the value that will be watched. (Since
+ * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
+ * `watchExpression` can execute multiple times per
+ * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
+ * - The `listener` is called only when the value from the current `watchExpression` and the
+ * previous call to `watchExpression` are not equal (with the exception of the initial run,
+ * see below). Inequality is determined according to reference inequality,
+ * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
+ * via the `!==` Javascript operator, unless `objectEquality == true`
+ * (see next point)
+ * - When `objectEquality == true`, inequality of the `watchExpression` is determined
+ * according to the {@link angular.equals} function. To save the value of the object for
+ * later comparison, the {@link angular.copy} function is used. This therefore means that
+ * watching complex objects will have adverse memory and performance implications.
+ * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
+ * This is achieved by rerunning the watchers until no changes are detected. The rerun
+ * iteration limit is 10 to prevent an infinite loop deadlock.
+ *
+ *
+ * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
+ * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
+ * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
+ * change is detected, be prepared for multiple calls to your listener.)
+ *
+ * After a watcher is registered with the scope, the `listener` fn is called asynchronously
+ * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
+ * watcher. In rare cases, this is undesirable because the listener is called when the result
+ * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
+ * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
+ * listener was called due to initialization.
+ *
+ * The example below contains an illustration of using a function as your $watch listener
+ *
+ *
+ * # Example
+ * ```js
+ // let's assume that scope was dependency injected as the $rootScope
+ var scope = $rootScope;
+ scope.name = 'misko';
+ scope.counter = 0;
+
+ expect(scope.counter).toEqual(0);
+ scope.$watch('name', function(newValue, oldValue) {
+ scope.counter = scope.counter + 1;
+ });
+ expect(scope.counter).toEqual(0);
+
+ scope.$digest();
+ // the listener is always called during the first $digest loop after it was registered
+ expect(scope.counter).toEqual(1);
+
+ scope.$digest();
+ // but now it will not be called unless the value changes
+ expect(scope.counter).toEqual(1);
+
+ scope.name = 'adam';
+ scope.$digest();
+ expect(scope.counter).toEqual(2);
+
+
+
+ // Using a listener function
+ var food;
+ scope.foodCounter = 0;
+ expect(scope.foodCounter).toEqual(0);
+ scope.$watch(
+ // This is the listener function
+ function() { return food; },
+ // This is the change handler
+ function(newValue, oldValue) {
+ if ( newValue !== oldValue ) {
+ // Only increment the counter if the value changed
+ scope.foodCounter = scope.foodCounter + 1;
+ }
+ }
+ );
+ // No digest has been run so the counter will be zero
+ expect(scope.foodCounter).toEqual(0);
+
+ // Run the digest but since food has not changed count will still be zero
+ scope.$digest();
+ expect(scope.foodCounter).toEqual(0);
+
+ // Update food and run digest. Now the counter will increment
+ food = 'cheeseburger';
+ scope.$digest();
+ expect(scope.foodCounter).toEqual(1);
+
+ * ```
+ *
+ *
+ *
+ * @param {(function()|string)} watchExpression Expression that is evaluated on each
+ * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
+ * a call to the `listener`.
+ *
+ * - `string`: Evaluated as {@link guide/expression expression}
+ * - `function(scope)`: called with current `scope` as a parameter.
+ * @param {(function()|string)=} listener Callback called whenever the return value of
+ * the `watchExpression` changes.
+ *
+ * - `string`: Evaluated as {@link guide/expression expression}
+ * - `function(newValue, oldValue, scope)`: called with current and previous values as
+ * parameters.
+ *
+ * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
+ * comparing for reference equality.
+ * @returns {function()} Returns a deregistration function for this listener.
+ */
+ $watch: function(watchExp, listener, objectEquality) {
+ var scope = this,
+ get = compileToFn(watchExp, 'watch'),
+ array = scope.$$watchers,
+ watcher = {
+ fn: listener,
+ last: initWatchVal,
+ get: get,
+ exp: watchExp,
+ eq: !!objectEquality
+ };
+
+ lastDirtyWatch = null;
+
+ // in the case user pass string, we need to compile it, do we really need this ?
+ if (!isFunction(listener)) {
+ var listenFn = compileToFn(listener || noop, 'listener');
+ watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
+ }
+
+ if (typeof watchExp == 'string' && get.constant) {
+ var originalFn = watcher.fn;
+ watcher.fn = function(newVal, oldVal, scope) {
+ originalFn.call(this, newVal, oldVal, scope);
+ arrayRemove(array, watcher);
+ };
+ }
+
+ if (!array) {
+ array = scope.$$watchers = [];
+ }
+ // we use unshift since we use a while loop in $digest for speed.
+ // the while loop reads in reverse order.
+ array.unshift(watcher);
+
+ return function deregisterWatch() {
+ arrayRemove(array, watcher);
+ lastDirtyWatch = null;
+ };
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$watchCollection
+ * @kind function
+ *
+ * @description
+ * Shallow watches the properties of an object and fires whenever any of the properties change
+ * (for arrays, this implies watching the array items; for object maps, this implies watching
+ * the properties). If a change is detected, the `listener` callback is fired.
+ *
+ * - The `obj` collection is observed via standard $watch operation and is examined on every
+ * call to $digest() to see if any items have been added, removed, or moved.
+ * - The `listener` is called whenever anything within the `obj` has changed. Examples include
+ * adding, removing, and moving items belonging to an object or array.
+ *
+ *
+ * # Example
+ * ```js
+ $scope.names = ['igor', 'matias', 'misko', 'james'];
+ $scope.dataCount = 4;
+
+ $scope.$watchCollection('names', function(newNames, oldNames) {
+ $scope.dataCount = newNames.length;
+ });
+
+ expect($scope.dataCount).toEqual(4);
+ $scope.$digest();
+
+ //still at 4 ... no changes
+ expect($scope.dataCount).toEqual(4);
+
+ $scope.names.pop();
+ $scope.$digest();
+
+ //now there's been a change
+ expect($scope.dataCount).toEqual(3);
+ * ```
+ *
+ *
+ * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
+ * expression value should evaluate to an object or an array which is observed on each
+ * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
+ * collection will trigger a call to the `listener`.
+ *
+ * @param {function(newCollection, oldCollection, scope)} listener a callback function called
+ * when a change is detected.
+ * - The `newCollection` object is the newly modified data obtained from the `obj` expression
+ * - The `oldCollection` object is a copy of the former collection data.
+ * Due to performance considerations, the`oldCollection` value is computed only if the
+ * `listener` function declares two or more arguments.
+ * - The `scope` argument refers to the current scope.
+ *
+ * @returns {function()} Returns a de-registration function for this listener. When the
+ * de-registration function is executed, the internal watch operation is terminated.
+ */
+ $watchCollection: function(obj, listener) {
+ var self = this;
+ // the current value, updated on each dirty-check run
+ var newValue;
+ // a shallow copy of the newValue from the last dirty-check run,
+ // updated to match newValue during dirty-check run
+ var oldValue;
+ // a shallow copy of the newValue from when the last change happened
+ var veryOldValue;
+ // only track veryOldValue if the listener is asking for it
+ var trackVeryOldValue = (listener.length > 1);
+ var changeDetected = 0;
+ var objGetter = $parse(obj);
+ var internalArray = [];
+ var internalObject = {};
+ var initRun = true;
+ var oldLength = 0;
+
+ function $watchCollectionWatch() {
+ newValue = objGetter(self);
+ var newLength, key;
+
+ if (!isObject(newValue)) { // if primitive
+ if (oldValue !== newValue) {
+ oldValue = newValue;
+ changeDetected++;
+ }
+ } else if (isArrayLike(newValue)) {
+ if (oldValue !== internalArray) {
+ // we are transitioning from something which was not an array into array.
+ oldValue = internalArray;
+ oldLength = oldValue.length = 0;
+ changeDetected++;
+ }
+
+ newLength = newValue.length;
+
+ if (oldLength !== newLength) {
+ // if lengths do not match we need to trigger change notification
+ changeDetected++;
+ oldValue.length = oldLength = newLength;
+ }
+ // copy the items to oldValue and look for changes.
+ for (var i = 0; i < newLength; i++) {
+ var bothNaN = (oldValue[i] !== oldValue[i]) &&
+ (newValue[i] !== newValue[i]);
+ if (!bothNaN && (oldValue[i] !== newValue[i])) {
+ changeDetected++;
+ oldValue[i] = newValue[i];
+ }
+ }
+ } else {
+ if (oldValue !== internalObject) {
+ // we are transitioning from something which was not an object into object.
+ oldValue = internalObject = {};
+ oldLength = 0;
+ changeDetected++;
+ }
+ // copy the items to oldValue and look for changes.
+ newLength = 0;
+ for (key in newValue) {
+ if (newValue.hasOwnProperty(key)) {
+ newLength++;
+ if (oldValue.hasOwnProperty(key)) {
+ if (oldValue[key] !== newValue[key]) {
+ changeDetected++;
+ oldValue[key] = newValue[key];
+ }
+ } else {
+ oldLength++;
+ oldValue[key] = newValue[key];
+ changeDetected++;
+ }
+ }
+ }
+ if (oldLength > newLength) {
+ // we used to have more keys, need to find them and destroy them.
+ changeDetected++;
+ for(key in oldValue) {
+ if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
+ oldLength--;
+ delete oldValue[key];
+ }
+ }
+ }
+ }
+ return changeDetected;
+ }
+
+ function $watchCollectionAction() {
+ if (initRun) {
+ initRun = false;
+ listener(newValue, newValue, self);
+ } else {
+ listener(newValue, veryOldValue, self);
+ }
+
+ // make a copy for the next time a collection is changed
+ if (trackVeryOldValue) {
+ if (!isObject(newValue)) {
+ //primitive
+ veryOldValue = newValue;
+ } else if (isArrayLike(newValue)) {
+ veryOldValue = new Array(newValue.length);
+ for (var i = 0; i < newValue.length; i++) {
+ veryOldValue[i] = newValue[i];
+ }
+ } else { // if object
+ veryOldValue = {};
+ for (var key in newValue) {
+ if (hasOwnProperty.call(newValue, key)) {
+ veryOldValue[key] = newValue[key];
+ }
+ }
+ }
+ }
+ }
+
+ return this.$watch($watchCollectionWatch, $watchCollectionAction);
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$digest
+ * @kind function
+ *
+ * @description
+ * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
+ * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
+ * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
+ * until no more listeners are firing. This means that it is possible to get into an infinite
+ * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
+ * iterations exceeds 10.
+ *
+ * Usually, you don't call `$digest()` directly in
+ * {@link ng.directive:ngController controllers} or in
+ * {@link ng.$compileProvider#directive directives}.
+ * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
+ * a {@link ng.$compileProvider#directive directives}), which will force a `$digest()`.
+ *
+ * If you want to be notified whenever `$digest()` is called,
+ * you can register a `watchExpression` function with
+ * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
+ *
+ * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
+ *
+ * # Example
+ * ```js
+ var scope = ...;
+ scope.name = 'misko';
+ scope.counter = 0;
+
+ expect(scope.counter).toEqual(0);
+ scope.$watch('name', function(newValue, oldValue) {
+ scope.counter = scope.counter + 1;
+ });
+ expect(scope.counter).toEqual(0);
+
+ scope.$digest();
+ // the listener is always called during the first $digest loop after it was registered
+ expect(scope.counter).toEqual(1);
+
+ scope.$digest();
+ // but now it will not be called unless the value changes
+ expect(scope.counter).toEqual(1);
+
+ scope.name = 'adam';
+ scope.$digest();
+ expect(scope.counter).toEqual(2);
+ * ```
+ *
+ */
+ $digest: function() {
+ var watch, value, last,
+ watchers,
+ asyncQueue = this.$$asyncQueue,
+ postDigestQueue = this.$$postDigestQueue,
+ length,
+ dirty, ttl = TTL,
+ next, current, target = this,
+ watchLog = [],
+ logIdx, logMsg, asyncTask;
+
+ beginPhase('$digest');
+
+ lastDirtyWatch = null;
+
+ do { // "while dirty" loop
+ dirty = false;
+ current = target;
+
+ while(asyncQueue.length) {
+ try {
+ asyncTask = asyncQueue.shift();
+ asyncTask.scope.$eval(asyncTask.expression);
+ } catch (e) {
+ clearPhase();
+ $exceptionHandler(e);
+ }
+ lastDirtyWatch = null;
+ }
+
+ traverseScopesLoop:
+ do { // "traverse the scopes" loop
+ if ((watchers = current.$$watchers)) {
+ // process our watches
+ length = watchers.length;
+ while (length--) {
+ try {
+ watch = watchers[length];
+ // Most common watches are on primitives, in which case we can short
+ // circuit it with === operator, only when === fails do we use .equals
+ if (watch) {
+ if ((value = watch.get(current)) !== (last = watch.last) &&
+ !(watch.eq
+ ? equals(value, last)
+ : (typeof value === 'number' && typeof last === 'number'
+ && isNaN(value) && isNaN(last)))) {
+ dirty = true;
+ lastDirtyWatch = watch;
+ watch.last = watch.eq ? copy(value, null) : value;
+ watch.fn(value, ((last === initWatchVal) ? value : last), current);
+ if (ttl < 5) {
+ logIdx = 4 - ttl;
+ if (!watchLog[logIdx]) watchLog[logIdx] = [];
+ logMsg = (isFunction(watch.exp))
+ ? 'fn: ' + (watch.exp.name || watch.exp.toString())
+ : watch.exp;
+ logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
+ watchLog[logIdx].push(logMsg);
+ }
+ } else if (watch === lastDirtyWatch) {
+ // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
+ // have already been tested.
+ dirty = false;
+ break traverseScopesLoop;
+ }
+ }
+ } catch (e) {
+ clearPhase();
+ $exceptionHandler(e);
+ }
+ }
+ }
+
+ // Insanity Warning: scope depth-first traversal
+ // yes, this code is a bit crazy, but it works and we have tests to prove it!
+ // this piece should be kept in sync with the traversal in $broadcast
+ if (!(next = (current.$$childHead ||
+ (current !== target && current.$$nextSibling)))) {
+ while(current !== target && !(next = current.$$nextSibling)) {
+ current = current.$parent;
+ }
+ }
+ } while ((current = next));
+
+ // `break traverseScopesLoop;` takes us to here
+
+ if((dirty || asyncQueue.length) && !(ttl--)) {
+ clearPhase();
+ throw $rootScopeMinErr('infdig',
+ '{0} $digest() iterations reached. Aborting!\n' +
+ 'Watchers fired in the last 5 iterations: {1}',
+ TTL, toJson(watchLog));
+ }
+
+ } while (dirty || asyncQueue.length);
+
+ clearPhase();
+
+ while(postDigestQueue.length) {
+ try {
+ postDigestQueue.shift()();
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ }
+ },
+
+
+ /**
+ * @ngdoc event
+ * @name $rootScope.Scope#$destroy
+ * @eventType broadcast on scope being destroyed
+ *
+ * @description
+ * Broadcasted when a scope and its children are being destroyed.
+ *
+ * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
+ * clean up DOM bindings before an element is removed from the DOM.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$destroy
+ * @kind function
+ *
+ * @description
+ * Removes the current scope (and all of its children) from the parent scope. Removal implies
+ * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
+ * propagate to the current scope and its children. Removal also implies that the current
+ * scope is eligible for garbage collection.
+ *
+ * The `$destroy()` is usually used by directives such as
+ * {@link ng.directive:ngRepeat ngRepeat} for managing the
+ * unrolling of the loop.
+ *
+ * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
+ * Application code can register a `$destroy` event handler that will give it a chance to
+ * perform any necessary cleanup.
+ *
+ * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
+ * clean up DOM bindings before an element is removed from the DOM.
+ */
+ $destroy: function() {
+ // we can't destroy the root scope or a scope that has been already destroyed
+ if (this.$$destroyed) return;
+ var parent = this.$parent;
+
+ this.$broadcast('$destroy');
+ this.$$destroyed = true;
+ if (this === $rootScope) return;
+
+ forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));
+
+ // sever all the references to parent scopes (after this cleanup, the current scope should
+ // not be retained by any of our references and should be eligible for garbage collection)
+ if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
+ if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
+ if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
+ if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
+
+
+ // All of the code below is bogus code that works around V8's memory leak via optimized code
+ // and inline caches.
+ //
+ // see:
+ // - https://code.google.com/p/v8/issues/detail?id=2073#c26
+ // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
+ // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
+
+ this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
+ this.$$childTail = this.$root = null;
+
+ // don't reset these to null in case some async task tries to register a listener/watch/task
+ this.$$listeners = {};
+ this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = [];
+
+ // prevent NPEs since these methods have references to properties we nulled out
+ this.$destroy = this.$digest = this.$apply = noop;
+ this.$on = this.$watch = function() { return noop; };
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$eval
+ * @kind function
+ *
+ * @description
+ * Executes the `expression` on the current scope and returns the result. Any exceptions in
+ * the expression are propagated (uncaught). This is useful when evaluating Angular
+ * expressions.
+ *
+ * # Example
+ * ```js
+ var scope = ng.$rootScope.Scope();
+ scope.a = 1;
+ scope.b = 2;
+
+ expect(scope.$eval('a+b')).toEqual(3);
+ expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
+ * ```
+ *
+ * @param {(string|function())=} expression An angular expression to be executed.
+ *
+ * - `string`: execute using the rules as defined in {@link guide/expression expression}.
+ * - `function(scope)`: execute the function with the current `scope` parameter.
+ *
+ * @param {(object)=} locals Local variables object, useful for overriding values in scope.
+ * @returns {*} The result of evaluating the expression.
+ */
+ $eval: function(expr, locals) {
+ return $parse(expr)(this, locals);
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$evalAsync
+ * @kind function
+ *
+ * @description
+ * Executes the expression on the current scope at a later point in time.
+ *
+ * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
+ * that:
+ *
+ * - it will execute after the function that scheduled the evaluation (preferably before DOM
+ * rendering).
+ * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
+ * `expression` execution.
+ *
+ * Any exceptions from the execution of the expression are forwarded to the
+ * {@link ng.$exceptionHandler $exceptionHandler} service.
+ *
+ * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
+ * will be scheduled. However, it is encouraged to always call code that changes the model
+ * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
+ *
+ * @param {(string|function())=} expression An angular expression to be executed.
+ *
+ * - `string`: execute using the rules as defined in {@link guide/expression expression}.
+ * - `function(scope)`: execute the function with the current `scope` parameter.
+ *
+ */
+ $evalAsync: function(expr) {
+ // if we are outside of an $digest loop and this is the first time we are scheduling async
+ // task also schedule async auto-flush
+ if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) {
+ $browser.defer(function() {
+ if ($rootScope.$$asyncQueue.length) {
+ $rootScope.$digest();
+ }
+ });
+ }
+
+ this.$$asyncQueue.push({scope: this, expression: expr});
+ },
+
+ $$postDigest : function(fn) {
+ this.$$postDigestQueue.push(fn);
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$apply
+ * @kind function
+ *
+ * @description
+ * `$apply()` is used to execute an expression in angular from outside of the angular
+ * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
+ * Because we are calling into the angular framework we need to perform proper scope life
+ * cycle of {@link ng.$exceptionHandler exception handling},
+ * {@link ng.$rootScope.Scope#$digest executing watches}.
+ *
+ * ## Life cycle
+ *
+ * # Pseudo-Code of `$apply()`
+ * ```js
+ function $apply(expr) {
+ try {
+ return $eval(expr);
+ } catch (e) {
+ $exceptionHandler(e);
+ } finally {
+ $root.$digest();
+ }
+ }
+ * ```
+ *
+ *
+ * Scope's `$apply()` method transitions through the following stages:
+ *
+ * 1. The {@link guide/expression expression} is executed using the
+ * {@link ng.$rootScope.Scope#$eval $eval()} method.
+ * 2. Any exceptions from the execution of the expression are forwarded to the
+ * {@link ng.$exceptionHandler $exceptionHandler} service.
+ * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
+ * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
+ *
+ *
+ * @param {(string|function())=} exp An angular expression to be executed.
+ *
+ * - `string`: execute using the rules as defined in {@link guide/expression expression}.
+ * - `function(scope)`: execute the function with current `scope` parameter.
+ *
+ * @returns {*} The result of evaluating the expression.
+ */
+ $apply: function(expr) {
+ try {
+ beginPhase('$apply');
+ return this.$eval(expr);
+ } catch (e) {
+ $exceptionHandler(e);
+ } finally {
+ clearPhase();
+ try {
+ $rootScope.$digest();
+ } catch (e) {
+ $exceptionHandler(e);
+ throw e;
+ }
+ }
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$on
+ * @kind function
+ *
+ * @description
+ * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
+ * discussion of event life cycle.
+ *
+ * The event listener function format is: `function(event, args...)`. The `event` object
+ * passed into the listener has the following attributes:
+ *
+ * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
+ * `$broadcast`-ed.
+ * - `currentScope` - `{Scope}`: the current scope which is handling the event.
+ * - `name` - `{string}`: name of the event.
+ * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
+ * further event propagation (available only for events that were `$emit`-ed).
+ * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
+ * to true.
+ * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
+ *
+ * @param {string} name Event name to listen on.
+ * @param {function(event, ...args)} listener Function to call when the event is emitted.
+ * @returns {function()} Returns a deregistration function for this listener.
+ */
+ $on: function(name, listener) {
+ var namedListeners = this.$$listeners[name];
+ if (!namedListeners) {
+ this.$$listeners[name] = namedListeners = [];
+ }
+ namedListeners.push(listener);
+
+ var current = this;
+ do {
+ if (!current.$$listenerCount[name]) {
+ current.$$listenerCount[name] = 0;
+ }
+ current.$$listenerCount[name]++;
+ } while ((current = current.$parent));
+
+ var self = this;
+ return function() {
+ namedListeners[indexOf(namedListeners, listener)] = null;
+ decrementListenerCount(self, 1, name);
+ };
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$emit
+ * @kind function
+ *
+ * @description
+ * Dispatches an event `name` upwards through the scope hierarchy notifying the
+ * registered {@link ng.$rootScope.Scope#$on} listeners.
+ *
+ * The event life cycle starts at the scope on which `$emit` was called. All
+ * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
+ * notified. Afterwards, the event traverses upwards toward the root scope and calls all
+ * registered listeners along the way. The event will stop propagating if one of the listeners
+ * cancels it.
+ *
+ * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
+ * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
+ *
+ * @param {string} name Event name to emit.
+ * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
+ * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
+ */
+ $emit: function(name, args) {
+ var empty = [],
+ namedListeners,
+ scope = this,
+ stopPropagation = false,
+ event = {
+ name: name,
+ targetScope: scope,
+ stopPropagation: function() {stopPropagation = true;},
+ preventDefault: function() {
+ event.defaultPrevented = true;
+ },
+ defaultPrevented: false
+ },
+ listenerArgs = concat([event], arguments, 1),
+ i, length;
+
+ do {
+ namedListeners = scope.$$listeners[name] || empty;
+ event.currentScope = scope;
+ for (i=0, length=namedListeners.length; i= 8 ) {
+ normalizedVal = urlResolve(uri).href;
+ if (normalizedVal !== '' && !normalizedVal.match(regex)) {
+ return 'unsafe:'+normalizedVal;
+ }
+ }
+ return uri;
+ };
+ };
+}
+
+var $sceMinErr = minErr('$sce');
+
+var SCE_CONTEXTS = {
+ HTML: 'html',
+ CSS: 'css',
+ URL: 'url',
+ // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
+ // url. (e.g. ng-include, script src, templateUrl)
+ RESOURCE_URL: 'resourceUrl',
+ JS: 'js'
+};
+
+// Helper functions follow.
+
+// Copied from:
+// http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962
+// Prereq: s is a string.
+function escapeForRegexp(s) {
+ return s.replace(/([-()\[\]{}+?*.$\^|,:# -1) {
+ throw $sceMinErr('iwcard',
+ 'Illegal sequence *** in string matcher. String: {0}', matcher);
+ }
+ matcher = escapeForRegexp(matcher).
+ replace('\\*\\*', '.*').
+ replace('\\*', '[^:/.?&;]*');
+ return new RegExp('^' + matcher + '$');
+ } else if (isRegExp(matcher)) {
+ // The only other type of matcher allowed is a Regexp.
+ // Match entire URL / disallow partial matches.
+ // Flags are reset (i.e. no global, ignoreCase or multiline)
+ return new RegExp('^' + matcher.source + '$');
+ } else {
+ throw $sceMinErr('imatcher',
+ 'Matchers may only be "self", string patterns or RegExp objects');
+ }
+}
+
+
+function adjustMatchers(matchers) {
+ var adjustedMatchers = [];
+ if (isDefined(matchers)) {
+ forEach(matchers, function(matcher) {
+ adjustedMatchers.push(adjustMatcher(matcher));
+ });
+ }
+ return adjustedMatchers;
+}
+
+
+/**
+ * @ngdoc service
+ * @name $sceDelegate
+ * @kind function
+ *
+ * @description
+ *
+ * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
+ * Contextual Escaping (SCE)} services to AngularJS.
+ *
+ * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
+ * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
+ * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
+ * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
+ * work because `$sce` delegates to `$sceDelegate` for these operations.
+ *
+ * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
+ *
+ * The default instance of `$sceDelegate` should work out of the box with little pain. While you
+ * can override it completely to change the behavior of `$sce`, the common case would
+ * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
+ * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
+ * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
+ * $sceDelegateProvider.resourceUrlWhitelist} and {@link
+ * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
+ */
+
+/**
+ * @ngdoc provider
+ * @name $sceDelegateProvider
+ * @description
+ *
+ * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
+ * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
+ * that the URLs used for sourcing Angular templates are safe. Refer {@link
+ * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
+ * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
+ *
+ * For the general details about this service in Angular, read the main page for {@link ng.$sce
+ * Strict Contextual Escaping (SCE)}.
+ *
+ * **Example**: Consider the following case.
+ *
+ * - your app is hosted at url `http://myapp.example.com/`
+ * - but some of your templates are hosted on other domains you control such as
+ * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
+ * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
+ *
+ * Here is what a secure configuration for this scenario might look like:
+ *
+ *
+ * angular.module('myApp', []).config(function($sceDelegateProvider) {
+ * $sceDelegateProvider.resourceUrlWhitelist([
+ * // Allow same origin resource loads.
+ * 'self',
+ * // Allow loading from our assets domain. Notice the difference between * and **.
+ * 'http://srv*.assets.example.com/**']);
+ *
+ * // The blacklist overrides the whitelist so the open redirect here is blocked.
+ * $sceDelegateProvider.resourceUrlBlacklist([
+ * 'http://myapp.example.com/clickThru**']);
+ * });
+ *
+ */
+
+function $SceDelegateProvider() {
+ this.SCE_CONTEXTS = SCE_CONTEXTS;
+
+ // Resource URLs can also be trusted by policy.
+ var resourceUrlWhitelist = ['self'],
+ resourceUrlBlacklist = [];
+
+ /**
+ * @ngdoc method
+ * @name $sceDelegateProvider#resourceUrlWhitelist
+ * @kind function
+ *
+ * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
+ * provided. This must be an array or null. A snapshot of this array is used so further
+ * changes to the array are ignored.
+ *
+ * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
+ * allowed in this array.
+ *
+ * Note: **an empty whitelist array will block all URLs**!
+ *
+ * @return {Array} the currently set whitelist array.
+ *
+ * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
+ * same origin resource requests.
+ *
+ * @description
+ * Sets/Gets the whitelist of trusted resource URLs.
+ */
+ this.resourceUrlWhitelist = function (value) {
+ if (arguments.length) {
+ resourceUrlWhitelist = adjustMatchers(value);
+ }
+ return resourceUrlWhitelist;
+ };
+
+ /**
+ * @ngdoc method
+ * @name $sceDelegateProvider#resourceUrlBlacklist
+ * @kind function
+ *
+ * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
+ * provided. This must be an array or null. A snapshot of this array is used so further
+ * changes to the array are ignored.
+ *
+ * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
+ * allowed in this array.
+ *
+ * The typical usage for the blacklist is to **block
+ * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
+ * these would otherwise be trusted but actually return content from the redirected domain.
+ *
+ * Finally, **the blacklist overrides the whitelist** and has the final say.
+ *
+ * @return {Array} the currently set blacklist array.
+ *
+ * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
+ * is no blacklist.)
+ *
+ * @description
+ * Sets/Gets the blacklist of trusted resource URLs.
+ */
+
+ this.resourceUrlBlacklist = function (value) {
+ if (arguments.length) {
+ resourceUrlBlacklist = adjustMatchers(value);
+ }
+ return resourceUrlBlacklist;
+ };
+
+ this.$get = ['$injector', function($injector) {
+
+ var htmlSanitizer = function htmlSanitizer(html) {
+ throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
+ };
+
+ if ($injector.has('$sanitize')) {
+ htmlSanitizer = $injector.get('$sanitize');
+ }
+
+
+ function matchUrl(matcher, parsedUrl) {
+ if (matcher === 'self') {
+ return urlIsSameOrigin(parsedUrl);
+ } else {
+ // definitely a regex. See adjustMatchers()
+ return !!matcher.exec(parsedUrl.href);
+ }
+ }
+
+ function isResourceUrlAllowedByPolicy(url) {
+ var parsedUrl = urlResolve(url.toString());
+ var i, n, allowed = false;
+ // Ensure that at least one item from the whitelist allows this url.
+ for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
+ if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
+ allowed = true;
+ break;
+ }
+ }
+ if (allowed) {
+ // Ensure that no item from the blacklist blocked this url.
+ for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
+ if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
+ allowed = false;
+ break;
+ }
+ }
+ }
+ return allowed;
+ }
+
+ function generateHolderType(Base) {
+ var holderType = function TrustedValueHolderType(trustedValue) {
+ this.$$unwrapTrustedValue = function() {
+ return trustedValue;
+ };
+ };
+ if (Base) {
+ holderType.prototype = new Base();
+ }
+ holderType.prototype.valueOf = function sceValueOf() {
+ return this.$$unwrapTrustedValue();
+ };
+ holderType.prototype.toString = function sceToString() {
+ return this.$$unwrapTrustedValue().toString();
+ };
+ return holderType;
+ }
+
+ var trustedValueHolderBase = generateHolderType(),
+ byType = {};
+
+ byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
+ byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
+ byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
+ byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
+ byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
+
+ /**
+ * @ngdoc method
+ * @name $sceDelegate#trustAs
+ *
+ * @description
+ * Returns an object that is trusted by angular for use in specified strict
+ * contextual escaping contexts (such as ng-bind-html, ng-include, any src
+ * attribute interpolation, any dom event binding attribute interpolation
+ * such as for onclick, etc.) that uses the provided value.
+ * See {@link ng.$sce $sce} for enabling strict contextual escaping.
+ *
+ * @param {string} type The kind of context in which this value is safe for use. e.g. url,
+ * resourceUrl, html, js and css.
+ * @param {*} value The value that that should be considered trusted/safe.
+ * @returns {*} A value that can be used to stand in for the provided `value` in places
+ * where Angular expects a $sce.trustAs() return value.
+ */
+ function trustAs(type, trustedValue) {
+ var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
+ if (!Constructor) {
+ throw $sceMinErr('icontext',
+ 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
+ type, trustedValue);
+ }
+ if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
+ return trustedValue;
+ }
+ // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
+ // mutable objects, we ensure here that the value passed in is actually a string.
+ if (typeof trustedValue !== 'string') {
+ throw $sceMinErr('itype',
+ 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
+ type);
+ }
+ return new Constructor(trustedValue);
+ }
+
+ /**
+ * @ngdoc method
+ * @name $sceDelegate#valueOf
+ *
+ * @description
+ * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
+ * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
+ * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
+ *
+ * If the passed parameter is not a value that had been returned by {@link
+ * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
+ *
+ * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
+ * call or anything else.
+ * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
+ * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
+ * `value` unchanged.
+ */
+ function valueOf(maybeTrusted) {
+ if (maybeTrusted instanceof trustedValueHolderBase) {
+ return maybeTrusted.$$unwrapTrustedValue();
+ } else {
+ return maybeTrusted;
+ }
+ }
+
+ /**
+ * @ngdoc method
+ * @name $sceDelegate#getTrusted
+ *
+ * @description
+ * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
+ * returns the originally supplied value if the queried context type is a supertype of the
+ * created type. If this condition isn't satisfied, throws an exception.
+ *
+ * @param {string} type The kind of context in which this value is to be used.
+ * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
+ * `$sceDelegate.trustAs`} call.
+ * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
+ * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
+ */
+ function getTrusted(type, maybeTrusted) {
+ if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
+ return maybeTrusted;
+ }
+ var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
+ if (constructor && maybeTrusted instanceof constructor) {
+ return maybeTrusted.$$unwrapTrustedValue();
+ }
+ // If we get here, then we may only take one of two actions.
+ // 1. sanitize the value for the requested type, or
+ // 2. throw an exception.
+ if (type === SCE_CONTEXTS.RESOURCE_URL) {
+ if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
+ return maybeTrusted;
+ } else {
+ throw $sceMinErr('insecurl',
+ 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
+ maybeTrusted.toString());
+ }
+ } else if (type === SCE_CONTEXTS.HTML) {
+ return htmlSanitizer(maybeTrusted);
+ }
+ throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
+ }
+
+ return { trustAs: trustAs,
+ getTrusted: getTrusted,
+ valueOf: valueOf };
+ }];
+}
+
+
+/**
+ * @ngdoc provider
+ * @name $sceProvider
+ * @description
+ *
+ * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
+ * - enable/disable Strict Contextual Escaping (SCE) in a module
+ * - override the default implementation with a custom delegate
+ *
+ * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
+ */
+
+/* jshint maxlen: false*/
+
+/**
+ * @ngdoc service
+ * @name $sce
+ * @kind function
+ *
+ * @description
+ *
+ * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
+ *
+ * # Strict Contextual Escaping
+ *
+ * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
+ * contexts to result in a value that is marked as safe to use for that context. One example of
+ * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
+ * to these contexts as privileged or SCE contexts.
+ *
+ * As of version 1.2, Angular ships with SCE enabled by default.
+ *
+ * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows
+ * one to execute arbitrary javascript by the use of the expression() syntax. Refer
+ * to learn more about them.
+ * You can ensure your document is in standards mode and not quirks mode by adding ``
+ * to the top of your HTML document.
+ *
+ * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
+ * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
+ *
+ * Here's an example of a binding in a privileged context:
+ *
+ *
+ *
+ *
+ *
+ *
+ * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
+ * disabled, this application allows the user to render arbitrary HTML into the DIV.
+ * In a more realistic example, one may be rendering user comments, blog articles, etc. via
+ * bindings. (HTML is just one example of a context where rendering user controlled input creates
+ * security vulnerabilities.)
+ *
+ * For the case of HTML, you might use a library, either on the client side, or on the server side,
+ * to sanitize unsafe HTML before binding to the value and rendering it in the document.
+ *
+ * How would you ensure that every place that used these types of bindings was bound to a value that
+ * was sanitized by your library (or returned as safe for rendering by your server?) How can you
+ * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
+ * properties/fields and forgot to update the binding to the sanitized value?
+ *
+ * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
+ * determine that something explicitly says it's safe to use a value for binding in that
+ * context. You can then audit your code (a simple grep would do) to ensure that this is only done
+ * for those values that you can easily tell are safe - because they were received from your server,
+ * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
+ * allowing only the files in a specific directory to do this. Ensuring that the internal API
+ * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
+ *
+ * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
+ * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
+ * obtain values that will be accepted by SCE / privileged contexts.
+ *
+ *
+ * ## How does it work?
+ *
+ * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
+ * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
+ * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
+ * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
+ *
+ * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
+ * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
+ * simplified):
+ *
+ *
+ *
+ * ## Impact on loading templates
+ *
+ * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
+ * `templateUrl`'s specified by {@link guide/directive directives}.
+ *
+ * By default, Angular only loads templates from the same domain and protocol as the application
+ * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
+ * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
+ * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
+ * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
+ *
+ * *Please note*:
+ * The browser's
+ * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
+ * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
+ * policy apply in addition to this and may further restrict whether the template is successfully
+ * loaded. This means that without the right CORS policy, loading templates from a different domain
+ * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
+ * browsers.
+ *
+ * ## This feels like too much overhead for the developer?
+ *
+ * It's important to remember that SCE only applies to interpolation expressions.
+ *
+ * If your expressions are constant literals, they're automatically trusted and you don't need to
+ * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
+ * ``) just works.
+ *
+ * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
+ * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
+ *
+ * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
+ * templates in `ng-include` from your application's domain without having to even know about SCE.
+ * It blocks loading templates from other domains or loading templates over http from an https
+ * served document. You can change these by setting your own custom {@link
+ * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
+ * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
+ *
+ * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
+ * application that's secure and can be audited to verify that with much more ease than bolting
+ * security onto an application later.
+ *
+ *
+ * ## What trusted context types are supported?
+ *
+ * | Context | Notes |
+ * |---------------------|----------------|
+ * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
+ * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
+ * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (` Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
+ * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
+ *
+ * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist}
+ *
+ * Each element in these arrays must be one of the following:
+ *
+ * - **'self'**
+ * - The special **string**, `'self'`, can be used to match against all URLs of the **same
+ * domain** as the application document using the **same protocol**.
+ * - **String** (except the special value `'self'`)
+ * - The string is matched against the full *normalized / absolute URL* of the resource
+ * being tested (substring matches are not good enough.)
+ * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
+ * match themselves.
+ * - `*`: matches zero or more occurrences of any character other than one of the following 6
+ * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
+ * in a whitelist.
+ * - `**`: matches zero or more occurrences of *any* character. As such, it's not
+ * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
+ * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
+ * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
+ * http://foo.example.com/templates/**).
+ * - **RegExp** (*see caveat below*)
+ * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
+ * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
+ * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
+ * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
+ * small number of cases. A `.` character in the regex used when matching the scheme or a
+ * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
+ * is highly recommended to use the string patterns and only fall back to regular expressions
+ * if they as a last resort.
+ * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
+ * matched against the **entire** *normalized / absolute URL* of the resource being tested
+ * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
+ * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
+ * - If you are generating your JavaScript from some other templating engine (not
+ * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
+ * remember to escape your regular expression (and be aware that you might need more than
+ * one level of escaping depending on your templating engine and the way you interpolated
+ * the value.) Do make use of your platform's escaping mechanism as it might be good
+ * enough before coding your own. e.g. Ruby has
+ * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
+ * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
+ * Javascript lacks a similar built in function for escaping. Take a look at Google
+ * Closure library's [goog.string.regExpEscape(s)](
+ * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
+ *
+ * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
+ *
+ * ## Show me an example using SCE.
+ *
+ * @example
+
+
+
+
+ User comments
+ By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
+ $sanitize is available. If $sanitize isn't available, this results in an error instead of an
+ exploit.
+
+
+ {{userComment.name}}:
+
+
+
+
+
+
+
+
+ var mySceApp = angular.module('mySceApp', ['ngSanitize']);
+
+ mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
+ var self = this;
+ $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
+ self.userComments = userComments;
+ });
+ self.explicitlyTrustedHtml = $sce.trustAsHtml(
+ 'Hover over this text.');
+ });
+
+
+
+[
+ { "name": "Alice",
+ "htmlComment":
+ "Is anyone reading this?"
+ },
+ { "name": "Bob",
+ "htmlComment": "Yes! Am I the only other one?"
+ }
+]
+
+
+
+ describe('SCE doc demo', function() {
+ it('should sanitize untrusted values', function() {
+ expect(element(by.css('.htmlComment')).getInnerHtml())
+ .toBe('Is anyone reading this?');
+ });
+
+ it('should NOT sanitize explicitly trusted values', function() {
+ expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
+ 'Hover over this text.');
+ });
+ });
+
+
+ *
+ *
+ *
+ * ## Can I disable SCE completely?
+ *
+ * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
+ * for little coding overhead. It will be much harder to take an SCE disabled application and
+ * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
+ * for cases where you have a lot of existing code that was written before SCE was introduced and
+ * you're migrating them a module at a time.
+ *
+ * That said, here's how you can completely disable SCE:
+ *
+ *
+ * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
+ * // Completely disable SCE. For demonstration purposes only!
+ * // Do not use in new projects.
+ * $sceProvider.enabled(false);
+ * });
+ *
+ *
+ */
+/* jshint maxlen: 100 */
+
+function $SceProvider() {
+ var enabled = true;
+
+ /**
+ * @ngdoc method
+ * @name $sceProvider#enabled
+ * @kind function
+ *
+ * @param {boolean=} value If provided, then enables/disables SCE.
+ * @return {boolean} true if SCE is enabled, false otherwise.
+ *
+ * @description
+ * Enables/disables SCE and returns the current value.
+ */
+ this.enabled = function (value) {
+ if (arguments.length) {
+ enabled = !!value;
+ }
+ return enabled;
+ };
+
+
+ /* Design notes on the default implementation for SCE.
+ *
+ * The API contract for the SCE delegate
+ * -------------------------------------
+ * The SCE delegate object must provide the following 3 methods:
+ *
+ * - trustAs(contextEnum, value)
+ * This method is used to tell the SCE service that the provided value is OK to use in the
+ * contexts specified by contextEnum. It must return an object that will be accepted by
+ * getTrusted() for a compatible contextEnum and return this value.
+ *
+ * - valueOf(value)
+ * For values that were not produced by trustAs(), return them as is. For values that were
+ * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
+ * trustAs is wrapping the given values into some type, this operation unwraps it when given
+ * such a value.
+ *
+ * - getTrusted(contextEnum, value)
+ * This function should return the a value that is safe to use in the context specified by
+ * contextEnum or throw and exception otherwise.
+ *
+ * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
+ * opaque or wrapped in some holder object. That happens to be an implementation detail. For
+ * instance, an implementation could maintain a registry of all trusted objects by context. In
+ * such a case, trustAs() would return the same object that was passed in. getTrusted() would
+ * return the same object passed in if it was found in the registry under a compatible context or
+ * throw an exception otherwise. An implementation might only wrap values some of the time based
+ * on some criteria. getTrusted() might return a value and not throw an exception for special
+ * constants or objects even if not wrapped. All such implementations fulfill this contract.
+ *
+ *
+ * A note on the inheritance model for SCE contexts
+ * ------------------------------------------------
+ * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
+ * is purely an implementation details.
+ *
+ * The contract is simply this:
+ *
+ * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
+ * will also succeed.
+ *
+ * Inheritance happens to capture this in a natural way. In some future, we
+ * may not use inheritance anymore. That is OK because no code outside of
+ * sce.js and sceSpecs.js would need to be aware of this detail.
+ */
+
+ this.$get = ['$parse', '$sniffer', '$sceDelegate', function(
+ $parse, $sniffer, $sceDelegate) {
+ // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows
+ // the "expression(javascript expression)" syntax which is insecure.
+ if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) {
+ throw $sceMinErr('iequirks',
+ 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' +
+ 'mode. You can fix this by adding the text to the top of your HTML ' +
+ 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
+ }
+
+ var sce = shallowCopy(SCE_CONTEXTS);
+
+ /**
+ * @ngdoc method
+ * @name $sce#isEnabled
+ * @kind function
+ *
+ * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
+ * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
+ *
+ * @description
+ * Returns a boolean indicating if SCE is enabled.
+ */
+ sce.isEnabled = function () {
+ return enabled;
+ };
+ sce.trustAs = $sceDelegate.trustAs;
+ sce.getTrusted = $sceDelegate.getTrusted;
+ sce.valueOf = $sceDelegate.valueOf;
+
+ if (!enabled) {
+ sce.trustAs = sce.getTrusted = function(type, value) { return value; };
+ sce.valueOf = identity;
+ }
+
+ /**
+ * @ngdoc method
+ * @name $sce#parseAs
+ *
+ * @description
+ * Converts Angular {@link guide/expression expression} into a function. This is like {@link
+ * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
+ * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
+ * *result*)}
+ *
+ * @param {string} type The kind of SCE context in which this result will be used.
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ */
+ sce.parseAs = function sceParseAs(type, expr) {
+ var parsed = $parse(expr);
+ if (parsed.literal && parsed.constant) {
+ return parsed;
+ } else {
+ return function sceParseAsTrusted(self, locals) {
+ return sce.getTrusted(type, parsed(self, locals));
+ };
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name $sce#trustAs
+ *
+ * @description
+ * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
+ * returns an object that is trusted by angular for use in specified strict contextual
+ * escaping contexts (such as ng-bind-html, ng-include, any src attribute
+ * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
+ * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
+ * escaping.
+ *
+ * @param {string} type The kind of context in which this value is safe for use. e.g. url,
+ * resource_url, html, js and css.
+ * @param {*} value The value that that should be considered trusted/safe.
+ * @returns {*} A value that can be used to stand in for the provided `value` in places
+ * where Angular expects a $sce.trustAs() return value.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#trustAsHtml
+ *
+ * @description
+ * Shorthand method. `$sce.trustAsHtml(value)` →
+ * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
+ *
+ * @param {*} value The value to trustAs.
+ * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
+ * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
+ * only accept expressions that are either literal constants or are the
+ * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#trustAsUrl
+ *
+ * @description
+ * Shorthand method. `$sce.trustAsUrl(value)` →
+ * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
+ *
+ * @param {*} value The value to trustAs.
+ * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
+ * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
+ * only accept expressions that are either literal constants or are the
+ * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#trustAsResourceUrl
+ *
+ * @description
+ * Shorthand method. `$sce.trustAsResourceUrl(value)` →
+ * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
+ *
+ * @param {*} value The value to trustAs.
+ * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
+ * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
+ * only accept expressions that are either literal constants or are the return
+ * value of {@link ng.$sce#trustAs $sce.trustAs}.)
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#trustAsJs
+ *
+ * @description
+ * Shorthand method. `$sce.trustAsJs(value)` →
+ * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
+ *
+ * @param {*} value The value to trustAs.
+ * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
+ * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
+ * only accept expressions that are either literal constants or are the
+ * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#getTrusted
+ *
+ * @description
+ * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
+ * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
+ * originally supplied value if the queried context type is a supertype of the created type.
+ * If this condition isn't satisfied, throws an exception.
+ *
+ * @param {string} type The kind of context in which this value is to be used.
+ * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
+ * call.
+ * @returns {*} The value the was originally provided to
+ * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
+ * Otherwise, throws an exception.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#getTrustedHtml
+ *
+ * @description
+ * Shorthand method. `$sce.getTrustedHtml(value)` →
+ * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
+ *
+ * @param {*} value The value to pass to `$sce.getTrusted`.
+ * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#getTrustedCss
+ *
+ * @description
+ * Shorthand method. `$sce.getTrustedCss(value)` →
+ * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
+ *
+ * @param {*} value The value to pass to `$sce.getTrusted`.
+ * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#getTrustedUrl
+ *
+ * @description
+ * Shorthand method. `$sce.getTrustedUrl(value)` →
+ * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
+ *
+ * @param {*} value The value to pass to `$sce.getTrusted`.
+ * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#getTrustedResourceUrl
+ *
+ * @description
+ * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
+ * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
+ *
+ * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
+ * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#getTrustedJs
+ *
+ * @description
+ * Shorthand method. `$sce.getTrustedJs(value)` →
+ * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
+ *
+ * @param {*} value The value to pass to `$sce.getTrusted`.
+ * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#parseAsHtml
+ *
+ * @description
+ * Shorthand method. `$sce.parseAsHtml(expression string)` →
+ * {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`}
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#parseAsCss
+ *
+ * @description
+ * Shorthand method. `$sce.parseAsCss(value)` →
+ * {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`}
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#parseAsUrl
+ *
+ * @description
+ * Shorthand method. `$sce.parseAsUrl(value)` →
+ * {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`}
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#parseAsResourceUrl
+ *
+ * @description
+ * Shorthand method. `$sce.parseAsResourceUrl(value)` →
+ * {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`}
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#parseAsJs
+ *
+ * @description
+ * Shorthand method. `$sce.parseAsJs(value)` →
+ * {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`}
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ */
+
+ // Shorthand delegations.
+ var parse = sce.parseAs,
+ getTrusted = sce.getTrusted,
+ trustAs = sce.trustAs;
+
+ forEach(SCE_CONTEXTS, function (enumValue, name) {
+ var lName = lowercase(name);
+ sce[camelCase("parse_as_" + lName)] = function (expr) {
+ return parse(enumValue, expr);
+ };
+ sce[camelCase("get_trusted_" + lName)] = function (value) {
+ return getTrusted(enumValue, value);
+ };
+ sce[camelCase("trust_as_" + lName)] = function (value) {
+ return trustAs(enumValue, value);
+ };
+ });
+
+ return sce;
+ }];
+}
+
+/**
+ * !!! This is an undocumented "private" service !!!
+ *
+ * @name $sniffer
+ * @requires $window
+ * @requires $document
+ *
+ * @property {boolean} history Does the browser support html5 history api ?
+ * @property {boolean} hashchange Does the browser support hashchange event ?
+ * @property {boolean} transitions Does the browser support CSS transition events ?
+ * @property {boolean} animations Does the browser support CSS animation events ?
+ *
+ * @description
+ * This is very simple implementation of testing browser's features.
+ */
+function $SnifferProvider() {
+ this.$get = ['$window', '$document', function($window, $document) {
+ var eventSupport = {},
+ android =
+ int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
+ boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
+ document = $document[0] || {},
+ documentMode = document.documentMode,
+ vendorPrefix,
+ vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
+ bodyStyle = document.body && document.body.style,
+ transitions = false,
+ animations = false,
+ match;
+
+ if (bodyStyle) {
+ for(var prop in bodyStyle) {
+ if(match = vendorRegex.exec(prop)) {
+ vendorPrefix = match[0];
+ vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
+ break;
+ }
+ }
+
+ if(!vendorPrefix) {
+ vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
+ }
+
+ transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
+ animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
+
+ if (android && (!transitions||!animations)) {
+ transitions = isString(document.body.style.webkitTransition);
+ animations = isString(document.body.style.webkitAnimation);
+ }
+ }
+
+
+ return {
+ // Android has history.pushState, but it does not update location correctly
+ // so let's not use the history API at all.
+ // http://code.google.com/p/android/issues/detail?id=17471
+ // https://github.com/angular/angular.js/issues/904
+
+ // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
+ // so let's not use the history API also
+ // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
+ // jshint -W018
+ history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
+ // jshint +W018
+ hashchange: 'onhashchange' in $window &&
+ // IE8 compatible mode lies
+ (!documentMode || documentMode > 7),
+ hasEvent: function(event) {
+ // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
+ // it. In particular the event is not fired when backspace or delete key are pressed or
+ // when cut operation is performed.
+ if (event == 'input' && msie == 9) return false;
+
+ if (isUndefined(eventSupport[event])) {
+ var divElm = document.createElement('div');
+ eventSupport[event] = 'on' + event in divElm;
+ }
+
+ return eventSupport[event];
+ },
+ csp: csp(),
+ vendorPrefix: vendorPrefix,
+ transitions : transitions,
+ animations : animations,
+ android: android,
+ msie : msie,
+ msieDocumentMode: documentMode
+ };
+ }];
+}
+
+function $TimeoutProvider() {
+ this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
+ function($rootScope, $browser, $q, $exceptionHandler) {
+ var deferreds = {};
+
+
+ /**
+ * @ngdoc service
+ * @name $timeout
+ *
+ * @description
+ * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
+ * block and delegates any exceptions to
+ * {@link ng.$exceptionHandler $exceptionHandler} service.
+ *
+ * The return value of registering a timeout function is a promise, which will be resolved when
+ * the timeout is reached and the timeout function is executed.
+ *
+ * To cancel a timeout request, call `$timeout.cancel(promise)`.
+ *
+ * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
+ * synchronously flush the queue of deferred functions.
+ *
+ * @param {function()} fn A function, whose execution should be delayed.
+ * @param {number=} [delay=0] Delay in milliseconds.
+ * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
+ * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
+ * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
+ * promise will be resolved with is the return value of the `fn` function.
+ *
+ */
+ function timeout(fn, delay, invokeApply) {
+ var deferred = $q.defer(),
+ promise = deferred.promise,
+ skipApply = (isDefined(invokeApply) && !invokeApply),
+ timeoutId;
+
+ timeoutId = $browser.defer(function() {
+ try {
+ deferred.resolve(fn());
+ } catch(e) {
+ deferred.reject(e);
+ $exceptionHandler(e);
+ }
+ finally {
+ delete deferreds[promise.$$timeoutId];
+ }
+
+ if (!skipApply) $rootScope.$apply();
+ }, delay);
+
+ promise.$$timeoutId = timeoutId;
+ deferreds[timeoutId] = deferred;
+
+ return promise;
+ }
+
+
+ /**
+ * @ngdoc method
+ * @name $timeout#cancel
+ *
+ * @description
+ * Cancels a task associated with the `promise`. As a result of this, the promise will be
+ * resolved with a rejection.
+ *
+ * @param {Promise=} promise Promise returned by the `$timeout` function.
+ * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
+ * canceled.
+ */
+ timeout.cancel = function(promise) {
+ if (promise && promise.$$timeoutId in deferreds) {
+ deferreds[promise.$$timeoutId].reject('canceled');
+ delete deferreds[promise.$$timeoutId];
+ return $browser.defer.cancel(promise.$$timeoutId);
+ }
+ return false;
+ };
+
+ return timeout;
+ }];
+}
+
+// NOTE: The usage of window and document instead of $window and $document here is
+// deliberate. This service depends on the specific behavior of anchor nodes created by the
+// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
+// cause us to break tests. In addition, when the browser resolves a URL for XHR, it
+// doesn't know about mocked locations and resolves URLs to the real document - which is
+// exactly the behavior needed here. There is little value is mocking these out for this
+// service.
+var urlParsingNode = document.createElement("a");
+var originUrl = urlResolve(window.location.href, true);
+
+
+/**
+ *
+ * Implementation Notes for non-IE browsers
+ * ----------------------------------------
+ * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
+ * results both in the normalizing and parsing of the URL. Normalizing means that a relative
+ * URL will be resolved into an absolute URL in the context of the application document.
+ * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
+ * properties are all populated to reflect the normalized URL. This approach has wide
+ * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
+ * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
+ *
+ * Implementation Notes for IE
+ * ---------------------------
+ * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
+ * browsers. However, the parsed components will not be set if the URL assigned did not specify
+ * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
+ * work around that by performing the parsing in a 2nd step by taking a previously normalized
+ * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
+ * properties such as protocol, hostname, port, etc.
+ *
+ * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
+ * uses the inner HTML approach to assign the URL as part of an HTML snippet -
+ * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
+ * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
+ * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
+ * method and IE < 8 is unsupported.
+ *
+ * References:
+ * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
+ * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
+ * http://url.spec.whatwg.org/#urlutils
+ * https://github.com/angular/angular.js/pull/2902
+ * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
+ *
+ * @kind function
+ * @param {string} url The URL to be parsed.
+ * @description Normalizes and parses a URL.
+ * @returns {object} Returns the normalized URL as a dictionary.
+ *
+ * | member name | Description |
+ * |---------------|----------------|
+ * | href | A normalized version of the provided URL if it was not an absolute URL |
+ * | protocol | The protocol including the trailing colon |
+ * | host | The host and port (if the port is non-default) of the normalizedUrl |
+ * | search | The search params, minus the question mark |
+ * | hash | The hash string, minus the hash symbol
+ * | hostname | The hostname
+ * | port | The port, without ":"
+ * | pathname | The pathname, beginning with "/"
+ *
+ */
+function urlResolve(url, base) {
+ var href = url;
+
+ if (msie) {
+ // Normalize before parse. Refer Implementation Notes on why this is
+ // done in two steps on IE.
+ urlParsingNode.setAttribute("href", href);
+ href = urlParsingNode.href;
+ }
+
+ urlParsingNode.setAttribute('href', href);
+
+ // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
+ return {
+ href: urlParsingNode.href,
+ protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
+ host: urlParsingNode.host,
+ search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
+ hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
+ hostname: urlParsingNode.hostname,
+ port: urlParsingNode.port,
+ pathname: (urlParsingNode.pathname.charAt(0) === '/')
+ ? urlParsingNode.pathname
+ : '/' + urlParsingNode.pathname
+ };
+}
+
+/**
+ * Parse a request URL and determine whether this is a same-origin request as the application document.
+ *
+ * @param {string|object} requestUrl The url of the request as a string that will be resolved
+ * or a parsed URL object.
+ * @returns {boolean} Whether the request is for the same origin as the application document.
+ */
+function urlIsSameOrigin(requestUrl) {
+ var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
+ return (parsed.protocol === originUrl.protocol &&
+ parsed.host === originUrl.host);
+}
+
+/**
+ * @ngdoc service
+ * @name $window
+ *
+ * @description
+ * A reference to the browser's `window` object. While `window`
+ * is globally available in JavaScript, it causes testability problems, because
+ * it is a global variable. In angular we always refer to it through the
+ * `$window` service, so it may be overridden, removed or mocked for testing.
+ *
+ * Expressions, like the one defined for the `ngClick` directive in the example
+ * below, are evaluated with respect to the current scope. Therefore, there is
+ * no risk of inadvertently coding in a dependency on a global value in such an
+ * expression.
+ *
+ * @example
+
+
+
+
+
+
+
+
+
+ it('should display the greeting in the input box', function() {
+ element(by.model('greeting')).sendKeys('Hello, E2E Tests');
+ // If we click the button it will block the test runner
+ // element(':button').click();
+ });
+
+
+ */
+function $WindowProvider(){
+ this.$get = valueFn(window);
+}
+
+/**
+ * @ngdoc provider
+ * @name $filterProvider
+ * @description
+ *
+ * Filters are just functions which transform input to an output. However filters need to be
+ * Dependency Injected. To achieve this a filter definition consists of a factory function which is
+ * annotated with dependencies and is responsible for creating a filter function.
+ *
+ * ```js
+ * // Filter registration
+ * function MyModule($provide, $filterProvider) {
+ * // create a service to demonstrate injection (not always needed)
+ * $provide.value('greet', function(name){
+ * return 'Hello ' + name + '!';
+ * });
+ *
+ * // register a filter factory which uses the
+ * // greet service to demonstrate DI.
+ * $filterProvider.register('greet', function(greet){
+ * // return the filter function which uses the greet service
+ * // to generate salutation
+ * return function(text) {
+ * // filters need to be forgiving so check input validity
+ * return text && greet(text) || text;
+ * };
+ * });
+ * }
+ * ```
+ *
+ * The filter function is registered with the `$injector` under the filter name suffix with
+ * `Filter`.
+ *
+ * ```js
+ * it('should be the same instance', inject(
+ * function($filterProvider) {
+ * $filterProvider.register('reverse', function(){
+ * return ...;
+ * });
+ * },
+ * function($filter, reverseFilter) {
+ * expect($filter('reverse')).toBe(reverseFilter);
+ * });
+ * ```
+ *
+ *
+ * For more information about how angular filters work, and how to create your own filters, see
+ * {@link guide/filter Filters} in the Angular Developer Guide.
+ */
+/**
+ * @ngdoc method
+ * @name $filterProvider#register
+ * @description
+ * Register filter factory function.
+ *
+ * @param {String} name Name of the filter.
+ * @param {Function} fn The filter factory function which is injectable.
+ */
+
+
+/**
+ * @ngdoc service
+ * @name $filter
+ * @kind function
+ * @description
+ * Filters are used for formatting data displayed to the user.
+ *
+ * The general syntax in templates is as follows:
+ *
+ * {{ expression [| filter_name[:parameter_value] ... ] }}
+ *
+ * @param {String} name Name of the filter function to retrieve
+ * @return {Function} the filter function
+ * @example
+
+
+
+
{{ originalText }}
+
{{ filteredText }}
+
+
+
+
+ angular.module('filterExample', [])
+ .controller('MainCtrl', function($scope, $filter) {
+ $scope.originalText = 'hello';
+ $scope.filteredText = $filter('uppercase')($scope.originalText);
+ });
+
+
+ */
+$FilterProvider.$inject = ['$provide'];
+function $FilterProvider($provide) {
+ var suffix = 'Filter';
+
+ /**
+ * @ngdoc method
+ * @name $controllerProvider#register
+ * @param {string|Object} name Name of the filter function, or an object map of filters where
+ * the keys are the filter names and the values are the filter factories.
+ * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
+ * of the registered filter instances.
+ */
+ function register(name, factory) {
+ if(isObject(name)) {
+ var filters = {};
+ forEach(name, function(filter, key) {
+ filters[key] = register(key, filter);
+ });
+ return filters;
+ } else {
+ return $provide.factory(name + suffix, factory);
+ }
+ }
+ this.register = register;
+
+ this.$get = ['$injector', function($injector) {
+ return function(name) {
+ return $injector.get(name + suffix);
+ };
+ }];
+
+ ////////////////////////////////////////
+
+ /* global
+ currencyFilter: false,
+ dateFilter: false,
+ filterFilter: false,
+ jsonFilter: false,
+ limitToFilter: false,
+ lowercaseFilter: false,
+ numberFilter: false,
+ orderByFilter: false,
+ uppercaseFilter: false,
+ */
+
+ register('currency', currencyFilter);
+ register('date', dateFilter);
+ register('filter', filterFilter);
+ register('json', jsonFilter);
+ register('limitTo', limitToFilter);
+ register('lowercase', lowercaseFilter);
+ register('number', numberFilter);
+ register('orderBy', orderByFilter);
+ register('uppercase', uppercaseFilter);
+}
+
+/**
+ * @ngdoc filter
+ * @name filter
+ * @kind function
+ *
+ * @description
+ * Selects a subset of items from `array` and returns it as a new array.
+ *
+ * @param {Array} array The source array.
+ * @param {string|Object|function()} expression The predicate to be used for selecting items from
+ * `array`.
+ *
+ * Can be one of:
+ *
+ * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against
+ * the contents of the `array`. All strings or objects with string properties in `array` that contain this string
+ * will be returned. The predicate can be negated by prefixing the string with `!`.
+ *
+ * - `Object`: A pattern object can be used to filter specific properties on objects contained
+ * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
+ * which have property `name` containing "M" and property `phone` containing "1". A special
+ * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
+ * property of the object. That's equivalent to the simple substring match with a `string`
+ * as described above.
+ *
+ * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is
+ * called for each element of `array`. The final result is an array of those elements that
+ * the predicate returned true for.
+ *
+ * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
+ * determining if the expected value (from the filter expression) and actual value (from
+ * the object in the array) should be considered a match.
+ *
+ * Can be one of:
+ *
+ * - `function(actual, expected)`:
+ * The function will be given the object value and the predicate value to compare and
+ * should return true if the item should be included in filtered result.
+ *
+ * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`.
+ * this is essentially strict comparison of expected and actual.
+ *
+ * - `false|undefined`: A short hand for a function which will look for a substring match in case
+ * insensitive way.
+ *
+ * @example
+
+
+
+
+ Search:
+
+
Name
Phone
+
+
{{friend.name}}
+
{{friend.phone}}
+
+
+
+ Any:
+ Name only
+ Phone only
+ Equality
+
+
Name
Phone
+
+
{{friendObj.name}}
+
{{friendObj.phone}}
+
+
+
+
+ var expectFriendNames = function(expectedNames, key) {
+ element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
+ arr.forEach(function(wd, i) {
+ expect(wd.getText()).toMatch(expectedNames[i]);
+ });
+ });
+ };
+
+ it('should search across all fields when filtering with a string', function() {
+ var searchText = element(by.model('searchText'));
+ searchText.clear();
+ searchText.sendKeys('m');
+ expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
+
+ searchText.clear();
+ searchText.sendKeys('76');
+ expectFriendNames(['John', 'Julie'], 'friend');
+ });
+
+ it('should search in specific fields when filtering with a predicate object', function() {
+ var searchAny = element(by.model('search.$'));
+ searchAny.clear();
+ searchAny.sendKeys('i');
+ expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
+ });
+ it('should use a equal comparison when comparator is true', function() {
+ var searchName = element(by.model('search.name'));
+ var strict = element(by.model('strict'));
+ searchName.clear();
+ searchName.sendKeys('Julie');
+ strict.click();
+ expectFriendNames(['Julie'], 'friendObj');
+ });
+
+
+ */
+function filterFilter() {
+ return function(array, expression, comparator) {
+ if (!isArray(array)) return array;
+
+ var comparatorType = typeof(comparator),
+ predicates = [];
+
+ predicates.check = function(value) {
+ for (var j = 0; j < predicates.length; j++) {
+ if(!predicates[j](value)) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ if (comparatorType !== 'function') {
+ if (comparatorType === 'boolean' && comparator) {
+ comparator = function(obj, text) {
+ return angular.equals(obj, text);
+ };
+ } else {
+ comparator = function(obj, text) {
+ if (obj && text && typeof obj === 'object' && typeof text === 'object') {
+ for (var objKey in obj) {
+ if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
+ comparator(obj[objKey], text[objKey])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ text = (''+text).toLowerCase();
+ return (''+obj).toLowerCase().indexOf(text) > -1;
+ };
+ }
+ }
+
+ var search = function(obj, text){
+ if (typeof text == 'string' && text.charAt(0) === '!') {
+ return !search(obj, text.substr(1));
+ }
+ switch (typeof obj) {
+ case "boolean":
+ case "number":
+ case "string":
+ return comparator(obj, text);
+ case "object":
+ switch (typeof text) {
+ case "object":
+ return comparator(obj, text);
+ default:
+ for ( var objKey in obj) {
+ if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
+ return true;
+ }
+ }
+ break;
+ }
+ return false;
+ case "array":
+ for ( var i = 0; i < obj.length; i++) {
+ if (search(obj[i], text)) {
+ return true;
+ }
+ }
+ return false;
+ default:
+ return false;
+ }
+ };
+ switch (typeof expression) {
+ case "boolean":
+ case "number":
+ case "string":
+ // Set up expression object and fall through
+ expression = {$:expression};
+ // jshint -W086
+ case "object":
+ // jshint +W086
+ for (var key in expression) {
+ (function(path) {
+ if (typeof expression[path] === 'undefined') return;
+ predicates.push(function(value) {
+ return search(path == '$' ? value : (value && value[path]), expression[path]);
+ });
+ })(key);
+ }
+ break;
+ case 'function':
+ predicates.push(expression);
+ break;
+ default:
+ return array;
+ }
+ var filtered = [];
+ for ( var j = 0; j < array.length; j++) {
+ var value = array[j];
+ if (predicates.check(value)) {
+ filtered.push(value);
+ }
+ }
+ return filtered;
+ };
+}
+
+/**
+ * @ngdoc filter
+ * @name currency
+ * @kind function
+ *
+ * @description
+ * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
+ * symbol for current locale is used.
+ *
+ * @param {number} amount Input to filter.
+ * @param {string=} symbol Currency symbol or identifier to be displayed.
+ * @returns {string} Formatted number.
+ *
+ *
+ * @example
+
+
+
+
+
+
+ it('should init with 1234.56', function() {
+ expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
+ expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56');
+ });
+ it('should update', function() {
+ if (browser.params.browser == 'safari') {
+ // Safari does not understand the minus key. See
+ // https://github.com/angular/protractor/issues/481
+ return;
+ }
+ element(by.model('amount')).clear();
+ element(by.model('amount')).sendKeys('-1234');
+ expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
+ expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)');
+ });
+
+
+ */
+currencyFilter.$inject = ['$locale'];
+function currencyFilter($locale) {
+ var formats = $locale.NUMBER_FORMATS;
+ return function(amount, currencySymbol){
+ if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
+ return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
+ replace(/\u00A4/g, currencySymbol);
+ };
+}
+
+/**
+ * @ngdoc filter
+ * @name number
+ * @kind function
+ *
+ * @description
+ * Formats a number as text.
+ *
+ * If the input is not a number an empty string is returned.
+ *
+ * @param {number|string} number Number to format.
+ * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
+ * If this is not provided then the fraction size is computed from the current locale's number
+ * formatting pattern. In the case of the default locale, it will be 3.
+ * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
+ *
+ * @example
+
+
+
+
+
+
+ it('should format numbers', function() {
+ expect(element(by.id('number-default')).getText()).toBe('1,234.568');
+ expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
+ expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
+ });
+
+ it('should update', function() {
+ element(by.model('val')).clear();
+ element(by.model('val')).sendKeys('3374.333');
+ expect(element(by.id('number-default')).getText()).toBe('3,374.333');
+ expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
+ expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
+ });
+
+
+ */
+
+
+numberFilter.$inject = ['$locale'];
+function numberFilter($locale) {
+ var formats = $locale.NUMBER_FORMATS;
+ return function(number, fractionSize) {
+ return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
+ fractionSize);
+ };
+}
+
+var DECIMAL_SEP = '.';
+function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
+ if (number == null || !isFinite(number) || isObject(number)) return '';
+
+ var isNegative = number < 0;
+ number = Math.abs(number);
+ var numStr = number + '',
+ formatedText = '',
+ parts = [];
+
+ var hasExponent = false;
+ if (numStr.indexOf('e') !== -1) {
+ var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
+ if (match && match[2] == '-' && match[3] > fractionSize + 1) {
+ numStr = '0';
+ number = 0;
+ } else {
+ formatedText = numStr;
+ hasExponent = true;
+ }
+ }
+
+ if (!hasExponent) {
+ var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
+
+ // determine fractionSize if it is not specified
+ if (isUndefined(fractionSize)) {
+ fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
+ }
+
+ // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
+ // inspired by:
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
+ number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
+
+ var fraction = ('' + number).split(DECIMAL_SEP);
+ var whole = fraction[0];
+ fraction = fraction[1] || '';
+
+ var i, pos = 0,
+ lgroup = pattern.lgSize,
+ group = pattern.gSize;
+
+ if (whole.length >= (lgroup + group)) {
+ pos = whole.length - lgroup;
+ for (i = 0; i < pos; i++) {
+ if ((pos - i)%group === 0 && i !== 0) {
+ formatedText += groupSep;
+ }
+ formatedText += whole.charAt(i);
+ }
+ }
+
+ for (i = pos; i < whole.length; i++) {
+ if ((whole.length - i)%lgroup === 0 && i !== 0) {
+ formatedText += groupSep;
+ }
+ formatedText += whole.charAt(i);
+ }
+
+ // format fraction part.
+ while(fraction.length < fractionSize) {
+ fraction += '0';
+ }
+
+ if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
+ } else {
+
+ if (fractionSize > 0 && number > -1 && number < 1) {
+ formatedText = number.toFixed(fractionSize);
+ }
+ }
+
+ parts.push(isNegative ? pattern.negPre : pattern.posPre);
+ parts.push(formatedText);
+ parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
+ return parts.join('');
+}
+
+function padNumber(num, digits, trim) {
+ var neg = '';
+ if (num < 0) {
+ neg = '-';
+ num = -num;
+ }
+ num = '' + num;
+ while(num.length < digits) num = '0' + num;
+ if (trim)
+ num = num.substr(num.length - digits);
+ return neg + num;
+}
+
+
+function dateGetter(name, size, offset, trim) {
+ offset = offset || 0;
+ return function(date) {
+ var value = date['get' + name]();
+ if (offset > 0 || value > -offset)
+ value += offset;
+ if (value === 0 && offset == -12 ) value = 12;
+ return padNumber(value, size, trim);
+ };
+}
+
+function dateStrGetter(name, shortForm) {
+ return function(date, formats) {
+ var value = date['get' + name]();
+ var get = uppercase(shortForm ? ('SHORT' + name) : name);
+
+ return formats[get][value];
+ };
+}
+
+function timeZoneGetter(date) {
+ var zone = -1 * date.getTimezoneOffset();
+ var paddedZone = (zone >= 0) ? "+" : "";
+
+ paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
+ padNumber(Math.abs(zone % 60), 2);
+
+ return paddedZone;
+}
+
+function ampmGetter(date, formats) {
+ return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
+}
+
+var DATE_FORMATS = {
+ yyyy: dateGetter('FullYear', 4),
+ yy: dateGetter('FullYear', 2, 0, true),
+ y: dateGetter('FullYear', 1),
+ MMMM: dateStrGetter('Month'),
+ MMM: dateStrGetter('Month', true),
+ MM: dateGetter('Month', 2, 1),
+ M: dateGetter('Month', 1, 1),
+ dd: dateGetter('Date', 2),
+ d: dateGetter('Date', 1),
+ HH: dateGetter('Hours', 2),
+ H: dateGetter('Hours', 1),
+ hh: dateGetter('Hours', 2, -12),
+ h: dateGetter('Hours', 1, -12),
+ mm: dateGetter('Minutes', 2),
+ m: dateGetter('Minutes', 1),
+ ss: dateGetter('Seconds', 2),
+ s: dateGetter('Seconds', 1),
+ // while ISO 8601 requires fractions to be prefixed with `.` or `,`
+ // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
+ sss: dateGetter('Milliseconds', 3),
+ EEEE: dateStrGetter('Day'),
+ EEE: dateStrGetter('Day', true),
+ a: ampmGetter,
+ Z: timeZoneGetter
+};
+
+var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
+ NUMBER_STRING = /^\-?\d+$/;
+
+/**
+ * @ngdoc filter
+ * @name date
+ * @kind function
+ *
+ * @description
+ * Formats `date` to a string based on the requested `format`.
+ *
+ * `format` string can be composed of the following elements:
+ *
+ * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
+ * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
+ * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
+ * * `'MMMM'`: Month in year (January-December)
+ * * `'MMM'`: Month in year (Jan-Dec)
+ * * `'MM'`: Month in year, padded (01-12)
+ * * `'M'`: Month in year (1-12)
+ * * `'dd'`: Day in month, padded (01-31)
+ * * `'d'`: Day in month (1-31)
+ * * `'EEEE'`: Day in Week,(Sunday-Saturday)
+ * * `'EEE'`: Day in Week, (Sun-Sat)
+ * * `'HH'`: Hour in day, padded (00-23)
+ * * `'H'`: Hour in day (0-23)
+ * * `'hh'`: Hour in am/pm, padded (01-12)
+ * * `'h'`: Hour in am/pm, (1-12)
+ * * `'mm'`: Minute in hour, padded (00-59)
+ * * `'m'`: Minute in hour (0-59)
+ * * `'ss'`: Second in minute, padded (00-59)
+ * * `'s'`: Second in minute (0-59)
+ * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
+ * * `'a'`: am/pm marker
+ * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
+ *
+ * `format` string can also be one of the following predefined
+ * {@link guide/i18n localizable formats}:
+ *
+ * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
+ * (e.g. Sep 3, 2010 12:05:08 pm)
+ * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
+ * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
+ * (e.g. Friday, September 3, 2010)
+ * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
+ * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
+ * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
+ * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
+ * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
+ *
+ * `format` string can contain literal values. These need to be quoted with single quotes (e.g.
+ * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
+ * (e.g. `"h 'o''clock'"`).
+ *
+ * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
+ * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
+ * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
+ * specified in the string input, the time is considered to be in the local timezone.
+ * @param {string=} format Formatting rules (see Description). If not specified,
+ * `mediumDate` is used.
+ * @returns {string} Formatted string or the input if input is not recognized as date/millis.
+ *
+ * @example
+
+
+ {{1288323623006 | date:'medium'}}:
+ {{1288323623006 | date:'medium'}}
+ {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}:
+ {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
+ {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}:
+ {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
+
+
+ it('should format date', function() {
+ expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
+ toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
+ expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
+ toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
+ expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
+ toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
+ });
+
+
+ */
+dateFilter.$inject = ['$locale'];
+function dateFilter($locale) {
+
+
+ var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
+ // 1 2 3 4 5 6 7 8 9 10 11
+ function jsonStringToDate(string) {
+ var match;
+ if (match = string.match(R_ISO8601_STR)) {
+ var date = new Date(0),
+ tzHour = 0,
+ tzMin = 0,
+ dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
+ timeSetter = match[8] ? date.setUTCHours : date.setHours;
+
+ if (match[9]) {
+ tzHour = int(match[9] + match[10]);
+ tzMin = int(match[9] + match[11]);
+ }
+ dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
+ var h = int(match[4]||0) - tzHour;
+ var m = int(match[5]||0) - tzMin;
+ var s = int(match[6]||0);
+ var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
+ timeSetter.call(date, h, m, s, ms);
+ return date;
+ }
+ return string;
+ }
+
+
+ return function(date, format) {
+ var text = '',
+ parts = [],
+ fn, match;
+
+ format = format || 'mediumDate';
+ format = $locale.DATETIME_FORMATS[format] || format;
+ if (isString(date)) {
+ if (NUMBER_STRING.test(date)) {
+ date = int(date);
+ } else {
+ date = jsonStringToDate(date);
+ }
+ }
+
+ if (isNumber(date)) {
+ date = new Date(date);
+ }
+
+ if (!isDate(date)) {
+ return date;
+ }
+
+ while(format) {
+ match = DATE_FORMATS_SPLIT.exec(format);
+ if (match) {
+ parts = concat(parts, match, 1);
+ format = parts.pop();
+ } else {
+ parts.push(format);
+ format = null;
+ }
+ }
+
+ forEach(parts, function(value){
+ fn = DATE_FORMATS[value];
+ text += fn ? fn(date, $locale.DATETIME_FORMATS)
+ : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
+ });
+
+ return text;
+ };
+}
+
+
+/**
+ * @ngdoc filter
+ * @name json
+ * @kind function
+ *
+ * @description
+ * Allows you to convert a JavaScript object into JSON string.
+ *
+ * This filter is mostly useful for debugging. When using the double curly {{value}} notation
+ * the binding is automatically converted to JSON.
+ *
+ * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
+ * @returns {string} JSON string.
+ *
+ *
+ * @example
+
+
+
{{ {'name':'value'} | json }}
+
+
+ it('should jsonify filtered objects', function() {
+ expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/);
+ });
+
+
+ *
+ */
+function jsonFilter() {
+ return function(object) {
+ return toJson(object, true);
+ };
+}
+
+
+/**
+ * @ngdoc filter
+ * @name lowercase
+ * @kind function
+ * @description
+ * Converts string to lowercase.
+ * @see angular.lowercase
+ */
+var lowercaseFilter = valueFn(lowercase);
+
+
+/**
+ * @ngdoc filter
+ * @name uppercase
+ * @kind function
+ * @description
+ * Converts string to uppercase.
+ * @see angular.uppercase
+ */
+var uppercaseFilter = valueFn(uppercase);
+
+/**
+ * @ngdoc filter
+ * @name limitTo
+ * @kind function
+ *
+ * @description
+ * Creates a new array or string containing only a specified number of elements. The elements
+ * are taken from either the beginning or the end of the source array or string, as specified by
+ * the value and sign (positive or negative) of `limit`.
+ *
+ * @param {Array|string} input Source array or string to be limited.
+ * @param {string|number} limit The length of the returned array or string. If the `limit` number
+ * is positive, `limit` number of items from the beginning of the source array/string are copied.
+ * If the number is negative, `limit` number of items from the end of the source array/string
+ * are copied. The `limit` will be trimmed if it exceeds `array.length`
+ * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
+ * had less than `limit` elements.
+ *
+ * @example
+
+
+
+
+
+
+ var numLimitInput = element(by.model('numLimit'));
+ var letterLimitInput = element(by.model('letterLimit'));
+ var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
+ var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
+
+ it('should limit the number array to first three items', function() {
+ expect(numLimitInput.getAttribute('value')).toBe('3');
+ expect(letterLimitInput.getAttribute('value')).toBe('3');
+ expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
+ expect(limitedLetters.getText()).toEqual('Output letters: abc');
+ });
+
+ it('should update the output when -3 is entered', function() {
+ numLimitInput.clear();
+ numLimitInput.sendKeys('-3');
+ letterLimitInput.clear();
+ letterLimitInput.sendKeys('-3');
+ expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
+ expect(limitedLetters.getText()).toEqual('Output letters: ghi');
+ });
+
+ it('should not exceed the maximum size of input array', function() {
+ numLimitInput.clear();
+ numLimitInput.sendKeys('100');
+ letterLimitInput.clear();
+ letterLimitInput.sendKeys('100');
+ expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
+ expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
+ });
+
+
+ */
+function limitToFilter(){
+ return function(input, limit) {
+ if (!isArray(input) && !isString(input)) return input;
+
+ if (Math.abs(Number(limit)) === Infinity) {
+ limit = Number(limit);
+ } else {
+ limit = int(limit);
+ }
+
+ if (isString(input)) {
+ //NaN check on limit
+ if (limit) {
+ return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
+ } else {
+ return "";
+ }
+ }
+
+ var out = [],
+ i, n;
+
+ // if abs(limit) exceeds maximum length, trim it
+ if (limit > input.length)
+ limit = input.length;
+ else if (limit < -input.length)
+ limit = -input.length;
+
+ if (limit > 0) {
+ i = 0;
+ n = limit;
+ } else {
+ i = input.length + limit;
+ n = input.length;
+ }
+
+ for (; i} expression A predicate to be
+ * used by the comparator to determine the order of elements.
+ *
+ * Can be one of:
+ *
+ * - `function`: Getter function. The result of this function will be sorted using the
+ * `<`, `=`, `>` operator.
+ * - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
+ * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
+ * ascending or descending sort order (for example, +name or -name).
+ * - `Array`: An array of function or string predicates. The first predicate in the array
+ * is used for sorting, but when two items are equivalent, the next predicate is used.
+ *
+ * @param {boolean=} reverse Reverse the order of the array.
+ * @returns {Array} Sorted copy of the source array.
+ *
+ * @example
+
+
+
+
+
+
+ *
+ * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
+ * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
+ * desired parameters.
+ *
+ * Example:
+ *
+ * @example
+
+
+
+
+
+
+ function Ctrl($scope, $filter) {
+ var orderBy = $filter('orderBy');
+ $scope.friends = [
+ { name: 'John', phone: '555-1212', age: 10 },
+ { name: 'Mary', phone: '555-9876', age: 19 },
+ { name: 'Mike', phone: '555-4321', age: 21 },
+ { name: 'Adam', phone: '555-5678', age: 35 },
+ { name: 'Julie', phone: '555-8765', age: 29 }
+ ];
+
+ $scope.order = function(predicate, reverse) {
+ $scope.friends = orderBy($scope.friends, predicate, reverse);
+ };
+ $scope.order('-age',false);
+ }
+
+
+ */
+orderByFilter.$inject = ['$parse'];
+function orderByFilter($parse){
+ return function(array, sortPredicate, reverseOrder) {
+ if (!isArray(array)) return array;
+ if (!sortPredicate) return array;
+ sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
+ sortPredicate = map(sortPredicate, function(predicate){
+ var descending = false, get = predicate || identity;
+ if (isString(predicate)) {
+ if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
+ descending = predicate.charAt(0) == '-';
+ predicate = predicate.substring(1);
+ }
+ get = $parse(predicate);
+ if (get.constant) {
+ var key = get();
+ return reverseComparator(function(a,b) {
+ return compare(a[key], b[key]);
+ }, descending);
+ }
+ }
+ return reverseComparator(function(a,b){
+ return compare(get(a),get(b));
+ }, descending);
+ });
+ var arrayCopy = [];
+ for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
+ return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
+
+ function comparator(o1, o2){
+ for ( var i = 0; i < sortPredicate.length; i++) {
+ var comp = sortPredicate[i](o1, o2);
+ if (comp !== 0) return comp;
+ }
+ return 0;
+ }
+ function reverseComparator(comp, descending) {
+ return toBoolean(descending)
+ ? function(a,b){return comp(b,a);}
+ : comp;
+ }
+ function compare(v1, v2){
+ var t1 = typeof v1;
+ var t2 = typeof v2;
+ if (t1 == t2) {
+ if (t1 == "string") {
+ v1 = v1.toLowerCase();
+ v2 = v2.toLowerCase();
+ }
+ if (v1 === v2) return 0;
+ return v1 < v2 ? -1 : 1;
+ } else {
+ return t1 < t2 ? -1 : 1;
+ }
+ }
+ };
+}
+
+function ngDirective(directive) {
+ if (isFunction(directive)) {
+ directive = {
+ link: directive
+ };
+ }
+ directive.restrict = directive.restrict || 'AC';
+ return valueFn(directive);
+}
+
+/**
+ * @ngdoc directive
+ * @name a
+ * @restrict E
+ *
+ * @description
+ * Modifies the default behavior of the html A tag so that the default action is prevented when
+ * the href attribute is empty.
+ *
+ * This change permits the easy creation of action links with the `ngClick` directive
+ * without changing the location or causing page reloads, e.g.:
+ * `Add Item`
+ */
+var htmlAnchorDirective = valueFn({
+ restrict: 'E',
+ compile: function(element, attr) {
+
+ if (msie <= 8) {
+
+ // turn link into a stylable link in IE
+ // but only if it doesn't have name attribute, in which case it's an anchor
+ if (!attr.href && !attr.name) {
+ attr.$set('href', '');
+ }
+
+ // add a comment node to anchors to workaround IE bug that causes element content to be reset
+ // to new attribute content if attribute is updated with value containing @ and element also
+ // contains value with @
+ // see issue #1949
+ element.append(document.createComment('IE fix'));
+ }
+
+ if (!attr.href && !attr.xlinkHref && !attr.name) {
+ return function(scope, element) {
+ // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
+ var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
+ 'xlink:href' : 'href';
+ element.on('click', function(event){
+ // if we have no href url, then don't navigate anywhere.
+ if (!element.attr(href)) {
+ event.preventDefault();
+ }
+ });
+ };
+ }
+ }
+});
+
+/**
+ * @ngdoc directive
+ * @name ngHref
+ * @restrict A
+ * @priority 99
+ *
+ * @description
+ * Using Angular markup like `{{hash}}` in an href attribute will
+ * make the link go to the wrong URL if the user clicks it before
+ * Angular has a chance to replace the `{{hash}}` markup with its
+ * value. Until Angular replaces the markup the link will be broken
+ * and will most likely return a 404 error.
+ *
+ * The `ngHref` directive solves this problem.
+ *
+ * The wrong way to write it:
+ * ```html
+ *
+ * ```
+ *
+ * The correct way to write it:
+ * ```html
+ *
+ * ```
+ *
+ * @element A
+ * @param {template} ngHref any string which can contain `{{}}` markup.
+ *
+ * @example
+ * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
+ * in links and their different behaviors:
+
+
+
+ link 1 (link, don't reload)
+ link 2 (link, don't reload)
+ link 3 (link, reload!)
+ anchor (link, don't reload)
+ anchor (no link)
+ link (link, change location)
+
+
+ it('should execute ng-click but not reload when href without value', function() {
+ element(by.id('link-1')).click();
+ expect(element(by.model('value')).getAttribute('value')).toEqual('1');
+ expect(element(by.id('link-1')).getAttribute('href')).toBe('');
+ });
+
+ it('should execute ng-click but not reload when href empty string', function() {
+ element(by.id('link-2')).click();
+ expect(element(by.model('value')).getAttribute('value')).toEqual('2');
+ expect(element(by.id('link-2')).getAttribute('href')).toBe('');
+ });
+
+ it('should execute ng-click and change url when ng-href specified', function() {
+ expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
+
+ element(by.id('link-3')).click();
+
+ // At this point, we navigate away from an Angular page, so we need
+ // to use browser.driver to get the base webdriver.
+
+ browser.wait(function() {
+ return browser.driver.getCurrentUrl().then(function(url) {
+ return url.match(/\/123$/);
+ });
+ }, 1000, 'page should navigate to /123');
+ });
+
+ xit('should execute ng-click but not reload when href empty string and name specified', function() {
+ element(by.id('link-4')).click();
+ expect(element(by.model('value')).getAttribute('value')).toEqual('4');
+ expect(element(by.id('link-4')).getAttribute('href')).toBe('');
+ });
+
+ it('should execute ng-click but not reload when no href but name specified', function() {
+ element(by.id('link-5')).click();
+ expect(element(by.model('value')).getAttribute('value')).toEqual('5');
+ expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
+ });
+
+ it('should only change url when only ng-href', function() {
+ element(by.model('value')).clear();
+ element(by.model('value')).sendKeys('6');
+ expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
+
+ element(by.id('link-6')).click();
+
+ // At this point, we navigate away from an Angular page, so we need
+ // to use browser.driver to get the base webdriver.
+ browser.wait(function() {
+ return browser.driver.getCurrentUrl().then(function(url) {
+ return url.match(/\/6$/);
+ });
+ }, 1000, 'page should navigate to /6');
+ });
+
+
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngSrc
+ * @restrict A
+ * @priority 99
+ *
+ * @description
+ * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
+ * work right: The browser will fetch from the URL with the literal
+ * text `{{hash}}` until Angular replaces the expression inside
+ * `{{hash}}`. The `ngSrc` directive solves this problem.
+ *
+ * The buggy way to write it:
+ * ```html
+ *
+ * ```
+ *
+ * The correct way to write it:
+ * ```html
+ *
+ * ```
+ *
+ * @element IMG
+ * @param {template} ngSrc any string which can contain `{{}}` markup.
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngSrcset
+ * @restrict A
+ * @priority 99
+ *
+ * @description
+ * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
+ * work right: The browser will fetch from the URL with the literal
+ * text `{{hash}}` until Angular replaces the expression inside
+ * `{{hash}}`. The `ngSrcset` directive solves this problem.
+ *
+ * The buggy way to write it:
+ * ```html
+ *
+ * ```
+ *
+ * The correct way to write it:
+ * ```html
+ *
+ * ```
+ *
+ * @element IMG
+ * @param {template} ngSrcset any string which can contain `{{}}` markup.
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngDisabled
+ * @restrict A
+ * @priority 100
+ *
+ * @description
+ *
+ * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
+ * ```html
+ *
+ *
+ *
+ * ```
+ *
+ * The HTML specification does not require browsers to preserve the values of boolean attributes
+ * such as disabled. (Their presence means true and their absence means false.)
+ * If we put an Angular interpolation expression into such an attribute then the
+ * binding information would be lost when the browser removes the attribute.
+ * The `ngDisabled` directive solves this problem for the `disabled` attribute.
+ * This complementary directive is not removed by the browser and so provides
+ * a permanent reliable place to store the binding information.
+ *
+ * @example
+
+
+ Click me to toggle:
+
+
+
+ it('should toggle button', function() {
+ expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
+ element(by.model('checked')).click();
+ expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
+ });
+
+
+ *
+ * @element INPUT
+ * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
+ * then special attribute "disabled" will be set on the element
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngChecked
+ * @restrict A
+ * @priority 100
+ *
+ * @description
+ * The HTML specification does not require browsers to preserve the values of boolean attributes
+ * such as checked. (Their presence means true and their absence means false.)
+ * If we put an Angular interpolation expression into such an attribute then the
+ * binding information would be lost when the browser removes the attribute.
+ * The `ngChecked` directive solves this problem for the `checked` attribute.
+ * This complementary directive is not removed by the browser and so provides
+ * a permanent reliable place to store the binding information.
+ * @example
+
+
+ Check me to check both:
+
+
+
+ it('should check both checkBoxes', function() {
+ expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
+ element(by.model('master')).click();
+ expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
+ });
+
+
+ *
+ * @element INPUT
+ * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
+ * then special attribute "checked" will be set on the element
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngReadonly
+ * @restrict A
+ * @priority 100
+ *
+ * @description
+ * The HTML specification does not require browsers to preserve the values of boolean attributes
+ * such as readonly. (Their presence means true and their absence means false.)
+ * If we put an Angular interpolation expression into such an attribute then the
+ * binding information would be lost when the browser removes the attribute.
+ * The `ngReadonly` directive solves this problem for the `readonly` attribute.
+ * This complementary directive is not removed by the browser and so provides
+ * a permanent reliable place to store the binding information.
+ * @example
+
+
+ Check me to make text readonly:
+
+
+
+ it('should toggle readonly attr', function() {
+ expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
+ element(by.model('checked')).click();
+ expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
+ });
+
+
+ *
+ * @element INPUT
+ * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
+ * then special attribute "readonly" will be set on the element
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngSelected
+ * @restrict A
+ * @priority 100
+ *
+ * @description
+ * The HTML specification does not require browsers to preserve the values of boolean attributes
+ * such as selected. (Their presence means true and their absence means false.)
+ * If we put an Angular interpolation expression into such an attribute then the
+ * binding information would be lost when the browser removes the attribute.
+ * The `ngSelected` directive solves this problem for the `selected` attribute.
+ * This complementary directive is not removed by the browser and so provides
+ * a permanent reliable place to store the binding information.
+ *
+ * @example
+
+
+ Check me to select:
+
+
+
+ it('should select Greetings!', function() {
+ expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
+ element(by.model('selected')).click();
+ expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
+ });
+
+
+ *
+ * @element OPTION
+ * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
+ * then special attribute "selected" will be set on the element
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngOpen
+ * @restrict A
+ * @priority 100
+ *
+ * @description
+ * The HTML specification does not require browsers to preserve the values of boolean attributes
+ * such as open. (Their presence means true and their absence means false.)
+ * If we put an Angular interpolation expression into such an attribute then the
+ * binding information would be lost when the browser removes the attribute.
+ * The `ngOpen` directive solves this problem for the `open` attribute.
+ * This complementary directive is not removed by the browser and so provides
+ * a permanent reliable place to store the binding information.
+ * @example
+
+
+ Check me check multiple:
+
+ Show/Hide me
+
+
+
+ it('should toggle open', function() {
+ expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
+ element(by.model('open')).click();
+ expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
+ });
+
+
+ *
+ * @element DETAILS
+ * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
+ * then special attribute "open" will be set on the element
+ */
+
+var ngAttributeAliasDirectives = {};
+
+
+// boolean attrs are evaluated
+forEach(BOOLEAN_ATTR, function(propName, attrName) {
+ // binding to multiple is not supported
+ if (propName == "multiple") return;
+
+ var normalized = directiveNormalize('ng-' + attrName);
+ ngAttributeAliasDirectives[normalized] = function() {
+ return {
+ priority: 100,
+ link: function(scope, element, attr) {
+ scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
+ attr.$set(attrName, !!value);
+ });
+ }
+ };
+ };
+});
+
+
+// ng-src, ng-srcset, ng-href are interpolated
+forEach(['src', 'srcset', 'href'], function(attrName) {
+ var normalized = directiveNormalize('ng-' + attrName);
+ ngAttributeAliasDirectives[normalized] = function() {
+ return {
+ priority: 99, // it needs to run after the attributes are interpolated
+ link: function(scope, element, attr) {
+ var propName = attrName,
+ name = attrName;
+
+ if (attrName === 'href' &&
+ toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
+ name = 'xlinkHref';
+ attr.$attr[name] = 'xlink:href';
+ propName = null;
+ }
+
+ attr.$observe(normalized, function(value) {
+ if (!value)
+ return;
+
+ attr.$set(name, value);
+
+ // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
+ // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
+ // to set the property as well to achieve the desired effect.
+ // we use attr[attrName] value since $set can sanitize the url.
+ if (msie && propName) element.prop(propName, attr[name]);
+ });
+ }
+ };
+ };
+});
+
+/* global -nullFormCtrl */
+var nullFormCtrl = {
+ $addControl: noop,
+ $removeControl: noop,
+ $setValidity: noop,
+ $setDirty: noop,
+ $setPristine: noop
+};
+
+/**
+ * @ngdoc type
+ * @name form.FormController
+ *
+ * @property {boolean} $pristine True if user has not interacted with the form yet.
+ * @property {boolean} $dirty True if user has already interacted with the form.
+ * @property {boolean} $valid True if all of the containing forms and controls are valid.
+ * @property {boolean} $invalid True if at least one containing control or form is invalid.
+ *
+ * @property {Object} $error Is an object hash, containing references to all invalid controls or
+ * forms, where:
+ *
+ * - keys are validation tokens (error names),
+ * - values are arrays of controls or forms that are invalid for given error name.
+ *
+ *
+ * Built-in validation tokens:
+ *
+ * - `email`
+ * - `max`
+ * - `maxlength`
+ * - `min`
+ * - `minlength`
+ * - `number`
+ * - `pattern`
+ * - `required`
+ * - `url`
+ *
+ * @description
+ * `FormController` keeps track of all its controls and nested forms as well as the state of them,
+ * such as being valid/invalid or dirty/pristine.
+ *
+ * Each {@link ng.directive:form form} directive creates an instance
+ * of `FormController`.
+ *
+ */
+//asks for $scope to fool the BC controller module
+FormController.$inject = ['$element', '$attrs', '$scope', '$animate'];
+function FormController(element, attrs, $scope, $animate) {
+ var form = this,
+ parentForm = element.parent().controller('form') || nullFormCtrl,
+ invalidCount = 0, // used to easily determine if we are valid
+ errors = form.$error = {},
+ controls = [];
+
+ // init state
+ form.$name = attrs.name || attrs.ngForm;
+ form.$dirty = false;
+ form.$pristine = true;
+ form.$valid = true;
+ form.$invalid = false;
+
+ parentForm.$addControl(form);
+
+ // Setup initial state of the control
+ element.addClass(PRISTINE_CLASS);
+ toggleValidCss(true);
+
+ // convenience method for easy toggling of classes
+ function toggleValidCss(isValid, validationErrorKey) {
+ validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
+ $animate.removeClass(element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
+ $animate.addClass(element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
+ }
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$addControl
+ *
+ * @description
+ * Register a control with the form.
+ *
+ * Input elements using ngModelController do this automatically when they are linked.
+ */
+ form.$addControl = function(control) {
+ // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
+ // and not added to the scope. Now we throw an error.
+ assertNotHasOwnProperty(control.$name, 'input');
+ controls.push(control);
+
+ if (control.$name) {
+ form[control.$name] = control;
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$removeControl
+ *
+ * @description
+ * Deregister a control from the form.
+ *
+ * Input elements using ngModelController do this automatically when they are destroyed.
+ */
+ form.$removeControl = function(control) {
+ if (control.$name && form[control.$name] === control) {
+ delete form[control.$name];
+ }
+ forEach(errors, function(queue, validationToken) {
+ form.$setValidity(validationToken, true, control);
+ });
+
+ arrayRemove(controls, control);
+ };
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$setValidity
+ *
+ * @description
+ * Sets the validity of a form control.
+ *
+ * This method will also propagate to parent forms.
+ */
+ form.$setValidity = function(validationToken, isValid, control) {
+ var queue = errors[validationToken];
+
+ if (isValid) {
+ if (queue) {
+ arrayRemove(queue, control);
+ if (!queue.length) {
+ invalidCount--;
+ if (!invalidCount) {
+ toggleValidCss(isValid);
+ form.$valid = true;
+ form.$invalid = false;
+ }
+ errors[validationToken] = false;
+ toggleValidCss(true, validationToken);
+ parentForm.$setValidity(validationToken, true, form);
+ }
+ }
+
+ } else {
+ if (!invalidCount) {
+ toggleValidCss(isValid);
+ }
+ if (queue) {
+ if (includes(queue, control)) return;
+ } else {
+ errors[validationToken] = queue = [];
+ invalidCount++;
+ toggleValidCss(false, validationToken);
+ parentForm.$setValidity(validationToken, false, form);
+ }
+ queue.push(control);
+
+ form.$valid = false;
+ form.$invalid = true;
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$setDirty
+ *
+ * @description
+ * Sets the form to a dirty state.
+ *
+ * This method can be called to add the 'ng-dirty' class and set the form to a dirty
+ * state (ng-dirty class). This method will also propagate to parent forms.
+ */
+ form.$setDirty = function() {
+ $animate.removeClass(element, PRISTINE_CLASS);
+ $animate.addClass(element, DIRTY_CLASS);
+ form.$dirty = true;
+ form.$pristine = false;
+ parentForm.$setDirty();
+ };
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$setPristine
+ *
+ * @description
+ * Sets the form to its pristine state.
+ *
+ * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
+ * state (ng-pristine class). This method will also propagate to all the controls contained
+ * in this form.
+ *
+ * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
+ * saving or resetting it.
+ */
+ form.$setPristine = function () {
+ $animate.removeClass(element, DIRTY_CLASS);
+ $animate.addClass(element, PRISTINE_CLASS);
+ form.$dirty = false;
+ form.$pristine = true;
+ forEach(controls, function(control) {
+ control.$setPristine();
+ });
+ };
+}
+
+
+/**
+ * @ngdoc directive
+ * @name ngForm
+ * @restrict EAC
+ *
+ * @description
+ * Nestable alias of {@link ng.directive:form `form`} directive. HTML
+ * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
+ * sub-group of controls needs to be determined.
+ *
+ * Note: the purpose of `ngForm` is to group controls,
+ * but not to be a replacement for the `
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport),this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c&&c.$tip&&c.$tip.is(":visible")?void(c.hoverState="in"):(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.options.container?a(this.options.container):this.$element.parent(),p=this.getPosition(o);h="bottom"==h&&k.bottom+m>p.bottom?"top":"top"==h&&k.top-mp.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type)})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.4",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'