diff --git a/.gitignore b/.gitignore index 48028fce32a..2b0c90fed2e 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ geonetwork*.db changes-* web/coverage.ec */target/ +*/.externalToolBuilders web/src/main/webapp/data/ web/src/main/webapp/WEB-INF/lucene/ web/src/main/webapp/WEB-INF/metadata_subversion/ @@ -40,3 +41,6 @@ web/src/main/webapp/WEB-INF/data/index web-itest/jcs_caching datadir/ web/src/main/webapp/WEB-INF/data/removed/ +web-ui/src/main/resources/catalog/lib/gn*.min.js +web-ui/src/main/resources/catalog/style/gn*.css +web-ui/src/main/resources/catalog/style/gn.css diff --git a/core/src/main/java/org/fao/geonet/constants/Geonet.java b/core/src/main/java/org/fao/geonet/constants/Geonet.java index 1587761b7a5..b216f3589e0 100644 --- a/core/src/main/java/org/fao/geonet/constants/Geonet.java +++ b/core/src/main/java/org/fao/geonet/constants/Geonet.java @@ -138,6 +138,7 @@ public static final class Path { public static final String CSW = Jeeves.Path.XML + "csw/"; public static final String VALIDATION = Jeeves.Path.XML + "validation/"; public static final String STYLESHEETS = "/xsl"; + public static final String XSLT_FOLDER = java.io.File.separator + "xslt"; public static final String CONV_STYLESHEETS = STYLESHEETS + "/conversion"; public static final String IMPORT_STYLESHEETS = CONV_STYLESHEETS + "/import"; public static final String WFS_STYLESHEETS = "/convert/WFSToFragments"; diff --git a/core/src/main/java/org/fao/geonet/kernel/DataManager.java b/core/src/main/java/org/fao/geonet/kernel/DataManager.java index 07e32334bc1..457c7d0675c 100644 --- a/core/src/main/java/org/fao/geonet/kernel/DataManager.java +++ b/core/src/main/java/org/fao/geonet/kernel/DataManager.java @@ -27,6 +27,27 @@ package org.fao.geonet.kernel; +import java.io.File; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Vector; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; + import jeeves.config.springutil.JeevesApplicationContext; import jeeves.constants.Jeeves; import jeeves.exceptions.JeevesException; @@ -42,6 +63,7 @@ import jeeves.utils.Xml; import jeeves.utils.Xml.ErrorHandler; import jeeves.xlink.Processor; + import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.fao.geonet.GeonetContext; @@ -67,25 +89,6 @@ import org.jdom.Namespace; import org.jdom.filter.ElementFilter; -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; -import java.io.File; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.Vector; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - /** * Handles all operations on metadata (select,insert,update,delete etc...). * @@ -101,6 +104,7 @@ public class DataManager { //--- //-------------------------------------------------------------------------- + private static final String MD_ON_HARV = "(SELECT id FROM Metadata WHERE harvestUuid=?)"; /** * * @return @@ -1592,6 +1596,24 @@ public Element getMetadata(Dbms dbms, String id) throws Exception { */ public Element getMetadata(ServiceContext srvContext, String id, boolean forEditing, boolean withEditorValidationErrors, boolean keepXlinkAttributes) throws Exception { Dbms dbms = (Dbms) srvContext.getResourceManager().open(Geonet.Res.MAIN_DB); + + return getMetadata(srvContext, dbms, id, forEditing, withEditorValidationErrors, keepXlinkAttributes); + } + + /** + * Retrieves a metadata (in xml) given its id; adds editing information if requested and validation errors if + * requested. + * + * @param srvContext + * @param dbms + * @param id + * @param forEditing Add extra element to build metadocument {@link EditLib#expandElements(String, Element)} + * @param withEditorValidationErrors + * @param keepXlinkAttributes When XLinks are resolved in non edit mode, do not remove XLink attributes. + * @return + * @throws Exception + */ + public Element getMetadata(ServiceContext srvContext, Dbms dbms, String id, boolean forEditing, boolean withEditorValidationErrors, boolean keepXlinkAttributes) throws Exception { boolean doXLinks = xmlSerializer.resolveXLinks(); Element md = xmlSerializer.selectNoXLinkResolver(dbms, "Metadata", id, false); if (md == null) return null; @@ -1732,7 +1754,8 @@ public synchronized boolean updateMetadata(ServiceContext context, Dbms dbms, St } String uuid = null; - if (schemaMan.getSchema(schema).isReadwriteUUID()) { + if (schemaMan.getSchema(schema).isReadwriteUUID() + && !getMetadataTemplate(dbms, id).equals("s")) { uuid = extractUUID(schema, md); } @@ -2048,6 +2071,69 @@ public synchronized void deleteMetadata(ServiceContext context, Dbms dbms, Strin searchMan.delete("_id", id+""); } + + /** + * Removes all metadata associated to one harvester. Faster than doing one by one. + * + * @param context + * @param dbms + * @param id + * @throws Exception + */ + public synchronized void deleteBatchMetadata(ServiceContext context, + Dbms dbms, String harvesterId) throws Exception { + + // --- remove operations + deleteBatchMetadataOper(dbms, harvesterId, false); + + // --- remove categories + deleteBatchAllMetadataCateg(dbms, harvesterId); + + dbms.execute( + "DELETE FROM MetadataRating WHERE metadataId in " + DataManager.MD_ON_HARV, + harvesterId); + dbms.execute( + "DELETE FROM Validation WHERE metadataId in " + DataManager.MD_ON_HARV, + harvesterId); + + dbms.execute( + "DELETE FROM MetadataStatus WHERE metadataId in " + DataManager.MD_ON_HARV, + harvesterId); + + + //Notify templates in Batch + String getQuery = "SELECT id, uuid FROM Metadata WHERE harvestUuid=? AND isTemplate like 'n'"; + for (Object o : dbms.select(getQuery, harvesterId).getChildren()) + { + Element el = (Element) o; + String id = el.getChildText("id"); + String uuid = el.getChildText("uuid"); + notifyMetadataDelete(dbms, id, uuid); + } + + //TODO improve this, try to do it batch too + getQuery = "SELECT id FROM Metadata WHERE harvestUuid=?"; + List ids = new LinkedList(); + for (Object o : dbms.select(getQuery, harvesterId).getChildren()) + { + Element el = (Element) o; + String id = el.getChildText("id"); + + // --- remove metadata + xmlSerializer.delete(dbms, "Metadata", id, context); + + ids.add(id); + } + + // --- update search criteria + searchMan.delete("_id", ids); + + dbms.execute( + "DELETE FROM Metadata WHERE harvestUuid = ?", + harvesterId); + dbms.commit(); + } + /** * * @param context @@ -2076,7 +2162,21 @@ public void deleteMetadataOper(Dbms dbms, String id, boolean skipAllIntranet) th dbms.execute(query, Integer.valueOf(id)); } + /** + * Removes all operations stored for all metadata on a harvester. + * @param dbms + * @param harvesterId + * @param skipAllIntranet + * @throws Exception + */ + public void deleteBatchMetadataOper(Dbms dbms, String harvesterId, boolean skipAllIntranet) throws Exception { + String query = "DELETE FROM OperationAllowed WHERE metadataId in " + DataManager.MD_ON_HARV; + if (skipAllIntranet) + query += " AND groupId>1"; + + dbms.execute(query, harvesterId); + } /** * Removes all categories stored for a metadata. * @@ -2090,6 +2190,19 @@ public void deleteAllMetadataCateg(Dbms dbms, String id) throws Exception { dbms.execute(query, Integer.valueOf(id)); } + /** + * Removes all categories stored for all metadata in a harvester + * + * @param dbms + * @param harvesterId + * @throws Exception + */ + public void deleteBatchAllMetadataCateg(Dbms dbms, String harvesterId) throws Exception { + String query = "DELETE FROM MetadataCateg WHERE metadataId in " + DataManager.MD_ON_HARV; + + dbms.execute(query, harvesterId); + } + //-------------------------------------------------------------------------- //--- //--- Metadata thumbnail API @@ -2175,7 +2288,7 @@ public void unsetThumbnail(ServiceContext context, Dbms dbms, String id, boolean private void manageThumbnail(ServiceContext context, Dbms dbms, String id, boolean small, Element env, String styleSheet, boolean indexAfterChange) throws Exception { boolean forEditing = false, withValidationErrors = false, keepXlinkAttributes = true; - Element md = getMetadata(context, id, forEditing, withValidationErrors, keepXlinkAttributes); + Element md = getMetadata(context, dbms, id, forEditing, withValidationErrors, keepXlinkAttributes); if (md == null) return; @@ -3364,4 +3477,4 @@ public void run() { public enum UpdateDatestamp { yes, no } -} \ No newline at end of file +} diff --git a/core/src/main/java/org/fao/geonet/kernel/search/SearchManager.java b/core/src/main/java/org/fao/geonet/kernel/search/SearchManager.java index 0d2daca2466..5c664af6c65 100644 --- a/core/src/main/java/org/fao/geonet/kernel/search/SearchManager.java +++ b/core/src/main/java/org/fao/geonet/kernel/search/SearchManager.java @@ -924,6 +924,22 @@ public void delete(String fld, String txt) throws Exception { _indexWriter.deleteDocuments(new Term(fld, txt)); _spatial.writer().delete(txt); } + + /** + * deletes a list of documents. + * + * @param fld + * @param txt + * @throws Exception + */ + public void delete(String fld, List txts) throws Exception { + // possibly remove old document + for(String txt : txts) { + _indexWriter.deleteDocuments(new Term(fld, txt)); + } + _spatial.writer().delete(txts); + } + /** * TODO javadoc. diff --git a/core/src/main/java/org/fao/geonet/kernel/search/spatial/SpatialIndexWriter.java b/core/src/main/java/org/fao/geonet/kernel/search/spatial/SpatialIndexWriter.java index 5689c2c9532..340e4c4e6b7 100644 --- a/core/src/main/java/org/fao/geonet/kernel/search/spatial/SpatialIndexWriter.java +++ b/core/src/main/java/org/fao/geonet/kernel/search/spatial/SpatialIndexWriter.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; @@ -228,6 +229,34 @@ public void delete(String id) throws IOException } } + + public void delete(List ids) throws IOException + { + _lock.lock(); + try { + FilterFactory2 factory = CommonFactoryFinder + .getFilterFactory2(GeoTools.getDefaultHints()); + + List filters = new LinkedList(); + + for(String id : ids) { + filters.add(factory.equals( + factory.property(_idColumn), factory.literal(id))); + } + + _index = null; + + _featureStore.removeFeatures(factory.or(filters)); + try { + SpatialFilter.getJCSCache().clear(); + } catch (Throwable e) { + e.printStackTrace(); + } + _writes++; + } finally { + _lock.unlock(); + } + } public void commit() throws IOException { _lock.lock(); diff --git a/core/src/main/java/org/fao/geonet/kernel/setting/SettingManager.java b/core/src/main/java/org/fao/geonet/kernel/setting/SettingManager.java index 732f1e7a69b..3f47ffb02c7 100644 --- a/core/src/main/java/org/fao/geonet/kernel/setting/SettingManager.java +++ b/core/src/main/java/org/fao/geonet/kernel/setting/SettingManager.java @@ -311,6 +311,7 @@ public boolean setValues(Dbms dbms, Map values) throws Exception } setting.setValue(value); } catch (Exception e) { + e.printStackTrace(); Log.warning(Geonet.SETTINGS, "Failed to save setting with name: " + key + ", value: " + value + ". Error: " + e.getMessage()); throw e; } diff --git a/core/src/main/java/org/fao/geonet/services/main/Info.java b/core/src/main/java/org/fao/geonet/services/main/Info.java index b3df3a77853..63194e2c401 100644 --- a/core/src/main/java/org/fao/geonet/services/main/Info.java +++ b/core/src/main/java/org/fao/geonet/services/main/Info.java @@ -139,6 +139,12 @@ else if (type.equals("harvester")) new String[]{ "system/harvester/enableEditing" })); + + else if (type.equals("userGroupOnly")) + result.addContent(gc.getBean(SettingManager.class).getValues( + new String[]{ + "system/metadataprivs/usergrouponly" + })); else if (type.equals("categories")) result.addContent(Lib.local.retrieve(dbms, "Categories")); diff --git a/core/src/main/java/org/fao/geonet/util/ISODate.java b/core/src/main/java/org/fao/geonet/util/ISODate.java index ef58168d033..eec11b87cbc 100644 --- a/core/src/main/java/org/fao/geonet/util/ISODate.java +++ b/core/src/main/java/org/fao/geonet/util/ISODate.java @@ -129,28 +129,41 @@ public void setDate(String isoDate) try { - year = Integer.parseInt(isoDate.substring(0, 4)); - month = Integer.parseInt(isoDate.substring(5, 7)); - day = Integer.parseInt(isoDate.substring(8, 10)); + if (isoDate.contains("T")) { + // Check if iso date contains time info and if using non UTC time zone to parse the date with + // JODAISODate. This class converts to UTC format to avoid timezones issues. + boolean timeZoneInfo = ((isoDate.split("T")[1].contains("+")) || (isoDate.split("T")[1].contains("-"))); - isShort = true; + if (timeZoneInfo) { + isoDate = JODAISODate.parseISODateTime(isoDate); + } + } - hour = 0; - min = 0; - sec = 0; + year = Integer.parseInt(isoDate.substring(0, 4)); + month = Integer.parseInt(isoDate.substring(5, 7)); + day = Integer.parseInt(isoDate.substring(8, 10)); - //--- is the date in 'yyyy-mm-dd' or 'yyyy-mm-ddZ' format? + isShort = true; - if (isoDate.length() < 12) - return; + hour = 0; + min = 0; + sec = 0; - isoDate = isoDate.substring(11); + //--- is the date in 'yyyy-mm-dd' or 'yyyy-mm-ddZ' format? - hour = Integer.parseInt(isoDate.substring(0,2)); - min = Integer.parseInt(isoDate.substring(3,5)); - sec = Integer.parseInt(isoDate.substring(6,8)); + if (isoDate.length() < 12) + return; + + isoDate = isoDate.substring(11); + + hour = Integer.parseInt(isoDate.substring(0,2)); + min = Integer.parseInt(isoDate.substring(3,5)); + sec = Integer.parseInt(isoDate.substring(6,8)); + + + + isShort = false; - isShort = false; } catch(Exception e) { diff --git a/core/src/main/java/org/fao/geonet/util/JODAISODate.java b/core/src/main/java/org/fao/geonet/util/JODAISODate.java index be23656581d..4bb0e0fd801 100644 --- a/core/src/main/java/org/fao/geonet/util/JODAISODate.java +++ b/core/src/main/java/org/fao/geonet/util/JODAISODate.java @@ -27,6 +27,11 @@ package org.fao.geonet.util; +import java.util.Calendar; +import java.util.TimeZone; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Period; @@ -37,102 +42,163 @@ //============================================================================== -public class JODAISODate -{ - private static String dt = "3000-01-01T00:00:00.000Z"; // JUNK Value - - /* - * Converts a given ISO date time into the form used to index in Lucene - * Returns null if it gets back a ridiculous value - */ - public static String parseISODateTime(String input1) - { - String newDateTime = parseISODateTimes(input1, null); - if (newDateTime.equals(dt)) return null; - else return newDateTime; - } - - /* - * Converts two ISO date times into standard form used to index in Lucene - * Always returns something because it is used during the indexing of the - * metadata record in Lucene - if exception during parsing then it is - * something ridiculous like JUNK value above - */ - public static String parseISODateTimes(String input1,String input2) - { - DateTimeFormatter dto = ISODateTimeFormat.dateTime(); - PeriodFormatter p = ISOPeriodFormat.standard(); - DateTime odt1; - String odt = ""; - - // input1 should be some sort of ISO time - // eg. basic: 20080909, full: 2008-09-09T12:21:00 etc - // convert everything to UTC so that we remove any timezone - // problems - try { - DateTime idt = parseBasicOrFullDateTime(input1); - odt1 = dto.parseDateTime(idt.toString()).withZone(DateTimeZone.forID("UTC")); - odt = odt1.toString(); - - } catch (Exception e) { - e.printStackTrace(); - return dt; - } - - if (input2 == null || input2.equals("")) return odt; - - - // input2 can be an ISO time as for input1 but also an ISO time period - // eg. -P3D or P3D - if an ISO time period then it must be added to the - // DateTime generated for input1 (odt1) - // convert everything to UTC so that we remove any timezone - // problems - try { - boolean minus = false; - if (input2.startsWith("-P")) { - input2 = input2.substring(1); - minus = true; - } - - if (input2.startsWith("P")) { - Period ip = p.parsePeriod(input2); - DateTime odt2; - if (!minus) odt2 = odt1.plus(ip.toStandardDuration().getMillis()); - else odt2 = odt1.minus(ip.toStandardDuration().getMillis()); - odt = odt+"|"+odt2.toString(); - } else { - DateTime idt = parseBasicOrFullDateTime(input2); - DateTime odt2 = dto.parseDateTime(idt.toString()).withZone(DateTimeZone.forID("UTC")); - odt = odt+"|"+odt2.toString(); - } - } catch (Exception e) { - e.printStackTrace(); - return odt+"|"+dt; - } - - return odt; - } - - public static DateTime parseBasicOrFullDateTime(String input1) throws Exception { - DateTimeFormatter bd = ISODateTimeFormat.basicDate(); - DateTimeFormatter bt = ISODateTimeFormat.basicTime(); - DateTimeFormatter bdt = ISODateTimeFormat.basicDateTime(); - DateTimeFormatter dtp = ISODateTimeFormat.dateTimeParser(); - DateTime idt; - if (input1.length() == 8 && !input1.startsWith("T")) { - idt = bd.parseDateTime(input1); - } else if (input1.startsWith("T") && !input1.contains(":")) { - idt = bt.parseDateTime(input1); - } else if (input1.contains("T") && !input1.contains(":") && !input1.contains("-")) { - idt = bdt.parseDateTime(input1); - } else { - idt = dtp.parseDateTime(input1); - } - return idt; - } +public class JODAISODate { + private static String dt = "3000-01-01T00:00:00.000Z"; // JUNK Value + + // Pattern to check dates + private static Pattern gsYear = Pattern + .compile("([0-9]{4})(-([0-2][0-9]):([0-5][0-9])([A-Z]))?"); + private static Pattern gsYearMonth = Pattern + .compile("([0-9]{4})-([0-1][0-9])(-([0-2][0-9]):([0-5][0-9])([A-Z]))?"); + + /* + * Converts a given ISO date time into the form used to index in Lucene + * Returns null if it gets back a ridiculous value + */ + public static String parseISODateTime(String input1) { + String newDateTime = parseISODateTimes(input1, null); + if (newDateTime.equals(dt)) + return null; + else + return newDateTime; + } + + /* + * Converts two ISO date times into standard form used to index in Lucene + * Always returns something because it is used during the indexing of the + * metadata record in Lucene - if exception during parsing then it is + * something ridiculous like JUNK value above + */ + public static String parseISODateTimes(String input1, String input2) { + DateTimeFormatter dto = ISODateTimeFormat.dateTime(); + PeriodFormatter p = ISOPeriodFormat.standard(); + DateTime odt1; + String odt = ""; + + // input1 should be some sort of ISO time + // eg. basic: 20080909, full: 2008-09-09T12:21:00 etc + // convert everything to UTC so that we remove any timezone + // problems + try { + DateTime idt = parseBasicOrFullDateTime(input1); + odt1 = dto.parseDateTime(idt.toString()).withZone( + DateTimeZone.forID("UTC")); + odt = odt1.toString(); + + } catch (Exception e) { + e.printStackTrace(); + return dt; + } + + if (input2 == null || input2.equals("")) + return odt; + + // input2 can be an ISO time as for input1 but also an ISO time period + // eg. -P3D or P3D - if an ISO time period then it must be added to the + // DateTime generated for input1 (odt1) + // convert everything to UTC so that we remove any timezone + // problems + try { + boolean minus = false; + if (input2.startsWith("-P")) { + input2 = input2.substring(1); + minus = true; + } + + if (input2.startsWith("P")) { + Period ip = p.parsePeriod(input2); + DateTime odt2; + if (!minus) + odt2 = odt1.plus(ip.toStandardDuration().getMillis()); + else + odt2 = odt1.minus(ip.toStandardDuration().getMillis()); + odt = odt + "|" + odt2.toString(); + } else { + DateTime idt = parseBasicOrFullDateTime(input2); + DateTime odt2 = dto.parseDateTime(idt.toString()).withZone( + DateTimeZone.forID("UTC")); + odt = odt + "|" + odt2.toString(); + } + } catch (Exception e) { + e.printStackTrace(); + return odt + "|" + dt; + } + + return odt; + } + + public static DateTime parseBasicOrFullDateTime(String input1) + throws Exception { + DateTimeFormatter bd = ISODateTimeFormat.basicDate(); + DateTimeFormatter bt = ISODateTimeFormat.basicTime(); + DateTimeFormatter bdt = ISODateTimeFormat.basicDateTime(); + DateTimeFormatter dtp = ISODateTimeFormat.dateTimeParser(); + DateTime idt; + Matcher matcher; + if (input1.length() == 8 && !input1.startsWith("T")) { + idt = bd.parseDateTime(input1); + } else if (input1.startsWith("T") && !input1.contains(":")) { + idt = bt.parseDateTime(input1); + } else if (input1.contains("T") && !input1.contains(":") + && !input1.contains("-")) { + idt = bdt.parseDateTime(input1); + } else if ((matcher = gsYearMonth.matcher(input1)).matches()) { + String year = matcher.group(1); + String month = matcher.group(2); + String minute = "00"; + String hour = "00"; + String timezone = "Z"; + if (matcher.group(4) != null) { + minute = matcher.group(5); + hour = matcher.group(4); + timezone = matcher.group(6); + } + + idt = generateDate(year, month, minute, hour, timezone); + } else if ((matcher = gsYear.matcher(input1)).matches()) { + String year = matcher.group(1); + String month = "01"; + String minute = "00"; + String hour = "00"; + String timezone = "Z"; + if (matcher.group(3) != null) { + minute = matcher.group(4); + hour = matcher.group(3); + timezone = matcher.group(5); + } + + idt = generateDate(year, month, minute, hour, timezone); + } else { + idt = dtp.parseDateTime(input1); + } + return idt; + } + + /** + * @param year + * @param month + * @param minute + * @param hour + * @return + */ + private static DateTime generateDate(String year, String month, + String minute, String hour, String timezone) { + + Calendar c = Calendar.getInstance(); + c.set(Calendar.YEAR, Integer.valueOf(year)); + c.set(Calendar.MONTH, Integer.valueOf(month) - 1); + c.set(Calendar.DAY_OF_MONTH, 1); + + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + c.set(Calendar.HOUR_OF_DAY, Integer.valueOf(hour)); + c.set(Calendar.MINUTE, Integer.valueOf(minute)); + + TimeZone zone = TimeZone.getTimeZone(timezone); + c.setTimeZone(zone ); + + return new DateTime(c.getTimeInMillis()); + } } -//============================================================================== - - - +// ============================================================================== diff --git a/core/src/main/java/org/fao/geonet/util/MailSender.java b/core/src/main/java/org/fao/geonet/util/MailSender.java index 3193e1b7229..a266fe6827e 100644 --- a/core/src/main/java/org/fao/geonet/util/MailSender.java +++ b/core/src/main/java/org/fao/geonet/util/MailSender.java @@ -30,9 +30,14 @@ import org.apache.commons.mail.SimpleEmail; import javax.mail.internet.InternetAddress; + import java.util.ArrayList; import java.util.List; - +/** + * see {@link MailUtil} + * * + */ +@Deprecated public class MailSender extends Thread { Logger _logger; @@ -73,8 +78,9 @@ private void setUp(String server, int port, String username, String password, bo } /** - * TODO Javadoc. - * + * Better use through MailUtil, as it takes the settings directly from the + * BBDD. + * * @param server * @param port * @param username TODO @@ -100,8 +106,9 @@ public void send(String server, int port, String username, String password, bool } /** - * TODO Javadoc. - * + * Better use through MailUtil, as it takes the settings directly from the + * BBDD. + * * @param server * @param port * @param from @@ -146,10 +153,12 @@ public void run() private void logEx(Exception e) { + if(_logger != null) { _logger.error("Unable to mail feedback"); _logger.error(" Exception : " + e); _logger.error(" Message : " + e.getMessage()); _logger.error(" Stack : " + Util.getStackTrace(e)); + } } }; diff --git a/core/src/main/java/org/fao/geonet/util/MailUtil.java b/core/src/main/java/org/fao/geonet/util/MailUtil.java new file mode 100644 index 00000000000..e501e7eb559 --- /dev/null +++ b/core/src/main/java/org/fao/geonet/util/MailUtil.java @@ -0,0 +1,411 @@ +package org.fao.geonet.util; + +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import javax.mail.internet.InternetAddress; + +import org.apache.commons.mail.DefaultAuthenticator; +import org.apache.commons.mail.Email; +import org.apache.commons.mail.EmailAttachment; +import org.apache.commons.mail.EmailException; +import org.apache.commons.mail.HtmlEmail; +import org.apache.commons.mail.SimpleEmail; +import org.fao.geonet.kernel.setting.SettingManager; + +/** + * Utility class to send mails. Supports both html and plain text. It usually + * takes the settings from the database, but you can also indicate all params. + * + * @author delawen + * + */ +public class MailUtil { + + /** + * Send an html mail. Will look on the settings directly to know the + * remitent + * + * @param toAddress + * @param subject + * @param htmlMessage + * @param settings + * @throws EmailException + */ + public static Boolean sendHtmlMail(List toAddress, String subject, + String htmlMessage, SettingManager settings) { + // Create data information to compose the mail + HtmlEmail email = new HtmlEmail(); + configureBasics(settings, email); + + email.setSubject(subject); + try { + email.setHtmlMsg(htmlMessage); + } catch (EmailException e1) { + e1.printStackTrace(); + return false; + } + + // send to all mails extracted from settings + for (String add : toAddress) { + try { + email.addBcc(add); + } catch (EmailException e) { + e.printStackTrace(); + return false; + } + } + + return send(email); + } + + /** + * Send a plain text mail. Will look on the settings directly to know the + * remitent + * + * @param toAddress + * @param subject + * @param htmlMessage + * @param settings + * @throws EmailException + */ + public static Boolean sendMail(List toAddress, String subject, + String message, SettingManager settings) { + // Create data information to compose the mail + Email email = new SimpleEmail(); + configureBasics(settings, email); + + email.setSubject(subject); + try { + email.setMsg(message); + } catch (EmailException e1) { + e1.printStackTrace(); + return false; + } + email.setSSL(true); + + // send to all mails extracted from settings + for (String add : toAddress) { + try { + email.addBcc(add); + } catch (EmailException e) { + e.printStackTrace(); + } + } + + return send(email); + } + + /** + * Send a plain text mail. Will look on the settings directly to know the + * remitent + * + * @param toAddress + * @param subject + * @param htmlMessage + * @param settings + * @throws EmailException + */ + public static Boolean sendMail(List toAddress, String subject, + String message, SettingManager settings, String replyTo, + String replyToDesc) { + // Create data information to compose the mail + Email email = new SimpleEmail(); + configureBasics(settings, email); + + List addressColl = new ArrayList(); + try { + addressColl.add(new InternetAddress(replyTo, replyToDesc)); + email.setReplyTo(addressColl); + } catch (UnsupportedEncodingException e2) { + e2.printStackTrace(); + return false; + } catch (EmailException e) { + e.printStackTrace(); + return false; + } + + email.setSubject(subject); + try { + email.setMsg(message); + } catch (EmailException e1) { + e1.printStackTrace(); + return false; + } + email.setSSL(true); + + // send to all mails extracted from settings + for (String add : toAddress) { + try { + email.addBcc(add); + } catch (EmailException e) { + e.printStackTrace(); + } + } + + return send(email); + } + + /** + * Send an html mail + * + * @param toAddress + * @param hostName + * @param smtpPort + * @param mail + * @param username + * @param password + * @param subject + * @param htmlMessage + * @throws EmailException + */ + public static Boolean sendHtmlMail(List toAddress, String hostName, + Integer smtpPort, String from, String username, String password, + String subject, String htmlMessage) { + // Create data information to compose the mail + HtmlEmail email = new HtmlEmail(); + + configureBasics(hostName, smtpPort, from, username, password, email, false); + + email.setSubject(subject); + try { + email.setHtmlMsg(htmlMessage); + } catch (EmailException e1) { + e1.printStackTrace(); + return false; + } + email.setSSL(true); + + // send to all mails extracted from settings + for (String add : toAddress) { + try { + email.addBcc(add); + } catch (EmailException e) { + return false; + } + } + + return send(email); + } + + /** + * Send an html mail with atachments + * + * @param toAddress + * @param hostName + * @param smtpPort + * @param mail + * @param username + * @param password + * @param subject + * @param htmlMessage + * @param attachment + * @throws EmailException + */ + public static Boolean sendHtmlMailWithAttachment(List toAddress, + String hostName, Integer smtpPort, String from, String username, + String password, String subject, String htmlMessage, + List attachment) { + // Create data information to compose the mail + HtmlEmail email = new HtmlEmail(); + + configureBasics(hostName, smtpPort, from, username, password, email, false); + + for (EmailAttachment attach : attachment) { + try { + email.attach(attach); + } catch (EmailException e) { + e.printStackTrace(); + } + } + + email.setSubject(subject); + try { + email.setHtmlMsg(htmlMessage); + } catch (EmailException e1) { + e1.printStackTrace(); + return false; + } + email.setSSL(true); + + // send to all mails extracted from settings + for (String add : toAddress) { + try { + email.addBcc(add); + } catch (EmailException e) { + e.printStackTrace(); + return false; + } + } + + return send(email); + } + + private static Boolean send(final Email email) { + try { + Thread t = new Thread() { + @Override + public void run() { + super.run(); + try { + email.send(); + } catch (EmailException e) { + e.printStackTrace(); + } + } + }; + + t.start(); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * Send a plain text mail + * + * @param toAddress + * @param hostName + * @param smtpPort + * @param mail + * @param username + * @param password + * @param subject + * @param htmlMessage + * @throws EmailException + */ + public static Boolean sendMail(List toAddress, String hostName, + Integer smtpPort, String from, String username, String password, + String subject, String message) { + + Email email = new SimpleEmail(); + configureBasics(hostName, smtpPort, from, username, password, email, false); + + email.setSubject(subject); + try { + email.setMsg(message); + } catch (EmailException e1) { + e1.printStackTrace(); + return false; + } + email.setSSL(true); + + // send to all mails extracted from settings + for (String add : toAddress) { + try { + email.addBcc(add); + } catch (EmailException e) { + e.printStackTrace(); + return false; + } + } + + return send(email); + } + + /** + * Create data information to compose the mail + * + * @param hostName + * @param smtpPort + * @param mail + * @param username + * @param password + * @param email + * @param ssl + */ + private static void configureBasics(String hostName, Integer smtpPort, + String from, String username, String password, Email email, Boolean ssl) { + if (hostName != null) { + email.setHostName(hostName); + } else { + throw new IllegalArgumentException( + "Missing settings in System Configuration (see Administration menu) - cannot send mail"); + } + if (smtpPort != null) { + email.setSmtpPort(smtpPort); + } else { + throw new IllegalArgumentException( + "Missing settings in System Configuration (see Administration menu) - cannot send mail"); + } + if (username != null) { + email.setAuthenticator(new DefaultAuthenticator(username, password)); + } + + if(ssl != null) { + email.setSSL(ssl); + } + if (from != null && !from.isEmpty()) { + try { + email.setFrom(from); + } catch (EmailException e) { + e.printStackTrace(); + } + } else { + throw new IllegalArgumentException( + "Missing settings in System Configuration (see Administration menu) - cannot send mail"); + } + } + + /** + * Configure the basics (hostname, port, username, password,...) + * + * @param settings + * @param email + */ + private static void configureBasics(SettingManager settings, Email email) { + String username = settings + .getValue("system/feedback/mailServer/username"); + String password = settings + .getValue("system/feedback/mailServer/password"); + Boolean ssl = settings + .getValueAsBool("system/feedback/mailServer/ssl"); + + String hostName = settings.getValue("system/feedback/mailServer/host"); + Integer smtpPort = Integer.valueOf(settings + .getValue("system/feedback/mailServer/port")); + + String from = settings.getValue("system/feedback/email"); + + configureBasics(hostName, smtpPort, from, username, password, email, ssl); + } + + public static Boolean sendMail(String email, String subject, + String message, SettingManager sm) { + List to = new ArrayList(1); + to.add(email); + return sendMail(to, subject, message, sm); + } + + public static Boolean sendHtmlMail(String email, String host, Integer port, + String from, String username, String password, String subject, + String content) { + List to = new ArrayList(1); + to.add(email); + return sendHtmlMail(to, host, port, from, username, password, subject, + content); + + } + + public static Boolean sendMail(String to, String subject, String message, + SettingManager sm, String replyTo, String replyToDescr) { + List to_ = new ArrayList(1); + to_.add(to); + return sendMail(to_, subject, message, sm, replyTo, replyToDescr); + } + + public static Boolean sendMail(String to, String hostName, + Integer smtpPort, String from, String username, String password, + String subject, String message) { + + List to_ = new ArrayList(1); + to_.add(to); + + return sendMail(to_, hostName, smtpPort, from, username, password, + subject, message); + } + +} diff --git a/core/src/test/java/org/fao/geonet/util/ISODateTest.java b/core/src/test/java/org/fao/geonet/util/ISODateTest.java new file mode 100644 index 00000000000..685d0d971e8 --- /dev/null +++ b/core/src/test/java/org/fao/geonet/util/ISODateTest.java @@ -0,0 +1,129 @@ +package org.fao.geonet.util; + +import org.fao.geonet.test.GeonetworkTestCase; + +/** + * Unit test for ISODate class. + * + * @author Jose García + */ +public class ISODateTest extends GeonetworkTestCase { + + public ISODateTest(String name) throws Exception { + super(name); + } + + public void testCreateISODateException() throws Exception { + try { + ISODate isoDate = new ISODate(null); + fail("iso date is null, IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException ex) { + + + } + + try { + ISODate isoDate = new ISODate("2001"); + fail("iso date is not valid, IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException ex) { + + } + + } + + public void testSetDateException() throws Exception { + try { + ISODate isoDate = new ISODate(); + isoDate.setDate(null); + fail("iso date is null, IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException ex) { + + + } + + try { + ISODate isoDate = new ISODate(); + isoDate.setDate("2001"); + fail("iso date is not valid, IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException ex) { + + } + + } + + public void testCreateISODateValid() throws Exception { + // Date format + ISODate isoDate = new ISODate("2013-10-10"); + assertTrue(isoDate.toString().equals("2013-10-10T00:00:00")); + + isoDate = new ISODate("2013-10-10Z"); + assertTrue(isoDate.toString().equals("2013-10-10T00:00:00")); + + // Datetime format + isoDate = new ISODate("2013-10-10T13:20:00"); + assertTrue(isoDate.toString().equals("2013-10-10T13:20:00")); + + isoDate = new ISODate("2013-10-10T13:20:00Z"); + assertTrue(isoDate.toString().equals("2013-10-10T13:20:00")); + } + + public void testSetDateISODateValid() throws Exception { + // Date format + ISODate isoDate = new ISODate(); + isoDate.setDate("2013-10-10"); + assertTrue(isoDate.toString().equals("2013-10-10T00:00:00")); + + isoDate = new ISODate(); + isoDate.setDate("2013-10-10Z"); + assertTrue(isoDate.toString().equals("2013-10-10T00:00:00")); + + // Datetime format + isoDate = new ISODate(); + isoDate.setDate("2013-10-10T13:20:00"); + assertTrue(isoDate.toString().equals("2013-10-10T13:20:00")); + + isoDate = new ISODate(); + isoDate.setDate("2013-10-10T13:20:00Z"); + assertTrue(isoDate.toString().equals("2013-10-10T13:20:00")); + + // Datetime with non UTC zone + isoDate = new ISODate(); + isoDate.setDate("2013-10-10T13:20:00+02:00"); + assertTrue(isoDate.toString().equals("2013-10-10T11:20:00")); + } + + public void testGetDate() throws Exception { + ISODate isoDate = new ISODate("2013-10-10T13:20:00Z"); + assertTrue(isoDate.getDate().equals("2013-10-10")); + } + + public void testGetTime() throws Exception { + ISODate isoDate = new ISODate("2013-10-10T13:20:00Z"); + assertTrue(isoDate.getTime().equals("13:20:00")); + } + + public void testGetSeconds() throws Exception { + ISODate isoDate = new ISODate("2013-10-10T13:20:40Z"); + + // Convert seconds to milliseconds + ISODate testDate = new ISODate(isoDate.getSeconds() * 1000); + assertTrue(isoDate.toString().equals(testDate.toString())); + } + + public void testClone() throws Exception { + ISODate isoDate = new ISODate("2013-10-10T13:20:40Z"); + ISODate clonedDate = isoDate.clone(); + + assertTrue(isoDate.toString().equals(clonedDate.toString())); + } + + public void testSub() throws Exception { + ISODate isoDate1 = new ISODate("2013-10-10T13:20:40Z"); + ISODate isoDate2 = new ISODate("2013-10-10T13:21:40Z"); + + assertTrue(isoDate2.sub(isoDate1) == 60); + + isoDate2 = new ISODate("2013-10-10T13:19:40Z"); + assertTrue(isoDate2.sub(isoDate1) == -60); + } +} diff --git a/core/src/test/java/org/fao/geonet/util/JODAISODateTest.java b/core/src/test/java/org/fao/geonet/util/JODAISODateTest.java new file mode 100644 index 00000000000..f133f0ff50c --- /dev/null +++ b/core/src/test/java/org/fao/geonet/util/JODAISODateTest.java @@ -0,0 +1,80 @@ +package org.fao.geonet.util; + +import org.fao.geonet.test.GeonetworkTestCase; + +/** + * Unit test for JODAISODate class. + * + * @author Jose García + */ +public class JODAISODateTest extends GeonetworkTestCase { + public void testParseISODateTime() throws Exception { + // Format: yyyy-mm-ddThh.mm:ss[+hh:mm|=+hh:mm] Time zone + String jodaISODate = JODAISODate + .parseISODateTime("2010-10-10T00:00:00+02:00"); + assertTrue(jodaISODate.equals("2010-10-09T22:00:00.000Z")); + + // Format: yyyy-mm-ddThh.mm:ss.ms[+hh:mm|=+hh:mm] Time zone + jodaISODate = JODAISODate + .parseISODateTime("2010-10-10T00:00:00.000+02:00"); + assertTrue(jodaISODate.equals("2010-10-09T22:00:00.000Z")); + + // Format: yyyy-mm-ddThh.mm:ssZ (UTC) + jodaISODate = JODAISODate.parseISODateTime("2010-10-10T00:00:00Z"); + assertTrue(jodaISODate.equals("2010-10-10T00:00:00.000Z")); + + // Format: yyyy-mm-ddThh.mm:ss.msZ (UTC) + jodaISODate = JODAISODate.parseISODateTime("2010-10-10T00:00:00.000Z"); + assertTrue(jodaISODate.equals("2010-10-10T00:00:00.000Z")); + } + + public void testParsegYearMonthDateTime() throws Exception { + // xs:gYearMonth + for (int i = 0; i < 10; i++) { + String year = "20" + getRandom(1, 0) + getRandom(9, 0); + String month = "0" + getRandom(9, 1); + String hour = getRandom(1, 0) + "" + getRandom(9, 0); + String minutes = getRandom(5, 1) + "" + getRandom(9, 0); + + // Format: yyyy-MM-hh:mm Time zone + String tmp = year + "-" + month + "-" + hour + ":" + minutes + "Z"; + String jodaISODate = JODAISODate.parseISODateTime(tmp); + assertEquals(jodaISODate, year + "-" + month + "-01T" + hour + ":" + + minutes + ":00.000Z"); + + year = "20" + getRandom(1, 0) + getRandom(9, 0); + month = "0" + getRandom(9, 1); + // Format: yyyy-MM + tmp = year + "-" + month; + jodaISODate = JODAISODate.parseISODateTime(tmp); + assertEquals(jodaISODate, tmp + "-01T00:00:00.000Z"); + + } + } + + public void testParsegYearDateTime() throws Exception { + // xs:gYear + for (int i = 0; i < 10; i++) { + String year = "20" + getRandom(1, 0) + getRandom(9, 0); + String hour = getRandom(1, 0) + "" + getRandom(9, 0); + String minutes = getRandom(5, 1) + "" + getRandom(9, 0); + + // Format: yyyy-hh:mm Time zone + String jodaISODate = JODAISODate.parseISODateTime(year + "-" + hour + + ":" + minutes + "Z"); + assertEquals(jodaISODate, year + "-01-01T" + hour + ":" + minutes + + ":00.000Z"); + + year = "20" + getRandom(1, 0) + getRandom(9, 0); + + // Format: yyyy + jodaISODate = JODAISODate.parseISODateTime(year); + assertEquals(jodaISODate, year + "-01-01T00:00:00.000Z"); + } + } + + private String getRandom(int max, int min) { + return Integer + .toString(min + (int) (Math.random() * ((max - min) + 1))); + } +} diff --git a/docs/eng/developer/source/development/index.rst b/docs/eng/developer/source/development/index.rst index 3d996d72ed2..630c4e179ff 100644 --- a/docs/eng/developer/source/development/index.rst +++ b/docs/eng/developer/source/development/index.rst @@ -60,6 +60,16 @@ The following tools are required to be installed to setup a development environm - **Sphinx** - To create the GeoNetwork documentation in a nice format `Sphinx `_ is used. +- **Python and closure** - To build Javascript:: + + cd /path/to/closure-library-parent-dir + git clone http://code.google.com/p/closure-library/ + cd closure-library + wget http://closure-compiler.googlecode.com/files/compiler-latest.zip + unzip compiler-latest.zip + + + Check out source code --------------------- @@ -115,31 +125,38 @@ Build GeoNetwork Once you checked out the code from Github repository, go inside the GeoNetwork’s root folder and execute the maven build command:: - $ mvn clean install + $ mvn clean install -Dclosure.path=/path/to/closure-library + If the build is succesful you'll get an output like:: + + [INFO] + [INFO] ------------------------------------------------------------------------ + [INFO] Reactor Summary: + [INFO] ------------------------------------------------------------------------ + [INFO] GeoNetwork opensource ................................. SUCCESS [1.345s] + [INFO] Caching xslt module ................................... SUCCESS [1.126s] + [INFO] Jeeves modules ........................................ SUCCESS [3.970s] + [INFO] ArcSDE module (dummy-api) ............................. SUCCESS [0.566s] + [INFO] GeoNetwork web client module .......................... SUCCESS [23.084s] + [INFO] GeoNetwork user interface module ...................... SUCCESS [15.940s] + [INFO] Oaipmh modules ........................................ SUCCESS [1.029s] + [INFO] GeoNetwork domain ..................................... SUCCESS [0.808s] + [INFO] GeoNetwork core ....................................... SUCCESS [6.426s] + [INFO] GeoNetwork CSW server ................................. SUCCESS [2.050s] + [INFO] GeoNetwork health monitor ............................. SUCCESS [1.014s] + [INFO] GeoNetwork harvesters ................................. SUCCESS [2.583s] + [INFO] GeoNetwork services ................................... SUCCESS [3.178s] + [INFO] GeoNetwork Web module ................................. SUCCESS [2:31.387s] + [INFO] ------------------------------------------------------------------------ + [INFO] ------------------------------------------------------------------------ + [INFO] BUILD SUCCESSFUL + [INFO] ------------------------------------------------------------------------ + [INFO] Total time: 3 minutes 35 seconds + [INFO] Finished at: Sun Oct 27 16:21:46 CET 2013 + - [INFO] - [INFO] ------------------------------------------------------------------------ - [INFO] Reactor Summary: - [INFO] ------------------------------------------------------------------------ - [INFO] GeoNetwork opensource ................................. SUCCESS [1.825s] - [INFO] Caching xslt module ................................... SUCCESS [1.579s] - [INFO] Jeeves modules ........................................ SUCCESS [1.140s] - [INFO] Oaipmh modules ........................................ SUCCESS [0.477s] - [INFO] ArcSDE module (dummy-api) ............................. SUCCESS [0.503s] - [INFO] GeoNetwork Web module ................................. SUCCESS [31.758s] - [INFO] GeoServer module ...................................... SUCCESS [16.510s] - [INFO] Gast module ........................................... SUCCESS [24.961s] - [INFO] ------------------------------------------------------------------------ - [INFO] ------------------------------------------------------------------------ - [INFO] BUILD SUCCESSFUL - [INFO] ------------------------------------------------------------------------ - [INFO] Total time: 1 minute 19 seconds - [INFO] Finished at: Tue Aug 03 16:49:15 CEST 2010 - [INFO] Final Memory: 79M/123M - [INFO] ------------------------------------------------------------------------ and your local maven repository should contain the GeoNetwork artifacts created (``$HOME/.m2/repository/org/geonetwork-opensource``). diff --git a/docs/eng/users/source/admin/gast/gast-main.png b/docs/eng/users/source/admin/gast/gast-main.png deleted file mode 100644 index b93388cf554..00000000000 Binary files a/docs/eng/users/source/admin/gast/gast-main.png and /dev/null differ diff --git a/docs/eng/users/source/admin/gast/gast-mef-export.png b/docs/eng/users/source/admin/gast/gast-mef-export.png deleted file mode 100644 index bda91763e2d..00000000000 Binary files a/docs/eng/users/source/admin/gast/gast-mef-export.png and /dev/null differ diff --git a/docs/eng/users/source/admin/gast/gast-mef-import.png b/docs/eng/users/source/admin/gast/gast-mef-import.png deleted file mode 100644 index e514f3349d3..00000000000 Binary files a/docs/eng/users/source/admin/gast/gast-mef-import.png and /dev/null differ diff --git a/docs/eng/users/source/admin/gast/gast-options.png b/docs/eng/users/source/admin/gast/gast-options.png deleted file mode 100644 index a66361a3d3b..00000000000 Binary files a/docs/eng/users/source/admin/gast/gast-options.png and /dev/null differ diff --git a/docs/eng/users/source/admin/gast/icons/launch.png b/docs/eng/users/source/admin/gast/icons/launch.png deleted file mode 100644 index 1e440e81a38..00000000000 Binary files a/docs/eng/users/source/admin/gast/icons/launch.png and /dev/null differ diff --git a/docs/eng/users/source/admin/gast/icons/reload.png b/docs/eng/users/source/admin/gast/icons/reload.png deleted file mode 100644 index db91c4c48c8..00000000000 Binary files a/docs/eng/users/source/admin/gast/icons/reload.png and /dev/null differ diff --git a/docs/eng/users/source/admin/gast/icons/stop.png b/docs/eng/users/source/admin/gast/icons/stop.png deleted file mode 100644 index 33dc9575a4a..00000000000 Binary files a/docs/eng/users/source/admin/gast/icons/stop.png and /dev/null differ diff --git a/docs/eng/users/source/admin/gast/index.rst b/docs/eng/users/source/admin/gast/index.rst deleted file mode 100644 index 6e814f9b116..00000000000 --- a/docs/eng/users/source/admin/gast/index.rst +++ /dev/null @@ -1,28 +0,0 @@ -.. _gast: - -GeoNetwork’s Administrator Survival Tool - GAST -############################################### - -What is GAST? -============= - -GAST used to stand for the GeoNetwork’s Administrator Survival Tool. However, most of the functions that used to be in GAST have moved into the 'Administration' page of the GeoNetwork web application. One function that is left to GAST is to provide a graphical user interface for configuring the basic JDBC database settings (see :ref:`basic_database_config`) used by GeoNetwork. - -Starting GAST -============= - -GAST is an optional component that can be chosen for installation in the GeoNetwork installer. See :ref:`installing`. - -On Windows computers, simply select the Start GAST option under the GeoNetwork opensource program group under :menuselection:`Start --> Programs --> GeoNetwork opensource` - -Other options to start GAST are either to use a Java command **from a terminal window** or just click on the GAST jar icon. To issue the Java command you have to: - -#. change directory to the GeoNetwork installation folder - -#. issue the command ``java -jar gast/gast.jar`` - -GAST will be in current system language if any translation is available. If you want to force GAST GUI language, you could start GAST using the -Duser.language option (e.g. ``./gast.sh -Duser.language=fr or java -Duser.language=fr -jar gast/gast.jar``). - -You can also open the GeoNetwork installation folder, go to the gast folder and double click on the gast.jar file. If you have Java installed, GAST should start in a few seconds. - -To run, GAST requires Java 1.5 or 1.6. It will not work on Java 1.4. diff --git a/docs/eng/users/source/quickstartguide/installing/index.rst b/docs/eng/users/source/quickstartguide/installing/index.rst index f7e411a1dd6..3b9b91cc888 100644 --- a/docs/eng/users/source/quickstartguide/installing/index.rst +++ b/docs/eng/users/source/quickstartguide/installing/index.rst @@ -54,7 +54,7 @@ On Windows If you use Windows, the following steps will guide you to complete the installation (other FOSS will follow): 1. Double click on **geonetwork-install-2.8.0.exe** to start the GeoNetwork opensource desktop installer -2. Follow the instructions on screen. You can choose to install the embedded map server (based on `GeoServer `_, GAST and the European Union Inspire Directive configuration pack. Developers may be interested in installing the source code and installer building tools. Full source code can be found in the GeoNetwork github code repository at http://github.com/geonetwork. +2. Follow the instructions on screen. You can choose to install the embedded map server (based on `GeoServer `_ and the European Union Inspire Directive configuration pack. Developers may be interested in installing the source code and installer building tools. Full source code can be found in the GeoNetwork github code repository at http://github.com/geonetwork. 3. After completion of the installation process, a 'GeoNetwork desktop' menu will be added to your Windows Start menu under 'Programs' 4. Click Start\>Programs\>GeoNetwork desktop\>Start server to start the Geonetwork opensource Web server. The first time you do this, the system will require about 1 minute to complete startup. 5. Click Start\>Programs\>Geonetwork desktop\>Open GeoNetwork opensource to start using GeoNetwork opensource, or connect your Web browser to `http://localhost:8080/geonetwork/ `_ @@ -78,8 +78,6 @@ The installer allows to install these additional packages: - INSPIRE search panel. - INSPIRE metadata view. -4. GAST: Installs GeoNetwork's Administrator Survival Tool. See :ref:`gast`. - Installation using the platform independent installer ````````````````````````````````````````````````````` @@ -107,15 +105,12 @@ To run the installation from the commandline, issue the following command in a t Try to add to selection [Name: Core and Index: 0] Try to add to selection [Name: GeoServer and Index: 1] Try to add to selection [Name: European Union INSPIRE Directive configuration pack and Index: 2] - Try to add to selection [Name: GAST and Index: 3] Modify pack selection. Pack [Name: European Union INSPIRE Directive configuration pack and Index: 2] added to selection. - Pack [Name: GAST and Index: 3] added to selection. [ Starting to unpack ] - [ Processing package: Core (1/4) ] - [ Processing package: GeoServer (2/4) ] - [ Processing package: European Union INSPIRE Directive configuration pack (3/4) ] - [ Processing package: GAST (4/4) ] + [ Processing package: Core (1/3) ] + [ Processing package: GeoServer (2/3) ] + [ Processing package: European Union INSPIRE Directive configuration pack (3/3) ] [ Unpacking finished ] [ Creating shortcuts ....... done. ] [ Add shortcuts to uninstaller done. ] @@ -239,9 +234,7 @@ For the Apache DBCP pool, JDBC database driver jar files should be in **INSTALL_ Specify configuration in GeoNetwork ``````````````````````````````````` -GAST provides a graphical user interface to make database configuration easy. You can find out how to do this in the GAST section of the manual: :ref:`gast`. - -Alternatively you can manually configure the database by editing **INSTALL_DIR/WEB-INF/config.xml**. In the resources element of this file, you will find a resource element for each database that GeoNetwork supports. Only one of these resource elements can be enabled. The following is an example for the default H2 database used by GeoNetwork:: +You can manually configure the database by editing **INSTALL_DIR/WEB-INF/config.xml**. In the resources element of this file, you will find a resource element for each database that GeoNetwork supports. Only one of these resource elements can be enabled. The following is an example for the default H2 database used by GeoNetwork:: main-db diff --git a/docs/fra/users/source/preface/preface.rst b/docs/fra/users/source/preface/preface.rst index d4a242268ee..98d0347cf80 100644 --- a/docs/fra/users/source/preface/preface.rst +++ b/docs/fra/users/source/preface/preface.rst @@ -207,12 +207,13 @@ Le comité de pilotage est actuellement composé des personnes suivantes : Contributeurs anciens et actuels -------------------------------- -Les développeurs actifs sur le trunk sont les suivants : +Les committers sur le trunk sont les suivants : +- María Arias de Reyna - Mathieu Coudert - Heikki Doeleman -- Jose Garcia - Jesse Eichar +- Jose Garcia - Roberto Giaccio - Simon Pigot - Francois Prunayre diff --git a/docs/lyx/admin-guide/images/gast-main.png b/docs/lyx/admin-guide/images/gast-main.png deleted file mode 100644 index b93388cf554..00000000000 Binary files a/docs/lyx/admin-guide/images/gast-main.png and /dev/null differ diff --git a/docs/lyx/admin-guide/images/gast-mef-export.png b/docs/lyx/admin-guide/images/gast-mef-export.png deleted file mode 100644 index bda91763e2d..00000000000 Binary files a/docs/lyx/admin-guide/images/gast-mef-export.png and /dev/null differ diff --git a/docs/lyx/admin-guide/images/gast-mef-import.png b/docs/lyx/admin-guide/images/gast-mef-import.png deleted file mode 100644 index e514f3349d3..00000000000 Binary files a/docs/lyx/admin-guide/images/gast-mef-import.png and /dev/null differ diff --git a/docs/lyx/admin-guide/images/gast-options.png b/docs/lyx/admin-guide/images/gast-options.png deleted file mode 100644 index a66361a3d3b..00000000000 Binary files a/docs/lyx/admin-guide/images/gast-options.png and /dev/null differ diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/BaseAligner.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/BaseAligner.java index 72e0b9caf06..a41ca3c481b 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/BaseAligner.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/BaseAligner.java @@ -3,12 +3,22 @@ import jeeves.interfaces.Logger; import jeeves.resources.dbms.Dbms; import jeeves.server.context.ServiceContext; + import org.fao.geonet.kernel.DataManager; +import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.CategoryMapper; import org.fao.geonet.kernel.harvest.harvester.GroupMapper; import org.fao.geonet.kernel.harvest.harvester.Privileges; /** + * + * This class helps {@link AbstractHarvester} instances to + * process all metadata collected on the harvest. + * + * Takes care of common properties like categories or privileges. + * + * Not all harvesters use this. They should. But don't. //FIXME? + * * @author heikki doeleman */ public abstract class BaseAligner { @@ -25,7 +35,7 @@ public abstract class BaseAligner { * @param log * @throws Exception */ - protected void addCategories(String id, Iterable categories, CategoryMapper localCateg, DataManager dataMan, Dbms dbms, ServiceContext context, Logger log, String serverCategory) throws Exception { + public void addCategories(String id, Iterable categories, CategoryMapper localCateg, DataManager dataMan, Dbms dbms, ServiceContext context, Logger log, String serverCategory) throws Exception { for(String catId : categories) { String name = localCateg.getName(catId); @@ -64,7 +74,7 @@ protected void addCategories(String id, Iterable categories, CategoryMap * @param log * @throws Exception */ - protected void addPrivileges(String id, Iterable privilegesIterable, GroupMapper localGroups, DataManager dataMan, ServiceContext context, Dbms dbms, Logger log) throws Exception { + public void addPrivileges(String id, Iterable privilegesIterable, GroupMapper localGroups, DataManager dataMan, ServiceContext context, Dbms dbms, Logger log) throws Exception { for (Privileges priv : privilegesIterable) { String name = localGroups.getName(priv.getGroupId()); diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/HarvestManager.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/HarvestManager.java index 190497a04ef..f922eaca92e 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/HarvestManager.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/HarvestManager.java @@ -50,7 +50,7 @@ import org.fao.geonet.kernel.harvest.harvester.HarversterJobListener; import org.fao.geonet.kernel.harvest.harvester.HarvesterHistoryDao; import org.fao.geonet.kernel.setting.HarvesterSettingsManager; -import org.fao.geonet.kernel.setting.SettingManager; +import org.fao.geonet.util.ISODate; import org.jdom.Element; import org.quartz.SchedulerException; @@ -98,6 +98,7 @@ public HarvestManager(ServiceContext context, GeonetContext gc, HarvesterSetting ah.init(node); hmHarvesters.put(ah.getID(), ah); hmHarvestLookup.put(ah.getParams().uuid, ah); + ah.initializeLog(); } } @@ -513,6 +514,44 @@ public AbstractHarvester getHarvester(String harvestUuid) { return hmHarvestLookup.get(harvestUuid); } + /** + * Remove all metadata associated to one harvester + * @param dbms to connect + * @param id of the harvester + * @return + * @throws Exception + */ + public synchronized OperResult clearBatch(Dbms dbms, String id) throws Exception + { + if(Log.isDebugEnabled(Geonet.HARVEST_MAN)) + Log.debug(Geonet.HARVEST_MAN, "Clearing harvesting with id : "+ id); + + AbstractHarvester ah = hmHarvesters.get(id); + + if (ah == null) + return OperResult.NOT_FOUND; + + long elapsedTime = System.currentTimeMillis(); + + String id_ = ah.getParams().uuid; + + dataMan.deleteBatchMetadata(context, dbms, id_); + + elapsedTime = (System.currentTimeMillis() - elapsedTime) / 1000; + System.out.println("Time: " + elapsedTime); + + Element history = new Element("result"); + history.addContent(new Element("cleared")); + String lastRun = new ISODate(System.currentTimeMillis()).toString(); + HarvesterHistoryDao.write(dbms, context.getSerialFactory(), + ah.getType(), ah.getParams().name, ah.getParams().uuid, + elapsedTime, + lastRun, ah.getParams().node, history); + + + return OperResult.OK; + } + //--------------------------------------------------------------------------- //--- //--- Private methods diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/AbstractHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/AbstractHarvester.java index a3f634bd7cf..373bbb517a6 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/AbstractHarvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/AbstractHarvester.java @@ -23,6 +23,19 @@ package org.fao.geonet.kernel.harvest.harvester; +import static org.quartz.JobKey.jobKey; + +import java.io.File; +import java.lang.reflect.Method; +import java.sql.SQLException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + import jeeves.exceptions.BadInputEx; import jeeves.exceptions.BadParameterEx; import jeeves.exceptions.JeevesException; @@ -35,11 +48,15 @@ import jeeves.server.resources.ResourceManager; import jeeves.utils.Log; import jeeves.utils.QuartzSchedulerUtils; + import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.time.StopWatch; +import org.apache.log4j.DailyRollingFileAppender; +import org.apache.log4j.PatternLayout; import org.fao.geonet.constants.Geonet; +import org.fao.geonet.csw.common.exceptions.InvalidParameterValueEx; import org.fao.geonet.kernel.DataManager; import org.fao.geonet.kernel.MetadataIndexerProcessor; -import org.fao.geonet.kernel.harvest.BaseAligner; import org.fao.geonet.kernel.harvest.Common.OperResult; import org.fao.geonet.kernel.harvest.Common.Status; import org.fao.geonet.kernel.harvest.harvester.arcsde.ArcSDEHarvester; @@ -59,6 +76,7 @@ import org.fao.geonet.lib.Lib; import org.fao.geonet.monitor.harvest.AbstractHarvesterErrorCounter; import org.fao.geonet.resources.Resources; +import org.fao.geonet.services.harvesting.notifier.SendNotification; import org.jdom.Element; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; @@ -67,20 +85,12 @@ import org.quartz.SchedulerException; import org.quartz.Trigger; -import java.io.File; -import java.lang.reflect.Method; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.Map; - -import static org.quartz.JobKey.jobKey; - /** - * TODO javadoc. + * Represents a harvester job. Used to launch harvester workers. * */ -public abstract class AbstractHarvester extends BaseAligner { - +public abstract class AbstractHarvester { + private static final String SCHEDULER_ID = "abstractHarvester"; public static final String HARVESTER_GROUP_NAME = "HARVESTER_GROUP_NAME"; @@ -91,7 +101,7 @@ public abstract class AbstractHarvester extends BaseAligner { //--------------------------------------------------------------------------- /** - * TODO Javadoc. + * Adds all AbstractHarvester instances * * @param context * @throws Exception @@ -114,7 +124,7 @@ public static void staticInit(ServiceContext context) throws Exception { } /** - * TODO Javadoc. + * Register one instance of {@link AbstractHarvester} on the singleton. * * @param context * @param harvester @@ -124,7 +134,7 @@ private static void register(ServiceContext context, Class harvester) throws try { Method initMethod = harvester.getMethod("init", context.getClass()); initMethod.invoke(null, context); - AbstractHarvester ah = (AbstractHarvester) harvester.newInstance(); + AbstractHarvester ah = (AbstractHarvester) harvester.newInstance(); hsHarvesters.put(ah.getType(), harvester); } catch(Exception e) { @@ -143,7 +153,7 @@ private static void register(ServiceContext context, Class harvester) throws * @throws BadParameterEx * @throws OperationAbortedEx */ - public static AbstractHarvester create(String type, ServiceContext context, HarvesterSettingsManager sm, DataManager dm) throws BadParameterEx, OperationAbortedEx { + public static AbstractHarvester create(String type, ServiceContext context, HarvesterSettingsManager sm, DataManager dm) throws BadParameterEx, OperationAbortedEx { //--- raises an exception if type is null if (type == null) { throw new BadParameterEx("type", null); @@ -156,7 +166,7 @@ public static AbstractHarvester create(String type, ServiceContext context, Harv } try { - AbstractHarvester ah = (AbstractHarvester) c.newInstance(); + AbstractHarvester ah = (AbstractHarvester) c.newInstance(); ah.context = context; ah.settingMan = sm; @@ -168,6 +178,45 @@ public static AbstractHarvester create(String type, ServiceContext context, Harv } } + /** + * For the log name + */ + private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm"); + + public String initializeLog() { + + // configure personalized logger + String packagename = getClass().getPackage().getName(); + String[] packages = packagename.split("\\."); + String packageType = packages[packages.length - 1]; + log = Log.createLogger(this.getParams().name, + "geonetwork.harvester"); + + String directory = log.getFileAppender(); + if(directory.isEmpty()) { + directory = "./"; + } + File d = new File(directory); + if (!d.isDirectory()) { + directory = d.getParent() + File.separator; + } + + DailyRollingFileAppender fa = new DailyRollingFileAppender(); + fa.setName(this.getParams().name); + String logfile = directory + "harvester_" + packageType + "_" + + this.getParams().name + "_" + + dateFormat.format(new Date(System.currentTimeMillis())) + + ".log"; + fa.setFile(logfile); + fa.setLayout(new PatternLayout("%d{ISO8601} %-5p [%c] - %m%n")); + fa.setThreshold(log.getThreshold()); + fa.setAppend(true); + fa.activateOptions(); + + log.setAppender(fa); + + return logfile; + } //-------------------------------------------------------------------------- //--- //--- API methods @@ -347,7 +396,7 @@ public synchronized OperResult invoke(ResourceManager rm) { try { status = Status.ACTIVE; log.info("Started harvesting from node : " + nodeName); - doHarvest(log, rm); + doHarvest_(log, rm); log.info("Ended harvesting from node : " + nodeName); rm.close(); } @@ -464,7 +513,7 @@ public HarvestWithIndexProcessor(DataManager dm, Logger logger, ResourceManager */ @Override public void process() throws Exception { - doHarvest(logger, rm); + doHarvest_(logger, rm); } } @@ -511,8 +560,11 @@ private void login() throws Exception { void harvest() { running = true; long startTime = System.currentTimeMillis(); + String logfile = initializeLog(); + this.log.info("Starting harvesting of " + this.getParams().name); try { error = null; + errors.clear(); ResourceManager rm = new ResourceManager(context.getMonitorManager(), context.getProviderManager()); Logger logger = Log.createLogger(Geonet.HARVESTER); String lastRun = new DateTime().withZone(DateTimeZone.forID("UTC")).toString(); @@ -535,11 +587,26 @@ void harvest() { stop(dbms); } rm.close(); - } + } catch (InvalidParameterValueEx e) { + logger.error("The harvester " + this.getParams().name + "[" + + this.getType() + + "] didn't accept some of the parameters sent."); + + errors.add(new HarvestError(e, logger)); + error = e; + + try { + rm.abort(); + } catch (Exception ex) { + logger.fatal("CANNOT ABORT EXCEPTION"); + logger.fatal(" (C) Exc : " + ex.getMessage()); + } + } catch(Throwable t) { logger.warning("Raised exception while harvesting from : "+ nodeName); logger.warning(" (C) Class : "+ t.getClass().getSimpleName()); logger.warning(" (C) Message : "+ t.getMessage()); + errors.add(new HarvestError(t, logger)); error = t; t.printStackTrace(); try { @@ -549,6 +616,11 @@ void harvest() { logger.warning("CANNOT ABORT EXCEPTION"); logger.warning(" (C) Exc : "+ ex); } + } finally { + List harvesterErrors = getErrors(); + if (harvesterErrors != null) { + errors.addAll(harvesterErrors); + } } long elapsedTime = (System.currentTimeMillis() - startTime) / 1000; @@ -556,40 +628,98 @@ void harvest() { Dbms dbms = null; try { dbms = (Dbms) rm.openDirect(Geonet.Res.MAIN_DB); - Element result = getResult(); - if (error != null) result = JeevesException.toElement(error); + Element result = getResult(); + if (error != null) { + result = JeevesException.toElement(error); + } + Element logfile_ = new Element("logfile"); + logfile_.setText(logfile); + result.addContent(logfile_); + + result.addContent(toElement(errors)); + HarvesterHistoryDao.write(dbms, context.getSerialFactory(), getType(), getParams().name, getParams().uuid, elapsedTime, lastRun, getParams().node, result); + + //Send notification email, if needed + try { + SendNotification.process(context, HarvesterHistoryDao.retrieve(dbms, getParams().uuid), this); + } catch (Exception e) { + logger.error("Raised exception while attempting to send email"); + logger.error(" (C) Exc : "+ e); + e.printStackTrace(); + } finally { + try { + if (dbms != null) + rm.close(Geonet.Res.MAIN_DB, dbms); + + } catch (Exception dbe) { + dbe.printStackTrace(); + logger.error("Raised exception while attempting to close dbms connection to harvest history table"); + logger.error(" (C) Exc : " + dbe); + } } + + } catch (Exception e) { logger.warning("Raised exception while attempting to store harvest history from : "+ nodeName); e.printStackTrace(); logger.warning(" (C) Exc : "+ e); } finally { - try { - if (dbms != null) { - rm.close(Geonet.Res.MAIN_DB, dbms); - } - } - catch (Exception dbe) { - dbe.printStackTrace(); - logger.error("Raised exception while attempting to close dbms connection to harvest history table"); - logger.error(" (C) Exc : "+ dbe); - } } + + } finally { running = false; } } - + /** + * Convert {@link HarvestError} to an element that can be saved on the + * database + * + * @param errors + * @return + */ + private Element toElement(List errors) { + Element res = new Element("errors"); + for (HarvestError error : errors) { + Element herror = new Element("error"); + + Element desc = new Element("description"); + desc.setText(error.getDescription()); + herror.addContent(desc); + + Element hint = new Element("hint"); + hint.setText(error.getHint()); + herror.addContent(hint); + + herror.addContent(JeevesException.toElement(error.getOrigin())); + res.addContent(herror); + } + return res; + } //--------------------------------------------------------------------------- //--- //--- Abstract methods that must be overridden //--- //--------------------------------------------------------------------------- - + /** + * Should be overriden to get a better insight on harvesting + * + * Returns the list of exceptions that ocurred during the harvesting but + * didn't really stop and abort the harvest. + * + * @return + */ + protected List getErrors() { + if (h != null) { + return h.getErrors(); + } else { + return new LinkedList(); + } + } /** * * @return @@ -666,12 +796,25 @@ protected void doAddInfo(Element node) { } /** + * + * Extend to do the actual harvesting. * * @param l * @param rm * @throws Exception */ protected abstract void doHarvest(Logger l, ResourceManager rm) throws Exception; + + /** + * Outer function to get the execution time and common code. + * @param log + * @param rm + * @throws Exception + */ + protected void doHarvest_(Logger log, ResourceManager rm) throws Exception + { + doHarvest(log, rm); + } //--------------------------------------------------------------------------- //--- @@ -851,16 +994,51 @@ protected Element getResult() { } return res; } + + /** + * Get the list of registered harvester + * @return + */ + public static Set getHarvesterTypes() { + return hsHarvesters.keySet(); + } + + /** + * + * Who should we notify by default? + * + * @return + * @throws Exception + */ + public String getOwnerEmail() throws Exception { + String ownerId = getParams().ownerIdGroup; + + Dbms dbms = (Dbms) context.getResourceManager() + .open(Geonet.Res.MAIN_DB); + + Element e = dbms.select("SELECT email FROM Groups WHERE id = " + ownerId); + + e = e.getChild("record"); + e = e.getChild("email"); + + return e.getTextTrim(); + } + //-------------------------------------------------------------------------- //--- //--- Variables //--- //-------------------------------------------------------------------------- - private String id; private volatile Status status; - + /** + * Exception that aborted the harvesting + */ private Throwable error; + /** + * Contains all the warnings and errors that didn't abort the execution, but were thrown during harvesting + */ + private List errors = new LinkedList(); private boolean running = false; protected ServiceContext context; @@ -868,10 +1046,11 @@ protected Element getResult() { protected DataManager dataMan; protected AbstractParams params; - protected HarvestResult result; + protected T result; protected Logger log = Log.createLogger(Geonet.HARVESTER); private static Map> hsHarvesters = new HashMap>(); + protected IHarvester h = null; } \ No newline at end of file diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/AbstractParams.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/AbstractParams.java index d0baea9bd69..0a3e83fb2a6 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/AbstractParams.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/AbstractParams.java @@ -45,7 +45,8 @@ import static org.quartz.JobBuilder.newJob; /** - * TODO javadoc. + * Params to configure a harvester. It contains things like + * url, username, password,... * */ public abstract class AbstractParams { diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/HarvestError.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/HarvestError.java new file mode 100644 index 00000000000..c40c2364bef --- /dev/null +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/HarvestError.java @@ -0,0 +1,280 @@ +package org.fao.geonet.kernel.harvest.harvester; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.sql.SQLException; + +import jeeves.exceptions.BadServerResponseEx; +import jeeves.exceptions.BadSoapResponseEx; +import jeeves.exceptions.BadXmlResponseEx; +import jeeves.exceptions.UserNotFoundEx; +import jeeves.interfaces.Logger; + +import org.apache.commons.httpclient.HttpException; +import org.apache.jcs.access.exception.CacheException; +import org.fao.geonet.csw.common.exceptions.InvalidParameterValueEx; +import org.fao.geonet.exceptions.NoSchemaMatchesException; +import org.fao.geonet.exceptions.SchemaMatchConflictException; +import org.jdom.JDOMException; + +/** + * + *

+ * Master class for harvesting errors. + *

+ *

+ * Example of usage: + *

+ * + * SQLException e = ...; + * HarvestError harvestError = new HarvestError(e, log); + harvestError.setDescription("Error updating the source logos from " + + params.name + ": \n" + e.getSQLState()); + harvestError.setHint("Check the original resource (" + sourceUuid + ") is correctly defined."); + this.errors.add(harvestError); + + * + * @author delawen + * + */ +public class HarvestError { + + /** + * Exception that caused the harvest error + */ + private Throwable origin = null; + + /** + * Description of the error + */ + private String description = null; + + /** + * If there is any hint on how to solve the error, this is it. + * + * Example: check the username and password + */ + private String hint = "Check with your administrator the error."; + + public HarvestError(InvalidParameterValueEx ex, Logger log) { + super(); + + this.origin = ex; + this.description = "The server didn't accept one of the parameters" + + " sent on the request.\n The parameter rejected was: " + + ex.getLocator() + " (" + ex.getMessage() + ")"; + + this.hint = "Check that geonetwork supports the exact version of" + + " the server you are trying to connect"; + printLog(log); + } + + public HarvestError(Throwable ex, Logger log) { + super(); + + this.origin = ex; + this.description = ex.getMessage(); + if(this.description.isEmpty()) { + this.description = ex.getClass().toString(); + } + // Do not print log, as it is a very generic exception + // leave it to main caller + } + public HarvestError(CacheException ex, Logger log) { + super(); + + this.origin = ex; + this.description = "Failed to update Jeeves cache: " + ex.getMessage(); + printLog(log); + } + + public HarvestError(JDOMException ex, Logger log) { + super(); + + this.origin = ex; + this.description = "There was an error processing the response. " + ex.getMessage(); + printLog(log); + } + + public HarvestError(BadServerResponseEx e, Logger log) { + super(); + + this.origin = e; + this.description = "The server returned an answer that could not be processed: " + + e.getObject(); + this.hint = "Check the harvester is correctly configured."; + printLog(log); + } + + public HarvestError(BadSoapResponseEx e, Logger log) { + super(); + + this.origin = e; + this.description = "The server returned an answer that could not be processed."; + this.hint = "Check the harvester is correctly configured."; + printLog(log); + } + + public HarvestError(HttpException e, Logger log) { + super(); + + this.origin = e; + this.description = "There was an error trying to reach some URL. " + e.getMessage(); + printLog(log); + } + + public HarvestError(IOException e, Logger log) { + super(); + + this.origin = e; + this.description = "There was an error trying to reach an URI. " + e.getMessage(); + printLog(log); + } + + public HarvestError(MalformedURLException e, Logger log) { + super(); + + this.origin = e; + this.description = "There was an error trying to reach an URL. "; + this.hint = "Check the configuration of the harvest."; + printLog(log); + } + + public HarvestError(UnsupportedEncodingException e, Logger log) { + super(); + + this.origin = e; + this.description = "The metadata is defined on an unsupported encoding: " + + e.getMessage(); + this.hint = "Check with your administrator the encoding error."; + printLog(log); + } + + public HarvestError(java.text.ParseException e, Logger log) { + super(); + + this.origin = e; + this.description = "Unable to parse the metadata."; + this.hint = "Check with your administrator about possible " + + "network errors or corrupt data on harvested server."; + printLog(log); + } + + public HarvestError(SQLException e, Logger log) { + super(); + + this.origin = e; + this.description = "There was an error while updating the database: " + + e.getSQLState(); + this.hint = "Check with your administrator that the database is not corrupted."; + printLog(log); + } + + public HarvestError(UserNotFoundEx e, Logger log) { + super(); + + this.origin = e; + this.description = "Couldn't log in to harvest using " + e.getObject(); + this.hint = "Check username and password."; + printLog(log); + } + + public HarvestError(SchemaMatchConflictException e, Logger log, String name) { + super(); + + this.origin = e; + this.description = "Couldn't match the schema for " + name; + this.hint = "Check that the schemas used are defined on geonetwork."; + printLog(log); + } + public HarvestError(SchemaMatchConflictException e, Logger log) { + super(); + + this.origin = e; + this.description = "Couldn't match the schema."; + this.hint = "Check that the schemas used are defined on geonetwork."; + printLog(log); + } + + public HarvestError(NoSchemaMatchesException e, Logger log, String name) { + super(); + + this.origin = e; + this.description = "Couldn't recognize the schema for " + name; + this.hint = "Check that the schemas used are defined on geonetwork."; + printLog(log); + } + + public HarvestError(NoSchemaMatchesException e, Logger log) { + super(); + + this.origin = e; + this.description = "Couldn't recognize the schema."; + this.hint = "Check that the schemas used are defined on geonetwork."; + printLog(log); + } + + public HarvestError(BadXmlResponseEx e, Logger log, String capabUrl) { + super(); + this.origin = e; + this.description = "The response returned from the server doesn't look like XML"; + this.hint = "Check the URL is ok: " + capabUrl; + printLog(log); + } + + public HarvestError(BadXmlResponseEx e, Logger log) { + super(); + this.origin = e; + this.description = "The response returned from the server doesn't look like XML. " + e.getMessage(); + this.hint = "Check the URL is ok."; + printLog(log); + } + + public Throwable getOrigin() { + return origin; + } + + public void setOrigin(Throwable origin) { + this.origin = origin; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getHint() { + return hint; + } + + public void setHint(String hint) { + this.hint = hint; + } + + @Override + public String toString() { + return this.origin.getClass() + "[" + this.description + " -> " + + this.hint + "]"; + } + + /** + * Generic print on log of current harvest error + * + * @param log + */ + public void printLog(Logger log) { + if (this.description != null) { + log.warning(this.description); + } + if (this.hint != null) { + log.warning(this.hint); + } + if (this.origin != null) { + log.error(this.origin); + } + } +} \ No newline at end of file diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/HarvestResult.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/HarvestResult.java index 995c9d6408f..eb09fadeea9 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/HarvestResult.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/HarvestResult.java @@ -18,7 +18,6 @@ public class HarvestResult { public int layerUsingMdUrl; // = md for data using metadata URL document if ok public int locallyRemoved; // = md removed public int recordsBuilt; - public int recordsRemoved; public int recordsUpdated; public int schemaSkipped; public int serviceRecords; // = md for services @@ -26,6 +25,7 @@ public class HarvestResult { public int subtemplatesAdded; // = subtemplates for collection datasets public int subtemplatesRemoved; // = fragments generated public int subtemplatesUpdated; + public int originalMetadata = 0; //How many metadata was returned on the call public int totalMetadata; // = md for data and service (ie. data + 1) public int unchangedMetadata; public int unknownSchema; // = md with unknown schema (should be 0 if no layer loaded using md url) @@ -34,6 +34,4 @@ public class HarvestResult { public int uuidSkipped; public int thumbnails; // = number of thumbnail generated public int thumbnailsFailed; // = number of thumbnail creation which failed - - } diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/HarvesterHistoryDao.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/HarvesterHistoryDao.java index 8957e8a6d89..3f67ba0319c 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/HarvesterHistoryDao.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/HarvesterHistoryDao.java @@ -28,6 +28,9 @@ import jeeves.utils.Xml; import org.fao.geonet.constants.Geonet; import org.jdom.Element; + +import java.io.File; +import java.io.IOException; import java.sql.SQLException; import java.util.List; @@ -134,7 +137,7 @@ public static void setDeleted(Dbms dbms, String uuid) throws SQLException { * @throws SQLException * @return number of history records deleted */ - public static int deleteHistory(Dbms dbms, Listids) throws SQLException { + public static int deleteHistory(Dbms dbms, Listids, List files) throws SQLException { int nrRecs = 0; for (Element id : ids) { @@ -143,6 +146,22 @@ public static int deleteHistory(Dbms dbms, Listids) throws SQLException nrRecs++; dbms.commit(); } + + for(Element file : files) { + try{ + File f = new File(file.getTextTrim()); + if(f.exists() && f.canWrite()) { + if (!f.delete()) { + Log.warning(Geonet.HARVESTER, + "Removing history. Failed to delete file: " + f.getCanonicalPath()); + } + } + } + catch(Exception e){ + e.printStackTrace(); + } + } + return nrRecs; } diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/IHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/IHarvester.java new file mode 100644 index 00000000000..710f7fa822a --- /dev/null +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/IHarvester.java @@ -0,0 +1,30 @@ +package org.fao.geonet.kernel.harvest.harvester; + +import java.util.List; + +import jeeves.interfaces.Logger; + +/** + * Common interface for all Harvesters. T is the return type of the harvest + * function. + * + * @author delawen + * + */ +public interface IHarvester { + + /** + * Returns all the (important?) exceptions that were thrown during the + * execution + */ + List getErrors(); + + /** + * Actual harvest function. + * + * @return + * @throws Exception + */ + T harvest(Logger log) throws Exception; + +} diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/arcsde/ArcSDEHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/arcsde/ArcSDEHarvester.java index 7601b206af9..443d5533142 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/arcsde/ArcSDEHarvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/arcsde/ArcSDEHarvester.java @@ -29,8 +29,10 @@ import jeeves.server.resources.ResourceManager; import jeeves.utils.Log; import jeeves.utils.Xml; + import org.fao.geonet.arcgis.ArcSDEMetadataAdapter; import org.fao.geonet.constants.Geonet; +import org.fao.geonet.kernel.harvest.BaseAligner; import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.AbstractParams; import org.fao.geonet.kernel.harvest.harvester.CategoryMapper; @@ -57,10 +59,11 @@ * @author heikki doeleman * */ -public class ArcSDEHarvester extends AbstractHarvester { +public class ArcSDEHarvester extends AbstractHarvester { private ArcSDEParams params; - private HarvestResult result; + //FIXME use custom class? + private BaseAligner aligner = new BaseAligner() {}; static final String ARCSDE_LOG_MODULE_NAME = Geonet.HARVESTER + ".arcsde"; private static final String ARC_TO_ISO19115_TRANSFORMER = "ArcCatalog8_to_ISO19115.xsl"; @@ -234,10 +237,10 @@ private void updateMetadata(Element xml, String id, Dbms dbms, GroupMapper local dataMan.updateMetadata(context, dbms, id, xml, validate, ufo, index, language, new ISODate().toString(), false); dbms.execute("DELETE FROM OperationAllowed WHERE metadataId=?", Integer.parseInt(id)); - addPrivileges(id, params.getPrivileges(), localGroups, dataMan, context, dbms, log); + aligner.addPrivileges(id, params.getPrivileges(), localGroups, dataMan, context, dbms, log); dbms.execute("DELETE FROM MetadataCateg WHERE metadataId=?", Integer.parseInt(id)); - addCategories(id, params.getCategories(), localCateg, dataMan, dbms, context, log, null); + aligner.addCategories(id, params.getCategories(), localCateg, dataMan, dbms, context, log, null); dbms.commit(); dataMan.indexMetadata(dbms, id); @@ -271,8 +274,8 @@ private String addMetadata(Element xml, String uuid, Dbms dbms, String schema, G dataMan.setTemplateExt(dbms, iId, "n", null); dataMan.setHarvestedExt(dbms, iId, source); - addPrivileges(id, params.getPrivileges(), localGroups, dataMan, context, dbms, log); - addCategories(id, params.getCategories(), localCateg, dataMan, dbms, context, log, null); + aligner.addPrivileges(id, params.getPrivileges(), localGroups, dataMan, context, dbms, log); + aligner.addCategories(id, params.getCategories(), localCateg, dataMan, dbms, context, log, null); dbms.commit(); dataMan.indexMetadata(dbms, id); diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/Aligner.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/Aligner.java index 89af815c6eb..f75c7798196 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/Aligner.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/Aligner.java @@ -45,6 +45,7 @@ import org.fao.geonet.kernel.harvest.BaseAligner; import org.fao.geonet.kernel.harvest.harvester.CategoryMapper; import org.fao.geonet.kernel.harvest.harvester.GroupMapper; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; import org.fao.geonet.kernel.harvest.harvester.RecordInfo; import org.fao.geonet.kernel.harvest.harvester.UUIDMapper; @@ -119,7 +120,7 @@ public Aligner(Logger log, ServiceContext sc, Dbms dbms, CswServer server, CswPa //--- //-------------------------------------------------------------------------- - public HarvestResult align(Set records) throws Exception + public HarvestResult align(Set records, List errors) throws Exception { log.info("Start of alignment for : "+ params.name); @@ -152,12 +153,20 @@ public HarvestResult align(Set records) throws Exception for(RecordInfo ri : records) { - result.totalMetadata++; - - String id = dataMan.getMetadataId(dbms, ri.uuid); - - if (id == null) addMetadata(ri); - else updateMetadata(ri, id); + try{ + + String id = dataMan.getMetadataId(dbms, ri.uuid); + + if (id == null) addMetadata(ri); + else updateMetadata(ri, id); + result.totalMetadata++; + }catch(Throwable t) { + errors.add(new HarvestError(t, log)); + log.error("Unable to process record from csw (" + this.params.name + ")"); + log.error(" Record failed: " + ri.uuid); + } finally { + result.originalMetadata++; + } } log.info("End of alignment for : "+ params.name); diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/CswHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/CswHarvester.java index 9fdef11377a..0b4c3c2c105 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/CswHarvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/CswHarvester.java @@ -23,26 +23,28 @@ package org.fao.geonet.kernel.harvest.harvester.csw; +import java.io.File; +import java.sql.SQLException; +import java.util.UUID; + import jeeves.exceptions.BadInputEx; import jeeves.interfaces.Logger; import jeeves.resources.dbms.Dbms; import jeeves.server.context.ServiceContext; import jeeves.server.resources.ResourceManager; + import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.AbstractParams; +import org.fao.geonet.kernel.harvest.harvester.HarvestResult; import org.fao.geonet.lib.Lib; import org.fao.geonet.resources.Resources; import org.jdom.Element; -import java.io.File; -import java.sql.SQLException; -import java.util.UUID; - /** * */ -public class CswHarvester extends AbstractHarvester { +public class CswHarvester extends AbstractHarvester { //-------------------------------------------------------------------------- //--- //--- Static init @@ -158,7 +160,9 @@ protected void storeNodeExtra(Dbms dbms, AbstractParams p, String path, String s settingMan.add(dbms, "id:"+siteId, "capabUrl", params.capabUrl); settingMan.add(dbms, "id:"+siteId, "icon", params.icon); - settingMan.add(dbms, "id:"+siteId, "rejectDuplicateResource", params.rejectDuplicateResource); + settingMan.add(dbms, "id:"+siteId, "rejectDuplicateResource", params.rejectDuplicateResource); + settingMan.add(dbms, "id:"+siteId, "queryScope", params.queryScope); + settingMan.add(dbms, "id:"+siteId, "hopCount", params.hopCount); //--- store dynamic search nodes String searchID = settingMan.add(dbms, path, "search", ""); @@ -201,7 +205,7 @@ protected void doHarvest(Logger log, ResourceManager rm) throws Exception { Dbms dbms = (Dbms) rm.open(Geonet.Res.MAIN_DB); Harvester h = new Harvester(log, context, dbms, params); - this.result = h.harvest(); + result = h.harvest(log); } //--------------------------------------------------------------------------- diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/CswParams.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/CswParams.java index fc622960edb..c1ea5eb2b65 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/CswParams.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/CswParams.java @@ -63,6 +63,8 @@ public void create(Element node) throws BadInputEx { capabUrl = Util.getParam(site, "capabilitiesUrl", ""); rejectDuplicateResource = Util.getParam(site, "rejectDuplicateResource", false); + queryScope = Util.getParam(site, "queryScope", "off"); + hopCount = Util.getParam(site, "hopCount", 2); try { capabUrl = URLDecoder.decode(capabUrl, Jeeves.ENCODING); @@ -111,6 +113,8 @@ public void update(Element node) throws BadInputEx { x.printStackTrace(); // TODO should not swallow } + queryScope = Util.getParam(site, "queryScope", queryScope); + hopCount = Util.getParam(site, "hopCount", hopCount); icon = Util.getParam(site, "icon", icon); @@ -164,6 +168,8 @@ public CswParams copy() { copy.capabUrl = capabUrl; copy.icon = icon; copy.rejectDuplicateResource = rejectDuplicateResource; + copy.queryScope = queryScope; + copy.hopCount = hopCount; for (Search s : alSearches) copy.alSearches.add(s.copy()); @@ -206,6 +212,8 @@ private void addSearches(Element searches) { public String capabUrl; public String icon; public boolean rejectDuplicateResource; + public String queryScope; + public Integer hopCount; private List alSearches = new ArrayList(); public List eltSearches = new ArrayList(); diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/Harvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/Harvester.java index 65f75ca7c66..ada2743c774 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/Harvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/csw/Harvester.java @@ -23,13 +23,23 @@ package org.fao.geonet.kernel.harvest.harvester.csw; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; + import jeeves.exceptions.BadParameterEx; +import jeeves.exceptions.BadXmlResponseEx; import jeeves.exceptions.OperationAbortedEx; import jeeves.interfaces.Logger; import jeeves.resources.dbms.Dbms; import jeeves.server.context.ServiceContext; import jeeves.utils.Xml; import jeeves.utils.XmlRequest; + import org.fao.geonet.GeonetContext; import org.fao.geonet.constants.Geonet; import org.fao.geonet.csw.common.ConstraintLanguage; @@ -43,21 +53,16 @@ import org.fao.geonet.csw.common.requests.CatalogRequest; import org.fao.geonet.csw.common.requests.GetRecordsRequest; import org.fao.geonet.kernel.DataManager; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; +import org.fao.geonet.kernel.harvest.harvester.IHarvester; import org.fao.geonet.kernel.harvest.harvester.RecordInfo; import org.fao.geonet.lib.Lib; import org.jdom.Element; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; - //============================================================================= -class Harvester +class Harvester implements IHarvester { //-------------------------------------------------------------------------- //--- @@ -79,8 +84,9 @@ public Harvester(Logger log, ServiceContext context, Dbms dbms, CswParams params //--- //--------------------------------------------------------------------------- - public HarvestResult harvest() throws Exception - { + public HarvestResult harvest(Logger log) throws Exception + { + this.log = log; log.info("Retrieving capabilities file for : "+ params.name); CswServer server = retrieveCapabilities(log); @@ -101,16 +107,34 @@ public HarvestResult harvest() throws Exception } } - records.addAll(search(server,s)); - - /* - for(Search s : params.getSearches()){ - records.addAll(search(server, s)); - }*/ + try { + records.addAll(search(server, s)); + } catch (Exception t) { + log.error("Unknown error trying to harvest"); + log.error(t.getMessage()); + log.error(t); + errors.add(new HarvestError(t, log)); + } catch (Throwable t) { + log.fatal("Something unknown and terrible happened while harvesting"); + log.fatal(t.getMessage()); + errors.add(new HarvestError(t, log)); + } - if (params.isSearchEmpty()){ - records.addAll(search(server, Search.createEmptySearch())); - } + if (params.isSearchEmpty()) { + try { + log.debug("Doing an empty search"); + records.addAll(search(server, Search.createEmptySearch())); + } catch(Exception t) { + log.error("Unknown error trying to harvest"); + log.error(t.getMessage()); + log.error(t); + errors.add(new HarvestError(t, log)); + } catch(Throwable t) { + log.fatal("Something unknown and terrible happened while harvesting"); + log.fatal(t.getMessage()); + errors.add(new HarvestError(t, log)); + } + } log.info("Total records processed in all searches :"+ records.size()); @@ -118,7 +142,7 @@ public HarvestResult harvest() throws Exception Aligner aligner = new Aligner(log, context, dbms, server, params); - return aligner.align(records); + return aligner.align(records, errors); } //--------------------------------------------------------------------------- @@ -145,23 +169,29 @@ private CswServer retrieveCapabilities(Logger log) throws Exception { if (params.useAccount) req.setCredentials(params.username, params.password); - - Element capabil = req.execute(); - - if(log.isDebugEnabled()) - log.debug("Capabilities:\n"+Xml.getString(capabil)); + CswServer server = null; + try{ + Element capabil = req.execute(); + + if(log.isDebugEnabled()) + log.debug("Capabilities:\n"+Xml.getString(capabil)); + + if (capabil.getName().equals("ExceptionReport")) + CatalogException.unmarshal(capabil); + + server = new CswServer(capabil); + + if (!checkOperation(log, server, "GetRecords")) + throw new OperationAbortedEx("GetRecords operation not found"); + + if (!checkOperation(log, server, "GetRecordById")) + throw new OperationAbortedEx("GetRecordById operation not found"); + + } catch(BadXmlResponseEx e) { + errors.add(new HarvestError(e, log, params.capabUrl)); + throw e; + } - if (capabil.getName().equals("ExceptionReport")) - CatalogException.unmarshal(capabil); - - CswServer server = new CswServer(capabil); - - if (!checkOperation(log, server, "GetRecords")) - throw new OperationAbortedEx("GetRecords operation not found"); - - if (!checkOperation(log, server, "GetRecordById")) - throw new OperationAbortedEx("GetRecordById operation not found"); - return server; } @@ -201,6 +231,8 @@ private Set search(CswServer server, Search s) throws Exception //request.setOutputSchema(OutputSchema.OGC_CORE); // Use default value request.setElementSetName(ElementSetName.SUMMARY); request.setMaxRecords(GETRECORDS_NUMBER_OF_RESULTS_PER_PAGE +""); + request.setDistribSearch(params.queryScope.equalsIgnoreCase("true")); + request.setHopCount(params.hopCount + ""); CswOperation oper = server.getOperation(CswServer.GET_RECORDS); @@ -208,11 +240,13 @@ private Set search(CswServer server, Search s) throws Exception configRequest(request, oper, server, s, PREFERRED_HTTP_METHOD); - if (params.useAccount) + if (params.useAccount) { + log.debug("Logging into server (" + params.username + ")"); request.setCredentials(params.username, params.password); - + } // Simple fallback mechanism. Try search with PREFERRED_HTTP_METHOD method, if fails change it try { + log.info("Re-trying the search with another HTTP method."); request.setStartPosition(start +""); doSearch(request, start, 1); } catch(Exception ex) { @@ -220,6 +254,7 @@ private Set search(CswServer server, Search s) throws Exception log.debug(ex.getMessage()); log.debug("Changing to CSW harvester to use " + (PREFERRED_HTTP_METHOD.equals("GET")?"POST":"GET")); } + errors.add(new HarvestError(ex, log)); configRequest(request, oper, server, s, PREFERRED_HTTP_METHOD.equals("GET")?"POST":"GET"); } @@ -250,15 +285,24 @@ private Set search(CswServer server, Search s) throws Exception List list = results.getChildren(); int counter = 0; - for (Element record :list) - { - RecordInfo recInfo= getRecordInfo((Element)record.clone()); + log.debug("Extracting all elements in the csw harvesting response"); + for (Element record :list) { + try { + RecordInfo recInfo= getRecordInfo((Element)record.clone()); - if (recInfo != null) - records.add(recInfo); + if (recInfo != null) + records.add(recInfo); - counter++; - } + counter++; + + } catch (Exception ex) { + errors.add(new HarvestError(ex, log)); + log.error("Unable to process record from csw (" + this.params.name + ")"); + log.error(" Record failed: " + counter); + log.debug(" Record: " + ((Element)record).getName()); + } + + } //--- check to see if we have to perform other searches @@ -504,6 +548,7 @@ private Element doSearch(CatalogRequest request, int start, int max) throws Exce } catch(Exception e) { + errors.add(new HarvestError(e, log)); log.warning("Raised exception when searching : "+ e); throw new OperationAbortedEx("Raised exception when searching: " + e.getMessage(), e); } @@ -564,6 +609,11 @@ private RecordInfo getRecordInfo(Element record) } + + public List getErrors() { + return errors; + } + //--------------------------------------------------------------------------- //--- //--- Variables @@ -573,11 +623,18 @@ private RecordInfo getRecordInfo(Element record) public static final String PREFERRED_HTTP_METHOD = CatalogRequest.Method.GET.toString(); private static int GETRECORDS_NUMBER_OF_RESULTS_PER_PAGE = 20; private static String CONSTRAINT_LANGUAGE_VERSION = "1.1.0"; + + //FIXME version should be parametrized private static String GETCAPABILITIES_PARAMETERS = "SERVICE=CSW&REQUEST=GetCapabilities&VERSION=2.0.2"; private Logger log; private Dbms dbms; private CswParams params; private ServiceContext context; + + /** + * Contains a list of accumulated errors during the executing of this harvest. + */ + private List errors = new LinkedList(); } //============================================================================= diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geoPREST/Aligner.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geoPREST/Aligner.java index 8821b12443c..b821ab1b836 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geoPREST/Aligner.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geoPREST/Aligner.java @@ -28,18 +28,21 @@ import jeeves.server.context.ServiceContext; import jeeves.utils.Xml; import jeeves.utils.XmlRequest; + import org.fao.geonet.GeonetContext; import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.DataManager; import org.fao.geonet.kernel.harvest.BaseAligner; import org.fao.geonet.kernel.harvest.harvester.CategoryMapper; import org.fao.geonet.kernel.harvest.harvester.GroupMapper; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; import org.fao.geonet.kernel.harvest.harvester.RecordInfo; import org.fao.geonet.kernel.harvest.harvester.UUIDMapper; import org.jdom.Element; import java.net.URL; +import java.util.List; import java.util.Set; //============================================================================= @@ -74,8 +77,8 @@ public Aligner(Logger log, ServiceContext sc, Dbms dbms, GeoPRESTParams params) //--- //-------------------------------------------------------------------------- - public HarvestResult align(Set records) throws Exception { - log.info("Start of alignment for : "+ params.name); + + public HarvestResult align(Set records, List errors) throws Exception { log.info("Start of alignment for : "+ params.name); //----------------------------------------------------------------------- //--- retrieve all local categories and groups @@ -105,12 +108,18 @@ public HarvestResult align(Set records) throws Exception { //--- insert/update new metadata for (RecordInfo ri : records) { - result.totalMetadata++; - - String id = dataMan.getMetadataId(dbms, ri.uuid); - - if (id == null) addMetadata(ri); - else updateMetadata(ri, id); + try { + String id = dataMan.getMetadataId(dbms, ri.uuid); + + if (id == null) addMetadata(ri); + else updateMetadata(ri, id); + result.totalMetadata++; + + }catch (Throwable t) { + errors.add(new HarvestError(t, log)); + log.error("Unable to process record from csw (" + this.params.name + ")"); + log.error(" Record failed: " + ri.uuid); + } } log.info("End of alignment for : "+ params.name); diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geoPREST/GeoPRESTHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geoPREST/GeoPRESTHarvester.java index 41117b4b78b..0f6f517522b 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geoPREST/GeoPRESTHarvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geoPREST/GeoPRESTHarvester.java @@ -31,6 +31,7 @@ import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.AbstractParams; +import org.fao.geonet.kernel.harvest.harvester.HarvestResult; import org.fao.geonet.lib.Lib; import org.fao.geonet.resources.Resources; import org.jdom.Element; @@ -41,7 +42,7 @@ //============================================================================= -public class GeoPRESTHarvester extends AbstractHarvester +public class GeoPRESTHarvester extends AbstractHarvester { //-------------------------------------------------------------------------- //--- @@ -160,7 +161,7 @@ protected void doHarvest(Logger log, ResourceManager rm) throws Exception Dbms dbms = (Dbms) rm.open(Geonet.Res.MAIN_DB); Harvester h = new Harvester(log, context, dbms, params); - result = h.harvest(); + result = h.harvest(log); } //--------------------------------------------------------------------------- diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geoPREST/Harvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geoPREST/Harvester.java index 63b7d282f69..6c251bdc0b2 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geoPREST/Harvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geoPREST/Harvester.java @@ -23,31 +23,41 @@ package org.fao.geonet.kernel.harvest.harvester.geoPREST; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.net.URLDecoder; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + import jeeves.constants.Jeeves; +import jeeves.exceptions.BadSoapResponseEx; +import jeeves.exceptions.BadXmlResponseEx; import jeeves.exceptions.OperationAbortedEx; import jeeves.interfaces.Logger; import jeeves.resources.dbms.Dbms; import jeeves.server.context.ServiceContext; import jeeves.utils.Xml; import jeeves.utils.XmlRequest; + import org.apache.commons.lang.StringUtils; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; +import org.fao.geonet.kernel.harvest.harvester.IHarvester; import org.fao.geonet.kernel.harvest.harvester.RecordInfo; import org.fao.geonet.util.ISODate; import org.jdom.Element; -import java.net.URL; -import java.net.URLDecoder; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; //============================================================================= -class Harvester +class Harvester implements IHarvester { //-------------------------------------------------------------------------- //--- @@ -70,20 +80,49 @@ public Harvester(Logger log, ServiceContext context, Dbms dbms, GeoPRESTParams p //--- //--------------------------------------------------------------------------- - public HarvestResult harvest() throws Exception + public HarvestResult harvest(Logger log) throws Exception { + this.log = log; //--- perform all searches XmlRequest request = new XmlRequest(new URL(params.baseUrl+"/rest/find/document")); Set records = new HashSet(); - for(Search s : params.getSearches()) - records.addAll(search(request, s)); - if (params.isSearchEmpty()) - records.addAll(search(request, Search.createEmptySearch())); + for (Search s : params.getSearches()) { + try { + records.addAll(search(request, s)); + } catch (Exception t) { + log.error("Unknown error trying to harvest"); + log.error(t.getMessage()); + t.printStackTrace(); + errors.add(new HarvestError(t, log)); + } catch (Throwable t) { + log.fatal("Something unknown and terrible happened while harvesting"); + log.fatal(t.getMessage()); + t.printStackTrace(); + errors.add(new HarvestError(t, log)); + } + } + + if (params.isSearchEmpty()) { + try { + log.debug("Doing an empty search"); + records.addAll(search(request, Search.createEmptySearch())); + } catch(Exception t) { + log.error("Unknown error trying to harvest"); + log.error(t.getMessage()); + t.printStackTrace(); + errors.add(new HarvestError(t, log)); + } catch(Throwable t) { + log.fatal("Something unknown and terrible happened while harvesting"); + log.fatal(t.getMessage()); + t.printStackTrace(); + errors.add(new HarvestError(t, log)); + } + } log.info("Total records processed in all searches :"+ records.size()); @@ -91,7 +130,7 @@ public HarvestResult harvest() throws Exception Aligner aligner = new Aligner(log, context, dbms, params); - return aligner.align(records); + return aligner.align(records, errors); } //--------------------------------------------------------------------------- @@ -138,22 +177,29 @@ private Set search(XmlRequest request, Search s) throws Exception //--------------------------------------------------------------------------- - private Element doSearch(XmlRequest request) throws Exception - { - try { - log.info("Searching on : "+ params.name); - Element response = request.execute(); - if (log.isDebugEnabled()) { - log.debug("Sent request "+request.getSentData()); - log.debug("Search results:\n"+Xml.getString(response)); - } - return response; - } catch(Exception e) { - log.warning("Raised exception when searching : "+ e); - e.printStackTrace(); - throw new OperationAbortedEx("Raised exception when searching: " + e.getMessage(), e); - } - } + private Element doSearch(XmlRequest request) throws OperationAbortedEx { + try { + log.info("Searching on : " + params.name); + Element response = request.execute(); + if (log.isDebugEnabled()) { + log.debug("Sent request " + request.getSentData()); + log.debug("Search results:\n" + Xml.getString(response)); + } + return response; + } catch (BadSoapResponseEx e) { + errors.add(new HarvestError(e, log)); + throw new OperationAbortedEx("Raised exception when searching: " + + e.getMessage(), e); + } catch (BadXmlResponseEx e) { + errors.add(new HarvestError(e, log)); + throw new OperationAbortedEx("Raised exception when searching: " + + e.getMessage(), e); + } catch (IOException e) { + errors.add(new HarvestError(e, log)); + throw new OperationAbortedEx("Raised exception when searching: " + + e.getMessage(), e); + } + } //--------------------------------------------------------------------------- @@ -187,15 +233,24 @@ private RecordInfo getRecordInfo(Element record) if (log.isDebugEnabled()) log.debug("getRecordInfo: adding "+identif+" with modification date "+modified); return new RecordInfo(identif, modified); - } catch (Exception e) { - log.warning("Skipped record not in supported format : "+ Xml.getString(record)); - e.printStackTrace(); - } + } catch (UnsupportedEncodingException e) { + HarvestError harvestError = new HarvestError(e, log); + harvestError.setDescription(harvestError.getDescription() + "\n record: " + Xml.getString(record)); + errors.add(harvestError); + } catch (ParseException e) { + HarvestError harvestError = new HarvestError(e, log); + harvestError.setDescription(harvestError.getDescription() + "\n record: " + Xml.getString(record)); + errors.add(new HarvestError(e, log)); + } // we get here if we couldn't get the UUID or date modified return null; } + + public List getErrors() { + return errors; + } //--------------------------------------------------------------------------- //--- @@ -207,8 +262,11 @@ private RecordInfo getRecordInfo(Element record) private GeoPRESTParams params; private ServiceContext context; private SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); + /** + * Contains a list of accumulated errors during the executing of this harvest. + */ + private List errors = new LinkedList(); } -//============================================================================= - +// ============================================================================= diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geonet/Aligner.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geonet/Aligner.java index 5d523efbecc..41ea2d1a7f5 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geonet/Aligner.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geonet/Aligner.java @@ -38,6 +38,7 @@ import org.fao.geonet.kernel.harvest.BaseAligner; import org.fao.geonet.kernel.harvest.harvester.CategoryMapper; import org.fao.geonet.kernel.harvest.harvester.GroupMapper; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; import org.fao.geonet.kernel.harvest.harvester.RecordInfo; import org.fao.geonet.kernel.harvest.harvester.UUIDMapper; @@ -117,7 +118,7 @@ private void setupLocEntity(List list, HashMap records) throws Exception + public HarvestResult align(Set records, List errors) throws Exception { log.info("Start of alignment for : "+ params.name); diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geonet/GeonetHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geonet/GeonetHarvester.java index 2e7838f4115..f2c56c6c300 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geonet/GeonetHarvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geonet/GeonetHarvester.java @@ -23,23 +23,26 @@ package org.fao.geonet.kernel.harvest.harvester.geonet; +import java.sql.SQLException; +import java.util.UUID; + import jeeves.exceptions.BadInputEx; import jeeves.interfaces.Logger; import jeeves.resources.dbms.Dbms; import jeeves.server.context.ServiceContext; import jeeves.server.resources.ResourceManager; + +import org.apache.commons.lang.time.StopWatch; import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.AbstractParams; +import org.fao.geonet.kernel.harvest.harvester.HarvestResult; import org.fao.geonet.lib.Lib; import org.jdom.Element; -import java.sql.SQLException; -import java.util.UUID; - //============================================================================= -public class GeonetHarvester extends AbstractHarvester +public class GeonetHarvester extends AbstractHarvester { public static final String TYPE = "geonetwork"; @@ -201,7 +204,7 @@ protected void doHarvest(Logger log, ResourceManager rm) throws Exception Dbms dbms = (Dbms) rm.open(Geonet.Res.MAIN_DB); Harvester h = new Harvester(log, context, dbms, params); - result = h.harvest(); + result = h.harvest(log); } //--------------------------------------------------------------------------- diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geonet/Harvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geonet/Harvester.java index 65cb4698272..19605b54e02 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geonet/Harvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/geonet/Harvester.java @@ -33,10 +33,13 @@ import jeeves.server.context.ServiceContext; import jeeves.utils.Xml; import jeeves.utils.XmlRequest; + import org.fao.geonet.GeonetContext; import org.fao.geonet.constants.Edit; import org.fao.geonet.constants.Geonet; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; +import org.fao.geonet.kernel.harvest.harvester.IHarvester; import org.fao.geonet.kernel.harvest.harvester.RecordInfo; import org.fao.geonet.kernel.setting.SettingManager; import org.fao.geonet.lib.Lib; @@ -49,13 +52,14 @@ import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; import java.util.Map; import java.util.Set; //============================================================================= -class Harvester -{ +class Harvester implements IHarvester { //-------------------------------------------------------------------------- //--- //--- Constructor @@ -76,8 +80,9 @@ public Harvester(Logger log, ServiceContext context, Dbms dbms, GeonetParams par //--- //-------------------------------------------------------------------------- - public HarvestResult harvest() throws Exception + public HarvestResult harvest(Logger log) throws Exception { + this.log = log; XmlRequest req = new XmlRequest(new URL(params.host)); Lib.net.setupProxy(context, req); @@ -121,18 +126,45 @@ public HarvestResult harvest() throws Exception Set records = new HashSet(); - for(Search s : params.getSearches()) - records.addAll(search(req, s)); - - if (params.isSearchEmpty()) - records.addAll(search(req, Search.createEmptySearch())); + for (Search s : params.getSearches()) { + try { + records.addAll(search(req, s)); + } catch (Exception t) { + log.error("Unknown error trying to harvest"); + log.error(t.getMessage()); + log.error(t); + errors.add(new HarvestError(t, log)); + } catch (Throwable t) { + log.fatal("Something unknown and terrible happened while harvesting"); + log.fatal(t.getMessage()); + t.printStackTrace(); + errors.add(new HarvestError(t, log)); + } + } + + if (params.isSearchEmpty()) { + try { + log.debug("Doing an empty search"); + records.addAll(search(req, Search.createEmptySearch())); + } catch (Exception t) { + log.error("Unknown error trying to harvest"); + log.error(t.getMessage()); + log.error(t); + errors.add(new HarvestError(t, log)); + } catch (Throwable t) { + log.fatal("Something unknown and terrible happened while harvesting"); + log.fatal(t.getMessage()); + t.printStackTrace(); + errors.add(new HarvestError(t, log)); + } + } log.info("Total records processed in all searches :"+ records.size()); //--- align local node Aligner aligner = new Aligner(log, context, dbms, req, params, remoteInfo); - HarvestResult result = aligner.align(records); + HarvestResult result = aligner.align(records, errors); Map sources = buildSources(remoteInfo); updateSources(dbms, records, sources); @@ -162,8 +194,9 @@ private Set search(XmlRequest request, Search s) throws OperationAbo for (Object o : doSearch(request, s).getChildren("metadata")) { - Element md = (Element) o; - Element info = md.getChild("info", Edit.NAMESPACE); + try { + Element md = (Element) o; + Element info = md.getChild("info", Edit.NAMESPACE); if (info == null) log.warning("Missing 'geonet:info' element in 'metadata' element"); @@ -176,6 +209,14 @@ private Set search(XmlRequest request, Search s) throws OperationAbo records.add(new RecordInfo(uuid, changeDate, schema, source)); } + } catch (Exception e) { + HarvestError harvestError = new HarvestError(e, log); + harvestError.setDescription("Malformed element '" + + o.toString() + "'"); + harvestError + .setHint("It seems that there was some malformed element. Check with your administrator."); + this.errors.add(harvestError); + } } log.info("Records added to result list : "+ records.size()); @@ -196,6 +237,25 @@ private Element doSearch(XmlRequest request, Search s) throws OperationAbortedEx if(log.isDebugEnabled()) log.debug("Search results:\n"+ Xml.getString(response)); return response; + } catch (BadSoapResponseEx e) { + log.warning("Raised exception when searching : " + e.getMessage()); + this.errors.add(new HarvestError(e, log)); + throw new OperationAbortedEx("Raised exception when searching", e); + } catch (BadXmlResponseEx e) { + HarvestError harvestError = new HarvestError(e, log); + harvestError.setDescription("Error while searching on " + + params.name + ". Excepted XML, returned: " + + e.getMessage()); + harvestError.setHint("Check with your administrator."); + this.errors.add(harvestError); + throw new OperationAbortedEx("Raised exception when searching", e); + } catch (IOException e) { + HarvestError harvestError = new HarvestError(e, log); + harvestError.setDescription("Error while searching on " + + params.name + ". "); + harvestError.setHint("Check with your administrator."); + this.errors.add(harvestError); + throw new OperationAbortedEx("Raised exception when searching", e); } catch(Exception e) { @@ -251,9 +311,10 @@ private void updateSources(Dbms dbms, Set records, String siteId = getSiteId(); for (String sourceUuid : sources) - if (!siteId.equals(sourceUuid)) - { - String sourceName = remoteSources.get(sourceUuid); + try { + if (!siteId.equals(sourceUuid)) + { + String sourceName = remoteSources.get(sourceUuid); if (sourceName != null) Lib.sources.retrieveLogo(context, params.host, sourceUuid); @@ -263,9 +324,25 @@ private void updateSources(Dbms dbms, Set records, Resources.copyUnknownLogo(context, sourceUuid); } - Lib.sources.update(dbms, sourceUuid, sourceName, false); - } - } + Lib.sources.update(dbms, sourceUuid, sourceName, false); + } + } catch (SQLException e) { + HarvestError harvestError = new HarvestError(e, log); + harvestError + .setDescription("Error updating the source logos from " + + params.name + ": \n" + e.getSQLState()); + harvestError.setHint("Check the original resource (" + + sourceUuid + ") is correctly defined."); + this.errors.add(harvestError); + } catch (MalformedURLException e) { + HarvestError harvestError = new HarvestError(e, log); + harvestError + .setDescription("Error retrieving the logo from url"); + harvestError.setHint("Check the original resource (" + + sourceUuid + ") is correctly defined."); + this.errors.add(harvestError); + } + } //--------------------------------------------------------------------------- @@ -282,11 +359,20 @@ private String getSiteId() //--- Variables //--- //--------------------------------------------------------------------------- - private Logger log; private Dbms dbms; private GeonetParams params; private ServiceContext context; + public List getErrors() { + return errors; + } + + + /** + * Contains a list of accumulated errors during the executing of this + * harvest. + */ + private List errors = new LinkedList(); } //============================================================================= diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/localfilesystem/LocalFilesystemHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/localfilesystem/LocalFilesystemHarvester.java index 865988c4ed3..bb61e1732e1 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/localfilesystem/LocalFilesystemHarvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/localfilesystem/LocalFilesystemHarvester.java @@ -39,6 +39,7 @@ import jeeves.utils.Xml; import org.fao.geonet.constants.Geonet; +import org.fao.geonet.kernel.harvest.BaseAligner; import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.AbstractParams; import org.fao.geonet.kernel.harvest.harvester.CategoryMapper; @@ -57,8 +58,10 @@ * @author heikki doeleman * */ -public class LocalFilesystemHarvester extends AbstractHarvester { +public class LocalFilesystemHarvester extends AbstractHarvester { + //FIXME Put on a different file? + private BaseAligner aligner = new BaseAligner() {}; private LocalFilesystemParams params; public static void init(ServiceContext context) throws Exception { @@ -253,10 +256,10 @@ private void updateMetadata(Element xml, String id, Dbms dbms, GroupMapper local dataMan.updateMetadata(context, dbms, id, xml, validate, ufo, index, language, new ISODate().toString(), false); dbms.execute("DELETE FROM OperationAllowed WHERE metadataId=?", Integer.parseInt(id)); - addPrivileges(id, params.getPrivileges(), localGroups, dataMan, context, dbms, log); + aligner.addPrivileges(id, params.getPrivileges(), localGroups, dataMan, context, dbms, log); dbms.execute("DELETE FROM MetadataCateg WHERE metadataId=?", Integer.parseInt(id)); - addCategories(id, params.getCategories(), localCateg, dataMan, dbms, context, log, null); + aligner.addCategories(id, params.getCategories(), localCateg, dataMan, dbms, context, log, null); dbms.commit(); dataMan.indexMetadata(dbms, id); @@ -291,8 +294,8 @@ private String addMetadata(Element xml, String uuid, Dbms dbms, String schema, G dataMan.setTemplateExt(dbms, iId, "n", null); dataMan.setHarvestedExt(dbms, iId, source); - addPrivileges(id, params.getPrivileges(), localGroups, dataMan, context, dbms, log); - addCategories(id, params.getCategories(), localCateg, dataMan, dbms, context, log, null); + aligner.addPrivileges(id, params.getPrivileges(), localGroups, dataMan, context, dbms, log); + aligner.addCategories(id, params.getCategories(), localCateg, dataMan, dbms, context, log, null); dbms.commit(); dataMan.indexMetadata(dbms, id); diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/oaipmh/Harvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/oaipmh/Harvester.java index 17323f59c89..da7e379c8a2 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/oaipmh/Harvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/oaipmh/Harvester.java @@ -29,13 +29,17 @@ import jeeves.server.context.ServiceContext; import jeeves.utils.Util; import jeeves.utils.Xml; + +import org.eclipse.emf.common.command.AbortExecutionException; import org.fao.geonet.GeonetContext; import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.DataManager; import org.fao.geonet.kernel.harvest.BaseAligner; import org.fao.geonet.kernel.harvest.harvester.CategoryMapper; import org.fao.geonet.kernel.harvest.harvester.GroupMapper; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; +import org.fao.geonet.kernel.harvest.harvester.IHarvester; import org.fao.geonet.kernel.harvest.harvester.UUIDMapper; import org.fao.geonet.lib.Lib; import org.fao.oaipmh.OaiPmh; @@ -51,14 +55,18 @@ import org.jdom.JDOMException; import java.io.File; +import java.net.MalformedURLException; import java.net.URL; import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; import java.util.Set; //============================================================================= -class Harvester extends BaseAligner +class Harvester extends BaseAligner implements IHarvester { + private HarvestResult result; //-------------------------------------------------------------------------- //--- //--- Constructor @@ -84,13 +92,22 @@ public Harvester(Logger log, ServiceContext context, Dbms dbms, OaiPmhParams par //--- //--------------------------------------------------------------------------- - public HarvestResult harvest() throws Exception + public HarvestResult harvest(Logger log) throws Exception { + this.log = log; + ListIdentifiersRequest req = new ListIdentifiersRequest(); req.setSchemaPath(new File(context.getAppPath() + Geonet.SchemaPath.OAI_PMH)); Transport t = req.getTransport(); - t.setUrl(new URL(params.url)); + try { + t.setUrl(new URL(params.url)); + } catch (MalformedURLException e1) { + HarvestError harvestError = new HarvestError(e1, log); + harvestError.setDescription(harvestError.getDescription() + " " + params.url); + errors.add(harvestError); + throw new AbortExecutionException(e1); + } if (params.useAccount) t.setCredentials(params.username, params.password); @@ -102,11 +119,38 @@ public HarvestResult harvest() throws Exception Set records = new HashSet(); - for(Search s : params.getSearches()) - records.addAll(search(req, s)); - - if (params.isSearchEmpty()) - records.addAll(search(req, Search.createEmptySearch())); + for (Search s : params.getSearches()) { + try { + records.addAll(search(req, s)); + } catch (Exception e) { + log.error("Unknown error trying to harvest"); + log.error(e.getMessage()); + e.printStackTrace(); + errors.add(new HarvestError(e, log)); + } catch (Throwable e) { + log.fatal("Something unknown and terrible happened while harvesting"); + log.fatal(e.getMessage()); + e.printStackTrace(); + errors.add(new HarvestError(e, log)); + } + } + + if (params.isSearchEmpty()) { + try { + log.debug("Doing an empty search"); + records.addAll(search(req, Search.createEmptySearch())); + } catch(Exception e) { + log.error("Unknown error trying to harvest"); + log.error(e.getMessage()); + e.printStackTrace(); + errors.add(new HarvestError(e, log)); + } catch(Throwable e) { + log.fatal("Something unknown and terrible happened while harvesting"); + log.fatal(e.getMessage()); + e.printStackTrace(); + errors.add(new HarvestError(e, log)); + } + } log.info("Total records processed in all searches :"+ records.size()); @@ -163,7 +207,8 @@ private Set search(ListIdentifiersRequest req, Search s) throws Oper } catch(NoRecordsMatchException e) { - //--- return gracefully + log.warning("No records were matched: " + e.getMessage()); + this.errors.add(new HarvestError(e, log)); return records; } @@ -171,6 +216,7 @@ private Set search(ListIdentifiersRequest req, Search s) throws Oper { log.warning("Raised exception when searching : "+ e); log.warning(Util.getStackTrace(e)); + this.errors.add(new HarvestError(e, log)); throw new OperationAbortedEx("Raised exception when searching", e); } } @@ -320,14 +366,19 @@ private Element retrieveMetadata(Transport t, RecordInfo ri) catch(JDOMException e) { - log.warning("Skipping metadata with bad XML format. Remote id : "+ ri.id); + HarvestError harvestError = new HarvestError(e, log); + harvestError.setDescription("Skipping metadata with bad XML format. Remote id : "+ ri.id); + harvestError.printLog(log); + this.errors.add(harvestError); result.badFormat++; } catch(Exception e) { - log.warning("Raised exception while getting metadata file : "+ e); - log.warning(Util.getStackTrace(e)); + HarvestError harvestError = new HarvestError(e, log); + harvestError.setDescription("Raised exception while getting metadata file : "+ e); + this.errors.add(harvestError); + harvestError.printLog(log); result.unretrievable++; } @@ -354,7 +405,10 @@ private Element toDublinCore(Element md) } catch (Exception e) { - log.warning("Cannot convert oai_dc to dublin core : "+ e); + HarvestError harvestError = new HarvestError(e, log); + harvestError.setDescription("Cannot convert oai_dc to dublin core : "+ e); + this.errors.add(harvestError); + harvestError.printLog(log); return null; } } @@ -370,6 +424,8 @@ private boolean validates(String schema, Element md) } catch (Exception e) { + HarvestError harvestError = new HarvestError(e, log); + this.errors.add(harvestError); return false; } } @@ -422,6 +478,11 @@ private void updateMetadata(Transport t, RecordInfo ri, String id) throws Except } } + + public List getErrors() { + return errors; + } + //--------------------------------------------------------------------------- //--- //--- Variables @@ -436,5 +497,12 @@ private void updateMetadata(Transport t, RecordInfo ri, String id) throws Except private CategoryMapper localCateg; private GroupMapper localGroups; private UUIDMapper localUuids; - private HarvestResult result; -} \ No newline at end of file + /** + * Contains a list of accumulated errors during the executing of this harvest. + */ + private List errors = new LinkedList(); +} + +//============================================================================= + + diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/oaipmh/OaiPmhHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/oaipmh/OaiPmhHarvester.java index f481605842e..487834476c4 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/oaipmh/OaiPmhHarvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/oaipmh/OaiPmhHarvester.java @@ -28,9 +28,11 @@ import jeeves.resources.dbms.Dbms; import jeeves.server.context.ServiceContext; import jeeves.server.resources.ResourceManager; + import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.AbstractParams; +import org.fao.geonet.kernel.harvest.harvester.HarvestResult; import org.fao.geonet.lib.Lib; import org.fao.geonet.resources.Resources; import org.jdom.Element; @@ -41,7 +43,7 @@ //============================================================================= -public class OaiPmhHarvester extends AbstractHarvester +public class OaiPmhHarvester extends AbstractHarvester { //-------------------------------------------------------------------------- //--- @@ -166,9 +168,8 @@ protected void storeNodeExtra(Dbms dbms, AbstractParams p, String path, protected void doHarvest(Logger log, ResourceManager rm) throws Exception { Dbms dbms = (Dbms) rm.open(Geonet.Res.MAIN_DB); - - Harvester h = new Harvester(log, context, dbms, params); - result = h.harvest(); + h = new Harvester(log, context, dbms, params); + result = h.harvest(log); } //--------------------------------------------------------------------------- diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/ogcwxs/Harvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/ogcwxs/Harvester.java index 81d200343a9..9168c20ab74 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/ogcwxs/Harvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/ogcwxs/Harvester.java @@ -23,12 +23,15 @@ package org.fao.geonet.kernel.harvest.harvester.ogcwxs; +import jeeves.exceptions.BadInputEx; import jeeves.interfaces.Logger; import jeeves.resources.dbms.Dbms; import jeeves.server.context.ServiceContext; +import jeeves.server.resources.ResourceManager; import jeeves.utils.BinaryFile; import jeeves.utils.Xml; import jeeves.utils.XmlRequest; + import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.methods.GetMethod; @@ -39,9 +42,12 @@ import org.fao.geonet.kernel.DataManager; import org.fao.geonet.kernel.SchemaManager; import org.fao.geonet.kernel.harvest.BaseAligner; +import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.CategoryMapper; import org.fao.geonet.kernel.harvest.harvester.GroupMapper; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; +import org.fao.geonet.kernel.harvest.harvester.IHarvester; import org.fao.geonet.kernel.harvest.harvester.UUIDMapper; import org.fao.geonet.lib.Lib; import org.fao.geonet.services.thumbnail.Set; @@ -59,6 +65,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.URL; +import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -138,7 +145,7 @@ * @author fxprunayre * */ -class Harvester extends BaseAligner +class Harvester extends BaseAligner implements IHarvester { @@ -161,7 +168,7 @@ public Harvester(Logger log, this.dbms = dbms; this.params = params; - result = new HarvestResult (); + result = new HarvestResult(); GeonetContext gc = (GeonetContext) context.getHandlerContext (Geonet.CONTEXT_NAME); dataMan = gc.getBean(DataManager.class); @@ -176,8 +183,10 @@ public Harvester(Logger log, /** * Start the harvesting of a WMS, WFS or WCS node. */ - public HarvestResult harvest() throws Exception { + public HarvestResult harvest(Logger log) throws Exception { Element xml; + + this.log = log; log.info("Retrieving remote metadata information for : " + params.name); @@ -613,7 +622,7 @@ private WxSLayerRegistry addLayerMetadata (Element layer, Element capa) throws J //--- using GetCapabilities document - if (!loaded){ + if (!loaded && params.useLayer){ try { //--- set XSL param to filter on layer and set uuid Map param = new HashMap(); @@ -909,4 +918,13 @@ private static class WxSLayerRegistry { public Double maxy = 90.0; } + /* (non-Javadoc) + * @see org.fao.geonet.kernel.harvest.harvester.IHarvester#getErrors() + */ + @Override + public List getErrors() { + // TODO Auto-generated method stub + return null; + } + } \ No newline at end of file diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/ogcwxs/OgcWxSHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/ogcwxs/OgcWxSHarvester.java index ef09022bfe3..921637bd317 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/ogcwxs/OgcWxSHarvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/ogcwxs/OgcWxSHarvester.java @@ -31,6 +31,7 @@ import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.AbstractParams; +import org.fao.geonet.kernel.harvest.harvester.HarvestResult; import org.fao.geonet.lib.Lib; import org.fao.geonet.resources.Resources; import org.jdom.Element; @@ -41,7 +42,7 @@ //============================================================================= -public class OgcWxSHarvester extends AbstractHarvester +public class OgcWxSHarvester extends AbstractHarvester { //-------------------------------------------------------------------------- //--- @@ -160,8 +161,8 @@ protected void doHarvest(Logger log, ResourceManager rm) throws Exception { Dbms dbms = (Dbms) rm.open(Geonet.Res.MAIN_DB); - Harvester h = new Harvester(log, context, dbms, params); - result = h.harvest(); + h = new Harvester(log, context, dbms, params); + result = h.harvest(log); } //--------------------------------------------------------------------------- @@ -171,4 +172,5 @@ protected void doHarvest(Logger log, ResourceManager rm) throws Exception //--------------------------------------------------------------------------- private OgcWxSParams params; -} \ No newline at end of file +} + diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/thredds/Harvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/thredds/Harvester.java index 59ea1da60a2..999212f32be 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/thredds/Harvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/thredds/Harvester.java @@ -44,7 +44,9 @@ import org.fao.geonet.kernel.harvest.BaseAligner; import org.fao.geonet.kernel.harvest.harvester.CategoryMapper; import org.fao.geonet.kernel.harvest.harvester.GroupMapper; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; +import org.fao.geonet.kernel.harvest.harvester.IHarvester; import org.fao.geonet.kernel.harvest.harvester.RecordInfo; import org.fao.geonet.kernel.harvest.harvester.UriMapper; import org.fao.geonet.kernel.harvest.harvester.fragment.FragmentHarvester; @@ -90,6 +92,7 @@ import java.util.Date; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -170,7 +173,7 @@ * @author Simon Pigot * */ -class Harvester extends BaseAligner +class Harvester extends BaseAligner implements IHarvester { @@ -224,7 +227,8 @@ public Harvester(Logger log, ServiceContext context, Dbms dbms, ThreddsParams pa * Start the harvesting of a thredds catalog **/ - public HarvestResult harvest() throws Exception { + public HarvestResult harvest(Logger log) throws Exception { + this.log = log; Element xml = null; log.info("Retrieving remote metadata information for : " + params.name); @@ -1355,5 +1359,11 @@ private static class ThreddsService { static private final Namespace gmd = Namespace.getNamespace("gmd", "http://www.isotc211.org/2005/gmd"); static private final Namespace srv = Namespace.getNamespace("srv", "http://www.isotc211.org/2005/srv"); static private final Namespace xlink = Namespace.getNamespace("xlink", "http://www.w3.org/1999/xlink"); + + private List errors = new LinkedList(); + @Override + public List getErrors() { + return errors; + } } \ No newline at end of file diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/thredds/ThreddsHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/thredds/ThreddsHarvester.java index e8b082c0202..1839eb7b19a 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/thredds/ThreddsHarvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/thredds/ThreddsHarvester.java @@ -31,6 +31,7 @@ import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.AbstractParams; +import org.fao.geonet.kernel.harvest.harvester.HarvestResult; import org.fao.geonet.lib.Lib; import org.fao.geonet.resources.Resources; import org.jdom.Element; @@ -41,7 +42,7 @@ //============================================================================= -public class ThreddsHarvester extends AbstractHarvester +public class ThreddsHarvester extends AbstractHarvester { //-------------------------------------------------------------------------- //--- @@ -176,8 +177,8 @@ protected void doHarvest(Logger log, ResourceManager rm) throws Exception { Dbms dbms = (Dbms) rm.open(Geonet.Res.MAIN_DB); - Harvester h = new Harvester(log, context, dbms, params); - result = h.harvest(); + h = new Harvester(log, context, dbms, params); + result = h.harvest(log); } //--------------------------------------------------------------------------- diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/webdav/Harvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/webdav/Harvester.java index c4d802ee20b..4192ba61c85 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/webdav/Harvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/webdav/Harvester.java @@ -36,19 +36,22 @@ import org.fao.geonet.kernel.harvest.BaseAligner; import org.fao.geonet.kernel.harvest.harvester.CategoryMapper; import org.fao.geonet.kernel.harvest.harvester.GroupMapper; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; +import org.fao.geonet.kernel.harvest.harvester.IHarvester; import org.fao.geonet.kernel.harvest.harvester.RecordInfo; import org.fao.geonet.kernel.harvest.harvester.UriMapper; import org.jdom.Element; import org.jdom.JDOMException; import java.io.IOException; +import java.util.LinkedList; import java.util.List; import java.util.UUID; //============================================================================= -class Harvester extends BaseAligner { +class Harvester extends BaseAligner implements IHarvester { //-------------------------------------------------------------------------- //--- //--- Constructor @@ -73,8 +76,9 @@ public Harvester(Logger log, ServiceContext context, Dbms dbms, WebDavParams par //--- API methods //--- //--------------------------------------------------------------------------- - - public HarvestResult harvest() throws Exception { + @Override + public HarvestResult harvest(Logger log) throws Exception { + this.log = log; if(log.isDebugEnabled()) log.debug("Retrieving remote metadata information for : "+ params.name); RemoteRetriever rr = null; @@ -202,6 +206,7 @@ private void addMetadata(RemoteFile rf) throws Exception { } catch (Exception e) { log.error(" - Failed to set uuid for metadata with remote path : " + rf.getPath()); + errors.add(new HarvestError(e, this.log)); return; } } @@ -334,6 +339,10 @@ private void updateMetadata(RemoteFile rf, RecordInfo record) throws Exception { } } + public List getErrors() { + return errors; + } + //--------------------------------------------------------------------------- //--- //--- Variables @@ -350,6 +359,7 @@ private void updateMetadata(RemoteFile rf, RecordInfo record) throws Exception { private UriMapper localUris; private HarvestResult result; private SchemaManager schemaMan; + private List errors = new LinkedList(); } //============================================================================= diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/webdav/WebDavHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/webdav/WebDavHarvester.java index 0624f9047a8..2142418e236 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/webdav/WebDavHarvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/webdav/WebDavHarvester.java @@ -30,6 +30,7 @@ import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.AbstractParams; +import org.fao.geonet.kernel.harvest.harvester.HarvestResult; import org.fao.geonet.lib.Lib; import org.fao.geonet.resources.Resources; import org.jdom.Element; @@ -40,7 +41,7 @@ //============================================================================= -public class WebDavHarvester extends AbstractHarvester { +public class WebDavHarvester extends AbstractHarvester { //-------------------------------------------------------------------------- //--- //--- Static init @@ -129,8 +130,8 @@ protected void storeNodeExtra(Dbms dbms, AbstractParams p, String path, String s protected void doHarvest(Logger log, ResourceManager rm) throws Exception { log.info("WebDav doHarvest start"); Dbms dbms = (Dbms) rm.open(Geonet.Res.MAIN_DB); - Harvester h = new Harvester(log, context, dbms, params); - result = h.harvest(); + h = new Harvester(log, context, dbms, params); + result = h.harvest(log); log.info("WebDav doHarvest end"); } diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/wfsfeatures/Harvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/wfsfeatures/Harvester.java index 0d3950c248a..6e9b4da2ffa 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/wfsfeatures/Harvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/wfsfeatures/Harvester.java @@ -32,12 +32,16 @@ import jeeves.utils.XmlElementReader; import jeeves.utils.XmlRequest; import jeeves.xlink.Processor; + import org.apache.commons.httpclient.HttpException; +import org.apache.jcs.access.exception.CacheException; import org.fao.geonet.GeonetContext; import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.DataManager; import org.fao.geonet.kernel.SchemaManager; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; +import org.fao.geonet.kernel.harvest.harvester.IHarvester; import org.fao.geonet.kernel.harvest.harvester.UUIDMapper; import org.fao.geonet.kernel.harvest.harvester.fragment.FragmentHarvester; import org.fao.geonet.kernel.harvest.harvester.fragment.FragmentHarvester.FragmentParams; @@ -50,14 +54,17 @@ import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLStreamException; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; +import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; @@ -116,7 +123,7 @@ * @author sppigot * */ -class Harvester +class Harvester implements IHarvester { @@ -189,8 +196,9 @@ public Harvester(Logger log, ServiceContext context, Dbms dbms, WfsFeaturesParam * * */ - public HarvestResult harvest() throws Exception { + public HarvestResult harvest(Logger log) throws Exception { + this.log = log; log.info("Retrieving metadata fragments for : " + params.name); //--- collect all existing metadata uuids before we update @@ -204,7 +212,7 @@ public HarvestResult harvest() throws Exception { try { wfsQuery = Xml.loadString(params.query, false); } catch (JDOMException e) { - e.printStackTrace(); + errors.add(new HarvestError(e, log)); throw new BadParameterEx("GetFeature Query failed to parse\n", params.query); } @@ -310,7 +318,8 @@ private void harvest(Element xml, FragmentHarvester fragmentHarvester) result.recordsUpdated += fragmentResult.recordsUpdated; result.subtemplatesUpdated += fragmentResult.fragmentsUpdated; - result.totalMetadata = result.subtemplatesAdded + result.recordsBuilt; + result.totalMetadata = result.subtemplatesAdded + result.addedMetadata; + result.originalMetadata = result.fragmentsReturned; } /** @@ -322,25 +331,38 @@ public void deleteOrphanedMetadata(Set updatedMetadata) throws Exception if(log.isDebugEnabled()) log.debug(" - Removing orphaned metadata records and fragments after update"); for (String uuid : localUuids.getUUIDs()) { - String isTemplate = localUuids.getTemplate(uuid); - if (isTemplate.equals("s")) { - Processor.uncacheXLinkUri(metadataGetService+"?uuid=" + uuid); - } - - if (!updatedMetadata.contains(uuid)) { - String id = localUuids.getID(uuid); - dataMan.deleteMetadata(context, dbms, id); - - if (isTemplate.equals("s")) { - result.subtemplatesRemoved ++; - } else { - result.recordsRemoved ++; - } - } + try { + String isTemplate = localUuids.getTemplate(uuid); + if (isTemplate.equals("s")) { + Processor.uncacheXLinkUri(metadataGetService+"?uuid=" + uuid); + } + + if (!updatedMetadata.contains(uuid)) { + String id = localUuids.getID(uuid); + dataMan.deleteMetadata(context, dbms, id); + + if (isTemplate.equals("s")) { + result.subtemplatesRemoved ++; + } else { + result.locallyRemoved ++; + } + } + } catch(CacheException e) { + HarvestError error = new HarvestError(e, log); + this.errors.add(error); + } catch (Exception e) { + HarvestError error = new HarvestError(e, log); + this.errors.add(error); + } } - if (result.subtemplatesRemoved + result.recordsRemoved > 0) { - dbms.commit(); + if (result.subtemplatesRemoved + result.locallyRemoved > 0) { + try { + dbms.commit(); + } catch (SQLException e) { + HarvestError error = new HarvestError(e, log); + this.errors.add(error); + } } } @@ -362,6 +384,11 @@ private FragmentParams getFragmentHarvesterParams() { return fragmentParams; } + public List getErrors() { + return errors; + } + + //--------------------------------------------------------------------------- //--- //--- Variables @@ -379,4 +406,8 @@ private FragmentParams getFragmentHarvesterParams() { private String metadataGetService; private String stylesheetDirectory; private Map ssParams = new HashMap(); + /** + * Contains a list of accumulated errors during the executing of this harvest. + */ + private List errors = new LinkedList(); } \ No newline at end of file diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/wfsfeatures/WfsFeaturesHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/wfsfeatures/WfsFeaturesHarvester.java index da17cbd069d..6911eebbd3f 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/wfsfeatures/WfsFeaturesHarvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/wfsfeatures/WfsFeaturesHarvester.java @@ -28,9 +28,11 @@ import jeeves.resources.dbms.Dbms; import jeeves.server.context.ServiceContext; import jeeves.server.resources.ResourceManager; + import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.AbstractParams; +import org.fao.geonet.kernel.harvest.harvester.HarvestResult; import org.fao.geonet.lib.Lib; import org.fao.geonet.resources.Resources; import org.jdom.Element; @@ -41,7 +43,7 @@ //============================================================================= -public class WfsFeaturesHarvester extends AbstractHarvester +public class WfsFeaturesHarvester extends AbstractHarvester { //-------------------------------------------------------------------------- //--- @@ -159,8 +161,8 @@ protected void doHarvest(Logger log, ResourceManager rm) throws Exception { Dbms dbms = (Dbms) rm.open(Geonet.Res.MAIN_DB); - Harvester h = new Harvester(log, context, dbms, params); - result = h.harvest(); + h = new Harvester(log, context, dbms, params); + result = h.harvest(log); } //--------------------------------------------------------------------------- diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950/Harvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950/Harvester.java index 2622e5f1796..d50c8533e18 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950/Harvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950/Harvester.java @@ -24,8 +24,10 @@ import jeeves.interfaces.Logger; import jeeves.resources.dbms.Dbms; import jeeves.server.ServiceConfig; +import jeeves.server.UserSession; import jeeves.server.context.ServiceContext; import jeeves.utils.Xml; + import org.fao.geonet.GeonetContext; import org.fao.geonet.constants.Edit; import org.fao.geonet.constants.Geonet; @@ -33,7 +35,10 @@ import org.fao.geonet.kernel.harvest.BaseAligner; import org.fao.geonet.kernel.harvest.harvester.CategoryMapper; import org.fao.geonet.kernel.harvest.harvester.GroupMapper; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; +import org.fao.geonet.kernel.harvest.harvester.IHarvester; +import org.fao.geonet.kernel.harvest.harvester.Privileges; import org.fao.geonet.kernel.harvest.harvester.UUIDMapper; import org.fao.geonet.kernel.search.MetaSearcher; import org.fao.geonet.kernel.search.SearchManager; @@ -47,14 +52,14 @@ import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; //============================================================================= -class Harvester extends BaseAligner { - +class Harvester extends BaseAligner implements IHarvester { private UUIDMapper localUuids; private final DataManager dataMan; private final SearchManager searchMan; @@ -84,11 +89,12 @@ public Harvester(Logger log, ServiceContext context, Dbms dbms, Z3950Params para // --- // --------------------------------------------------------------------------- - public Z3950ServerResults harvest() throws Exception { + public Z3950ServerResults harvest(Logger log) throws Exception { Set newUuids = new HashSet(); int groupSize = 10; + this.log = log; log.info("Retrieving remote metadata information:" + params.uuid); Z3950ServerResults serverResults = new Z3950ServerResults(); @@ -99,7 +105,7 @@ public Z3950ServerResults harvest() throws Exception { // --- remove old metadata for (String uuid : localUuids.getUUIDs()) { String id = localUuids.getID(uuid); - if(log.isDebugEnabled()) log.debug(" - Removing old metadata before update with id: " + id); + if(this.log.isDebugEnabled()) log.debug(" - Removing old metadata before update with id: " + id); dataMan.deleteMetadataGroup(context, dbms, id); serverResults.locallyRemoved++; } @@ -253,7 +259,10 @@ public Z3950ServerResults harvest() throws Exception { md = Xml.transform(md, thisXslt); if(log.isDebugEnabled()) log.debug("After transform: "+Xml.getString(md)); } catch (Exception e) { - System.out.println("Cannot transform XML, ignoring. Error was: "+e.getMessage()); + HarvestError error = new HarvestError(e, log); + error.setDescription("Cannot transform XML, ignoring. Error was: "+e.getMessage()); + this.errors.add(error); + error.printLog(log); result.badFormat++; continue; // skip this one } @@ -271,8 +280,10 @@ public Z3950ServerResults harvest() throws Exception { try { uuid = dataMan.extractUUID(schema, md); } catch (Exception e) { - log.error("Unable to extract UUID: "+e.getMessage()); - e.printStackTrace(); + HarvestError error = new HarvestError(e, log); + error.setDescription("Unable to extract UUID. " + e.getMessage()); + this.errors.add(error); + error.printLog(log); } if (uuid == null || uuid.equals("")) { @@ -317,8 +328,10 @@ public Z3950ServerResults harvest() throws Exception { } catch (Exception e) { - log.error("Unable to insert metadata "+e.getMessage()); - e.printStackTrace(); + HarvestError error = new HarvestError(e, log); + error.setDescription("Unable to insert metadata. "+e.getMessage()); + this.errors.add(error); + error.printLog(log); result.couldNotInsert++; continue; } @@ -360,10 +373,18 @@ public Z3950ServerResults harvest() throws Exception { // --- // --------------------------------------------------------------------------- - private final Logger log; + private Logger log; private final Dbms dbms; private final Z3950Params params; private ServiceContext context; private CategoryMapper localCateg; private GroupMapper localGroups; + /** + * Contains a list of accumulated errors during the executing of this harvest. + */ + private List errors = new LinkedList(); + @Override + public List getErrors() { + return errors; + } } \ No newline at end of file diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950/Z3950Harvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950/Z3950Harvester.java index ede3c763adc..de98a881fc1 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950/Z3950Harvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950/Z3950Harvester.java @@ -47,7 +47,7 @@ * @author fxprunayre * @author sppigot */ -public class Z3950Harvester extends AbstractHarvester { +public class Z3950Harvester extends AbstractHarvester { public static void init(ServiceContext context) throws Exception { } @@ -185,6 +185,7 @@ protected Element getResult() { // --- put here harvesting information after it has been executed add(res, "total", result.totalMetadata); + add(res, "originalMetadata", result.totalMetadata); add(res, "added", result.addedMetadata); add(res, "updated", result.updatedMetadata); add(res, "unchanged", result.unchangedMetadata); @@ -201,8 +202,8 @@ protected Element getResult() { protected void doHarvest(Logger log, ResourceManager rm) throws Exception { Dbms dbms = (Dbms) rm.open(Geonet.Res.MAIN_DB); - Harvester h = new Harvester(log, context, dbms, params); - serverResults = h.harvest(); + h = new Harvester(log, context, dbms, params); + result = h.harvest(log); } private Z3950Params params; @@ -210,11 +211,9 @@ protected void doHarvest(Logger log, ResourceManager rm) throws Exception { } -class Z3950ServerResults { +class Z3950ServerResults extends HarvestResult { private Map serverResults = new HashMap(); - public int locallyRemoved; - public HarvestResult getServerResult(String serverName) { HarvestResult result = serverResults.get(serverName); if (result == null) { diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950Config/Harvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950Config/Harvester.java index b7f6077e3da..a907488691c 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950Config/Harvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950Config/Harvester.java @@ -32,17 +32,21 @@ import jeeves.utils.XmlRequest; import org.fao.geonet.constants.Edit; import org.fao.geonet.constants.Geonet; +import org.fao.geonet.kernel.harvest.harvester.HarvestError; import org.fao.geonet.kernel.harvest.harvester.HarvestResult; +import org.fao.geonet.kernel.harvest.harvester.IHarvester; import org.fao.geonet.kernel.harvest.harvester.RecordInfo; import org.fao.geonet.lib.Lib; import org.jdom.Element; import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; import java.util.Set; //============================================================================= -class Harvester +class Harvester implements IHarvester { //-------------------------------------------------------------------------- //--- @@ -63,8 +67,9 @@ public Harvester(Logger log, ServiceContext context, Dbms dbms, Z3950ConfigParam //--- //-------------------------------------------------------------------------- - public HarvestResult harvest() throws Exception + public HarvestResult harvest(Logger log) throws Exception { + this.log = log; XmlRequest req = new XmlRequest(params.host, Integer.valueOf(params.port)); @@ -135,11 +140,18 @@ private Element doSearch(XmlRequest request, Search s) throws OperationAbortedEx } catch(Exception e) { - log.warning("Raised exception when searching : "+ e); + HarvestError error = new HarvestError(e, log); + error.setDescription("Raised exception when searching : "+ e); + this.errors.add(error); + error.printLog(log); throw new OperationAbortedEx("Raised exception when searching", e); } } + public List getErrors() { + return errors; + } + //--------------------------------------------------------------------------- //--- //--- Variables @@ -149,6 +161,10 @@ private Element doSearch(XmlRequest request, Search s) throws OperationAbortedEx private Logger log; private Z3950ConfigParams params; private ServiceContext context; + /** + * Contains a list of accumulated errors during the executing of this harvest. + */ + private List errors = new LinkedList(); } //============================================================================= diff --git a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950Config/Z3950ConfigHarvester.java b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950Config/Z3950ConfigHarvester.java index 5fff4829010..26396028acf 100644 --- a/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950Config/Z3950ConfigHarvester.java +++ b/harvesters/src/main/java/org/fao/geonet/kernel/harvest/harvester/z3950Config/Z3950ConfigHarvester.java @@ -31,13 +31,14 @@ import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.kernel.harvest.harvester.AbstractParams; +import org.fao.geonet.kernel.harvest.harvester.HarvestResult; import org.jdom.Element; import java.sql.SQLException; //============================================================================= -public class Z3950ConfigHarvester extends AbstractHarvester +public class Z3950ConfigHarvester extends AbstractHarvester { public static final String TYPE = "z3950Config"; @@ -167,8 +168,8 @@ protected void doHarvest(Logger log, ResourceManager rm) throws Exception { Dbms dbms = (Dbms) rm.open(Geonet.Res.MAIN_DB); - Harvester h = new Harvester(log, context, dbms, params); - result = h.harvest(); + h = new Harvester(log, context, dbms, params); + result = h.harvest(log); } //--------------------------------------------------------------------------- diff --git a/harvesters/src/main/java/org/fao/geonet/services/harvesting/Clear.java b/harvesters/src/main/java/org/fao/geonet/services/harvesting/Clear.java new file mode 100644 index 00000000000..0a51fdf7f39 --- /dev/null +++ b/harvesters/src/main/java/org/fao/geonet/services/harvesting/Clear.java @@ -0,0 +1,69 @@ +//============================================================================= +//=== Copyright (C) 2001-2013 Food and Agriculture Organization of the +//=== United Nations (FAO-UN), United Nations World Food Programme (WFP) +//=== and United Nations Environment Programme (UNEP) +//=== +//=== This program is free software; you can redistribute it and/or modify +//=== it under the terms of the GNU General Public License as published by +//=== the Free Software Foundation; either version 2 of the License, or (at +//=== your option) any later version. +//=== +//=== This program is distributed in the hope that it will be useful, but +//=== WITHOUT ANY WARRANTY; without even the implied warranty of +//=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +//=== General Public License for more details. +//=== +//=== You should have received a copy of the GNU General Public License +//=== along with this program; if not, write to the Free Software +//=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA +//=== +//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, +//=== Rome - Italy. email: geonetwork@osgeo.org +//============================================================================== + +package org.fao.geonet.services.harvesting; + +import jeeves.interfaces.Service; +import jeeves.resources.dbms.Dbms; +import jeeves.server.ServiceConfig; +import jeeves.server.context.ServiceContext; +import org.fao.geonet.kernel.harvest.Common.OperResult; +import org.fao.geonet.kernel.harvest.HarvestManager; +import org.jdom.Element; + + +/** + * This service removes all metadata associated to one harvester + * + * @author delawen + * + */ +public class Clear implements Service +{ + //-------------------------------------------------------------------------- + //--- + //--- Init + //--- + //-------------------------------------------------------------------------- + + public void init(String appPath, ServiceConfig params) throws Exception {} + + //-------------------------------------------------------------------------- + //--- + //--- Service + //--- + //-------------------------------------------------------------------------- + + public Element exec(Element params, ServiceContext context) throws Exception + { + return Util.exec(params, context, new Util.Job() + { + public OperResult execute(Dbms dbms, HarvestManager hm, String id) throws Exception + { + return hm.clearBatch(dbms, id); + } + }); + } +} + +//============================================================================= diff --git a/harvesters/src/main/java/org/fao/geonet/services/harvesting/HistoryDelete.java b/harvesters/src/main/java/org/fao/geonet/services/harvesting/HistoryDelete.java index 0fd49b07f06..dc61ddf4c2a 100644 --- a/harvesters/src/main/java/org/fao/geonet/services/harvesting/HistoryDelete.java +++ b/harvesters/src/main/java/org/fao/geonet/services/harvesting/HistoryDelete.java @@ -5,7 +5,10 @@ import jeeves.resources.dbms.Dbms; import jeeves.server.ServiceConfig; import jeeves.server.context.ServiceContext; +import jeeves.utils.Util; +import org.fao.geonet.GeonetContext; import org.fao.geonet.constants.Geonet; +import org.fao.geonet.constants.Params; import org.fao.geonet.kernel.harvest.harvester.HarvesterHistoryDao; import org.jdom.Element; import java.util.List; @@ -28,11 +31,11 @@ public void init(String appPath, ServiceConfig config) throws Exception {} public Element exec(Element params, ServiceContext context) throws Exception { - @SuppressWarnings("unchecked") List ids = params.getChildren("id"); + List files = params.getChildren("file"); Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB); - int nrRecs = HarvesterHistoryDao.deleteHistory(dbms, ids); + int nrRecs = HarvesterHistoryDao.deleteHistory(dbms, ids, files); return new Element(Jeeves.Elem.RESPONSE).setText(nrRecs+""); } diff --git a/harvesters/src/main/java/org/fao/geonet/services/harvesting/Info.java b/harvesters/src/main/java/org/fao/geonet/services/harvesting/Info.java index 391db2ada5b..9f775948cab 100644 --- a/harvesters/src/main/java/org/fao/geonet/services/harvesting/Info.java +++ b/harvesters/src/main/java/org/fao/geonet/services/harvesting/Info.java @@ -44,6 +44,8 @@ import org.fao.geonet.GeonetContext; import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.SchemaManager; +import org.fao.geonet.kernel.harvest.HarvestManager; +import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; import org.fao.geonet.lib.Lib; import org.fao.geonet.resources.Resources; import org.fao.oaipmh.exceptions.NoSetHierarchyException; @@ -99,6 +101,9 @@ public Element exec(Element params, ServiceContext context) throws Exception if (type.equals("icons")) result.addContent(getIcons(context)); + else if (type.equals("harvesterTypes")) + result.addContent(getHarvesterTypes(context)); + else if (type.equals("oaiPmhServer")) result.addContent(getOaiPmhServer(el, context)); @@ -140,7 +145,15 @@ else if (type.equals("importStylesheets")) //--- //-------------------------------------------------------------------------- - private Element getIcons(ServiceContext context) + private Element getHarvesterTypes(ServiceContext context) { + Element types = new Element("types"); + for (String type : AbstractHarvester.getHarvesterTypes()) { + types.addContent(new Element("type").setText(type)); + } + return types; + } + + private Element getIcons(ServiceContext context) { Set icons = Resources.listFiles(context, "harvesting", iconFilter); List list = new ArrayList(icons); diff --git a/harvesters/src/main/java/org/fao/geonet/services/harvesting/Log.java b/harvesters/src/main/java/org/fao/geonet/services/harvesting/Log.java new file mode 100644 index 00000000000..0bb7529fac3 --- /dev/null +++ b/harvesters/src/main/java/org/fao/geonet/services/harvesting/Log.java @@ -0,0 +1,59 @@ +package org.fao.geonet.services.harvesting; + +import java.io.File; + +import jeeves.interfaces.Service; +import jeeves.server.ServiceConfig; +import jeeves.server.context.ServiceContext; +import jeeves.utils.BinaryFile; + +import opendap.servlet.BadURLException; + +import org.jdom.Element; + +/** + * Download a logfile from harvesting + * + * @author delawen + * + */ +public class Log implements Service { + public void init(String appPath, ServiceConfig config) throws Exception { + + } + + public Element exec(Element params, ServiceContext context) + throws Exception { + String logfile = params.getChildText("file").trim(); + + // Security checks, this is no free proxy!! + if (logfile.startsWith("http") || logfile.startsWith("ftp") + || logfile.startsWith("sftp")) { + throw new BadURLException( + "This is no proxy. Stopping possible hacking attempt to url: " + + logfile); + } + + if (!logfile.endsWith(".log")) { + throw new BadURLException( + "Strange suffix for this log file. Stopping possible hacking attempt to uri: " + + logfile); + } + + if (!logfile.contains("/harvester_")) { + throw new BadURLException( + "This doesn't seem like a harvester log file. Stopping possible hacking attempt to uri: " + + logfile); + } + + File file = new File(logfile); + + if (!file.exists() || !file.canRead()) { + throw new NullPointerException( + "Couldn't find or read the logfile. Somebody moved it? " + file.getAbsolutePath()); + } + + return BinaryFile.encode(200, file.getAbsolutePath(), false); + } + +} diff --git a/harvesters/src/main/java/org/fao/geonet/services/harvesting/notifier/GetNotificationSettings.java b/harvesters/src/main/java/org/fao/geonet/services/harvesting/notifier/GetNotificationSettings.java new file mode 100644 index 00000000000..7abeef561dc --- /dev/null +++ b/harvesters/src/main/java/org/fao/geonet/services/harvesting/notifier/GetNotificationSettings.java @@ -0,0 +1,86 @@ +/** + * Copyright (C) 2013 GeoNetwork + * + * This file is part of GeoNetwork + * + * GeoNetwork is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoNetwork is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GeoNetwork. If not, see . + */ + +package org.fao.geonet.services.harvesting.notifier; + +import jeeves.interfaces.Service; +import jeeves.server.ServiceConfig; +import jeeves.server.context.ServiceContext; + +import org.fao.geonet.GeonetContext; +import org.fao.geonet.constants.Geonet; +import org.fao.geonet.kernel.setting.SettingManager; +import org.jdom.Element; + +public class GetNotificationSettings implements Service { + + @Override + public void init(String appPath, ServiceConfig params) throws Exception { + + } + + @Override + public Element exec(Element params, ServiceContext context) + throws Exception { + Element res = new Element("notification"); + + GeonetContext gc = (GeonetContext) context + .getHandlerContext(Geonet.CONTEXT_NAME); + SettingManager settings = gc.getBean(SettingManager.class); + setProperty(res, settings, "template", "mail/template"); + setProperty(res, settings, "templateError", "mail/templateError"); + setProperty(res, settings, "templateWarning", "mail/templateWarning"); + setProperty(res, settings, "subject", "mail/subject"); + setProperty(res, settings, "enabled", "mail/enabled"); + setProperty(res, settings, "level1", "mail/level1"); + setProperty(res, settings, "level2", "mail/level2"); + setProperty(res, settings, "level3", "mail/level3"); + setProperty(res, settings, "recipient", "mail/recipient", ","); + + return res; + } + + private void setProperty(Element res, SettingManager settings, + String property, String path) { + setProperty(res, settings, property, path, null); + } + + private void setProperty(Element res, SettingManager settings, + String property, String path, String split) { + try { + String value = settings.getValue("system/harvesting/" + path); + + if (split != null && value != null) { + String[] values = value.split(split); + for (String v : values) { + Element tmp = new Element(property); + tmp.setText(v); + res.addContent(tmp); + } + } else { + Element tmp = new Element(property); + tmp.setText(value); + res.addContent(tmp); + } + } catch (Throwable t) { + t.printStackTrace(); + } + } + +} diff --git a/harvesters/src/main/java/org/fao/geonet/services/harvesting/notifier/SaveNotificationSettings.java b/harvesters/src/main/java/org/fao/geonet/services/harvesting/notifier/SaveNotificationSettings.java new file mode 100644 index 00000000000..1a634b0c986 --- /dev/null +++ b/harvesters/src/main/java/org/fao/geonet/services/harvesting/notifier/SaveNotificationSettings.java @@ -0,0 +1,93 @@ +/** + * Copyright (C) 2013 GeoNetwork + * + * This file is part of GeoNetwork + * + * GeoNetwork is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoNetwork is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GeoNetwork. If not, see . + */ + +package org.fao.geonet.services.harvesting.notifier; + +import jeeves.interfaces.Service; +import jeeves.resources.dbms.Dbms; +import jeeves.server.ServiceConfig; +import jeeves.server.context.ServiceContext; + +import org.fao.geonet.GeonetContext; +import org.fao.geonet.constants.Geonet; +import org.fao.geonet.kernel.setting.SettingManager; +import org.jdom.Element; + +public class SaveNotificationSettings implements Service { + + @Override + public void init(String appPath, ServiceConfig params) throws Exception { + + } + + @Override + public Element exec(Element params, ServiceContext context) + throws Exception { + GeonetContext gc = (GeonetContext) context + .getHandlerContext(Geonet.CONTEXT_NAME); + SettingManager settings = gc.getBean(SettingManager.class); + Dbms dbms = (Dbms) context.getResourceManager() + .open(Geonet.Res.MAIN_DB); + + String sendTo = ""; + + for (Object o : params.getChildren()) { + Element param = ((Element) o); + + if (param.getName().equalsIgnoreCase("recipient")) { + if (!param.getValue().trim().isEmpty()) { + if(sendTo.isEmpty()) { + sendTo = param.getValue().trim(); + } else { + sendTo += "," + param.getValue().trim(); + } + } + } else if (param.getName().equalsIgnoreCase("template")) { + settings.setValue(dbms, "system/harvesting/mail/template", + param.getValue()); + } else if (param.getName().equalsIgnoreCase("templateError")) { + settings.setValue(dbms, "system/harvesting/mail/templateError", + param.getValue()); + } else if (param.getName().equalsIgnoreCase("templateWarning")) { + settings.setValue(dbms, "system/harvesting/mail/templateWarning", + param.getValue()); + } else if (param.getName().equalsIgnoreCase("subject")) { + settings.setValue(dbms, "system/harvesting/mail/subject", + param.getValue()); + } else if (param.getName().equalsIgnoreCase("enabled")) { + settings.setValue(dbms, "system/harvesting/mail/enabled", + param.getValue()); + } else if (param.getName().equalsIgnoreCase("level1")) { + settings.setValue(dbms, "system/harvesting/mail/level1", + param.getValue()); + } else if (param.getName().equalsIgnoreCase("level2")) { + settings.setValue(dbms, "system/harvesting/mail/level2", + param.getValue()); + } else if (param.getName().equalsIgnoreCase("level3")) { + settings.setValue(dbms, "system/harvesting/mail/level3", + param.getValue()); + } + } + + settings.setValue(dbms, "system/harvesting/mail/recipient", sendTo); + + return new Element("ok"); + } + +} diff --git a/harvesters/src/main/java/org/fao/geonet/services/harvesting/notifier/SendNotification.java b/harvesters/src/main/java/org/fao/geonet/services/harvesting/notifier/SendNotification.java new file mode 100644 index 00000000000..7049cc1ae23 --- /dev/null +++ b/harvesters/src/main/java/org/fao/geonet/services/harvesting/notifier/SendNotification.java @@ -0,0 +1,251 @@ +/** + * Copyright (C) 2013 GeoNetwork + * + * This file is part of GeoNetwork + * + * GeoNetwork is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoNetwork is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GeoNetwork. If not, see . + */ + +package org.fao.geonet.services.harvesting.notifier; + +import java.util.ArrayList; +import java.util.List; + +import jeeves.server.context.ServiceContext; + +import org.apache.commons.mail.EmailException; +import org.fao.geonet.GeonetContext; +import org.fao.geonet.constants.Geonet; +import org.fao.geonet.kernel.DataManager; +import org.fao.geonet.kernel.harvest.harvester.AbstractHarvester; +import org.fao.geonet.kernel.setting.SettingManager; +import org.fao.geonet.util.MailUtil; +import org.jdom.Element; + +/** + * This class send an email after a harvester has been run + * + * @author Maria Arias de Reyna + */ +public class SendNotification { + + /** + * Launches the notification manager + * + * @param context + * @param abstractHarvester + * @param dbms + * @param catalogRequestId + * Catalog request identifier to reject + * @param errors + * @throws EmailException + */ + public static void process(ServiceContext context, Element element, + @SuppressWarnings("rawtypes") AbstractHarvester abstractHarvester) + throws EmailException { + GeonetContext gc = (GeonetContext) context + .getHandlerContext(Geonet.CONTEXT_NAME); + SettingManager settings = gc.getBean(SettingManager.class); + notifyByMail(settings, element, abstractHarvester); + } + + /** + * Send the mail + * + * @param settings + * @param element + * @param ah + * @throws EmailException + */ + private static void notifyByMail(SettingManager settings, Element element, + @SuppressWarnings("rawtypes") AbstractHarvester ah) + throws EmailException { + + if (!settings.getValueAsBool("system/harvesting/mail/enabled")) { + return; + } + + String receiver = settings.getValue("system/harvesting/mail/recipient"); + List toAddress = new ArrayList(); + + // If no email to send, take the email of the owner of the harvester + if (receiver == null || receiver.trim().isEmpty()) { + try { + receiver = ah.getOwnerEmail(); + } catch (Exception e1) { + e1.printStackTrace(); + } + } + + toAddress.add(receiver); + + String subject = settings.getValue("system/harvesting/mail/subject"); + + String htmlMessage = settings + .getValue("system/harvesting/mail/template"); + + Element lastHarvest = (Element) element.getChildren().get(0); + + @SuppressWarnings("unchecked") + List tmp = lastHarvest.getChildren(); + Element info = null; + + for (Element e : tmp) { + if (e.getName().equalsIgnoreCase("info")) { + info = e; + break; + } + } + + // We should always get a info report BTW + if (info != null) { + // Success, but with warnings or clean? + Element result = (Element) info.getChildren().get(0); + + // switch between normal and error template + if (info.getChildren("error").size() > 0) { + // Error, Level 3, let's check it: + if (!settings.getValueAsBool("system/harvesting/mail/level3")) { + return; + } + htmlMessage = settings + .getValue("system/harvesting/mail/templateError"); + Element error = (Element) info.getChildren("error").get(0); + String errorMsg = error.getChildText("message"); + // do not convert it to html, dangerous! + errorMsg = errorMsg.replace("<", " "); + + errorMsg += extractWarningsTrace(info); + + htmlMessage = htmlMessage.replace("$$errorMsg$$", errorMsg); + + String[] values = new String[] { "total", "added", "updated", + "removed", "unchanged", "unretrievable", "doesNotValidate" }; + + for (String value : values) { + htmlMessage = replace(result, htmlMessage, value); + subject = replace(result, subject, value); + } + + } else { + + if (result.getChildren("errors").size() > 0) { + // Success with warnings, Level 2, let's check it: + if (!settings.getValueAsBool("system/harvesting/mail/level2")) { + return; + } + + htmlMessage = settings + .getValue("system/harvesting/mail/templateWarning"); + + String errorMsg = extractWarningsTrace(result); + + htmlMessage = htmlMessage.replace("$$errorMsg$$", errorMsg); + + String[] values = new String[] { "total", "added", "updated", + "removed", "unchanged", "unretrievable", + "doesNotValidate" }; + + for (String value : values) { + htmlMessage = replace(result, htmlMessage, value); + subject = replace(result, subject, value); + } + } else { + // Success!! Level 1, let's check it: + if (!settings.getValueAsBool("system/harvesting/mail/level1")) { + return; + } + + String[] values = new String[] { "total", "added", "updated", + "removed", "unchanged", "unretrievable", + "doesNotValidate" }; + + for (String value : values) { + htmlMessage = replace(result, htmlMessage, value); + subject = replace(result, subject, value); + } + } + } + } + + htmlMessage = htmlMessage.replace("$$harvesterName$$", + ah.getParams().name); + subject = subject.replace("$$harvesterName$$", ah.getParams().name); + + htmlMessage = htmlMessage.replace("$$harvesterType$$", ah.getType()); + subject = subject.replace("$$harvesterType$$", ah.getType()); + + MailUtil.sendHtmlMail(toAddress, subject, htmlMessage, settings); + } + + /** + * @param result + * @return + */ + private static String extractWarningsTrace(Element result) { + StringBuffer errorMsg = new StringBuffer(""); + + for (Object o : result.getChildren("errors")) { + Element errores = ((Element) o); + for (Object a : errores.getChildren("error")) { + Element error = ((Element) a); + String desc = error.getChildText("description"); + String hint = error.getChildText("hint"); + String trace = getErrorTrace(error); + + // do not convert it to html, dangerous! + errorMsg = errorMsg.append("
  • '") + .append(desc) + .append("':") + .append(hint) + .append("

    ") + .append(trace) + .append("

  • "); + } + } + errorMsg.append("
      ").append(errorMsg).append("
    "); + return errorMsg.toString(); + } + + /** + * @param error + * @return + */ + private static String getErrorTrace(Element error) { + String trace = ""; + for (Object e : error.getChildren("error")) { + Element error_ = ((Element) e); + trace = error_.getChildText("message"); + } + return trace.replace("<", " "); + } + + /** + * Helps in the transformation of template to message + * + * @param element + * @param htmlMessage + * @param value + * @return + */ + private static String replace(Element element, String htmlMessage, + String value) { + String tmp = element.getChildText(value); + if (tmp == null) { + return htmlMessage.replace("$$" + value + "$$", "0"); + } else { + return htmlMessage.replace("$$" + value + "$$", tmp); + } + } +} \ No newline at end of file diff --git a/healthmonitor/src/main/java/org/fao/geonet/monitor/webapp/GeonetworkHealthCheckServlet.java b/healthmonitor/src/main/java/org/fao/geonet/monitor/webapp/GeonetworkHealthCheckServlet.java index e7891979306..1eefa9d260b 100644 --- a/healthmonitor/src/main/java/org/fao/geonet/monitor/webapp/GeonetworkHealthCheckServlet.java +++ b/healthmonitor/src/main/java/org/fao/geonet/monitor/webapp/GeonetworkHealthCheckServlet.java @@ -10,6 +10,11 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import jeeves.utils.Xml; + +import org.hibernate.exception.ExceptionUtils; +import org.jdom.Element; + import com.yammer.metrics.HealthChecks; import com.yammer.metrics.core.HealthCheck; import com.yammer.metrics.core.HealthCheckRegistry; @@ -29,7 +34,7 @@ public class GeonetworkHealthCheckServlet extends HttpServlet { * The attribute name of the {@link HealthCheckRegistry} instance in the servlet context. */ public static final String REGISTRY_ATTRIBUTE_KEY = "REGISTRY_ATTRIBUTE_KEY"; - private static final String CONTENT_TYPE = "text/plain"; + private static final String CONTENT_TYPE = "application/json"; private transient HealthCheckRegistry registry; @@ -49,9 +54,10 @@ protected void doGet(HttpServletRequest req, resp.setContentType(CONTENT_TYPE); resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); final PrintWriter writer = resp.getWriter(); + Element report = new Element("report"); if (results.isEmpty()) { resp.setStatus(HttpServletResponse.SC_OK); - writer.println("No health checks registered."); + report.addContent(new Element("msg").setText("No health checks registered.")); } else { if (isAllHealthy(results)) { resp.setStatus(HttpServletResponse.SC_OK); @@ -59,26 +65,27 @@ protected void doGet(HttpServletRequest req, resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } for (Map.Entry entry : results.entrySet()) { + Element healthcheck = new Element("healthcheck"); final HealthCheck.Result result = entry.getValue(); + healthcheck.addContent(new Element("name").setText(entry.getKey())); if (result.isHealthy()) { + healthcheck.addContent(new Element("status").setText("OK")); if (result.getMessage() != null) { - writer.format("* %s: OK%n %s%n", entry.getKey(), result.getMessage()); - } else { - writer.format("* %s: OK%n", entry.getKey()); + healthcheck.addContent(new Element("msg").setText(result.getMessage())); } } else { + healthcheck.addContent(new Element("status").setText("ERROR")); if (result.getMessage() != null) { - writer.format("! %s: ERROR%n! %s%n", entry.getKey(), result.getMessage()); + healthcheck.addContent(new Element("msg").setText(result.getMessage())); } - final Throwable error = result.getError(); if (error != null) { - writer.println(); - error.printStackTrace(writer); - writer.println(); + healthcheck.addContent(new Element("exception").setText(ExceptionUtils.getStackTrace(error))); } } + report.addContent(healthcheck); } + writer.println(Xml.getJSON(report)); } writer.close(); } @@ -91,4 +98,4 @@ private static boolean isAllHealthy(Map results) { } return true; } -} +} \ No newline at end of file diff --git a/installer/build.xml b/installer/build.xml index eac4bce5ffe..7c024829830 100644 --- a/installer/build.xml +++ b/installer/build.xml @@ -103,8 +103,8 @@ - + comment="GeoNetwork opensource properties. These are also used by geonetwork at runtime"> + diff --git a/installer/installer-config-win-jre.xml b/installer/installer-config-win-jre.xml index a450ff9ef35..d919fb2e3f9 100644 --- a/installer/installer-config-win-jre.xml +++ b/installer/installer-config-win-jre.xml @@ -98,13 +98,9 @@ - - - - @@ -137,31 +133,7 @@ - - - - - - - - - - - - - - - - - - diff --git a/installer/installer-config.xml b/installer/installer-config.xml index a1c4f322150..01c8e4206ae 100644 --- a/installer/installer-config.xml +++ b/installer/installer-config.xml @@ -127,7 +127,6 @@ - @@ -170,18 +169,6 @@ override="true"/> - - - - - - - - - - - - diff --git a/installer/unix-shortcuts.xml b/installer/unix-shortcuts.xml index d67254e558d..2e71bef83da 100644 --- a/installer/unix-shortcuts.xml +++ b/installer/unix-shortcuts.xml @@ -61,23 +61,6 @@ - - - - - - diff --git a/installer/windows-shortcuts.xml b/installer/windows-shortcuts.xml index 2ffbb220225..4e666f1b217 100644 --- a/installer/windows-shortcuts.xml +++ b/installer/windows-shortcuts.xml @@ -63,24 +63,6 @@ - - - - - - diff --git a/jeeves/pom.xml b/jeeves/pom.xml index 0bdc3d86d2d..e144166c663 100644 --- a/jeeves/pom.xml +++ b/jeeves/pom.xml @@ -172,6 +172,18 @@ org.springframework.security spring-security-web + + + net.sf.json-lib + json-lib + 2.4 + jdk15 + + + xom + xom + 1.1 + diff --git a/jeeves/src/main/java/jeeves/interfaces/Logger.java b/jeeves/src/main/java/jeeves/interfaces/Logger.java index 9a3a979a4f6..6379a07d9ae 100644 --- a/jeeves/src/main/java/jeeves/interfaces/Logger.java +++ b/jeeves/src/main/java/jeeves/interfaces/Logger.java @@ -23,6 +23,8 @@ package jeeves.interfaces; +import org.apache.log4j.FileAppender; + //============================================================================= public interface Logger @@ -32,8 +34,13 @@ public interface Logger public void info (String message); public void warning(String message); public void error (String message); + public void error (Throwable ex); public void fatal (String message); public String getModule(); + public void setAppender(FileAppender fa); + public String getFileAppender(); + public org.apache.log4j.Level getThreshold(); + } //============================================================================= diff --git a/jeeves/src/main/java/jeeves/server/dispatchers/ServiceManager.java b/jeeves/src/main/java/jeeves/server/dispatchers/ServiceManager.java index efe93dbe1dc..25e5e67f735 100644 --- a/jeeves/src/main/java/jeeves/server/dispatchers/ServiceManager.java +++ b/jeeves/src/main/java/jeeves/server/dispatchers/ServiceManager.java @@ -619,13 +619,21 @@ private String dispatchOutput(ServiceRequest req, ServiceContext context, req.beginStream("application/soap+xml; charset=UTF-8", cache); - if (!SOAPUtil.isEnvelope(response)) + if (!SOAPUtil.isEnvelope(response)) { response = SOAPUtil.embed(response); - } - else - req.beginStream("application/xml; charset=UTF-8", cache); - - req.write(response); + req.write(response); + } + } else { + + if (req.hasJSONOutput()) { + req.beginStream("application/json; charset=UTF-8", cache); + req.getOutputStream().write(Xml.getJSON(response).getBytes(Jeeves.ENCODING)); + req.endStream(); + } else { + req.beginStream("application/xml; charset=UTF-8", cache); + req.write(response); + } + } } } diff --git a/jeeves/src/main/java/jeeves/server/sources/ServiceRequest.java b/jeeves/src/main/java/jeeves/server/sources/ServiceRequest.java index 047ceea67b9..652e96ea8f3 100644 --- a/jeeves/src/main/java/jeeves/server/sources/ServiceRequest.java +++ b/jeeves/src/main/java/jeeves/server/sources/ServiceRequest.java @@ -49,6 +49,7 @@ public enum OutputMethod { DEFAULT, XML, SOAP } protected String language = null; protected Element params = new Element(Jeeves.Elem.REQUEST); protected boolean debug = false; + protected boolean jsonOutput = false; protected OutputStream outStream = null; protected String address = "0.0.0.0"; protected int statusCode= 200; @@ -128,6 +129,9 @@ public ServiceRequest() {} public void setDebug(boolean yesno) { debug = yesno; } + public void setJSONOutput(boolean yesno) { jsonOutput = yesno; } + public boolean hasJSONOutput() { return jsonOutput; } + //--------------------------------------------------------------------------- public void write(Element response) throws IOException diff --git a/jeeves/src/main/java/jeeves/server/sources/ServiceRequestFactory.java b/jeeves/src/main/java/jeeves/server/sources/ServiceRequestFactory.java index 5a9ac10731f..d97fd65ea0e 100644 --- a/jeeves/src/main/java/jeeves/server/sources/ServiceRequestFactory.java +++ b/jeeves/src/main/java/jeeves/server/sources/ServiceRequestFactory.java @@ -51,6 +51,10 @@ public final class ServiceRequestFactory { + + private static String JSON_URL_FLAG = "@json"; + private static String DEBUG_URL_FLAG = "!"; + /** * Default constructor. * Builds a ServiceRequestFactory. @@ -91,6 +95,7 @@ public static ServiceRequest create(HttpServletRequest req, HttpServletResponse srvReq.setDebug (extractDebug(url)); srvReq.setLanguage (extractLanguage(url)); srvReq.setService (extractService(url)); + srvReq.setJSONOutput (extractJSONFlag(url)); String ip = req.getRemoteAddr(); String forwardedFor = req.getHeader("x-forwarded-for"); if (forwardedFor != null) ip = forwardedFor; @@ -191,9 +196,18 @@ private static boolean extractDebug(String url) if (url == null) return false; - return url.indexOf('!') != -1; + return url.indexOf(DEBUG_URL_FLAG) != -1; } + /** + * Extracts the JSON output flag from the url + */ + private static boolean extractJSONFlag(String url) { + if (url == null) + return false; + + return url.indexOf(JSON_URL_FLAG) != -1; + } //--------------------------------------------------------------------------- /** Extracts the language code from the url */ @@ -222,8 +236,11 @@ private static String extractService(String url) if (url == null) return null; - if (url.endsWith("!")) - url = url.substring(0, url.length() -1); + if (url.endsWith(DEBUG_URL_FLAG)) + url = url.substring(0, url.length() - 1); + + if (url.endsWith(JSON_URL_FLAG)) + url = url.substring(0, url.length() - JSON_URL_FLAG.length()); int pos = url.lastIndexOf('/'); diff --git a/jeeves/src/main/java/jeeves/utils/Log.java b/jeeves/src/main/java/jeeves/utils/Log.java index e5e385eca03..4b8fc3e76a4 100644 --- a/jeeves/src/main/java/jeeves/utils/Log.java +++ b/jeeves/src/main/java/jeeves/utils/Log.java @@ -24,6 +24,11 @@ package jeeves.utils; +import java.util.Enumeration; + +import org.apache.log4j.Appender; +import org.apache.log4j.FileAppender; +import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.Priority; @@ -152,19 +157,81 @@ public static void fatal(String module, Object message) //-------------------------------------------------------------------------- /** Returns a simple logger object */ - public static jeeves.interfaces.Logger createLogger(final String module) { - return new jeeves.interfaces.Logger() - { - - @Override public boolean isDebugEnabled() { return Log.isDebugEnabled(module);} - @Override public void debug (String message) { Log.debug (module, message); } - @Override public void info (String message) { Log.info (module, message); } - @Override public void warning(String message) { Log.warning(module, message); } - @Override public void error (String message) { Log.error (module, message); } - @Override public void fatal (String message) { Log.fatal (module, message); } - @Override public String getModule() {return module;} + return createLogger(module, null); + } + + public static jeeves.interfaces.Logger createLogger(final String module, + final String fallbackModule) { + return new jeeves.interfaces.Logger() { + + public boolean isDebugEnabled() { + return Log.isDebugEnabled(module); + } + + public void debug(String message) { + Log.debug(module, message); + } + + public void info(String message) { + Log.info(module, message); + } + + public void warning(String message) { + Log.warning(module, message); + } + + public void error(String message) { + Log.error(module, message); + } + + public void fatal(String message) { + Log.fatal(module, message); + } + + public void error(Throwable t) { + Log.error(module, t.getMessage(), t); + } + + public void setAppender(FileAppender fa) { + Logger.getLogger(module).removeAllAppenders(); + Logger.getLogger(module).addAppender(fa); + } + + public String getFileAppender() { + // Set effective level to be sure it writes the log + Logger.getLogger(module).setLevel(getThreshold()); + + @SuppressWarnings("rawtypes") + Enumeration appenders = Logger.getLogger(module) + .getAllAppenders(); + while (appenders.hasMoreElements()) { + Appender a = (Appender) appenders.nextElement(); + if (a instanceof FileAppender) { + return ((FileAppender) a).getFile(); + } + } + appenders = Logger.getLogger(fallbackModule).getAllAppenders(); + while (appenders.hasMoreElements()) { + Appender a = (Appender) appenders.nextElement(); + if (a instanceof FileAppender) { + return ((FileAppender) a).getFile(); + } + } + + return ""; + + } + + public Level getThreshold() { + return Logger.getLogger(fallbackModule).getEffectiveLevel(); + } + + @Override + public String getModule() { + return module; + } }; } diff --git a/jeeves/src/main/java/jeeves/utils/Xml.java b/jeeves/src/main/java/jeeves/utils/Xml.java index 47d256f1253..75efc753907 100644 --- a/jeeves/src/main/java/jeeves/utils/Xml.java +++ b/jeeves/src/main/java/jeeves/utils/Xml.java @@ -27,6 +27,8 @@ import jeeves.exceptions.XSDValidationErrorEx; import net.sf.saxon.Configuration; import net.sf.saxon.FeatureKeys; +import net.sf.json.JSON; +import net.sf.json.xml.XMLSerializer; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.SystemUtils; @@ -659,6 +661,27 @@ public static String getString(Element data) //--------------------------------------------------------------------------- + /** + * Converts an xml element to JSON + * + * @param xml the XML element + * @return the JSON response + * + * @throws JsonParseException + * @throws JsonMappingException + * @throws IOException + */ + public static String getJSON (Element xml) throws IOException { + XMLSerializer xmlSerializer = new XMLSerializer(); + + // Disable type hints. When enable, a type attribute in the root + // element will throw NPE. + // http://sourceforge.net/mailarchive/message.php?msg_id=27646519 + xmlSerializer.setTypeHintsEnabled(false); + xmlSerializer.setTypeHintsCompatibility(false); + JSON json = xmlSerializer.read(Xml.getString(xml)); + return json.toString(2); + } /** * * @param data diff --git a/pom.xml b/pom.xml index 34e6e2a2002..56ba7aadf3b 100644 --- a/pom.xml +++ b/pom.xml @@ -944,6 +944,7 @@ jeeves sde web-client + web-ui domain core oaipmh diff --git a/release/bin/gast.bat b/release/bin/gast.bat deleted file mode 100644 index 5ffa368bd22..00000000000 --- a/release/bin/gast.bat +++ /dev/null @@ -1,2 +0,0 @@ -cd ..\gast -start javaw %1 -jar gast.jar diff --git a/release/bin/gast.sh b/release/bin/gast.sh deleted file mode 100644 index b5295d126e4..00000000000 --- a/release/bin/gast.sh +++ /dev/null @@ -1,2 +0,0 @@ -cd ../gast -java $1 -jar gast.jar $2 diff --git a/release/bin/ico/gast.ico b/release/bin/ico/gast.ico deleted file mode 100644 index 238f8151661..00000000000 Binary files a/release/bin/ico/gast.ico and /dev/null differ diff --git a/release/bin/jre/gast-jre.bat b/release/bin/jre/gast-jre.bat deleted file mode 100644 index 5c1bf51c2c9..00000000000 --- a/release/bin/jre/gast-jre.bat +++ /dev/null @@ -1,2 +0,0 @@ -cd ..\gast -..\jre1.5.0_12\bin\java -jar gast.jar diff --git a/services/src/main/java/org/fao/geonet/guiservices/csw/Set2.java b/services/src/main/java/org/fao/geonet/guiservices/csw/Set2.java new file mode 100644 index 00000000000..71327e94a92 --- /dev/null +++ b/services/src/main/java/org/fao/geonet/guiservices/csw/Set2.java @@ -0,0 +1,90 @@ +//============================================================================= +//=== Copyright (C) 2001-2010 Food and Agriculture Organization of the +//=== United Nations (FAO-UN), United Nations World Food Programme (WFP) +//=== and United Nations Environment Programme (UNEP) +//=== +//=== This program is free software; you can redistribute it and/or modify +//=== it under the terms of the GNU General Public License as published by +//=== the Free Software Foundation; either version 2 of the License, or (at +//=== your option) any later version. +//=== +//=== This program is distributed in the hope that it will be useful, but +//=== WITHOUT ANY WARRANTY; without even the implied warranty of +//=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +//=== General Public License for more details. +//=== +//=== You should have received a copy of the GNU General Public License +//=== along with this program; if not, write to the Free Software +//=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA +//=== +//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, +//=== Rome - Italy. email: geonetwork@osgeo.org +//============================================================================== +package org.fao.geonet.guiservices.csw; + +import java.util.Map; + +import jeeves.constants.Jeeves; +import jeeves.interfaces.Service; +import jeeves.resources.dbms.Dbms; +import jeeves.server.ServiceConfig; +import jeeves.server.context.ServiceContext; + +import org.fao.geonet.GeonetContext; +import org.fao.geonet.constants.Geonet; +import org.fao.geonet.kernel.csw.domain.CswCapabilitiesInfo; +import org.fao.geonet.lib.Lib; +import org.jdom.Element; + +/** + * Copy of Set - only takes care of saving GetCapabilities properties + * and not settings. In order to save settings use the setting service. + * + */ +public class Set2 implements Service { + + public void init(String appPath, ServiceConfig params) throws Exception { + } + + public Element exec(Element params, ServiceContext context) throws Exception { + GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME); + Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB); + + // Process parameters and save capabilities information in database + saveCswCapabilitiesInfo(params, gc, dbms); + + // Build response + return new Element(Jeeves.Elem.RESPONSE).setText("ok"); + } + + private void saveCswCapabilitiesInfo(Element params, GeonetContext gc, Dbms dbms) throws Exception { + + Map langs = Lib.local.getLanguages(dbms); + + for (String langId : langs.keySet()) { + + CswCapabilitiesInfo cswCapInfo = new CswCapabilitiesInfo(); + + cswCapInfo.setLangId(langId); + Element title = params.getChild("csw.title_" + langId); + if (title != null) { + cswCapInfo.setTitle(title.getValue()); + } + Element abs = params.getChild("csw.abstract_" + langId); + if (abs != null) { + cswCapInfo.setAbstract(abs.getValue()); + } + Element fees = params.getChild("csw.fees_" + langId); + if (fees != null) { + cswCapInfo.setFees(fees.getValue()); + } + Element accessConstraints = params.getChild("csw.accessConstraints_" + langId); + if (accessConstraints != null) { + cswCapInfo.setAccessConstraints(accessConstraints.getValue()); + } + // Save item + CswCapabilitiesInfo.saveCswCapabilitiesInfo(dbms, cswCapInfo); + } + } + +} \ No newline at end of file diff --git a/services/src/main/java/org/fao/geonet/services/metadata/Create.java b/services/src/main/java/org/fao/geonet/services/metadata/Create.java index fab0a078d2e..4f36d4901ff 100644 --- a/services/src/main/java/org/fao/geonet/services/metadata/Create.java +++ b/services/src/main/java/org/fao/geonet/services/metadata/Create.java @@ -42,8 +42,12 @@ * Creates a metadata copying data from a given template. */ public class Create extends NotInReadOnlyModeService { - public void init(String appPath, ServiceConfig params) throws Exception {} + boolean useEditTab = false; + public void init(String appPath, ServiceConfig params) throws Exception { + useEditTab = params.getValue("editTab", "false").equals("true"); + } + //-------------------------------------------------------------------------- //--- //--- Service @@ -90,7 +94,6 @@ public Element serviceSpecificExec(Element params, ServiceContext context) throw java.util.List list = dbms.select(selectGroupIdQuery, Integer.valueOf(user.getUserId()), Integer.valueOf(groupOwner)).getChildren(); - System.out.println("Group found: " + list.size()); if (list.size() == 0) { throw new ServiceNotAllowedEx("Service not allowed. User needs to be Editor in group with id " + groupOwner); } @@ -104,6 +107,14 @@ public Element serviceSpecificExec(Element params, ServiceContext context) throw Element response = new Element(Jeeves.Elem.RESPONSE); response.addContent(new Element(Geonet.Elem.JUSTCREATED).setText("true")); + + String sessionTabProperty = useEditTab ? Geonet.Session.METADATA_EDITING_TAB : Geonet.Session.METADATA_SHOW; + + // Set current tab for new editing session if defined. + Element elCurrTab = params.getChild(Params.CURRTAB); + if (elCurrTab != null) { + context.getUserSession().setProperty(sessionTabProperty, elCurrTab.getText()); + } response.addContent(new Element(Geonet.Elem.ID).setText(newId)); return response; } diff --git a/services/src/main/java/org/fao/geonet/services/ownership/Groups.java b/services/src/main/java/org/fao/geonet/services/ownership/Groups.java index a12cb0da91a..a18142ce2ff 100644 --- a/services/src/main/java/org/fao/geonet/services/ownership/Groups.java +++ b/services/src/main/java/org/fao/geonet/services/ownership/Groups.java @@ -35,6 +35,7 @@ import org.fao.geonet.lib.Lib; import org.jdom.Element; +import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -107,19 +108,26 @@ public Element exec(Element params, ServiceContext context) throws Exception record.setName("targetGroup"); response.addContent(record); // List all group users or administrator - String query = "SELECT id, surname, name FROM Users LEFT JOIN UserGroups ON (id = userId) "+ + String query = "SELECT id, surname, name, username FROM Users LEFT JOIN UserGroups ON (id = userId) "+ " WHERE (groupId=? AND usergroups.profile != 'RegisteredUser') OR users.profile = 'Administrator'"; Element editors = dbms.select(query, Integer.valueOf(groupId)); - for (Object o : editors.getChildren()) + // Avoid duplicated users: if a user is a Reviewer in a group, in the database exists a row as Editor also + List editorsId = new ArrayList(); + + for (Object o : editors.getChildren()) { Element editor = (Element) o; + if (editorsId.contains(editor.getChildText("id"))) continue; + editor = (Element) editor.clone(); editor.removeChild("password"); editor.setName("editor"); record.addContent(editor); + + editorsId.add(editor.getChildText("id")); } } } diff --git a/services/src/main/java/org/fao/geonet/services/password/Change.java b/services/src/main/java/org/fao/geonet/services/password/Change.java index 614284bde6b..d88ed27558d 100644 --- a/services/src/main/java/org/fao/geonet/services/password/Change.java +++ b/services/src/main/java/org/fao/geonet/services/password/Change.java @@ -40,6 +40,7 @@ import org.fao.geonet.kernel.setting.SettingInfo; import org.fao.geonet.kernel.setting.SettingManager; import org.fao.geonet.services.NotInReadOnlyModeService; +import org.fao.geonet.util.MailUtil; import org.jdom.Element; import java.io.File; @@ -58,7 +59,7 @@ public class Change extends NotInReadOnlyModeService { // -------------------------------------------------------------------------- public void init(String appPath, ServiceConfig params) throws Exception { - this.stylePath = appPath + FS + Geonet.Path.STYLESHEETS + FS; + this.stylePath = appPath + Geonet.Path.XSLT_FOLDER + FS + "services" + FS + "account" + FS; } // -------------------------------------------------------------------------- @@ -101,19 +102,12 @@ public Element serviceSpecificExec(Element params, ServiceContext context) GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME); SettingManager sm = gc.getBean(SettingManager.class); - String host = sm.getValue("system/feedback/mailServer/host"); - String port = sm.getValue("system/feedback/mailServer/port"); String adminEmail = sm.getValue("system/feedback/email"); String thisSite = sm.getValue("system/site/name"); // get site URL SettingInfo si = new SettingInfo(context); String siteURL = si.getSiteUrl() + context.getBaseUrl(); - - // Do not allow an unconfigured site to send out change password emails - if (thisSite == null || host == null || port == null || adminEmail == null || thisSite.equals("dummy") || host.equals("") || port.equals("") || adminEmail.equals("")) { - throw new IllegalArgumentException("Missing settings in System Configuration (see Administration menu) - cannot change passwords"); - } // All ok so update password dbms.execute ( "UPDATE Users SET password=? WHERE username=?", PasswordUtil.encode(context, password), username); @@ -135,7 +129,7 @@ public Element serviceSpecificExec(Element params, ServiceContext context) String content = elEmail.getChildText("content"); // send password changed email - if (!sendMail(host, Integer.parseInt(port), subject, adminEmail, to, content, PROTOCOL)) { + if (!MailUtil.sendMail(to, subject, content, sm, adminEmail, "")) { throw new OperationAbortedEx("Could not send email"); } @@ -144,7 +138,6 @@ public Element serviceSpecificExec(Element params, ServiceContext context) private static String FS = File.separator; private String stylePath; - private static final String PROTOCOL = "smtp"; private static final String CHANGE_KEY = "changeKey"; private static final String PWD_CHANGED_XSLT = "password-changed-email.xsl"; public static final String DATE_FORMAT = "yyyy-MM-dd"; diff --git a/services/src/main/java/org/fao/geonet/services/password/SendLink.java b/services/src/main/java/org/fao/geonet/services/password/SendLink.java index 6bbbef91730..de30584a55d 100644 --- a/services/src/main/java/org/fao/geonet/services/password/SendLink.java +++ b/services/src/main/java/org/fao/geonet/services/password/SendLink.java @@ -39,6 +39,7 @@ import org.fao.geonet.kernel.setting.SettingInfo; import org.fao.geonet.kernel.setting.SettingManager; import org.fao.geonet.services.MailSendingService; +import org.fao.geonet.util.MailUtil; import org.jdom.Element; import java.io.File; @@ -60,7 +61,7 @@ public class SendLink extends MailSendingService { // -------------------------------------------------------------------------- public void init(String appPath, ServiceConfig params) throws Exception { - this.stylePath = appPath + FS + Geonet.Path.STYLESHEETS + FS; + this.stylePath = appPath + Geonet.Path.XSLT_FOLDER + FS + "services" + FS + "account" + FS; } // -------------------------------------------------------------------------- @@ -92,19 +93,12 @@ public Element exec(Element params, ServiceContext context) GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME); SettingManager sm = gc.getBean(SettingManager.class); - String host = sm.getValue("system/feedback/mailServer/host"); - String port = sm.getValue("system/feedback/mailServer/port"); String adminEmail = sm.getValue("system/feedback/email"); String thisSite = sm.getValue("system/site/name"); SettingInfo si = new SettingInfo(context); String siteURL = si.getSiteUrl() + context.getBaseUrl(); - // Do not allow an unconfigured site to send out change password emails - if (thisSite == null || host == null || port == null || adminEmail == null || thisSite.equals("dummy") || host.equals("") || port.equals("") || adminEmail.equals("")) { - throw new IllegalArgumentException("Missing settings in System Configuration (see Administration menu) - cannot change passwords"); - } - // construct change key - only valid today String scrambledPassword = elUser.getChild("record").getChildText(Params.PASSWORD); Calendar cal = Calendar.getInstance(); @@ -129,7 +123,7 @@ public Element exec(Element params, ServiceContext context) String content = elEmail.getChildText("content"); // send change link via email - if (!sendMail(host, Integer.parseInt(port), subject, adminEmail, to, content, PROTOCOL)) { + if (!MailUtil.sendMail(to, subject, content, sm, adminEmail, "")) { throw new OperationAbortedEx("Could not send email"); } @@ -138,7 +132,6 @@ public Element exec(Element params, ServiceContext context) private static String FS = File.separator; private String stylePath; - private static final String PROTOCOL = "smtp"; private static final String CHANGE_EMAIL_XSLT = "password-forgotten-email.xsl"; public static final String DATE_FORMAT = "yyyy-MM-dd"; diff --git a/services/src/main/java/org/fao/geonet/services/register/SelfRegister.java b/services/src/main/java/org/fao/geonet/services/register/SelfRegister.java index 04dd05410a3..6b3508a81f1 100644 --- a/services/src/main/java/org/fao/geonet/services/register/SelfRegister.java +++ b/services/src/main/java/org/fao/geonet/services/register/SelfRegister.java @@ -36,6 +36,7 @@ import org.fao.geonet.kernel.setting.SettingInfo; import org.fao.geonet.kernel.setting.SettingManager; import org.fao.geonet.services.NotInReadOnlyModeService; +import org.fao.geonet.util.MailUtil; import org.jdom.Element; import java.io.File; @@ -49,7 +50,6 @@ public class SelfRegister extends NotInReadOnlyModeService { private static final String PROFILE_TEMPLATE = "profileTemplate"; private static final String PROFILE = "RegisteredUser"; - private static final String PROTOCOL = "smtp"; private static String FS = File.separator; private String stylePath; private static final String PASSWORD_EMAIL_XSLT = "registration-pwd-email.xsl"; @@ -62,7 +62,7 @@ public class SelfRegister extends NotInReadOnlyModeService { // -------------------------------------------------------------------------- public void init(String appPath, ServiceConfig params) throws Exception { - this.stylePath = appPath + FS + Geonet.Path.STYLESHEETS + FS; + this.stylePath = appPath + Geonet.Path.XSLT_FOLDER + FS + "services" + FS + "account" + FS; } // -------------------------------------------------------------------------- @@ -97,15 +97,9 @@ public Element serviceSpecificExec(Element params, ServiceContext context) GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME); SettingManager sm = gc.getBean(SettingManager.class); - String host = sm.getValue("system/feedback/mailServer/host"); - String port = sm.getValue("system/feedback/mailServer/port"); - String from = sm.getValue("system/feedback/email"); + String catalogAdminEmail = sm.getValue("system/feedback/email"); String thisSite = sm.getValue("system/site/name"); - // Do not allow an unconfigured site to send out self-registration emails - if (thisSite == null || host == null || port == null || from == null || thisSite.equals("dummy") || host.equals("") || port.equals("") || from.equals("")) { - throw new IllegalArgumentException("Missing settings in System Configuration (see Administration menu) - cannot do self registration"); - } Element element = new Element(Jeeves.Elem.RESPONSE); element.setAttribute(Params.SURNAME,surname); @@ -136,14 +130,14 @@ public Element serviceSpecificExec(Element params, ServiceContext context) SettingInfo si = new SettingInfo(context); String siteURL = si.getSiteUrl() + context.getBaseUrl(); - if (!sendRegistrationEmail(params, password, host, port, from, thisSite, siteURL)) { + if (!sendRegistrationEmail(params, password, catalogAdminEmail, thisSite, siteURL, sm)) { dbms.abort(); return element.addContent(new Element("result").setText("errorEmailToAddressFailed")); } // Send email to admin requesting non-standard profile if required - if (!profile.equalsIgnoreCase(Geonet.Profile.REGISTERED_USER) && !sendProfileRequest(params, host, port, from, thisSite, siteURL)) { + if (!profile.equalsIgnoreCase(Geonet.Profile.REGISTERED_USER) && !sendProfileRequest(params, catalogAdminEmail, thisSite, siteURL, sm)) { return element.addContent(new Element("result").setText("errorProfileRequestFailed")); } @@ -163,8 +157,8 @@ public Element serviceSpecificExec(Element params, ServiceContext context) * @return */ private boolean sendRegistrationEmail(Element params, String password, - String host, String port, String from, String thisSite, - String siteURL) throws Exception, SQLException { + String from, String thisSite, + String siteURL, SettingManager sm) throws Exception, SQLException { //TODO: allow internationalised emails @@ -183,22 +177,20 @@ private boolean sendRegistrationEmail(Element params, String password, String subject = elEmail.getChildText("subject"); String message = elEmail.getChildText("content"); - return sendMail(host, Integer.parseInt(port), subject, from, email, message, PROTOCOL); + return MailUtil.sendMail(email, subject, message, sm); } /** - * Send the profile request. + * Send the profile request to the catalog administrator. * * @param params - * @param host - * @param port * @param from * @param thisSite * @param siteURL * @return */ - private boolean sendProfileRequest(Element params, String host, String port, String from, - String thisSite, String siteURL) throws Exception { + private boolean sendProfileRequest(Element params, String from, String thisSite, String siteURL, + SettingManager sm) throws Exception { //TODO: allow internationalised emails @@ -215,7 +207,7 @@ private boolean sendProfileRequest(Element params, String host, String port, Str String subject = elEmail.getChildText("subject"); String message = elEmail.getChildText("content"); - return sendMail(host, Integer.parseInt(port), subject, from, from, message, PROTOCOL); + return MailUtil.sendMail(from, subject, message, sm); } /** diff --git a/web-client/pom.xml b/web-client/pom.xml index e004e134c16..9aeeb3ed417 100644 --- a/web-client/pom.xml +++ b/web-client/pom.xml @@ -123,7 +123,8 @@ ${project.build.directory}/classes/apps/js/ext-ux/MultiselectItemSelector-3.0/Multiselect.js ${project.build.directory}/classes/apps/js/ext-ux/LightBox/lightbox.js ${project.build.directory}/classes/apps/js/ext-ux/SuperBoxSelect/SuperBoxSelect.js - + ${project.build.directory}/classes/apps/js/ext-ux/CheckColumn.js + ${project.build.directory}/classes/apps/js/proj4js-compressed.js @@ -411,7 +412,8 @@ ${project.build.directory}/classes/apps/js/GeoNetwork/lib/GeoNetwork/widgets/admin/MetadataInsertPanel.js ${project.build.directory}/classes/apps/js/GeoNetwork/lib/GeoNetwork/widgets/admin/SubTemplateManagerPanel.js ${project.build.directory}/classes/apps/js/GeoNetwork/lib/GeoNetwork/widgets/admin/ThesaurusManagerPanel.js - + ${project.build.directory}/classes/apps/js/GeoNetwork/lib/GeoNetwork/widgets/admin/PrivilegesPanel.js + ${project.build.directory}/classes/apps/js/GeoNetwork/lib/GeoNetwork/widgets/OGCServiceQuickRegister.js ${project.build.directory}/classes/apps/js/GeoNetwork/lib/GeoNetwork/map/ExtentMap.js diff --git a/web-client/src/main/resources/apps/css/gndefault.css b/web-client/src/main/resources/apps/css/gndefault.css index 0691d2c26f9..c7d25b0acac 100644 --- a/web-client/src/main/resources/apps/css/gndefault.css +++ b/web-client/src/main/resources/apps/css/gndefault.css @@ -541,6 +541,9 @@ div.facets * .facet-less-bt a { color: #777777 !important; } +.breadcrumb table.x-btn { + float: left; +} .breadcrumb * .x-btn-tl, .breadcrumb * .x-btn-tr, .breadcrumb * .x-btn-tc, @@ -732,6 +735,30 @@ ul.gn-relation-thumbnail { display: none; } +.filter-text-icon { + background-image: url(../images/default/find.png) !important; + width: 16px; + height: 16px; + border-color: transparent !important; + margin: 4px; +} + +.privilges-not-user-groups .x-grid3-cell-inner { + color: gray; +} +.privileges-internal .x-grid3-cell-inner { + font-weight: bold; +} + +.privileges-grid-disable { + color: gray; +} + +.privileges-grid-disable .x-grid3-check-col, +.privileges-grid-disable .x-grid3-check-col-on { + opacity:0.4; +} + #user-info-tip { border-top: 1px solid #b6b6b6; } diff --git a/web-client/src/main/resources/apps/css/gnmetadatadefault.css b/web-client/src/main/resources/apps/css/gnmetadatadefault.css index 863f2160692..36f7bdd4eac 100644 --- a/web-client/src/main/resources/apps/css/gnmetadatadefault.css +++ b/web-client/src/main/resources/apps/css/gnmetadatadefault.css @@ -411,11 +411,11 @@ span.buttons a.small span { } .buttons a.add span { background-image : url(../images/default/bullet_toggle_plus.png); - background-size: 8px; + background-size: 10px; } .buttons a.del span { background-image : url(../images/default/bullet_toggle_minus.png); - background-size: 8px; + background-size: 10px; } .buttons a.up span { background-image : url(../images/default/bullet_arrow_up.png); diff --git a/web-client/src/main/resources/apps/html5ui/css/colors.css b/web-client/src/main/resources/apps/html5ui/css/colors.css index 7940958e9fa..1d28cedc66e 100644 --- a/web-client/src/main/resources/apps/html5ui/css/colors.css +++ b/web-client/src/main/resources/apps/html5ui/css/colors.css @@ -5,11 +5,13 @@ This file contains all the color schema of the UI and only colors. If you want to customize the color schema, just use this file. **/ + + html,button,input,select,textarea { color: #222; } -div#resultsPanel .x-panel-bbar table.x-toolbar-ct,.x-panel-header,div#big-map .x-panel-tbar table.x-toolbar-ct,div#resultsPanel table.x-toolbar-ct,div#resultsPanel button,.main aside +div#resultsPanel .x-panel-bbar table.x-toolbar-ct,.x-panel-header,div#big-map .x-panel-tbar table.x-toolbar-ct,div#resultsPanel table.x-toolbar-ct,.main aside { background: #47A8DD; color: white; @@ -285,10 +287,11 @@ dl.xml { div#tabs .x-tab-strip span.x-tab-strip-text { color: black; - shadow: grey; + box-shadow: grey; } .emptyThumbnail span { color: #376690; -} \ No newline at end of file +} + diff --git a/web-client/src/main/resources/apps/html5ui/css/main.css b/web-client/src/main/resources/apps/html5ui/css/main.css index c540ee42a51..7f2e4899e21 100644 --- a/web-client/src/main/resources/apps/html5ui/css/main.css +++ b/web-client/src/main/resources/apps/html5ui/css/main.css @@ -1224,6 +1224,12 @@ div.facets * a { box-shadow: 3px 3px 12px 3px grey; } + + +#login_div input { + max-width: 180px; +} + #login_div #login_button { float: right; margin-top: 7px; diff --git a/web-client/src/main/resources/apps/html5ui/js/App.js b/web-client/src/main/resources/apps/html5ui/js/App.js index d833c76a2f6..f888593f496 100644 --- a/web-client/src/main/resources/apps/html5ui/js/App.js +++ b/web-client/src/main/resources/apps/html5ui/js/App.js @@ -583,7 +583,7 @@ GeoNetwork.app = function() { statusBarId : 'info', hostUrl : geonetworkUrl, mdOverlayedCmpId : 'resultsPanel', - adminAppUrl : geonetworkUrl + '/srv/' + lang + '/admin', + adminAppUrl : geonetworkUrl + '/srv/' + lang + '/admin.console', // Declare default store to be used for records and // summary metadataStore : GeoNetwork.Settings.mdStore ? new GeoNetwork.Settings.mdStore() @@ -648,6 +648,13 @@ GeoNetwork.app = function() { var actionCtn = Ext.getCmp('resultsPanel').getTopToolbar(); actionCtn.createMetadataAction.handler.apply(actionCtn); } + + if (urlParameters.insert !== undefined) { + setTimeout(function () { + var actionCtn = Ext.getCmp('resultsPanel').getTopToolbar(); + actionCtn.mdImportAction.handler.apply(actionCtn); + }, 500); + } }, edit : function(uuid) { edit(uuid); diff --git a/web-client/src/main/resources/apps/html5ui/js/Templates.js b/web-client/src/main/resources/apps/html5ui/js/Templates.js index db82e05a576..3affb1a1ab8 100644 --- a/web-client/src/main/resources/apps/html5ui/js/Templates.js +++ b/web-client/src/main/resources/apps/html5ui/js/Templates.js @@ -144,7 +144,7 @@ GeoNetwork.HTML5UI.Templates.SHORT_TITLE = checked="true" \ class="selector" \ - onclick="javascript:catalogue.metadataSelect((this.checked?\'add\':\'remove\'), [\'{uuid}\']);"\ + onclick="javascript:catalogue.metadataSelect((this.checked?\'add\':\'remove\'), [\'{uuid}\']);"/>\ \ {[Ext.util.Format.ellipsis(values.title, 30, true)]}\ '; @@ -153,7 +153,7 @@ GeoNetwork.HTML5UI.Templates.TITLE = checked="true" \ class="selector" \ - onclick="javascript:catalogue.metadataSelect((this.checked?\'add\':\'remove\'), [\'{uuid}\']);"\ + onclick="javascript:catalogue.metadataSelect((this.checked?\'add\':\'remove\'), [\'{uuid}\']);"/>\ {title}\ '; @@ -191,7 +191,7 @@ GeoNetwork.HTML5UI.Templates.SHOW_ON_MAP = '; GeoNetwork.HTML5UI.Templates.LINKCONTAINER = - '', '', '', @@ -204,7 +200,7 @@ GeoNetwork.Templates.FULL = new Ext.XTemplate( '{value}{[xindex==xcount?"":", "]}', '

    ', '', - '', v ? '-on' : ''); + }, + + // Deprecate use as a plugin. Remove in 4.0 + init: Ext.emptyFn +}); + +// register ptype. Deprecate. Remove in 4.0 +Ext.preg('checkcolumn', Ext.ux.grid.CheckColumn); + +// backwards compat. Remove in 4.0 +Ext.grid.CheckColumn = Ext.ux.grid.CheckColumn; + +// register Column xtype +Ext.grid.Column.types.checkcolumn = Ext.ux.grid.CheckColumn; \ No newline at end of file diff --git a/web-client/src/main/resources/apps/search/index_debug.html b/web-client/src/main/resources/apps/search/index_debug.html index 10169b4b75e..ffea29a139f 100644 --- a/web-client/src/main/resources/apps/search/index_debug.html +++ b/web-client/src/main/resources/apps/search/index_debug.html @@ -64,6 +64,7 @@ + diff --git a/web-client/src/main/resources/apps/search/js/App.js b/web-client/src/main/resources/apps/search/js/App.js index d9b04a523bc..4c1a2a4a0ea 100644 --- a/web-client/src/main/resources/apps/search/js/App.js +++ b/web-client/src/main/resources/apps/search/js/App.js @@ -32,7 +32,7 @@ GeoNetwork.app = function () { * An interactive map panel for data visualization */ var iMap, searchForm, facetsPanel, resultsPanel, metadataResultsView, tBar, bBar, - mainTagCloudViewPanel, infoPanel, + mainTagCloudViewPanel, infoPanel, latestView, visualizationModeInitialized = false; // private function: @@ -148,9 +148,11 @@ GeoNetwork.app = function () { // Register events to set cookie values catalogue.on('afterLogin', function () { cookie.set('user', catalogue.identifiedUser); + loadNews(); }); catalogue.on('afterLogout', function () { cookie.set('user', undefined); + loadNews(); }); // Refresh login form if needed @@ -484,26 +486,7 @@ GeoNetwork.app = function () { return tagCloudView; } - /** - * Create latest metadata panel. - */ - function createLatestUpdate() { - var latestView = new GeoNetwork.MetadataResultsView({ - catalogue: catalogue, - autoScroll: true, - tpl: GeoNetwork.Settings.latestTpl - }); - var latestStore = GeoNetwork.Settings.mdStore(); - latestView.setStore(latestStore); - latestStore.on('load', function () { - Ext.ux.Lightbox.register('a[rel^=lightbox]'); - }); - var p = new Ext.Panel({ - border: false, - bodyCssClass: 'md-view', - items: latestView, - renderTo: 'latest' - }); + function loadNews() { catalogue.kvpSearch(GeoNetwork.Settings.latestQuery, null, null, null, true, latestView.getStore()); } function loadCallback(el, success, response, options) { @@ -560,7 +543,7 @@ GeoNetwork.app = function () { * Create latest metadata panel. */ function createLatestUpdate(){ - var latestView = new GeoNetwork.MetadataResultsView({ + latestView = new GeoNetwork.MetadataResultsView({ catalogue: catalogue, autoScroll: true, tpl: GeoNetwork.Settings.latestTpl @@ -576,7 +559,7 @@ GeoNetwork.app = function () { items: latestView, renderTo: 'latest' }); - catalogue.kvpSearch(GeoNetwork.Settings.latestQuery, null, null, null, true, latestView.getStore()); + loadNews(); } function show(uuid, record, url, maximized, width, height) { var showFeedBackButton = record.get('email'); @@ -722,7 +705,7 @@ GeoNetwork.app = function () { lang: lang, hostUrl: geonetworkUrl, mdOverlayedCmpId: 'resultsPanel', - adminAppUrl: geonetworkUrl + '/srv/' + lang + '/admin', + adminAppUrl: geonetworkUrl + '/srv/' + lang + '/admin.console', // Declare default store to be used for records and summary metadataStore: GeoNetwork.Settings.mdStore ? GeoNetwork.Settings.mdStore() : GeoNetwork.data.MetadataResultsStore(), metadataCSWStore : GeoNetwork.data.MetadataCSWResultsStore(), @@ -758,14 +741,10 @@ GeoNetwork.app = function () { var margins = '35 0 0 0'; var breadcrumb = new Ext.Panel({ - layout:'table', cls: 'breadcrumb', defaultType: 'button', border: false, - split: false, - layoutConfig: { - columns:3 - } + split: false }); facetsPanel = new GeoNetwork.FacetsPanel({ searchForm: searchForm, @@ -844,6 +823,12 @@ GeoNetwork.app = function () { } else if (urlParameters.id !== undefined) { catalogue.metadataShowById(urlParameters.id, true); } + if (urlParameters.insert !== undefined) { + setTimeout(function () { + var actionCtn = Ext.getCmp('resultsPanel').getTopToolbar(); + actionCtn.mdImportAction.handler.apply(actionCtn); + }, 500); + } // FIXME : should be in Search field configuration Ext.get('E_any').setWidth(285); @@ -863,7 +848,6 @@ GeoNetwork.app = function () { } }); }); - // Hack to run search after all app is rendered within a sec ... // It could have been better to trigger event in SearchFormPanel#applyState // FIXME diff --git a/web-client/src/main/resources/apps/tabsearch/index_debug.html b/web-client/src/main/resources/apps/tabsearch/index_debug.html index 680215fbb54..d4f1dcd15c3 100644 --- a/web-client/src/main/resources/apps/tabsearch/index_debug.html +++ b/web-client/src/main/resources/apps/tabsearch/index_debug.html @@ -79,7 +79,7 @@ - + diff --git a/web-client/src/main/resources/apps/tabsearch/js/App.js b/web-client/src/main/resources/apps/tabsearch/js/App.js index 16be0f8657c..ae3b424e21f 100644 --- a/web-client/src/main/resources/apps/tabsearch/js/App.js +++ b/web-client/src/main/resources/apps/tabsearch/js/App.js @@ -830,7 +830,7 @@ GeoNetwork.app = function () { lang : lang, hostUrl : geonetworkUrl, mdOverlayedCmpId : 'resultsPanel', - adminAppUrl : geonetworkUrl + '/srv/' + lang + '/admin', + adminAppUrl : geonetworkUrl + '/srv/' + lang + '/admin.console', // Declare default store to be used for records and // summary metadataStore : GeoNetwork.Settings.mdStore ? GeoNetwork.Settings @@ -1037,6 +1037,13 @@ GeoNetwork.app = function () { catalogue.metadataShowById(urlParameters.id, true); } + if (urlParameters.insert !== undefined) { + setTimeout(function () { + var actionCtn = Ext.getCmp('resultsPanel').getTopToolbar(); + actionCtn.mdImportAction.handler.apply(actionCtn); + }, 500); + } + // FIXME : should be in Search field configuration Ext.get('E_any').setWidth(285); Ext.get('E_any').setHeight(28); diff --git a/web-ui/README.md b/web-ui/README.md new file mode 100644 index 00000000000..30152d7c069 --- /dev/null +++ b/web-ui/README.md @@ -0,0 +1,99 @@ +# web-ui module + +## Content + +This module contains a web user interface for GeoNetwork opensource based on AngularJS, Bootstrap and d3.js librairies. + + + +## Compile + +Closure project is used to check, compile and manage JS dependencies. + +### Install closure & closure utilities + +See https://developers.google.com/closure/compiler/?hl=fr + +See https://developers.google.com/closure/utilities/docs/linter_howto for installation + + +``` +cd /path/to/closure-library-parent-dir +git clone http://code.google.com/p/closure-library/ +cd closure-library +wget http://closure-compiler.googlecode.com/files/compiler-latest.zip +unzip compiler-latest.zip +``` + +### Build with maven + + +Maven compilation take care of running: + * fixjsstyle for fix JS style + * gjslint for checking JS files + * depswriter for building lib/closure.deps.js file containing JS dependency tree + * closurebuilder for minifying JS files for each module + * LESS compilation in CSS (mvn lesscss:compile) + + +``` + mvn clean install -Dclosure.path=/path/to/closure-library +or on windows + mvn clean install -Dclosure.path=c:/path/to/closure-library +``` + +### Build with closure utility with command line + +#### Build dependencies + +JS dependencies needs to be updated when adding a new module. + +``` +git clone http://code.google.com/p/closure-library/ +cd core-geonetwork/web-ui/src/main/resources +python ../../../../../closure-library/closure/bin/build/depswriter.py \ + --root_with_prefix="catalog/components ../../components" \ + --root_with_prefix="catalog/js ../../js" \ + --output_file=catalog/lib/closure/deps.js +``` + + +#### Minify JS + +Run closurebuilder to create minified version of each modules: +``` +export CLOSURE_LIB=/home/closure-library +cd web-ui/src/main/resources +python $CLOSURE_LIB/closure/bin/build/closurebuilder.py \ + --root=catalog \ + --namespace="gn" \ + --output_mode=compiled \ + --compiler_jar=$CLOSURE_LIB/compiler.jar \ + > catalog/lib/gn.min.js + + +python $CLOSURE_LIB/closure/bin/build/closurebuilder.py \ + --root=catalog \ + --namespace="gn_admin" \ + --output_mode=compiled \ + --compiler_jar=$CLOSURE_LIB/compiler.jar \ + > catalog/lib/gn_admin.min.js + +python $CLOSURE_LIB/closure/bin/build/closurebuilder.py \ + --root=catalog \ + --namespace="gn_login" \ + --output_mode=compiled \ + --compiler_jar=$CLOSURE_LIB/compiler.jar \ + > catalog/lib/gn_login.min.js + + +``` + + +## Run the application with the UI module + +``` +cd web +mvn jetty:run -Pui +``` +and access http://localhost:8080/geonetwork/ diff --git a/web-ui/check-locale.js b/web-ui/check-locale.js new file mode 100644 index 00000000000..a6ad084d999 --- /dev/null +++ b/web-ui/check-locale.js @@ -0,0 +1,36 @@ +var fs = require('fs'); +var sourceLang = 'en'; +var targetLang = 'fr'; +var sourceFile = 'src/main/resources/catalog/locales/' + sourceLang + '-admin.json'; +var targetFile = 'src/main/resources/catalog/locales/' + targetLang + '-admin.json'; + +fs.readFile(sourceFile, 'utf8', function (err, source) { + if (err) { + console.log('Error reading source file: ' + err); + return; + } + + fs.readFile(targetFile, 'utf8', function (targetErr, target) { + if (targetErr) { + console.log('Error reading target file: ' + targetErr); + return; + } + + + source = JSON.parse(source); + target = JSON.parse(target); + targetAndMissing = {}; + for (key in source) { + if (source.hasOwnProperty(key)) { + console.log(key + ':' + source[key]); + // check entry is in target locale + targetAndMissing[key] = target[key] || source[key]; + } + } + console.log('Missing terms: ' + (source.length - targetAndMissing.length)); + fs.writeFile(targetFile + '.new', JSON.stringify(targetAndMissing, null, 4), function (err) { + if (err) throw err; + console.log('Target file updated.'); + }); + }); +}); diff --git a/web-ui/pom.xml b/web-ui/pom.xml new file mode 100644 index 00000000000..e1d82893d6f --- /dev/null +++ b/web-ui/pom.xml @@ -0,0 +1,216 @@ + + + 4.0.0 + + + org.geonetwork-opensource + geonetwork + 2.11.0-SNAPSHOT + + + org.geonetwork-opensource + web-ui + jar + GeoNetwork user interface module + + + + + General Public License (GPL) + http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt + repo + + + + + + + src/main/resources + true + + + + + org.codehaus.mojo + exec-maven-plugin + + + + fixjsstyle + validate + + exec + + + fixjsstyle + + --strict + -r + src/main/resources/catalog/js + + + + + + gjslint + validate + + exec + + + gjslint + + --strict + -r + + src/main/resources/catalog/js + + + + + build-js-dependency + + validate + + exec + + + python + src/main/resources + + ${closure.path}/closure/bin/build/depswriter.py + --root_with_prefix=catalog/components ../../components + --root_with_prefix=catalog/js ../../js + --output_file=catalog/lib/closure/deps.js + + + + + minify-js-gn + + prepare-package + + exec + + + python + src/main/resources + + ${closure.path}/closure/bin/build/closurebuilder.py + --root=catalog + --namespace=gn + --output_mode=compiled + + --compiler_jar=${closure.path}/compiler.jar + --output_file=catalog/lib/gn.min.js + + + + + minify-js-gn-admin + prepare-package + + exec + + + python + src/main/resources + + ${closure.path}/closure/bin/build/closurebuilder.py + --root=catalog + --namespace=gn_admin + --output_mode=compiled + + --compiler_jar=${closure.path}/compiler.jar + --output_file=catalog/lib/gn_admin.min.js + + + + + minify-js-gn-login + prepare-package + + exec + + + python + src/main/resources + + ${closure.path}/closure/bin/build/closurebuilder.py + --root=catalog + --namespace=gn_login + --output_mode=compiled + + --compiler_jar=${closure.path}/compiler.jar + --output_file=catalog/lib/gn_login.min.js + + + + + minify-js-gn-editor + prepare-package + + exec + + + python + src/main/resources + + ${closure.path}/closure/bin/build/closurebuilder.py + --root=catalog + --namespace=gn_editor + --output_mode=compiled + + --compiler_jar=${closure.path}/compiler.jar + --output_file=catalog/lib/gn_editor.min.js + + + + + + + org.lesscss + lesscss-maven-plugin + 1.3.3 + + ${project.basedir}/src/main/resources/catalog/style + ${project.basedir}/src/main/resources/catalog/style + true + + gn.less + gn_admin.less + gn_login.less + gn_editor.less + + + + + + compile + + + + + + + + ${project.build.directory}/${project.build.finalName} + + + /path/to/closure-library + + diff --git a/web-ui/src/main/resources/catalog/components/admin/dbtranslation/DbTranslationDirective.js b/web-ui/src/main/resources/catalog/components/admin/dbtranslation/DbTranslationDirective.js new file mode 100644 index 00000000000..5c4e0ab305b --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/admin/dbtranslation/DbTranslationDirective.js @@ -0,0 +1,62 @@ +(function() { + goog.provide('gn_dbtranslation_directive'); + + var module = angular.module('gn_dbtranslation_directive', []); + + /** + * Provide a table layout to edit db translations + * for some types of entries (eg. groups, categories). + * + * Changes are saved on keyup event. + * + * Usage: + *
    + */ + module.directive('gnDbTranslation', ['$http', '$translate', '$rootScope', + function($http, $translate, $rootScope) { + + return { + restrict : 'A', + replace: true, + transclude: true, + scope: { + type: '@type', + element: '=gnDbTranslation' + }, + templateUrl: '../../catalog/components/admin/dbtranslation/partials/' + + 'dbtranslation.html', + link : function(scope, element, attrs) { + + /** + * Save a translation + */ + scope.saveTranslation = function(e) { + // TODO: No need to save if translation not updated + + // TODO : could we use Angular compile here ? + var xml = '<' + scope.type + ' id="{{id}}">' + + '' + + ''; + + // id may be in id property (eg. group) or @id (eg. category) + xml = xml.replace('{{id}}', scope.element.id || scope.element['@id']) + .replace(/{{key}}/g, e.key) + .replace('{{value}}', e.value); + $http.post('admin.' + scope.type + '.update.labels', xml, { + headers: {'Content-type': 'application/xml'} + }).success(function(data) { + }).error(function(data) { + // FIXME: XML error to be converted to JSON ? + $rootScope.$broadcast('StatusUpdated', { + title: $translate(scope.type + 'TranslationUpdateError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + } + }; + }]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/admin/dbtranslation/DbTranslationModule.js b/web-ui/src/main/resources/catalog/components/admin/dbtranslation/DbTranslationModule.js new file mode 100644 index 00000000000..ee91217cf26 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/admin/dbtranslation/DbTranslationModule.js @@ -0,0 +1,9 @@ +(function() { + goog.provide('gn_dbtranslation'); + + goog.require('gn_dbtranslation_directive'); + + angular.module('gn_dbtranslation', [ + 'gn_dbtranslation_directive' + ]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/admin/dbtranslation/partials/dbtranslation.html b/web-ui/src/main/resources/catalog/components/admin/dbtranslation/partials/dbtranslation.html new file mode 100644 index 00000000000..1c44a03f27c --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/admin/dbtranslation/partials/dbtranslation.html @@ -0,0 +1,11 @@ + + + + + +
    {{key}}
    \ No newline at end of file diff --git a/web-ui/src/main/resources/catalog/components/admin/harvester/HarvesterDirective.js b/web-ui/src/main/resources/catalog/components/admin/harvester/HarvesterDirective.js new file mode 100644 index 00000000000..de8959491b9 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/admin/harvester/HarvesterDirective.js @@ -0,0 +1,134 @@ +(function() { + goog.provide('gn_harvester_directive'); + + var module = angular.module('gn_harvester_directive', []); + + + /** + * Display harvester identification section with + * name, group and icon + */ + module.directive('gnHarvesterIdentification', ['$http', '$rootScope', + function($http, $rootScope) { + + return { + restrict : 'A', + replace: true, + transclude: true, + scope: { + harvester: '=gnHarvesterIdentification' +// lang: '@lang' + }, + templateUrl: '../../catalog/components/admin/harvester/partials/' + + 'identification.html', + link : function(scope, element, attrs) { + scope.lang = 'eng'; // FIXME + $http.get('admin.harvester.info@json?type=icons').success(function(data) { + scope.icons = data[0]; + }); +// $http.get('admin.usergroups.list@json?id=' + 1).success(function(data) { + $http.get('admin.group.list@json').success(function(data) { + scope.groups = data !== 'null' ? data : null; + }); + scope.setIcon = function(i) { + scope.harvester.site.icon = i; + } + } + }; + }]); + + /** + * Display account when remote login is used. + */ + module.directive('gnHarvesterAccount', [ + function() { + + return { + restrict : 'A', + replace: true, + transclude: true, + scope: { + harvester: '=gnHarvesterAccount' + }, + templateUrl: '../../catalog/components/admin/harvester/partials/' + + 'account.html', + link : function(scope, element, attrs) { + + } + }; + }]); + /** + * Display harvester schedule configuration. + */ + module.directive('gnHarvesterSchedule', ['$translate', + function($translate) { + + return { + restrict : 'A', + replace: true, + transclude: true, + scope: { + harvester: '=gnHarvesterSchedule' + }, + templateUrl: '../../catalog/components/admin/harvester/partials/' + + 'schedule.html', + link : function(scope, element, attrs) { + + } + }; + }]); + + + /** + * Display harvester privileges configuration with + * publish to all / none / custom switcher. + * + * TODO: Custom mode + */ + module.directive('gnHarvesterPrivileges', ['$http', '$translate', '$rootScope', + function($http, $translate, $rootScope) { + + return { + restrict : 'A', + replace: true, + transclude: true, + scope: { + harvester: '=gnHarvesterPrivileges' + }, + templateUrl: '../../catalog/components/admin/harvester/partials/' + + 'privileges.html', + link : function(scope, element, attrs) { + var defaultPrivileges = [{ + "@id" : "1", + "operation" : [ { + "@name" : "view" + }, { + "@name" : "dynamic" + }]}]; + + scope.visibleTo = function (who) { + if (who == 'all') { + scope.harvester.privileges = defaultPrivileges; + } else if (who == 'none') { + scope.harvester.privileges = []; + } else { + // TODO + } + } + + var init = function () { + // If only one privilege config + // and group name is equal to Internet (ie. 1) + if (scope.harvester.privileges && + scope.harvester.privileges.length === 1 && + scope.harvester.privileges[0]['@id'] == '1') { + $('#gn-harvester-visible-all').button('toggle'); + } + } + + init(); + + } + }; + }]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/admin/harvester/HarvesterModule.js b/web-ui/src/main/resources/catalog/components/admin/harvester/HarvesterModule.js new file mode 100644 index 00000000000..caa31b8ae1c --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/admin/harvester/HarvesterModule.js @@ -0,0 +1,9 @@ +(function() { + goog.provide('gn_harvester'); + + goog.require('gn_harvester_directive'); + + angular.module('gn_harvester', [ + 'gn_harvester_directive' + ]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/admin/harvester/partials/account.html b/web-ui/src/main/resources/catalog/components/admin/harvester/partials/account.html new file mode 100644 index 00000000000..6a450c36b54 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/admin/harvester/partials/account.html @@ -0,0 +1,19 @@ +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    \ No newline at end of file diff --git a/web-ui/src/main/resources/catalog/components/admin/harvester/partials/identification.html b/web-ui/src/main/resources/catalog/components/admin/harvester/partials/identification.html new file mode 100644 index 00000000000..6acab46a04c --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/admin/harvester/partials/identification.html @@ -0,0 +1,44 @@ +
    + harvesterIdentification +
    + + +
    + + + +
    + + +
    +
    +
    +

    harvesterNameHelp

    +
    +
    + + + +

    harvesterGroupHelp

    +
    +
    diff --git a/web-ui/src/main/resources/catalog/components/admin/harvester/partials/privileges.html b/web-ui/src/main/resources/catalog/components/admin/harvester/partials/privileges.html new file mode 100644 index 00000000000..343a48547b5 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/admin/harvester/partials/privileges.html @@ -0,0 +1,22 @@ +
    + harvestedRecordPrivileges + +
    + + + +
    +

    + + +

    +
    diff --git a/web-ui/src/main/resources/catalog/components/admin/harvester/partials/schedule.html b/web-ui/src/main/resources/catalog/components/admin/harvester/partials/schedule.html new file mode 100644 index 00000000000..87f2b15e492 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/admin/harvester/partials/schedule.html @@ -0,0 +1,34 @@ +
    + harvesterSchedule +
    + + +
    +
    + +
    + + +
    + +
    + +

    oneRunOnlyHelp

    +
    + +
    \ No newline at end of file diff --git a/web-ui/src/main/resources/catalog/components/admin/importxsl/ImportXSLDirective.js b/web-ui/src/main/resources/catalog/components/admin/importxsl/ImportXSLDirective.js new file mode 100644 index 00000000000..7a96fdd0290 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/admin/importxsl/ImportXSLDirective.js @@ -0,0 +1,29 @@ +(function() { + goog.provide('gn_importxsl_directive'); + + var module = angular.module('gn_importxsl_directive', []); + + /** + * Provide a list of available XSLT transformation + * + */ + module.directive('gnImportXsl', ['$http', '$translate', + function($http, $translate) { + + return { + restrict : 'A', + replace: true, + transclude: true, + scope: { + element: '=gnImportXsl' + }, + templateUrl: '../../catalog/components/admin/importxsl/partials/' + + 'importxsl.html', + link : function(scope, element, attrs) { + $http.get('info@json?type=importStylesheets').success(function(data) { + scope.stylesheets = data.stylesheets; + }); + } + }; + }]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/admin/importxsl/ImportXSLModule.js b/web-ui/src/main/resources/catalog/components/admin/importxsl/ImportXSLModule.js new file mode 100644 index 00000000000..1be6a415970 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/admin/importxsl/ImportXSLModule.js @@ -0,0 +1,9 @@ +(function() { + goog.provide('gn_importxsl'); + + goog.require('gn_importxsl_directive'); + + angular.module('gn_importxsl', [ + 'gn_importxsl_directive' + ]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/admin/importxsl/partials/importxsl.html b/web-ui/src/main/resources/catalog/components/admin/importxsl/partials/importxsl.html new file mode 100644 index 00000000000..9e69f1cbc55 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/admin/importxsl/partials/importxsl.html @@ -0,0 +1,4 @@ + \ No newline at end of file diff --git a/web-ui/src/main/resources/catalog/components/category/CategoryDirective.js b/web-ui/src/main/resources/catalog/components/category/CategoryDirective.js new file mode 100644 index 00000000000..9e38267fb15 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/category/CategoryDirective.js @@ -0,0 +1,34 @@ +(function() { + goog.provide('gn_category_directive'); + + var module = angular.module('gn_category_directive', []); + + /** + * Provide a list of categories if at least one + * exist in the catalog + * + */ + module.directive('gnCategory', ['$http', '$translate', + function($http, $translate) { + + return { + restrict : 'A', + replace: true, + transclude: true, + scope: { + element: '=gnCategory', + lang: '@lang', + label: '@label' + }, + templateUrl: '../../catalog/components/category/partials/' + + 'category.html', + link : function(scope, element, attrs) { + $http.get('info@json?type=categories').success(function(data) { + scope.categories = data.categories; + }).error(function(data) { + // TODO + }); + } + }; + }]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/category/CategoryModule.js b/web-ui/src/main/resources/catalog/components/category/CategoryModule.js new file mode 100644 index 00000000000..835492af3f9 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/category/CategoryModule.js @@ -0,0 +1,9 @@ +(function() { + goog.provide('gn_category'); + + goog.require('gn_category_directive'); + + angular.module('gn_category', [ + 'gn_category_directive' + ]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/category/partials/category.html b/web-ui/src/main/resources/catalog/components/category/partials/category.html new file mode 100644 index 00000000000..97be5bbe51d --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/category/partials/category.html @@ -0,0 +1,12 @@ +
    + + +
    diff --git a/web-ui/src/main/resources/catalog/components/dv/GaugeDirective.js b/web-ui/src/main/resources/catalog/components/dv/GaugeDirective.js new file mode 100644 index 00000000000..4923180b915 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/dv/GaugeDirective.js @@ -0,0 +1,59 @@ +(function() { + goog.provide('gn_gauge_directive'); + + var module = angular.module('gn_gauge_directive', []); + + module.directive('gnGauge', function() { + var gauges = []; + + /** + * Create and render a gauge + */ + function createGauge(config) { + var gauge, gaugeConfig = { + size : config.size || 120, + label : config.label, + min : config.min || 0, + max : config.max || 100, + minorTicks : config.ticks || 5 + } + + var range = gaugeConfig.max - gaugeConfig.min; + gaugeConfig.yellowZones = [ { + from : gaugeConfig.min + range * 0.75, + to : gaugeConfig.min + range * 0.9 + } ]; + gaugeConfig.redZones = [ { + from : gaugeConfig.min + range * 0.9, + to : gaugeConfig.max + } ]; + + gauge = new Gauge(config.id, gaugeConfig); + gauge.render(); + return gauge; + }; + + + return { + restrict : 'A', + require: '?ngModel', + link : function(scope, element, attrs) { + // TODO : How to handle directive constraints ? + if (!attrs.id) { + console.log('Define an ID attribute to locate the target element to put the gauge in.'); + } + scope.$watch(attrs.ngModel, function() { + var value = scope.$eval(attrs.gnGaugeValue); + if (value) { + scope.gauges[attrs.id] = createGauge({id: attrs.id, + label: attrs.gnGauge, + min: scope.$eval(attrs.gnGaugeMin), + max: scope.$eval(attrs.gnGaugeMax) + }); + scope.gauges[attrs.id].redraw(value); + } + }); + } + }; + }); +})(); diff --git a/web-ui/src/main/resources/catalog/components/dv/GaugeModule.js b/web-ui/src/main/resources/catalog/components/dv/GaugeModule.js new file mode 100644 index 00000000000..2a778111210 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/dv/GaugeModule.js @@ -0,0 +1,9 @@ +(function() { + goog.provide('gn_gauge'); + + goog.require('gn_gauge_directive'); + + angular.module('gn_gauge', [ + 'gn_gauge_directive' + ]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/languageswitcher/LanguageSwitcherDirective.js b/web-ui/src/main/resources/catalog/components/languageswitcher/LanguageSwitcherDirective.js new file mode 100644 index 00000000000..966d3563623 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/languageswitcher/LanguageSwitcherDirective.js @@ -0,0 +1,43 @@ +(function() { + goog.provide('gn_language_switcher_directive'); + + var module = angular.module('gn_language_switcher_directive', + ['pascalprecht.translate']); + + module.directive('gnLanguageSwitcher', ['$translate', + function($translate) { + + return { + restrict : 'A', + replace: false, + transclude: true, + scope: { + langs: '=langs', + lang: '=gnLanguageSwitcher' + }, + template: + '', + link : function(scope, element, attrs) { + scope.$watch('lang', function(value) { + var url = location.href.split('/'); + if (value != url[5]) { + url[5] = value; // Use ISO3 code +// if (window.history.pushState) { +// // Update translate with no page reload +// // And adding an history state to update browser URL +// $translate.uses(scope.langs[value]); // Use ISO2 code +// window.history.pushState(null, null, url.join('/')); +// } else { + // trigger a reload + location.href = url.join('/'); +// } + moment && moment.lang(scope.langs[value]); + } + }); + } + }; + }]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/languageswitcher/LanguageSwitcherModule.js b/web-ui/src/main/resources/catalog/components/languageswitcher/LanguageSwitcherModule.js new file mode 100644 index 00000000000..03ecc96fc7b --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/languageswitcher/LanguageSwitcherModule.js @@ -0,0 +1,9 @@ +(function() { + goog.provide('gn_language_switcher'); + + goog.require('gn_language_switcher_directive'); + + angular.module('gn_language_switcher', [ + 'gn_language_switcher_directive' + ]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/languageswitcher/partials/languageswitcher.html b/web-ui/src/main/resources/catalog/components/languageswitcher/partials/languageswitcher.html new file mode 100644 index 00000000000..e2971db4e6f --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/languageswitcher/partials/languageswitcher.html @@ -0,0 +1,8 @@ + diff --git a/web-ui/src/main/resources/catalog/components/metadatamanager/MetadataManagerModule.js b/web-ui/src/main/resources/catalog/components/metadatamanager/MetadataManagerModule.js new file mode 100644 index 00000000000..23599df75c1 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/metadatamanager/MetadataManagerModule.js @@ -0,0 +1,9 @@ +(function() { + goog.provide('gn_metadata_manager'); + + goog.require('gn_metadata_manager_service'); + + angular.module('gn_metadata_manager', [ + 'gn_metadata_manager_service' + ]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/metadatamanager/MetadataManagerService.js b/web-ui/src/main/resources/catalog/components/metadatamanager/MetadataManagerService.js new file mode 100644 index 00000000000..d4cf7ede763 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/metadatamanager/MetadataManagerService.js @@ -0,0 +1,57 @@ +(function() { + goog.provide('gn_metadata_manager_service'); + + var module = angular.module('gn_metadata_manager_service', []); + + var gnMetadataManagerService = function ($q, $rootScope, $http) { + + var apply = function () { + $rootScope.$apply(); + }; + var _select = function (uuid, andClearSelection, action) { + var defer = $q.defer(); + $http.get('metadata.select@json?' + + (uuid ? 'id=' + uuid : '') + + (andClearSelection ? '' : '&selected=' + action)). + success(function(data, status) { + defer.resolve(data); + }). + error(function(data, status) { + defer.reject(error); + }); + return defer.promise; + }; + var select = function (uuid, andClearSelection) { + return _select(uuid, andClearSelection, 'add'); + }; + var unselect = function (uuid) { + return _select(uuid, false, 'remove'); + }; + var selectAll = function () { + return _select(null, false, 'add-all'); + }; + var selectNone = function () { + return _select(null, false, 'remove-all'); + }; + var view = function(md) { + window.open('../../?uuid=' + md['geonet:info'].uuid, 'gn-view'); + }; + var edit = function(md) { +// window.open('../../?edit=' + md['geonet:info'].uuid, 'gn-view'); + location.href = 'catalog.edit?id=' + md['geonet:info'].id; + }; + return { + select: select, + unselect: unselect, + selectAll: selectAll, + selectNone: selectNone, + view: view, + edit: edit + }; + }; + + gnMetadataManagerService.$inject = ['$q', '$rootScope', '$http']; + + module.factory('gnMetadataManagerService', gnMetadataManagerService); + +})(); diff --git a/web-ui/src/main/resources/catalog/components/pagination/PaginationDirective.js b/web-ui/src/main/resources/catalog/components/pagination/PaginationDirective.js new file mode 100644 index 00000000000..e1474cf1538 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/pagination/PaginationDirective.js @@ -0,0 +1,31 @@ +(function() { + goog.provide('gn_pagination_directive'); + + var module = angular.module('gn_pagination_directive', []); + + module.directive('gnPagination', ['gnMetadataManagerService', function(gnMetadataManagerService) { + + return { + restrict : 'A', + replace: true, + transclude: true, + scope: { + config: '=gnPagination' + }, + templateUrl: '../../catalog/components/pagination/partials/' + + 'pagination.html', + link : function(scope, element, attrs) { + scope.previous = function () { + if (scope.config.currentPage > 0) { + scope.config.currentPage -= 1; + } + } + scope.next = function () { + if (scope.config.currentPage < scope.config.pages) { + scope.config.currentPage += 1; + } + } + } + }; + }]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/pagination/PaginationModule.js b/web-ui/src/main/resources/catalog/components/pagination/PaginationModule.js new file mode 100644 index 00000000000..274dbfd81f6 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/pagination/PaginationModule.js @@ -0,0 +1,9 @@ +(function() { + goog.provide('gn_pagination'); + + goog.require('gn_pagination_directive'); + + angular.module('gn_pagination', [ + 'gn_pagination_directive' + ]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/pagination/partials/pagination.html b/web-ui/src/main/resources/catalog/components/pagination/partials/pagination.html new file mode 100644 index 00000000000..5f619f89273 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/pagination/partials/pagination.html @@ -0,0 +1,11 @@ +
      +
    • + previous
    • +
    • {{config.currentPage + 1}} / {{config.pages + 1}}
    • +
    • + next
    • +
    \ No newline at end of file diff --git a/web-ui/src/main/resources/catalog/components/pagination/style/pagination.less b/web-ui/src/main/resources/catalog/components/pagination/style/pagination.less new file mode 100644 index 00000000000..e69de29bb2d diff --git a/web-ui/src/main/resources/catalog/components/searchmanager/SearchManagerModule.js b/web-ui/src/main/resources/catalog/components/searchmanager/SearchManagerModule.js new file mode 100644 index 00000000000..f388dd8b293 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/searchmanager/SearchManagerModule.js @@ -0,0 +1,9 @@ +(function() { + goog.provide('gn_search_manager'); + + goog.require('gn_search_manager_service'); + + angular.module('gn_search_manager', [ + 'gn_search_manager_service' + ]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/searchmanager/SearchManagerService.js b/web-ui/src/main/resources/catalog/components/searchmanager/SearchManagerService.js new file mode 100644 index 00000000000..c4dde6e27b6 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/searchmanager/SearchManagerService.js @@ -0,0 +1,156 @@ +(function() { + goog.provide('gn_search_manager_service'); + + var module = angular.module('gn_search_manager_service', []); + + var gnSearchManagerService = function ($q, $rootScope, $http) { + + /** + * Utility to format a search response. JSON response + * when containing one element will not make an array. + * Tidy the JSON to be always the same if one or more + * elements. + */ + var format = function (data) { + // Retrieve facet and add name as property and remove @count + var facets = {}, results = -1; + + // When using summaryOnly=true, the facet is the root element + if (data[0] && data[0]['@count']) { + data.summary = data[0]; + results = data[0]['@count']; + } + + // Cleaning facets + for (var facet in data.summary) { + if (facet != '@count') { + facets[facet] = data.summary[facet]; + facets[facet].name = facet; + } else { + // Number of results + results = data.summary[facet]; + } + } + + if (data.metadata) { + // Retrieve metadata + for (var i=0; i < data.metadata.length || + (!$.isArray(data.metadata) && i < 1 ); i++) { + var metadata = $.isArray(data.metadata) ? data.metadata[i] : data.metadata; + // Fix thumbnail, link which might be string or array of string + if (typeof metadata.image === 'string') { + metadata.image = [metadata.image]; + } + if (typeof metadata.link === 'string') { + metadata.link = [metadata.link]; + } + + // Parse selected to boolean + metadata['geonet:info'].selected = metadata['geonet:info'].selected == 'true'; + } + } + + var records = []; + if (data.metadata && data.metadata.length) { + records = data.metadata; // results is an array + } else if (data.metadata) { + records = [data.metadata]; // only one result + } + + return { + facet: facets, + count: results, + metadata: records + }; + + }; + + /** + * Link together records, filter and a pager. + * Return the search function to invoke. + * + * + * $scope.records = {}; + * $scope.filter = {}; + * + * // Pager config + * $scope.pagination = { + * pages: -1, + * currentPage: 0, + * hitsPerPage: 20 + * }; + * + * // Register the search results, filter and pager + * // and get the search function back + * searchFn = gnSearchManagerService.register({ + * records: 'records', + * filter: 'filter', + * pager: 'pagination' + * // error: function () {console.log('error');}, + * // success: function () {console.log('succ');} + * }, $scope); + * + * // Update search filter and reset page + * $scope.search = function(e) { + * $filter = {any: (e ? e.target.value : '')}; + * $scope.pagination.currentPage = 0; + * searchFn(); + * }; + * + * // When the current page change trigger the search + * $scope.$watch('pagination.currentPage', function() { + * $scope.search(); + * }); + * + */ + var register = function (config, scope) { + + var searchFn = function() { + var pageOptions = scope[config.pager], filter = ""; + + scope[config.filter] && $.each(scope[config.filter], function (key, value) { + filter += "&" + key + "=" + value + }); + search('q@json?fast=index' + + filter + + '&from=' + (pageOptions.currentPage * + pageOptions.hitsPerPage + 1) + + '&to=' + ((pageOptions.currentPage + 1) * + pageOptions.hitsPerPage), config.error) + .then(function(data) { + scope[config.records] = data; + pageOptions.count = parseInt(data.count); + pageOptions.pages = Math.round( + data.count / + pageOptions.hitsPerPage, 0); + config.success && config.success(data); + }); + }; + return searchFn; + }; + + /** + * Run a search. + */ + var search = function (url, error) { + var defer = $q.defer(); + $http.get(url). + success(function(data, status) { + defer.resolve(format(data)); + }). + error(function(data, status) { + defer.reject(error); + }); + return defer.promise; + }; + return { + search: search, + register: register + }; + }; + + gnSearchManagerService.$inject = ['$q', '$rootScope', '$http']; + + module.factory('gnSearchManagerService', gnSearchManagerService); + +})(); diff --git a/web-ui/src/main/resources/catalog/components/searchresults/SearchResultsDirective.js b/web-ui/src/main/resources/catalog/components/searchresults/SearchResultsDirective.js new file mode 100644 index 00000000000..e275a3c4186 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/searchresults/SearchResultsDirective.js @@ -0,0 +1,53 @@ +(function() { + goog.provide('gn_search_results_directive'); + + var module = angular.module('gn_search_results_directive', []); + + module.directive('gnSearchResults', ['gnMetadataManagerService', function(gnMetadataManagerService) { + + var activeClass = 'active'; + + return { + restrict : 'A', + replace: true, + transclude: true, + scope: { + allowSelection: '@allowSelection', + authenticated: '=authenticated', + selectedRecordsCount: '=selectedRecordsCount', + searchResults: '=gnSearchResults' + }, + templateUrl: '../../catalog/components/searchresults/partials/' + + 'searchresults.html', + link : function(scope, element, attrs) { + scope.select = function (md, e) { + var uuid = md['geonet:info'].uuid; + var fn = $("#gn-record-" + uuid).hasClass(activeClass) ? + gnMetadataManagerService.unselect : + gnMetadataManagerService.select; + fn(uuid).then(function (data) { + scope.selectedRecordsCount = data[0]; + md['geonet:info'].selected = md['geonet:info'].selected !== true; + }); + } + scope.selectAll = function (all) { + var fn = all ? + gnMetadataManagerService.selectAll : + gnMetadataManagerService.selectNone; + fn().then(function (data) { + scope.selectedRecordsCount = data[0]; + angular.forEach(scope.searchResults.metadata, function (md) { + md['geonet:info'].selected = all ? true : false; + }); + }); + } + scope.view = function (md, e) { + gnMetadataManagerService.view(md); + } + scope.edit = function (md, e) { + gnMetadataManagerService.edit(md); + } + } + }; + }]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/searchresults/SearchResultsModule.js b/web-ui/src/main/resources/catalog/components/searchresults/SearchResultsModule.js new file mode 100644 index 00000000000..e328921e383 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/searchresults/SearchResultsModule.js @@ -0,0 +1,10 @@ +(function() { + goog.provide('gn_search_results'); + + goog.require('gn_cat_controller'); + goog.require('gn_search_results_directive'); + + angular.module('gn_search_results', [ + 'gn_search_results_directive' + ]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/searchresults/partials/searchresults.html b/web-ui/src/main/resources/catalog/components/searchresults/partials/searchresults.html new file mode 100644 index 00000000000..51ac741207e --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/searchresults/partials/searchresults.html @@ -0,0 +1,44 @@ +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    diff --git a/web-ui/src/main/resources/catalog/components/searchresults/style/searchresults.less b/web-ui/src/main/resources/catalog/components/searchresults/style/searchresults.less new file mode 100644 index 00000000000..e69de29bb2d diff --git a/web-ui/src/main/resources/catalog/components/thesaurus-type/ThesaurusTypeDirective.js b/web-ui/src/main/resources/catalog/components/thesaurus-type/ThesaurusTypeDirective.js new file mode 100644 index 00000000000..6bd30a1890a --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/thesaurus-type/ThesaurusTypeDirective.js @@ -0,0 +1,24 @@ +(function() { + goog.provide('gn_thesaurus_type_directive'); + + var module = angular.module('gn_thesaurus_type_directive', []); + + module.directive('gnThesaurusType', [function() { + + return { + restrict : 'A', + replace: true, + transclude: true, + scope: { + typeList: '=gnThesaurusType', + model: '=gnModel', + disabled: '=gnDisabled' + }, + templateUrl: '../../catalog/components/thesaurus-type/partials/' + + 'thesaurus-type.html', + link : function(scope, element, attrs) { + scope.types = scope.typeList || ['theme', 'discipline', 'place', 'stratum', 'temporal']; + } + }; + }]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/thesaurus-type/ThesaurusTypeModule.js b/web-ui/src/main/resources/catalog/components/thesaurus-type/ThesaurusTypeModule.js new file mode 100644 index 00000000000..005a96cffb3 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/thesaurus-type/ThesaurusTypeModule.js @@ -0,0 +1,9 @@ +(function() { + goog.provide('gn_thesaurus_type'); + + goog.require('gn_thesaurus_type_directive'); + + angular.module('gn_thesaurus_type', [ + 'gn_thesaurus_type_directive' + ]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/thesaurus-type/partials/thesaurus-type.html b/web-ui/src/main/resources/catalog/components/thesaurus-type/partials/thesaurus-type.html new file mode 100644 index 00000000000..e56e56461f4 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/thesaurus-type/partials/thesaurus-type.html @@ -0,0 +1,7 @@ +
    + + +
    \ No newline at end of file diff --git a/web-ui/src/main/resources/catalog/components/utility/UtilityModule.js b/web-ui/src/main/resources/catalog/components/utility/UtilityModule.js new file mode 100644 index 00000000000..79ab5bc07a9 --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/utility/UtilityModule.js @@ -0,0 +1,9 @@ +(function() { + goog.provide('gn_utility'); + + goog.require('gn_utility_service'); + + angular.module('gn_utility', [ + 'gn_utility_service' + ]); +})(); diff --git a/web-ui/src/main/resources/catalog/components/utility/UtilityService.js b/web-ui/src/main/resources/catalog/components/utility/UtilityService.js new file mode 100644 index 00000000000..3b6d704a6cd --- /dev/null +++ b/web-ui/src/main/resources/catalog/components/utility/UtilityService.js @@ -0,0 +1,152 @@ +(function() { + goog.provide('gn_utility_service'); + + var module = angular.module('gn_utility_service', []); + + var gnUtilityService = function () { + /** + * Scroll page to element. + */ + var scrollTo = function (elementId, offset, duration, easing) { + $(document.body).animate({scrollTop: (offset ? + $(elementId).offset().top : + $(elementId).position().top) + }, + duration, easing); + }; + + /** + * Serialize form including unchecked checkboxes. + * See http://forum.jquery.com/topic/jquery-serialize-unchecked-checkboxes + */ + var serialize = function (formId) { + var form = $(formId), uc = []; + $(':checkbox:not(:checked)', form).each(function(){ + uc.push(encodeURIComponent(this.name) + '=false'); + }); + return form.serialize() + + (uc.length ? '&' + uc.join('&').replace(/%20/g, "+") : ''); + }; + + + /** + * Parse boolean value in object + */ + var parseBoolean = function (object) { + angular.forEach(object, function(value, key) { + if (typeof value == 'string') { + if (value == 'true' || value == 'false') { + object[key] = (value == 'true'); + } else if (value == 'on' || value == 'off') { + object[key] = (value == 'on'); + } + } else { + parseBoolean(value); + } + }); + }; + /** + * Converts a value to a string appropriate for entry into a CSV table. E.g., a string value will be surrounded by quotes. + * @param {string|number|object} theValue + * @param {string} sDelimiter The string delimiter. Defaults to a double quote (") if omitted. + */ + function toCsvValue(theValue, sDelimiter) { + var t = typeof (theValue), output; + + if (typeof (sDelimiter) === "undefined" || sDelimiter === null) { + sDelimiter = '"'; + } + + if (t === "undefined" || t === null) { + output = ""; + } else if (t === "string") { + output = sDelimiter + theValue + sDelimiter; + } else { + output = String(theValue); + } + + return output; + } + /** + * https://gist.github.com/JeffJacobson/2770509 + * Converts an array of objects (with identical schemas) into a CSV table. + * @param {Array} objArray An array of objects. Each object in the array must have the same property list. + * @param {string} sDelimiter The string delimiter. Defaults to a double quote (") if omitted. + * @param {string} cDelimiter The column delimiter. Defaults to a comma (,) if omitted. + * @return {string} The CSV equivalent of objArray. + */ + function toCsv(objArray, sDelimiter, cDelimiter) { + var i, l, names = [], name, value, obj, row, output = "", n, nl; + + // Initialize default parameters. + if (typeof (sDelimiter) === "undefined" || sDelimiter === null) { + sDelimiter = '"'; + } + if (typeof (cDelimiter) === "undefined" || cDelimiter === null) { + cDelimiter = ","; + } + + for (i = 0, l = objArray.length; i < l; i += 1) { + // Get the names of the properties. + obj = objArray[i]; + row = ""; + if (i === 0) { + // Loop through the names + for (name in obj) { + if (obj.hasOwnProperty(name)) { + names.push(name); + row += [sDelimiter, name, sDelimiter, cDelimiter].join(""); + } + } + row = row.substring(0, row.length - 1); + output += row; + } + + output += "\n"; + row = ""; + for (n = 0, nl = names.length; n < nl; n += 1) { + name = names[n]; + value = obj[name]; + if (n > 0) { + row += "," + } + row += toCsvValue(value, '"'); + } + output += row; + } + + return output; + } + /** + * Get a URL parameter + */ + var getUrlParameter = function (parameterName) { + var parameterValue = null; + angular.forEach(window.location + .search.replace('?', '').split('&'), + function(value) { + if (value.indexOf(parameterName) === 0) { + parameterValue = value.split('=')[1]; + } + // TODO; stop loop when found + }); + return parameterValue; + }; + return { + scrollTo: scrollTo, + serialize: serialize, + parseBoolean: parseBoolean, + toCsv: toCsv, + getUrlParameter: getUrlParameter + }; + }; + + + module.factory('gnUtilityService', gnUtilityService); + + module.filter('gnFromNow', function() { + return function(dateString) { + return moment(new Date(dateString)).fromNow() + }; + }); +})(); diff --git a/web-ui/src/main/resources/catalog/config/batch-process-cfg.json b/web-ui/src/main/resources/catalog/config/batch-process-cfg.json new file mode 100644 index 00000000000..edd35f77d70 --- /dev/null +++ b/web-ui/src/main/resources/catalog/config/batch-process-cfg.json @@ -0,0 +1,20 @@ +{"config": [{ + "key": "url-host-relocator", + "params": [ + {"name": "urlPrefix", "value": "http://oldurl"}, + {"name": "newUrlPrefix", "value": "http://newurl"} + ] + }, { + "key": "keywords-mapper", + "params": [ + {"name": "search", "value": "key1;key2"}, + {"name": "replace", "value": "newkey1;newkey2"} + ] + },{ + "key": "contact-updater", + "params": [ + {"name": "emailToSearch", "value": "", "type": "email"}, + {"name": "contactAsXML", "value": "", "type": "textarea"} + ] + }] +} \ No newline at end of file diff --git a/web-ui/src/main/resources/catalog/config/user-quicklinks.json b/web-ui/src/main/resources/catalog/config/user-quicklinks.json new file mode 100644 index 00000000000..114c3b6849f --- /dev/null +++ b/web-ui/src/main/resources/catalog/config/user-quicklinks.json @@ -0,0 +1,7 @@ +{ + 'Administrator': [ + {name: 'newMetadata', url:'../apps/search#create'}, + {name: 'myMetadata', url:'../apps/search#s_E__owner={userId}'}, + {name: 'addAUser', url:'#/user/add'} + ] +} \ No newline at end of file diff --git a/web-ui/src/main/resources/catalog/js/CatController.js b/web-ui/src/main/resources/catalog/js/CatController.js new file mode 100644 index 00000000000..eceae4993c7 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/CatController.js @@ -0,0 +1,171 @@ +(function() { + goog.provide('gn_cat_controller'); + + goog.require('gn_search_manager'); + + var module = angular.module('gn_cat_controller', ['gn_search_manager']); + + /** + * The catalogue controller takes care of + * loading site information, check user login state + * and a facet search to get main site information. + * + * A body-level scope makes sense for example: + * + * + */ + module.controller('GnCatController', [ + '$scope', '$http', '$q', '$rootScope', '$translate', + 'gnSearchManagerService', + function($scope, $http, $q, $rootScope, $translate, + gnSearchManagerService) { + $scope.version = '0.0.1'; + // TODO : add language + $scope.lang = location.href.split('/')[5]; + // TODO : get list from server side + $scope.langs = {'fre': 'fr', 'eng': 'en', 'spa': 'sp'}; + $scope.url = ''; + $scope.base = '../../catalog/'; + $scope.proxyUrl = '../../proxy?url='; + $scope.logoPath = '../../images/harvesting/'; + $scope.pages = { + home: 'home', + admin: 'admin.console', + signin: 'catalog.signin' + }; + + /** + * Number of selected metadata records. + * Only one selection per session is allowed. + */ + $scope.selectedRecordsCount = 0; + + /** + * An ordered list of profiles + */ + $scope.profiles = ['RegisteredUser', 'Editor', + 'Reviewer', 'UserAdmin', + 'Administrator']; + $scope.info = {}; + $scope.user = {}; + $scope.authenticated = false; + $scope.initialized = false; + + /** + * Catalog facet summary providing + * a global overview of the catalog content. + */ + $scope.searchInfo = {}; + + $scope.status = null; + var defaultStatus = { + title: '', + link: '', + msg: '', + error: '', + type: 'info', + timeout: -1 + }; + + $scope.loadCatalogInfo = function() { + var promiseStart = $q.when('start'); + + // Retrieve site information + // TODO: Add INSPIRE, harvester, ... information + var catInfo = promiseStart.then(function(value) { + url = $scope.url + 'info@json?type=site&type=auth'; + return $http.get(url). + success(function(data, status) { + $scope.info = data; + // Add the last time catalog info where updated. + // That could be useful to append to catalog image URL + // in order to trigger a reload of the logo when info are + // reloaded. + $scope.info.site.lastUpdate = new Date(); + $scope.initialized = true; + }). + error(function(data, status, headers, config) { + $rootScope.$broadcast('StatusUpdated', + { + title: $translate('somethingWrong'), + msg: $translate('msgNoCatalogInfo'), + type: 'danger'}); + }); + }); + + + + // Retrieve user information if catalog is online + var userLogin = catInfo.then(function(value) { + url = $scope.url + 'info@json?type=me'; + return $http.get(url). + success(function(data, status) { + $scope.user = data.me; + $scope.authenticated = data.me['@authenticated'] !== 'false'; + // TODO : should not be here, redirect to home + // if ($scope.authenticated) { + // // User is logged in + // } else { + // } + }). + error(function(data, status, headers, config) { + // TODO : translate + $rootScope.$broadcast('StatusUpdated', + {msg: $translate('msgNoUserInfo')} + ); + }); + }); + + + // Retrieve main search information + var searchInfo = userLogin.then(function(value) { + url = 'qi@json?summaryOnly=true'; + return gnSearchManagerService.search(url). + then(function(data) { + $scope.searchInfo = data; + }); + }); + }; + + + $scope.$on('loadCatalogInfo', function(event, status) { + $scope.loadCatalogInfo(); + }); + + $scope.clearStatusMessage = function() { + $scope.status = null; + $('.gn-info').hide(); + }; + + $scope.$on('StatusUpdated', function(event, status) { + $scope.status = {}; + $.extend($scope.status, defaultStatus, status); + $('.gn-info').show(); + // TODO : handle multiple messages + if ($scope.status.timeout > 0) { + setTimeout(function() { + $scope.clearStatusMessage(); + }, $scope.status.timeout * 1000); + } + }); + + + + + + + + $scope.selectMetadata = function(uuid) { + console.log('select ' + uuid); + }; + $scope.selectAllMetadata = function() { + console.log('select all '); + }; + + + $scope.loadCatalogInfo(); + + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/GnAdminModule.js b/web-ui/src/main/resources/catalog/js/GnAdminModule.js new file mode 100644 index 00000000000..b4d94a336b2 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/GnAdminModule.js @@ -0,0 +1,35 @@ +(function() { + goog.provide('gn_admin'); + + + + + + + + + + goog.require('gn'); + goog.require('gn_admin_controller'); + + var module = angular.module('gn_admin', [ + 'gn', + 'gn_admin_controller' + ]); + + // Define the translation files to load + module.constant('$LOCALES', ['core', 'admin']); + + module.config(['$translateProvider', '$LOCALES', + function($translateProvider, $LOCALES) { + $translateProvider.useLoader('localeLoader', { + locales: $LOCALES, + prefix: '../../catalog/locales/', + suffix: '.json' + }); + + var lang = location.href.split('/')[5].substring(0, 2) || 'en'; + $translateProvider.preferredLanguage(lang); + moment.lang(lang); + }]); +})(); diff --git a/web-ui/src/main/resources/catalog/js/GnEditorModule.js b/web-ui/src/main/resources/catalog/js/GnEditorModule.js new file mode 100644 index 00000000000..92eda7f8249 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/GnEditorModule.js @@ -0,0 +1,28 @@ +(function() { + goog.provide('gn_editor'); + + + goog.require('gn'); + goog.require('gn_editor_controller'); + + var module = angular.module('gn_editor', [ + 'gn', + 'gn_editor_controller' + ]); + + // Define the translation files to load + module.constant('$LOCALES', ['core', 'editor']); + + module.config(['$translateProvider', '$LOCALES', + function($translateProvider, $LOCALES) { + $translateProvider.useLoader('localeLoader', { + locales: $LOCALES, + prefix: '../../catalog/locales/', + suffix: '.json' + }); + + var lang = location.href.split('/')[5].substring(0, 2) || 'en'; + $translateProvider.preferredLanguage(lang); + moment.lang(lang); + }]); +})(); diff --git a/web-ui/src/main/resources/catalog/js/GnLoginModule.js b/web-ui/src/main/resources/catalog/js/GnLoginModule.js new file mode 100644 index 00000000000..d5b6c0c593d --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/GnLoginModule.js @@ -0,0 +1,28 @@ +(function() { + goog.provide('gn_login'); + + goog.require('gn'); + goog.require('gn_login_controller'); + + var module = angular.module('gn_login', [ + 'gn', + 'gn_login_controller' + ]); + + //Define the translation files to load + module.constant('$LOCALES', ['core']); + + module.config(['$translateProvider', '$LOCALES', + function($translateProvider, $LOCALES) { + $translateProvider.useLoader('localeLoader', { + locales: $LOCALES, + prefix: '../../catalog/locales/', + suffix: '.json' + }); + + + var lang = location.href.split('/')[5].substring(0, 2) || 'en'; + $translateProvider.preferredLanguage(lang); + moment.lang(lang); + }]); +})(); diff --git a/web-ui/src/main/resources/catalog/js/GnModule.js b/web-ui/src/main/resources/catalog/js/GnModule.js new file mode 100644 index 00000000000..ffc5f57678b --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/GnModule.js @@ -0,0 +1,73 @@ +(function() { + goog.provide('gn'); + + + + goog.require('gn_cat_controller'); + goog.require('gn_language_switcher'); + goog.require('gn_metadata_manager'); + goog.require('gn_pagination'); + goog.require('gn_search_controller'); + goog.require('gn_search_manager'); + goog.require('gn_search_results'); + goog.require('gn_utility_service'); + + var module = angular.module('gn', [ + 'ngRoute', + 'pascalprecht.translate', + 'gn_language_switcher', + 'gn_utility_service', + 'gn_search_manager', + 'gn_metadata_manager', + 'gn_search_results', + 'gn_pagination', + 'gn_cat_controller', + 'gn_search_controller' + ]); + + module.constant('$LOCALES', ['core']); + + + module.factory('localeLoader', ['$http', '$q', function($http, $q) { + return function(options) { + var allPromises = []; + angular.forEach(options.locales, function(value, index) { + var langUrl = options.prefix + + options.key + '-' + value + options.suffix; + + var deferredInst = $q.defer(); + allPromises.push(deferredInst.promise); + + $http({ + method: 'GET', + url: langUrl + }).success(function(data, status, header, config) { + deferredInst.resolve(data); + }).error(function(data, status, header, config) { + deferredInst.reject(options.key); + }); + }); + + // Finally, create a single promise containing all the promises + // for each app module: + var deferred = $q.all(allPromises); + return deferred; + }; + }]); + + + // TODO: could be improved instead of putting this in all main modules ? + module.config(['$translateProvider', '$LOCALES', + function($translateProvider, $LOCALES) { + $translateProvider.useLoader('localeLoader', { + locales: $LOCALES, + prefix: '../../catalog/locales/', + suffix: '.json' + }); + + var lang = location.href.split('/')[5].substring(0, 2) || 'en'; + $translateProvider.preferredLanguage(lang); + moment.lang(lang); + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/LoginController.js b/web-ui/src/main/resources/catalog/js/LoginController.js new file mode 100644 index 00000000000..0066622ffa6 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/LoginController.js @@ -0,0 +1,97 @@ +(function() { + goog.provide('gn_login_controller'); + + var module = angular.module('gn_login_controller', []); + + module.constant('$LOCALES', ['core']); + + /** + * Take care of login action, reset and update password. + */ + module.controller('GnLoginController', + ['$scope', '$http', '$rootScope', '$translate', '$location', '$window', + 'gnUtilityService', + function($scope, $http, $rootScope, $translate, $location, $window, + gnUtilityService) { + $scope.registrationStatus = null; + $scope.passwordReminderStatus = null; + $scope.sendPassword = false; + $scope.password = null; + $scope.passwordCheck = null; + $scope.userToRemind = null; + $scope.changeKey = null; + $scope.passwordUpdated = false; + + function initForm() { + if ($window.location.pathname.indexOf('new.password') !== -1) { + // Retrieve username from URL parameter + $scope.userToRemind = gnUtilityService.getUrlParameter('username'); + $scope.changeKey = gnUtilityService.getUrlParameter('changeKey'); + } + } + + $scope.setSendPassword = function(value) { + $scope.sendPassword = value; + $('#username').focus(); + }; + /** + * Register user. An email will be sent to the new + * user and another to the catalog admin if a profile + * higher than registered user is requested. + */ + $scope.register = function(formId) { + $http.get('create.account@json?' + $(formId).serialize()) + .success(function(data) { + $scope.registrationStatus = data; + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('registrationError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + /** + * Remind user password. + */ + $scope.remindMyPassword = function(formId) { + $http.get('password.reminder@json?' + $(formId).serialize()) + .success(function(data) { + $scope.passwordReminderStatus = data; + $scope.sendPassword = false; + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('passwordReminderError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + /** + * Change user password. + */ + $scope.updatePassword = function(formId) { + $http.get('password.change@json?' + $(formId).serialize()) + .success(function(data) { + if (data == 'null') { + $scope.passwordUpdated = true; + } + }) + .error(function(data) { + + $rootScope.$broadcast('StatusUpdated', { + title: $translate('passwordUpdateError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + initForm(); + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/AdminController.js b/web-ui/src/main/resources/catalog/js/admin/AdminController.js new file mode 100644 index 00000000000..3ebd1e481b8 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/AdminController.js @@ -0,0 +1,172 @@ +(function() { + goog.provide('gn_admin_controller'); + + + + goog.require('gn_adminmetadata_controller'); + goog.require('gn_admintools_controller'); + goog.require('gn_cat_controller'); + goog.require('gn_classification_controller'); + goog.require('gn_dashboard_controller'); + goog.require('gn_harvest_controller'); + goog.require('gn_settings_controller'); + goog.require('gn_standards_controller'); + goog.require('gn_usergroup_controller'); + + + var module = angular.module('gn_admin_controller', + ['gn_dashboard_controller', 'gn_usergroup_controller', + 'gn_admintools_controller', 'gn_settings_controller', + 'gn_adminmetadata_controller', 'gn_classification_controller', + 'gn_harvest_controller', 'gn_standards_controller']); + + + var tplFolder = '../../catalog/templates/admin/'; + + module.config(['$routeProvider', function($routeProvider) { + $routeProvider. + when('/metadata', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnAdminMetadataController'}). + when('/metadata/:tab', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnAdminMetadataController'}). + when('/metadata/:tab/:metadataAction/:schema', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnAdminMetadataController'}). + when('/dashboard', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnDashboardController'}). + when('/dashboard/:tab', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnDashboardController'}). + when('/organization', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnUserGroupController'}). + when('/organization/:tab', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnUserGroupController'}). + when('/organization/:tab/:userOrGroup', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnUserGroupController'}). + when('/classification', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnClassificationController'}). + when('/classification/:tab', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnClassificationController'}). + when('/tools', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnAdminToolsController'}). + when('/tools/:tab', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnAdminToolsController'}). + when('/harvest', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnHarvestController'}). + when('/settings', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnSettingsController'}). + when('/settings/:tab', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnSettingsController'}). + when('/standards', { + templateUrl: tplFolder + 'page-layout.html', + controller: 'GnStandardsController'}). + otherwise({templateUrl: tplFolder + 'admin.html'}); + }]); + + /** + * The admin console controller. + * + * Example: + * + * + */ + module.controller('GnAdminController', [ + '$scope', '$http', '$q', '$rootScope', '$route', '$routeParams', + 'gnUtilityService', + function($scope, $http, $q, $rootScope, $route, $routeParams, + gnUtilityService) { + /** + * Define admin console menu for each type of user + */ + var userAdminMenu = [ + {name: 'harvesters', route: '#harvest', + classes: 'btn-primary', icon: 'icon-cloud-download'}, + {name: 'statisticsAndStatus', route: '#dashboard', + classes: 'btn-success', icon: 'icon-dashboard'}, + {name: 'usersAndGroups', route: '#organization', + classes: 'btn-default', icon: 'icon-group'} + ]; + $scope.menu = { + UserAdmin: userAdminMenu, + Administrator: [ + // TODO : create gn classes + {name: 'metadatasAndTemplates', route: '#metadata', + classes: 'btn-primary', icon: 'icon-archive'}, + {name: 'io', + // Metadata import is made in the widget apps + url: 'home?insert', + classes: 'btn-primary', + icon: 'icon-upload'}, + {name: 'harvesters', route: '#harvest', //url: 'harvesting', + classes: 'btn-primary', icon: 'icon-cloud-download'}, + {name: 'statisticsAndStatus', route: '#dashboard', + classes: 'btn-success', icon: 'icon-dashboard'}, + {name: 'classificationSystems', route: '#classification', + classes: 'btn-info', icon: 'icon-tags'}, + {name: 'standards', route: '#standards', + classes: 'btn-info', icon: 'icon-puzzle-piece'}, + {name: 'usersAndGroups', route: '#organization', + classes: 'btn-default', icon: 'icon-group'}, + {name: 'settings', route: '#settings', + classes: 'btn-warning', icon: 'icon-gear'}, + {name: 'tools', route: '#tools', + classes: 'btn-warning', icon: 'icon-medkit'}] + // TODO : add other role menu + }; + + /** + * Define menu position on the left (nav-stacked) + * or on top of the page. + */ + $scope.navStacked = true; + + $scope.getTpl = function(pageMenu) { + $scope.type = pageMenu.defaultTab; + $.each(pageMenu.tabs, function(index, value) { + if (value.type === $routeParams.tab) { + $scope.type = $routeParams.tab; + } + }); + return tplFolder + pageMenu.folder + $scope.type + '.html'; + }; + + $scope.csvExport = function(json, e) { + $(e.target).next('pre.gn-csv-export').remove(); + $(e.target).after("
    " +
    +                gnUtilityService.toCsv(json) + '
    '); + }; + + /** + * Return menu Angular route or GeoNetwork legacy URLs + * according to $scope.menu configuration. + */ + $scope.getMenuUrl = function(menu) { + if (menu.route) { + return menu.route; + } else if (menu.url) { + return $scope.url + menu.url; + } + }; + + /** + * Return menu according to user profile + */ + $scope.getMenu = function() { + return $scope.menu[$scope.user.profile]; + }; + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/AdminMetadataController.js b/web-ui/src/main/resources/catalog/js/admin/AdminMetadataController.js new file mode 100644 index 00000000000..392d2765320 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/AdminMetadataController.js @@ -0,0 +1,182 @@ +(function() { + goog.provide('gn_adminmetadata_controller'); + + + var module = angular.module('gn_adminmetadata_controller', + []); + + + /** + * GnAdminMetadataController provides administration tools + * for metadata and templates + */ + module.controller('GnAdminMetadataController', [ + '$scope', '$routeParams', '$http', '$rootScope', '$translate', '$compile', + 'gnMetadataManagerService', + 'gnSearchManagerService', + 'gnUtilityService', + function($scope, $routeParams, $http, $rootScope, $translate, $compile, + gnMetadataManagerService, + gnSearchManagerService, + gnUtilityService) { + + $scope.pageMenu = { + folder: 'metadata/', + defaultTab: 'metadata-and-template', + tabs: + [{ + type: 'metadata-and-template', + label: 'metadataAndTemplates', + icon: 'icon-archive', + href: '#/metadata/metadata-and-template' + },{ + type: 'template-sort', + label: 'sortTemplate', + icon: 'icon-sort', + href: '#/metadata/template-sort' + }] + }; + + $scope.schemas = []; + $scope.selectedSchemas = []; + $scope.loadReport = null; + $scope.loadTplReport = null; + $scope.tplLoadRunning = false; + $scope.sampleLoadRunning = false; + + function loadSchemas() { + $http.get('admin.schema.list@json').success(function(data) { + for (var i = 0; i < data.length; i++) { + $scope.schemas.push(data[i]['#text'].trim()); + } + $scope.schemas.sort(); + + // Trigger load action according to route params + launchActions(); + }); + } + + function launchActions() { + // Select schema + if ($routeParams.schema === 'all') { + $scope.selectAllSchemas(true); + } else if ($routeParams.schema !== undefined) { + $scope.selectSchema($routeParams.schema.split(',')); + } + + // Load + if ($routeParams.metadataAction === + 'load-samples') { + $scope.loadSamples(); + } else if ($routeParams.metadataAction === + 'load-templates') { + $scope.loadTemplates(); + } else if ($routeParams.metadataAction === + 'load-samples-and-templates') { + $scope.loadSamples(); + $scope.loadTemplates(); + } + } + + selectSchema = function(schema) { + var idx = $scope.selectedSchemas.indexOf(schema); + if (idx === -1) { + $scope.selectedSchemas.push(schema); + } else { + $scope.selectedSchemas.splice(idx, 1); + } + }; + + /** + * Select one or more schemas. Schema parameter + * could be string or array. + */ + $scope.selectSchema = function(schema) { + if (Array.isArray(schema)) { + $.each(schema, function(index, value) { + selectSchema(value); + }); + } else { + selectSchema(schema); + } + $scope.loadReport = null; + $scope.loadTplReport = null; + }; + + + $scope.isSchemaSelected = function(schema) { + return $scope.selectedSchemas.indexOf(schema) !== -1; + }; + + $scope.selectAllSchemas = function(selectAll) { + if (selectAll) { + $scope.selectedSchemas = $scope.schemas; + } else { + $scope.selectedSchemas = []; + } + $scope.loadReport = null; + $scope.loadTplReport = null; + }; + + $scope.loadTemplates = function() { + $scope.tplLoadRunning = true; + $http.get('admin.load.templates@json?schema=' + + $scope.selectedSchemas.join(',') + ).success(function(data) { + $scope.loadTplReport = data; + $scope.tplLoadRunning = false; + }).error(function(data) { + $scope.tplLoadRunning = false; + }); + }; + + $scope.loadSamples = function() { + $scope.sampleLoadRunning = true; + $http.get('admin.load.samples@json?file_type=mef&uuidAction=overwrite' + + '&schema=' + + $scope.selectedSchemas.join(',') + ).success(function(data) { + $scope.loadReport = data; + $scope.sampleLoadRunning = false; + }).error(function(data) { + $scope.sampleLoadRunning = false; + }); + }; + + + $scope.templates = null; + + var loadTemplates = function() { + $http.get('admin.templates.list@json') + .success(function(data) { + $scope.templates = data; + }); + }; + + $scope.saveOrder = function(formId) { + $http.get('admin.templates.save.order?' + $(formId).serialize()) + .success(function(data) { + loadTemplates(); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('saveTemplateOrderError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + $scope.sortOrder = function(item) { + return parseInt(item.displayorder); + }; + + if ($routeParams.tab === 'template-sort') { + loadTemplates(); + } else { + loadSchemas(); + } + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/AdminToolsController.js b/web-ui/src/main/resources/catalog/js/admin/AdminToolsController.js new file mode 100644 index 00000000000..28feb1d37f8 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/AdminToolsController.js @@ -0,0 +1,397 @@ +(function() { + goog.provide('gn_admintools_controller'); + + + var module = angular.module('gn_admintools_controller', + []); + + + /** + * GnAdminToolsController provides administration tools + */ + module.controller('GnAdminToolsController', [ + '$scope', '$http', '$rootScope', '$translate', '$compile', + '$q', '$timeout', + 'gnMetadataManagerService', + 'gnSearchManagerService', + 'gnUtilityService', + function($scope, $http, $rootScope, $translate, $compile, + $q, $timeout, + gnMetadataManagerService, + gnSearchManagerService, + gnUtilityService) { + + + $scope.pageMenu = { + folder: 'tools/', + defaultTab: 'index', + tabs: + [{ + type: 'index', + label: 'indexAdmin', + icon: 'icon-search', + href: '#/tools/index' + },{ + type: 'batch', + label: 'batchProcess', + icon: 'icon-medkit', + href: '#/tools/batch' + },{ + type: 'transfert-privs', + label: 'transfertPrivs', + href: 'transfer.ownership' + }] + }; + + /** + * True if currently processing records + */ + $scope.processing = false; + + /** + * The full text search filter + * TODO : could be nice to filter by type of record + * and schema + */ + $scope.recordsToProcessFilter = ''; + + /** + * The process report returned by the batch + * processing service with information about the + * number of records processed, or not, process not found, ... + */ + $scope.processReport = null; + + /** + * True if no process found, or privileges issues. + */ + $scope.processReportWarning = false; + + /** + * The list of records to be processed + */ + $scope.recordsToProcess = null; + $scope.numberOfRecordsProcessed = null; + + /** + * The pagination config + */ + $scope.recordsToProcessPagination = { + pages: -1, + currentPage: 0, + hitsPerPage: 10 + }; + /** + * The selected process + */ + $scope.selectedProcess = null; + + /** + * The list of batch process available. + * Stored in batch-process-cfg.json. + * TODO: Move to server side configuration. + * TODO: i18n should not be shared in en-admin.json + * + */ + $scope.batchProcesses = null; + + /** + * Search filter selected for metadata and template type + */ + $scope.batchSearchTemplateY = true; + $scope.batchSearchTemplateN = true; + $scope.batchSearchTemplateS = false; + $scope.batchSearchGroups = {}; + $scope.batchSearchUsers = {}; + $scope.batchSearchCategories = {}; + + function loadProcessConfig() { + $http.get($scope.base + 'config/batch-process-cfg.json') + .success(function(data) { + $scope.batchProcesses = data.config; + }); + } + + function loadGroups() { + $http.get('admin.group.list@json').success(function(data) { + $scope.batchSearchGroups = data; + }).error(function(data) { + // TODO + }); + } + function loadUsers() { + $http.get('admin.user.list@json').success(function(data) { + $scope.batchSearchUsers = data; + }).error(function(data) { + // TODO + }); + } + + function loadCategories() { + $http.get('info@json?type=categories').success(function(data) { + $scope.batchSearchCategories = data.categories; + }).error(function(data) { + // TODO + }); + } + + /** + * Check process progress every ... + */ + var processCheckInterval = 1000; + + + function checkLastBatchProcessReport() { + // Check if processing + return $http.get('md.processing.batch.report@json'). + success(function(data, status) { + if (data != 'null') { + $scope.processReport = data; + $scope.numberOfRecordsProcessed = data['@processedRecords']; + } + if ($scope.processReport && + $scope.processReport['@running'] == 'true') { + $timeout(checkLastBatchProcessReport, processCheckInterval); + } + }); + } + + $scope.runProcess = function(formId) { + $scope.processing = true; + $scope.processReport = null; + $http.get('md.processing.batch@json?' + + $(formId).serialize()) + .success(function(data) { + $scope.processReport = data; + $scope.processReportWarning = data.notFound != 0 || + data.notOwner != 0 || + data.notProcessFound != 0; + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('processFinished'), + timeout: 2, + type: 'success'}); + $scope.processing = false; + + checkLastBatchProcessReport(); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('processError'), + error: data, + timeout: 0, + type: 'danger'}); + $scope.processing = false; + }); + + gnUtilityService.scrollTo('#gn-batch-process-report'); + $timeout(checkLastBatchProcessReport, processCheckInterval); + }; + + // TODO: Should only do that if batch process is the current page + loadProcessConfig(); + checkLastBatchProcessReport(); + loadGroups(); + loadUsers(); + loadCategories(); + + + $scope.recordsToProcessSearchFor = function(e) { + $scope.recordsToProcessFilter = (e ? e.target.value : ''); + $scope.recordsToProcessPagination.currentPage = 0; + $scope.recordsToProcessSearch(); + }; + + // Run a search according to paging option + // TODO Search criteria logic should probably move + // to some kind of SearchManager module + // FIXME : can't watch the recordsToProcessFilter changes ? + $scope.recordsToProcessSearch = function() { + var pageOptions = $scope.recordsToProcessPagination, + criteria = [ + {fast: 'index'}, + {from: + (pageOptions.currentPage * pageOptions.hitsPerPage + 1)}, + {to: + (pageOptions.currentPage + 1) * pageOptions.hitsPerPage}, + {any: $scope.recordsToProcessFilter}], + fields = {'#gn-batchSearchTemplateY': 'y', + '#gn-batchSearchTemplateN': 'n', + '#gn-batchSearchTemplateS': 's'}; + templateValues = []; + + angular.forEach(fields, function(value, key) { + $(key)[0] && $(key)[0].checked && templateValues.push(value); + }); + criteria.push({template: templateValues.join(' or ')}); + + if ($('#gn-batchSearchGroupOwner')[0]) { + var g = $('#gn-batchSearchGroupOwner')[0] + .options[$('#gn-batchSearchGroupOwner')[0] + .selectedIndex] + .value; + g !== '' && criteria.push({group: g}); + } + + if ($('#gn-batchSearchOwner')[0]) { + var g = $('#gn-batchSearchOwner')[0] + .options[$('#gn-batchSearchOwner')[0].selectedIndex] + .value; + g !== '' && criteria.push({_owner: g}); + } + if ($('#gn-batchSearchCategory')[0]) { + var g = $('#gn-batchSearchCategory')[0] + .options[$('#gn-batchSearchCategory')[0].selectedIndex] + .value; + g !== '' && criteria.push({category: g}); + } + var params = ''; + angular.forEach(criteria, function(value) { + angular.forEach(value, function(val, key) { + params += key + '=' + val + '&'; + }); + }); + gnSearchManagerService.search('q@json?' + params) + .then(function(data) { + $scope.recordsToProcess = data; + $scope.recordsToProcessPagination.pages = Math.round( + data.count / + $scope.recordsToProcessPagination.hitsPerPage, 0); + }, function(data) { + // TODO + }); + }; + + // When the current page or search criteria change trigger the search + angular.forEach(['recordsToProcessPagination.currentPage'], + function(value) { + $scope.$watch(value, function() { + $scope.recordsToProcessSearch(); + }); + }); + + // Search when typing a new filter FIXME ? + // $scope.$watch('recordsToProcessFilter', function() { + // console.log('changed' + $scope.recordsToProcessFilter); + // $scope.recordsToProcessSearch(); + // }); + + // Clear current selection and then search for all by default + gnMetadataManagerService.selectNone().then(function() { + $scope.recordsToProcessSearch(); + }); + + + + + // Indexing management + + /** + * Inform if indexing is ongoing or not + */ + $scope.isIndexing = false; + + /** + * Number of records in the index + */ + $scope.numberOfIndexedRecords = null; + + /** + * Check index every ... + */ + var indexCheckInterval = 1000; + + /** + * Get number of record in the index and + * then check if indexing is ongoing or not every + * indexCheckInterval. Stop when not indexing. + * + * TODO: Could we kill the check when switching to somewhere else? + */ + function checkIsIndexing() { + // Check if indexing + return $http.get('info@json?type=index'). + success(function(data, status) { + $scope.isIndexing = data.index == 'true'; + if ($scope.isIndexing) { + $timeout(checkIsIndexing, indexCheckInterval); + } + // Get the number of records (template, records, subtemplates) + $http.get('qi@json?template=y or n or s&summaryOnly=true'). + success(function(data, status) { + $scope.numberOfIndexedRecords = data[0]['@count']; + }); + }); + } + + checkIsIndexing(); + + $scope.rebuildIndex = function() { + $http.get('admin.index.rebuild?reset=yes') + .success(function(data) { + checkIsIndexing(); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('rebuildIndexError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + $scope.optimizeIndex = function() { + $http.get('admin.index.optimize') + .success(function(data) { + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('indexOptimizationInProgress'), + timeout: 2, + type: 'success'}); + // TODO: Does this is asynch and make the search unavailable? + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('rebuildIndexError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + $scope.reloadLuceneConfig = function() { + $http.get('admin.index.config.reload') + .success(function(data) { + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('luceneConfigReloaded'), + timeout: 2, + type: 'success'}); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('rebuildIndexError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + $scope.clearXLinkCache = function() { + $http.get('admin.index.rebuildxlinks') + .success(function(data) { + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('xlinkCacheCleared'), + timeout: 2, + type: 'success'}); + // TODO: Does this is asynch and make the search unavailable? + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('rebuildIndexError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/CSWSettingsController.js b/web-ui/src/main/resources/catalog/js/admin/CSWSettingsController.js new file mode 100644 index 00000000000..e0f08cc429d --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/CSWSettingsController.js @@ -0,0 +1,197 @@ +(function() { + goog.provide('gn_csw_settings_controller'); + + + var module = angular.module('gn_csw_settings_controller', + []); + + + /** + * GnCSWSettingsController provides management interface + * for CSW settings. + * + */ + module.controller('GnCSWSettingsController', [ + '$scope', '$http', '$rootScope', '$translate', 'gnUtilityService', + function($scope, $http, $rootScope, $translate, gnUtilityService) { + var cswSettings = ['system/csw/contactId']; + var cswBooleanSettings = ['system/csw/enable', + 'system/csw/metadataPublic']; + + /** + * CSW properties + */ + $scope.cswSettings = {}; + + /** + * CSW element set name (an array of xpath). + */ + $scope.cswElementSetName = []; + + /** + * The filter for field column + */ + $scope.cswFieldFilterValue = ''; + + /** + * The filter value for language + */ + $scope.cswLanguageFilterValue = $scope.lang; + + /** + * List of languages populated when settings are loaded. + */ + + $scope.cswLanguages = {}; + /** + * List of field populated when settings are loaded. + */ + $scope.cswFields = {}; + + /** + * Load catalog settings and extract CSW settings + */ + function loadSettings() { + $http.get('xml.config.get@json?asTree=false').success(function(data) { + for (var i = 0; i < data.length; i++) { + var setting = data[i]; + if (cswBooleanSettings.indexOf(setting['@name']) !== -1) { + var value = setting['#text'].toLowerCase(); + $scope.cswSettings[setting['@name']] = + (value == 'true' || value == 'on'); + } else if (cswSettings.indexOf(setting['@name']) !== -1) { + $scope.cswSettings[setting['@name']] = setting['#text']; + } + } + }).error(function(data) { + // TODO + }); + } + + function loadUsers() { + $http.get('admin.user.list@json').success(function(data) { + $scope.users = data; + loadSettings(); + }).error(function(data) { + // TODO + }); + } + + + function loadCSWConfig() { + $http.get('admin.config.csw@json').success(function(data) { + $scope.cswConfig = data.record; + angular.forEach($scope.cswConfig, function(value, key) { + $scope.cswLanguages[$scope.cswConfig[key].langid] = true; + $scope.cswFields[$scope.cswConfig[key].field] = true; + }); + loadSettings(); + }).error(function(data) { + // TODO + }); + } + + function loadCSWElementSetName() { + $http.get('admin.config.csw.customelementset@json') + .success(function(data) { + $scope.cswElementSetName = data.xpath; + }); + } + $scope.addCSWElementSetName = function() { + $scope.cswElementSetName.push(['']); + }; + $scope.deleteElementSetName = function(e) { + var index = $.inArray(e, $scope.cswElementSetName); + $scope.cswElementSetName.splice(index, 1); + }; + $scope.saveCSWElementSetName = function(formId) { + $http.get('admin.config.csw.customelementset.save@json?' + + $(formId).serialize()) + .success(function(data) { + loadCSWElementSetName(); + }); + }; + + /** + * Save the form containing all settings. When saved, + * broadcast success or failure status. + */ + $scope.saveSettings = function(formId) { + saveSettings(formId, 'admin.config.save'); + }; + /** + * Save the form containing all capabilities properties. When saved, + * broadcast success or failure status. + */ + $scope.saveProperties = function(formId) { + saveSettings(formId, 'admin.config.csw.save'); + }; + var saveSettings = function(formId, service) { + + $http.get(service + '?' + + gnUtilityService.serialize(formId)) + .success(function(data) { + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('settingsUpdated'), + timeout: 2, + type: 'success'}); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('settingsUpdateError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + /** + * Filter CSW settings by language and/or field + */ + $scope.cswFilter = function(items) { + var result = []; + var field = $scope.cswFieldFilterValue; + var lang = $scope.cswLanguageFilterValue; + + if (items) { + angular.forEach(items, function(value, key) { + var selected = false; + // Filter only by lang + if (lang !== '' && + field === '' && + items[key].langid === lang) { + selected = true; + } + //Filter only by field + if (field !== '' && + lang === '' && + items[key].field === field) { + selected = true; + } + // Filter by both + if (field !== '' && + lang !== '' && + items[key].langid === lang && + items[key].field === field) { + selected = true; + } + // All + if (field === '' && + lang === '') { + selected = true; + } + if (selected) { + result.push(items[key]); + } + }); + } + return result; + }; + + loadUsers(); // Which then load settings + loadCSWConfig(); + loadCSWElementSetName(); + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/CSWTestController.js b/web-ui/src/main/resources/catalog/js/admin/CSWTestController.js new file mode 100644 index 00000000000..f87876202d5 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/CSWTestController.js @@ -0,0 +1,55 @@ +(function() { + goog.provide('gn_csw_test_controller'); + + + var module = angular.module('gn_csw_test_controller', + []); + + + /** + * GnCSWTestController provides simple testing + * of CSW service + * + */ + module.controller('GnCSWTestController', [ + '$scope', '$http', + function($scope, $http) { + + /** + * CSW tests + */ + $scope.cswTests = {}; + $scope.currentTestId = null; + $scope.currentTest = null; + $scope.currentTestResponse = null; + + function loadCSWTest() { + $http.get('../../xml/csw/test/csw-tests.json').success(function(data) { + $scope.cswTests = data; + }); + } + + $scope.$watch('currentTestId', function() { + if ($scope.currentTestId != null) { + $http.get('../../xml/csw/test/' + $scope.currentTestId + '.xml') + .success(function(data) { + $scope.currentTest = data; + $scope.runCSWRequest(); + }); + } + }); + + $scope.runCSWRequest = function() { + $scope.currentTestResponse = ''; + $http.post('csw', $scope.currentTest, { + headers: {'Content-type': 'application/xml'} + }).success(function(data) { + $scope.currentTestResponse = data; + }); + }; + + loadCSWTest(); + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/CSWVirtualController.js b/web-ui/src/main/resources/catalog/js/admin/CSWVirtualController.js new file mode 100644 index 00000000000..a9064e94d7f --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/CSWVirtualController.js @@ -0,0 +1,139 @@ +(function() { + goog.provide('gn_csw_virtual_controller'); + + + var module = angular.module('gn_csw_virtual_controller', + []); + + + /** + * GnCSWVirtualController provides management interface + * for virtual CSW configuration. + * + */ + module.controller('GnCSWVirtualController', [ + '$scope', '$http', '$rootScope', '$translate', + function($scope, $http, $rootScope, $translate) { + + /** + * CSW virtual + */ + $scope.cswVirtual = {}; + $scope.virtualCSWSelected = null; + $scope.virtualCSWUpdated = false; + $scope.virtualCSWSearch = ''; + $scope.groupsFilter = {}; + $scope.sourcesFilter = {}; + $scope.categoriesFilter = {}; + var operation = ''; + + /** + * Load catalog settings and extract CSW settings + */ + function loadCSWVirtual() { + $scope.virtualCSWSelected = {}; + $http.get('admin.config.virtualcsw.list@json').success(function(data) { + $scope.cswVirtual = data; + }).error(function(data) { + // TODO + }); + + // TODO : load categories and sources + // to display combo in edit form + } + + + function loadFilterList() { + $http.get('admin.group.list@json').success(function(data) { + $scope.groupsFilter = data; + }).error(function(data) { + }); + } + + $scope.updatingVirtualCSW = function() { + $scope.virtualCSWUpdated = true; + }; + + $scope.selectVirtualCSW = function(v) { + operation = 'updateservice'; + $http.get('admin.config.virtualcsw.get@json?id=' + v.id) + .success(function(data) { + $scope.virtualCSWSelected = data; + // FIXME: XML to JSON converter only convert + // lonely child as array and not as object + $scope.virtualCSWUpdated = false; + }).error(function(data) { + // TODO + }); + }; + + $scope.addVirtualCSW = function() { + operation = 'newservice'; + $scope.virtualCSWSelected = { + 'record': { + 'id': '', + 'name': 'csw-servicename', + 'description': '' + }, + 'filter': { + 'any': '', + 'abstract': '', + 'title': '', + '_source': '', + '_groupPublished': '', + 'keyword': '', + '_cat': '', + 'denominator': '', + 'type': '' + } + }; + }; + $scope.saveVirtualCSW = function(formId) { + + $http.get('admin.config.virtualcsw.update@json?operation=' + operation + + '&' + $(formId).serialize()) + .success(function(data) { + loadCSWVirtual(); + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('virtualCswUpdated'), + timeout: 2, + type: 'success'}); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('virtualCswUpdateError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + $scope.deleteVirtualCSW = function() { + $http.get('admin.config.virtualcsw.remove?id=' + + $scope.virtualCSWSelected.record.id) + .success(function(data) { + loadCSWVirtual(); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('virtualCswDeleteError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + $scope.getCapabilitiesUrl = function(v) { + if (v && v.record) { + return v.record.name + '?SERVICE=CSW&REQUEST=GetCapabilities'; + } else { + return null; + } + }; + + loadCSWVirtual(); + loadFilterList(); + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/CategoriesController.js b/web-ui/src/main/resources/catalog/js/admin/CategoriesController.js new file mode 100644 index 00000000000..40b2592bb63 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/CategoriesController.js @@ -0,0 +1,93 @@ +(function() { + goog.provide('gn_categories_controller'); + + var module = angular.module('gn_categories_controller', + []); + + + /** + * CategoriesController provides all necessary operations + * to manage category. + */ + module.controller('GnCategoriesController', [ + '$scope', '$routeParams', '$http', '$rootScope', '$translate', + function($scope, $routeParams, $http, $rootScope, $translate) { + + $scope.categories = null; + $scope.categorySelected = {id: $routeParams.categoryId}; + + $scope.categoryUpdated = false; + + $scope.selectCategory = function(c) { + $scope.cateroryUpdated = false; + $scope.categorySelected = c; + }; + + + /** + * Delete a category + */ + $scope.deleteCategory = function(id) { + $http.get('admin.category.remove?id=' + + id) + .success(function(data) { + $scope.unselectCategory(); + loadCategories(); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('categoryDeleteError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + /** + * Save a category + */ + $scope.saveCategory = function(formId) { + $http.get('admin.category.update?' + $(formId).serialize()) + .success(function(data) { + $scope.unselectCategory(); + loadCategories(); + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('categoryUpdated'), + timeout: 2, + type: 'success'}); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('categoryUpdateError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + $scope.addCategory = function() { + $scope.unselectCategory(); + $scope.categorySelected = { + '@id': '', + name: '' + }; + }; + + $scope.unselectCategory = function() { + $scope.categorySelected = {}; + }; + $scope.updatingCategory = function() { + $scope.categoryUpdated = true; + }; + + function loadCategories() { + $http.get('info@json?type=categories').success(function(data) { + $scope.categories = data.categories; + }).error(function(data) { + // TODO + }); + } + loadCategories(); + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/ClassificationController.js b/web-ui/src/main/resources/catalog/js/admin/ClassificationController.js new file mode 100644 index 00000000000..3a765c5b0d4 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/ClassificationController.js @@ -0,0 +1,43 @@ +(function() { + goog.provide('gn_classification_controller'); + + + goog.require('gn_categories_controller'); + goog.require('gn_thesaurus_controller'); + + var module = angular.module('gn_classification_controller', + ['gn_thesaurus_controller', 'gn_categories_controller']); + + + /** + * + */ + module.controller('GnClassificationController', + ['$scope', '$http', + function($scope, $http) { + + $scope.pageMenu = { + folder: 'classification/', + defaultTab: 'thesaurus', + tabs: + [{ + type: 'thesaurus', + label: 'manageThesaurus', + icon: 'icon-archive', + href: '#/classification/thesaurus' + },{ + type: 'directory', + label: 'manageDirectory', + icon: 'icon-list-ul', + href: 'subtemplate.admin' // TODO + },{ + type: 'categories', + label: 'manageCategory', + icon: 'icon-tags', + href: '#/classification/categories' + }] + }; + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/DashboardContentStatController.js b/web-ui/src/main/resources/catalog/js/admin/DashboardContentStatController.js new file mode 100644 index 00000000000..b203e76ab28 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/DashboardContentStatController.js @@ -0,0 +1,155 @@ +(function() { + goog.provide('gn_dashboard_content_stat_controller'); + + var module = angular.module('gn_dashboard_content_stat_controller', + []); + + + + /** + * Provides statistics on the catalog content. + * + * TODO: Move NVD3 calls to specific module + */ + module.controller('GnDashboardContentStatController', [ + '$scope', '$routeParams', '$http', '$translate', + function($scope, $routeParams, $http, $translate) { + + $scope.statistics = {md: {}}; + $scope.hits = 10; + $scope.currentIndicator = null; + $scope.currentIndicatorData = null; + + /** + * Refresh graph on currently selected facet + */ + $scope.$watch('currentIndicator', function() { + // No data + if ($scope.currentIndicator === null) { + return; + } + + // Format results + var data = []; + var total = 0; + $.each($scope.currentIndicator, function(index, value) { + var count = parseInt(value['@count']); + data.push({label: value['@name'], count: count}); + total += count; + }); + + nv.addGraph(function() { + var chart = nv.models.pieChart() + .x(function(d) { return d.label}) + // TODO : Need to translate facet labels ? + .y(function(d) { return d.count}) + .values(function(d) { return d}) + .tooltips(true) + .tooltipContent(function(key, y, e, graph) { + // TODO : %age should be relative to + // the current set of displayed values + return '

    ' + key + '

    ' + + '

    ' + parseInt(y).toFixed() + ' ' + + $translate('records') + ' (' + + (y / total * 100).toFixed() + '%)

    '; + }) + .showLabels(true); + + d3.select('#gn-stat-md-by-facet') + .datum([data]) + .transition().duration(1200) + .call(chart); + + return chart; + + }); + + }); + + function getMainStat() { + $http.get('statistics-content@json') + .success(function(data) { + $scope.statistics.md.mainStatistics = data; + }).error(function(data) { + // TODO + }); + + $http.get('qi@json?fast=index&' + + 'sortBy=popularity&from=1&to=' + $scope.hits) + .success(function(data) { + $scope.statistics.md.popularity = data.metadata; + }).error(function(data) { + // TODO + }); + + $http.get('qi@json?fast=index&' + + 'sortBy=rating&from=1&to=' + $scope.hits) + .success(function(data) { + $scope.statistics.md.rating = data.metadata; + }).error(function(data) { + // TODO + }); + }; + + function getMetadataStat(by, isTemplate) { + isTemplate = isTemplate || 'n'; + // Search by service type statistics + $http.get('statistics-content-metadata@json?' + + 'by=' + by + + '&isTemplate=' + encodeURIComponent(isTemplate)) + .success(function(data) { + + if (data == 'null') { // Null response returned + // TODO : Add no data message + return; + } + var total = 0; + for (var i in data) { + data[i].total = parseInt(data[i].total); + total += data[i].total; + } + + $scope.statistics.md[by] = data; + nv.addGraph(function() { + var chart = nv.models.pieChart() + .x(function(d) { return $translate(d.label) }) + .y(function(d) { return d.total}) + .values(function(d) { return d}) + .tooltips(true) + .tooltipContent(function(key, y, e, graph) { + // TODO : %age should be relative to + // the current set of displayed values + return '

    ' + key + '

    ' + + '

    ' + parseInt(y).toFixed() + ' ' + + $translate('records') + ' (' + + (y / total * 100).toFixed() + '%)

    '; + }) + .showLabels(true); + + d3.select('#gn-stat-md-by-' + by) + .datum([data]) + .transition().duration(1200) + .call(chart); + + return chart; + }); + }).error(function(data) { + // TODO + }); + }; + + getMainStat(); + + getMetadataStat('schema'); + getMetadataStat('template', '%'); + getMetadataStat('source'); + getMetadataStat('harvest'); + getMetadataStat('category'); + getMetadataStat('status'); + getMetadataStat('validity'); + getMetadataStat('owner'); + getMetadataStat('groupowner'); + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/DashboardController.js b/web-ui/src/main/resources/catalog/js/admin/DashboardController.js new file mode 100644 index 00000000000..901efe729d3 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/DashboardController.js @@ -0,0 +1,60 @@ +(function() { + goog.provide('gn_dashboard_controller'); + + + + goog.require('gn_dashboard_content_stat_controller'); + goog.require('gn_dashboard_search_stat_controller'); + goog.require('gn_dashboard_status_controller'); + + var module = angular.module('gn_dashboard_controller', + ['gn_dashboard_status_controller', + 'gn_dashboard_search_stat_controller', + 'gn_dashboard_content_stat_controller']); + + + /** + * + */ + module.controller('GnDashboardController', ['$scope', '$http', + function($scope, $http) { + + + $scope.pageMenu = { + folder: 'dashboard/', + defaultTab: 'status', + tabs: + [{ + type: 'status', + label: 'status', + icon: 'icon-dashboard', + href: '#/dashboard/status' + },{ + type: 'statistics-search', + label: 'searchStatistics', + icon: 'icon-search', + href: '#/dashboard/statistics-search' + },{ + type: 'statistics-content', + label: 'contentStatistics', + icon: 'icon-bar-chart', + href: '#/dashboard/statistics-content' + },{ + type: 'information', + label: 'information', + icon: 'icon-list-ul', + href: '#/dashboard/information' + }] + }; + + $scope.info = {}; + + $http.get($scope.url + 'xml.config.info@json').success(function(data) { + $scope.info = data; + }).error(function(data) { + // TODO + }); + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/DashboardSearchStatController.js b/web-ui/src/main/resources/catalog/js/admin/DashboardSearchStatController.js new file mode 100644 index 00000000000..3d3265e601f --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/DashboardSearchStatController.js @@ -0,0 +1,276 @@ +(function() { + goog.provide('gn_dashboard_search_stat_controller'); + + var module = angular.module('gn_dashboard_search_stat_controller', + []); + + + + /** + * + */ + module.controller('GnDashboardSearchStatController', [ + '$scope', '$routeParams', '$http', '$translate', '$sce', + function($scope, $routeParams, $http, $translate, $sce) { + + $scope.statistics = {md: {}, search: { + mainSearchStatistics: {}, + terms: {}, + services: [] + }}; + + // By default, provide search terms for this service + $scope.termsForSearchService = 'q'; + $scope.currentField = 'any'; + + // The first search date + $scope.dateMin = null; + // The last search date + $scope.dateMax = null; + + // The beginning of the temporal range + $scope.dateFrom = null; + // The end of the temporal range + $scope.dateTo = null; + $scope.graphicType = 'MONTH'; + + + + function getMainSearchStat() { + // Get core statistics for q service + $http.get('statistics-search@json?service=q') + .success(function(data) { + $scope.statistics.search.mainSearchStatistics.q = data; + }).error(function(data) { + // TODO + }); + + // Get core statistics for csw service + $http.get('statistics-search@json?service=csw') + .success(function(data) { + $scope.statistics.search.mainSearchStatistics.csw = data; + }).error(function(data) { + // TODO + }); + + $http.get('statistics-search-ip@json') + .success(function(data) { + $scope.statistics.search.ip = data; + }).error(function(data) { + // TODO + }); + }; + + function getSearchStatByDate() { + var byType = true; + + // Search by date statistics + $http.get($scope.url + + 'statistics-search-by-date@json?' + + 'dateFrom=' + $scope.dateFrom + + '&dateTo=' + $scope.dateTo + + '&graphicType=' + $scope.graphicType + + '&byType=' + byType).success(function(data) { + // Get min/max range + $scope.dateMin = data.dateMin.substring(0, 10); + $scope.dateMax = data.dateMax.substring(0, 10); + + // No date defined, get min and max of search range + // and init dateFrom and dateTo to query full time range + if ($scope.dateFrom === null) { + $scope.dateFrom = $scope.dateMin; + $scope.dateTo = $scope.dateMax; + return; + } + + + // Format the data for multi bar chart + $scope.statistics.search.temporal = []; + + // Retrieve all possible labels for all series + // nvd3 require to have all values for all series + // (with 0 when no data) + // to stack series properly + // TODO : Add all possible dates between min / max + var xValues = []; + for (var i = 0; i < data.response.length; i++) { + var r = data.response[i]; + if (r.record) { + if ($.isArray(r.record)) { + for (var j = 0; j < r.record.length; j++) { + xValues.push(r.record[j].reqdate); + } + } else { + xValues.push(r.record.reqdate); + // Jeeves JSON output one xml child as an object and + // n children as array of object. Convert all to array + r.record = [r.record]; + } + } + } + xValues.sort(); + + // Build an array with all values for each series + for (var i = 0; i < data.response.length; i++) { + var records = data.response[i].record; + if (records && records.length > 0) { + var values = []; + for (var j = 0; j < xValues.length; j++) { + var valueFoundForSeries = false; + for (var k = 0; k < records.length; k++) { + var record = records[k]; + if (record.reqdate == xValues[j]) { + valueFoundForSeries = true; + values.push(record); + // The value exist for the serie - exit + k = records.length; + } + } + + // Add a zero value if no data available for current x value + if (!valueFoundForSeries) { + values.push({reqdate: xValues[j], number: 0}); + } + } + + $scope.statistics.search.temporal.push({ + key: $translate(data.response[i]['@service']), + values: values + }); + } + } + + // No data + if ($scope.statistics.search.temporal.length === 0) { + return; + } + + nv.addGraph(function() { + var chart = nv.models.multiBarChart() + .x(function(d) { return d.reqdate; }) + .y(function(d) { return parseInt(d.number); }) + .stacked(true); + // .rotateLabels(-90) + + + chart.reduceXTicks(false).staggerLabels(true); + + chart.yAxis + .axisLabel('Number of requests') + .tickFormat(d3.format('.f')); + + d3.select('#gn-stat-search-timeline') + .datum($scope.statistics.search.temporal) + .transition().duration(500) + .call(chart); + + nv.utils.windowResize(chart.update); + + return chart; + }); + }).error(function(data) { + // TODO + }); + }; + + function getSearchStatByService() { + // Search by service type statistics + $http.get('statistics-search-by-service-type@json') + .success(function(data) { + var total = 0; + for (var i in data) { + data[i].nbsearch = parseInt(data[i].nbsearch); + total += data[i].nbsearch; + } + $scope.statistics.search.byServiceType = data; + nv.addGraph(function() { + var chart = nv.models.pieChart() + .x(function(d) { return $translate(d.service) }) + .y(function(d) { return d.nbsearch}) + .values(function(d) { return d}) + .tooltips(true) + .tooltipContent(function(key, y, e, graph) { + // TODO : %age should be relative to + // the current set of displayed values + return '

    ' + key + '

    ' + + '

    ' + parseInt(y).toFixed() + ' ' + + $translate('searches') + ' (' + + (y / total * 100).toFixed() + '%)

    '; + }) + .showLabels(true); + + d3.select('#gn-stat-search-by-service') + .datum([data]) + .transition().duration(1200) + .call(chart); + + return chart; + }); + }).error(function(data) { + // TODO + }); + }; + + function getSearchStatForFieldsAndTerms() { + $http.get('statistics-search-fields@json') + .success(function(data) { + $scope.statistics.search.fields = data; + + // Retrieve the list of search services + for (var i in data) { + var value = data[i].service; + if ($scope.statistics.search.services.indexOf(value) === -1) { + $scope.statistics.search.services.push(value); + } + } + $scope.statistics.search.services.sort(); + }).error(function(data) { + // TODO + }); + + $scope.viewTermsForField = function(field, service) { + $scope.currentField = field; + $http.get('statistics-search-terms@json?' + + 'field=' + field + + '&service=' + service) + .success(function(data) { + $scope.statistics.search.terms.any = data; + }).error(function(data) { + // TODO + }); + }; + $scope.viewTermsForField($scope.currentField, + $scope.termsForSearchService); + } + + $scope.searchStatisticExport = function() { + $http.get('stat.tableExport?tableToExport=requests') + .success(function(data) { + $scope.requestsExport = $sce.trustAsHtml(data); + }).error(function(data) { + // TODO + }); + $http.get('stat.tableExport?tableToExport=params') + .success(function(data) { + $scope.paramsExport = $sce.trustAsHtml(data); + }).error(function(data) { + // TODO + }); + }; + + + // Refresh graph when model change + $scope.$watch('graphicType', getSearchStatByDate); + $scope.$watch('dateFrom', getSearchStatByDate); + $scope.$watch('dateTo', getSearchStatByDate); + + getMainSearchStat(); + getSearchStatByDate(); + getSearchStatByService(); + getSearchStatForFieldsAndTerms(); + + + // Status + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/DashboardStatusController.js b/web-ui/src/main/resources/catalog/js/admin/DashboardStatusController.js new file mode 100644 index 00000000000..2811ec13475 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/DashboardStatusController.js @@ -0,0 +1,44 @@ +(function() { + goog.provide('gn_dashboard_status_controller'); + + goog.require('gn_gauge'); + + var module = angular.module('gn_dashboard_status_controller', + ['gn_gauge']); + + + /** + * + */ + module.controller('GnDashboardStatusController', [ + '$scope', '$routeParams', '$http', + function($scope, $routeParams, $http) { + $scope.healthy = undefined; + $scope.gauges = []; + $scope.hits = 20; + + $http.get('../../criticalhealthcheck').success(function(data) { + $scope.healthy = true; + $scope.healthcheck = data; + }).error(function(data) { + $scope.healthy = false; + $scope.healthcheck = data; + }); + + + $http.get( + 'qi@json?fast=index&sortBy=changeDate&' + + '_indexingError=1&from=1&to=' + + $scope.hits).success(function(data) { + // TODO : mutualize search results formatting + if (data.metadata instanceof Array) { + $scope.mdWithIndexingError = data.metadata; + } else { + $scope.mdWithIndexingError = [data.metadata]; + } + }).error(function(data) { + // TODO + }); + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/HarvestController.js b/web-ui/src/main/resources/catalog/js/admin/HarvestController.js new file mode 100644 index 00000000000..6ab5452c5b4 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/HarvestController.js @@ -0,0 +1,507 @@ +(function() { + goog.provide('gn_harvest_controller'); + + + + + + goog.require('gn_category'); + goog.require('gn_harvester'); + goog.require('gn_importxsl'); + + var module = angular.module('gn_harvest_controller', + ['gn_harvester', 'gn_category']); + + + /** + * + */ + module.controller('GnHarvestController', [ + '$scope', '$http', '$translate', '$injector', '$rootScope', + 'gnSearchManagerService', 'gnUtilityService', + function($scope, $http, $translate, $injector, $rootScope, + gnSearchManagerService, gnUtilityService) { + + $scope.pageMenu = { + folder: 'harvest/', + defaultTab: 'harvest', + tabs: [] + }; + $scope.harvesterTypes = {}; + $scope.harvesters = {}; + $scope.harvesterSelected = null; + $scope.harvesterUpdated = false; + $scope.harvesterNew = false; + $scope.harvesterHistory = {}; + + + var unbindStatusListener = null; + $scope.harvesterRecordsPagination = { + pages: -1, + currentPage: 0, + hitsPerPage: 10 + }; + // List of metadata records attached to the selected user + $scope.harvesterRecords = null; + $scope.harvesterRecordsFilter = null; + + // Register the search results, filter and pager + // and get the search function back + $scope.harvesterRecordsSearch = gnSearchManagerService.register({ + records: 'harvesterRecords', + filter: 'harvesterRecordsFilter', + pager: 'harvesterRecordsPagination' + }, $scope); + + // When the current page change trigger the search + $scope.$watch('harvesterRecordsPagination.currentPage', function() { + $scope.harvesterRecordsSearch(); + }); + + function loadHarvesters() { + return $http.get('admin.harvester.list@json').success(function(data) { + if (data != 'null') { + $scope.harvesters = data; + gnUtilityService.parseBoolean($scope.harvesters); + } + }).error(function(data) { + // TODO + }); + } + + + function loadHistory() { + $scope.harvesterHistory = undefined; + $http.get('admin.harvester.history@json?uuid=' + + $scope.harvesterSelected.site.uuid).success(function(data) { + $scope.harvesterHistory = data.response; + }).error(function(data) { + // TODO + }); + } + + function loadHarvesterTypes() { + $http.get('admin.harvester.info@json?type=harvesterTypes') + .success(function(data) { + angular.forEach(data[0], function(value) { + $scope.harvesterTypes[value] = { + label: value, + text: $translate(value) + }; + $.getScript('../../catalog/templates/admin/harvest/type/' + + value + '.js') + .done(function(script, textStatus) { + $scope.harvesterTypes[value].loaded = true; + // FIXME: could we make those harvester specific + // function a controller + }) + .fail(function(jqxhr, settings, exception) { + $scope.harvesterTypes[value].loaded = false; + }); + }); + }).error(function(data) { + // TODO + }); + } + + $scope.getTplForHarvester = function() { + // TODO : return view by calling harvester ? + if ($scope.harvesterSelected) { + return '../../catalog/templates/admin/' + $scope.pageMenu.folder + + 'type/' + $scope.harvesterSelected['@type'] + '.html'; + } else { + return null; + } + }; + $scope.updatingHarvester = function() { + $scope.harvesterUpdated = true; + }; + $scope.addHarvester = function(type) { + $scope.harvesterNew = true; + $scope.harvesterHistory = {}; + $scope.harvesterSelected = window['gnHarvester' + type].createNew(); + }; + + $scope.cloneHarvester = function(id) { + $http.get('admin.harvester.clone@json?id=' + + id) + .success(function(data) { + loadHarvesters().then(function() { + // Select the clone + angular.forEach($scope.harvesters, function(h) { + if (h['@id'] === data[0]) { + $scope.selectHarvester(h); + } + }); + }); + }).error(function(data) { + // TODO + }); + }; + + $scope.buildResponseGroup = function(h) { + var groups = ''; + angular.forEach(h.privileges, function(p) { + var ops = ''; + angular.forEach(p.operation, function(o) { + ops += ''; + }); + groups += + '' + ops + ''; + }); + return '' + groups + ''; + }; + $scope.buildResponseCategory = function(h) { + var cats = ''; + angular.forEach(h.categories, function(c) { + cats += + ''; + }); + return '' + cats + ''; + }; + + + $scope.saveHarvester = function() { + var body = window['gnHarvester' + $scope.harvesterSelected['@type']] + .buildResponse($scope.harvesterSelected, $scope); + + $http.post('admin.harvester.' + + ($scope.harvesterNew ? 'add' : 'update') + + '@json', body, { + headers: {'Content-type': 'application/xml'} + }).success(function(data) { + loadHarvesters(); + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('harvesterUpdated'), + timeout: 2, + type: 'success'}); + }).error(function(data) { + console.log(data); + }); + }; + $scope.selectHarvester = function(h) { + + // TODO: Specific to thredds + if (h['@type'] === 'thredds') { + + $scope.threddsCollectionsMode = + h.options.outputSchemaOnAtomicsDIF !== '' ? 'DIF' : 'UNIDATA'; + $scope.threddsAtomicsMode = + h.options.outputSchemaOnCollectionsDIF !== '' ? 'DIF' : 'UNIDATA'; + + + } + $scope.harvesterSelected = h; + $scope.harvesterUpdated = false; + $scope.harvesterNew = false; + $scope.harvesterHistory = {}; + $scope.harvesterRecords = null; + + loadHistory(); + + // Retrieve records in that harvester + $scope.harvesterRecordsFilter = { + template: 'y or s or n', + siteId: $scope.harvesterSelected.site.uuid, + sortBy: 'title' + }; + $scope.harvesterRecordsSearch(); + }; + + $scope.refreshHarvester = function() { + loadHarvesters(); + }; + $scope.deleteHarvester = function() { + $http.get('admin.harvester.remove@json?id=' + + $scope.harvesterSelected['@id']) + .success(function(data) { + $scope.harvesterSelected = {}; + $scope.harvesterUpdated = false; + $scope.harvesterNew = false; + loadHarvesters(); + }).error(function(data) { + console.log(data); + }); + }; + + $scope.deleteHarvesterRecord = function() { + $http.get('admin.harvester.clear@json?id=' + + $scope.harvesterSelected['@id']) + .success(function(data) { + $scope.harvesterSelected = {}; + $scope.harvesterUpdated = false; + $scope.harvesterNew = false; + loadHarvesters(); + }).error(function(data) { + console.log(data); + }); + }; + $scope.deleteHarvesterHistory = function() { + var ids = []; + angular.forEach($scope.harvesterHistory, function(h) { + ids.push(h.id); + }); + $http.get('admin.harvester.history.delete@json?id=' + ids.join('&id=')) + .success(function(data) { + loadHarvesters().then(function() { + $scope.selectHarvester($scope.harvesterSelected); + }); + }); + }; + $scope.runHarvester = function() { + $http.get('admin.harvester.run@json?id=' + + $scope.harvesterSelected['@id']) + .success(function(data) { + loadHarvesters(); + }); + }; + + $scope.setHarvesterSchedule = function() { + if (!$scope.harvesterSelected) { + return; + } + var status = $scope.harvesterSelected.options.status; + $http.get('admin.harvester.' + + (status === 'active' ? 'start' : 'stop') + + '@json?id=' + + $scope.harvesterSelected['@id']) + .success(function(data) { + + }).error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('harvesterSchedule' + status), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + // Register status listener + unbindStatusListener = $scope.$watch('harvesterSelected.options.status', + function() { + $scope.setHarvesterSchedule(); + }); + + loadHarvesters(); + loadHarvesterTypes(); + + + // --------------------------------------- + // Those function are harvester dependant and + // should move in the harvester code + // TODO + $scope.geonetworkGetSources = function(url) { + $http.get($scope.proxyUrl + + encodeURIComponent(url + '/srv/eng/info?type=sources')) + .success(function(data) { + $scope.geonetworkSources = []; + var i = 0; + var xmlDoc = $.parseXML(data); + var $xml = $(xmlDoc); + $sources = $xml.find('uuid'); + $names = $xml.find('name'); + + angular.forEach($sources, function(s) { + // FIXME: probably some issue on IE ? + $scope.geonetworkSources.push({ + uuid: s.textContent, + name: $names[i].textContent + }); + i++; + }); + }).error(function(data) { + // TODO + }); + }; + + // TODO: Should move to OAIPMH + $scope.oaipmhSets = null; + $scope.oaipmhPrefix = null; + $scope.oaipmhInfo = null; + $scope.oaipmhGet = function() { + $scope.oaipmhInfo = null; + var body = 'oaiPmhServer'; + $http.post('admin.harvester.info@json', body, { + headers: {'Content-type': 'application/xml'} + }).success(function(data) { + if (data[0].sets && data[0].formats) { + $scope.oaipmhSets = data[0].sets; + $scope.oaipmhPrefix = data[0].formats; + } else { + $scope.oaipmhInfo = $translate('oaipmh-FailedToGetSetsAndPrefix'); + } + }).error(function(data) { + }); + }; + + // TODO : enable watch only if OAIPMH + $scope.$watch('harvesterSelected.site.url', function() { + if ($scope.harvesterSelected && + $scope.harvesterSelected['@type'] === 'oaipmh') { + $scope.oaipmhGet(); + } + }); + + // TODO: Should move to a CSW controller + $scope.cswCriteria = []; + $scope.cswCriteriaInfo = null; + + /** + * Retrieve GetCapabilities document to retrieve + * the list of possible search fields declared + * in *Queryables. + * + * If the service is unavailable for a while and a user + * go to the admin page, it may loose its filter. + */ + $scope.cswGetCapabilities = function() { + $scope.cswCriteriaInfo = null; + + if ($scope.harvesterSelected && + $scope.harvesterSelected.site && + $scope.harvesterSelected.site.capabilitiesUrl) { + + + var url = $scope.harvesterSelected.site.capabilitiesUrl; + + // Add GetCapabilities if not already in URL + // Parameter value is case sensitive. + // Append a ? if not already in there and if not & + if (url.indexOf('GetCapabilities') === -1) { + url += (url.indexOf('?') === -1 ? '?' : '&') + + 'SERVICE=CSW&REQUEST=GetCapabilities&VERSION=2.0.2'; + } + + $http.get($scope.proxyUrl + + encodeURIComponent(url)) + .success(function(data) { + $scope.cswCriteria = []; + + var i = 0; + try { + var xmlDoc = $.parseXML(data); + + // Create properties in model if no criteria defined + if (!$scope.harvesterSelected.searches) { + $scope.harvesterSelected.searches = [{}]; + } + + var $xml = $(xmlDoc); + var matches = ['SupportedISOQueryables', + 'SupportedQueryables', + 'AdditionalQueryables']; + + $xml.find('Constraint').each(function() { + if (matches.indexOf($(this).attr('name')) !== -1) { + + // Add all queryables to the list of possible parameters + // and to the current harvester if not exist. + // When harvester is saved only criteria with + // value will be saved. + $(this).find('Value').each(function() { + var name = $(this).text(); + $scope.cswCriteria.push(name); + if (!$scope.harvesterSelected.searches[0][name]) { + $scope.harvesterSelected.searches[0][name] = + {value: ''}; + } + }); + } + }); + + $scope.cswCriteria.sort(); + + } catch (e) { + $scope.cswCriteriaInfo = + $translate('csw-FailedToParseCapabilities'); + } + + }).error(function(data) { + // TODO + }); + } + }; + + $scope.$watch('harvesterSelected.site.capabilitiesUrl', function() { + $scope.cswGetCapabilities(); + }); + + + + + // WFS GetFeature harvester + $scope.harvesterTemplates = null; + var loadHarvesterTemplates = function() { + $http.get('info@json?type=templates') + .success(function(data) { + $scope.harvesterTemplates = data.templates; + }); + }; + + + $scope.harvesterGetFeatureXSLT = null; + var wfsGetFeatureXSLT = function() { + $scope.oaipmhInfo = null; + var body = 'wfsFragmentStylesheets' + + $scope.harvesterSelected.options.outputSchema + + ''; + $http.post('admin.harvester.info@json', body, { + headers: {'Content-type': 'application/xml'} + }).success(function(data) { + $scope.harvesterGetFeatureXSLT = data[0]; + }); + }; + + + // When schema change reload the available XSLTs and templates + $scope.$watch('harvesterSelected.options.outputSchema', function() { + if ($scope.harvesterSelected && + $scope.harvesterSelected['@type'] === 'wfsfeatures') { + wfsGetFeatureXSLT(); + loadHarvesterTemplates(); + } + }); + + + + // Thredds + $scope.threddsCollectionsMode = 'DIF'; + $scope.threddsAtomicsMode = 'DIF'; + $scope.harvesterThreddsXSLT = null; + var threddsGetXSLT = function() { + $scope.oaipmhInfo = null; + var opt = $scope.harvesterSelected.options; + var schema = ($scope.threddsCollectionsMode === 'DIF' ? + opt.outputSchemaOnCollectionsDIF : + opt.outputSchemaOnCollectionsFragments); + var body = 'threddsFragmentStylesheets' + + schema + + ''; + $http.post('admin.harvester.info@json', body, { + headers: {'Content-type': 'application/xml'} + }).success(function(data) { + $scope.harvesterThreddsXSLT = data[0]; + }); + }; + $scope.$watch('harvesterSelected.options.outputSchemaOnCollectionsDIF', + function() { + if ($scope.harvesterSelected && + $scope.harvesterSelected['@type'] === 'thredds') { + threddsGetXSLT(); + loadHarvesterTemplates(); + } + }); + $scope.$watch( + 'harvesterSelected.options.outputSchemaOnCollectionsFragments', + function() { + if ($scope.harvesterSelected && + $scope.harvesterSelected['@type'] === 'thredds') { + threddsGetXSLT(); + loadHarvesterTemplates(); + } + }); + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/LogoSettingsController.js b/web-ui/src/main/resources/catalog/js/admin/LogoSettingsController.js new file mode 100644 index 00000000000..a746e9fe6fb --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/LogoSettingsController.js @@ -0,0 +1,106 @@ +(function() { + goog.provide('gn_logo_settings_controller'); + + + var module = angular.module('gn_logo_settings_controller', + ['blueimp.fileupload']); + + + /** + * GnLogoSettingsController provides management interface + * for catalog logo and harvester logo. + * + */ + module.controller('GnLogoSettingsController', [ + '$scope', '$http', '$rootScope', '$translate', + function($scope, $http, $rootScope, $translate) { + /** + * The list of catalog logos + */ + $scope.logos = []; + + /** + * Load list of logos + */ + loadLogo = function() { + $scope.logos = []; + $http.get('admin.logo.list@json?type=icons').success(function(data) { + $scope.logos = data[0]; + }).error(function(data) { + // TODO + }); + }; + + /** + * Callback when error uploading file. + */ + loadLogoError = function(e, data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('logoUploadError'), + error: data.jqXHR.responseJSON, + timeout: 0, + type: 'danger'}); + }; + + /** + * Configure logo uploader + */ + $scope.logoUploadOptions = { + autoUpload: true, + done: loadLogo, + fail: loadLogoError + }; + + + /** + * Set the catalog logo and optionnaly the favicon + * if favicon parameter is set to true. + */ + $scope.setCatalogLogo = function(logoName, favicon) { + var setFavicon = favicon ? 1 : 0; + + $http.get('admin.logo.update?fname=' + logoName + + '&favicon=' + favicon) + .success(function(data) { + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('logoUpdated'), + timeout: 2, + type: 'success'}); + $rootScope.$broadcast('loadCatalogInfo'); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('logoUpdateError'), + error: data, + timeout: 0, + type: 'danger'}); + loadLogo(); + }); + }; + + /** + * Remove the logo and refresh the list when done. + */ + $scope.removeLogo = function(logoName) { + $http.get('admin.logo.remove?fname=' + logoName) + .success(function(data) { + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('logoRemoved'), + timeout: 2, + type: 'success'}); + loadLogo(); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('logoRemoveError'), + error: data, + timeout: 0, + type: 'danger'}); + loadLogo(); + }); + }; + + loadLogo(); + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/SettingsController.js b/web-ui/src/main/resources/catalog/js/admin/SettingsController.js new file mode 100644 index 00000000000..b80d25b65d9 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/SettingsController.js @@ -0,0 +1,66 @@ +(function() { + goog.provide('gn_settings_controller'); + + + + + + + + + + + + + + goog.require('gn_csw_settings_controller'); + goog.require('gn_csw_test_controller'); + goog.require('gn_csw_virtual_controller'); + goog.require('gn_logo_settings_controller'); + goog.require('gn_system_settings_controller'); + + var module = angular.module('gn_settings_controller', + ['gn_system_settings_controller', + 'gn_csw_settings_controller', + 'gn_csw_virtual_controller', + 'gn_csw_test_controller', + 'gn_logo_settings_controller']); + + + /** + * + */ + module.controller('GnSettingsController', ['$scope', + function($scope) { + + $scope.pageMenu = { + folder: 'settings/', + defaultTab: 'system', + tabs: + [{ + type: 'system', + label: 'settings', + icon: 'icon-cogs', + href: '#/settings/system' + },{ + type: 'logo', + label: 'manageLogo', + icon: 'icon-picture', + href: '#/settings/logo' + },{ + type: 'csw', + label: 'manageCSW', + href: '#/settings/csw' + },{ + type: 'csw-virtual', + label: 'manageVirtualCSW', + href: '#/settings/csw-virtual' + },{ + type: 'csw-test', + label: 'testCSW', + href: '#/settings/csw-test' + }] + }; + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/StandardsController.js b/web-ui/src/main/resources/catalog/js/admin/StandardsController.js new file mode 100644 index 00000000000..8a08195593e --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/StandardsController.js @@ -0,0 +1,87 @@ +(function() { + goog.provide('gn_standards_controller'); + + + var module = angular.module('gn_standards_controller', + []); + + + /** + * GnStandardsController provides administration tools + * for standards. + * + * TODO: More testing required on add/update action + * + */ + module.controller('GnStandardsController', [ + '$scope', '$routeParams', '$http', '$rootScope', '$translate', '$compile', + 'gnMetadataManagerService', + 'gnSearchManagerService', + 'gnUtilityService', + function($scope, $routeParams, $http, $rootScope, $translate, $compile, + gnMetadataManagerService, + gnSearchManagerService, + gnUtilityService) { + + $scope.pageMenu = { + folder: 'standards/', + defaultTab: 'standards', + tabs: [] + }; + + $scope.schemas = []; + + function loadSchemas() { + $http.get('admin.schema.list@json').success(function(data) { + for (var i = 0; i < data.length; i++) { + $scope.schemas.push({id: data[i]['#text'].trim(), props: data[i]}); + } + $scope.schemas.sort(); + }); + } + + $scope.addStandard = function(formId, action) { + $http.get('admin.schema.' + action + '?' + $(formId).serialize()) + .success(function(data) { + loadSchemas(); + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('standardAdded'), + timeout: 2, + type: 'success'}); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('standardAddError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + $scope.removeStandard = function(s) { + $http.get('admin.schema.remove@json?schema=' + s) + .success(function(data) { + if (data['@status'] === 'error') { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('standardsDeleteError'), + msg: data['@message'], + timeout: 0, + type: 'danger'}); + } else { + loadSchemas(); + } + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('standardsDeleteError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + loadSchemas(); + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/SystemSettingsController.js b/web-ui/src/main/resources/catalog/js/admin/SystemSettingsController.js new file mode 100644 index 00000000000..4d1fd833ea7 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/SystemSettingsController.js @@ -0,0 +1,129 @@ +(function() { + goog.provide('gn_system_settings_controller'); + + + var module = angular.module('gn_system_settings_controller', + []); + + + /** + * GnSystemSettingsController provides management interface + * for catalog settings. + * + * TODO: + * * Add custom forms for some settings (eg. contact for CSW, + * Metadata views > default views, Search only in requested language) + */ + module.controller('GnSystemSettingsController', [ + '$scope', '$http', '$rootScope', '$translate', 'gnUtilityService', + function($scope, $http, $rootScope, $translate, gnUtilityService) { + + $scope.settings = []; + var sectionsLevel1 = []; + var sectionsLevel2 = []; + $scope.sectionsLevel1 = []; + $scope.sectionsLevel2 = []; + $scope.systemUsers = null; + + /** + * Load catalog settings as a flat list and + * extract firs and second level sections. + * + * Form field name is also based on settings + * key replacing "/" by "." (to not create invalid + * element name in XML Jeeves request element). + */ + function loadSettings() { + $http.get('xml.config.get@json?asTree=false').success(function(data) { + + gnUtilityService.parseBoolean(data); + $scope.settings = data; + + for (var i = 0; i < $scope.settings.length; i++) { + var tokens = $scope.settings[i]['@name'].split('/'); + $scope.settings[i].formName = + $scope.settings[i]['@name'].replace(/\//g, '.'); + // Extract level 1 and 2 sections + if (tokens) { + if (sectionsLevel1.indexOf(tokens[0]) === -1) { + sectionsLevel1.push(tokens[0]); + $scope.sectionsLevel1.push({ + 'name': tokens[0], + '@position': $scope.settings[i]['@position']}); + } + var level2name = tokens[0] + '/' + tokens[1]; + if (sectionsLevel2.indexOf(level2name) === -1) { + sectionsLevel2.push(level2name); + $scope.sectionsLevel2.push({ + 'name': level2name, + '@position': $scope.settings[i]['@position']}); + } + } + } + }).error(function(data) { + // TODO + }); + } + + function loadUsers() { + $http.get('admin.user.list@json').success(function(data) { + $scope.systemUsers = data; + }); + } + /** + * Filter all settings for a section + */ + $scope.filterBySection = function(section) { + var settings = []; + + for (var i = 0; i < $scope.settings.length; i++) { + var s = $scope.settings[i]; + if (s['@name'].indexOf(section) !== -1) { + settings.push(s); + } + } + return settings; + }; + + /** + * Order by position + */ + $scope.getOrderBy = function(s) { + return s['@position']; + }; + + /** + * Save the form containing all settings. When saved, + * broadcast success status and reload catalog info. + */ + $scope.saveSettings = function(formId) { + + $http.get($scope.url + 'admin.config.save?' + + gnUtilityService.serialize(formId)) + .success(function(data) { + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('settingsUpdated'), + timeout: 2, + type: 'success'}); + + $scope.loadCatalogInfo(); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('settingsUpdateError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + /** + * Scroll to an element. + */ + $scope.scrollTo = gnUtilityService.scrollTo; + + loadUsers(); + loadSettings(); + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/ThesaurusController.js b/web-ui/src/main/resources/catalog/js/admin/ThesaurusController.js new file mode 100644 index 00000000000..cd41f29e998 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/ThesaurusController.js @@ -0,0 +1,500 @@ +(function() { + goog.provide('gn_thesaurus_controller'); + + goog.require('gn_thesaurus_type'); + + var module = angular.module('gn_thesaurus_controller', + ['gn_thesaurus_type', 'blueimp.fileupload']); + + + /** + * GnThesaurusController provides managment of thesaurus + * by adding new local thesaurus, uploading from SKOS file or by URL. + * + * Keyword can be searched and added to local thesaurus. + * + * Limitations: + * * Only keyword in the GUI language will be displayed + * and edited. TODO + * * Keyword relation can't be modified. + * * Thesaurus properties once created can't be modified + * + */ + module.controller('GnThesaurusController', [ + '$scope', '$http', '$rootScope', '$translate', + function($scope, $http, $rootScope, $translate) { + + /** + * Type of relations in SKOS thesaurus + */ + var relationTypes = ['broader', 'narrower', 'related']; + + /** + * Thesaurus type list as defined in ISO19139 + */ + $scope.thesaurusClass = ['theme', 'discipline', + 'place', 'stratum', 'temporal']; + + /** + * The list of thesaurus + */ + $scope.thesaurus = {}; + /** + * The currently selected thesaurus + */ + $scope.thesaurusSelected = null; + /** + * Is the selected thesaurus activated or not. + */ + $scope.thesaurusSelectedActivated = false; + /** + * A suggested namespace for new thesaurus based + * on other thesaurus properties + */ + $scope.thesaurusSuggestedNs = ''; + /** + * The thesaurus URL to upload + */ + $scope.thesaurusUrl = ''; + + + /** + * The current list of keywords + */ + $scope.keywords = {}; + /** + * The selected keyword + */ + $scope.keywordSelected = null; + /** + * The list of relation for the selected keyword + */ + $scope.keywordSelectedRelation = {}; + /** + * A suggestion for the new keyword identifier + * based on keyword properties + */ + $scope.keywordSuggestedUri = ''; + /** + * The current keyword filter + */ + $scope.keywordFilter = ''; + + $scope.maxNumberOfKeywords = 50; + + /** + * The type of thesaurus import. Could be new, file or url. + */ + $scope.importAs = null; + + var defaultMaxNumberOfKeywords = 50, + creatingThesaurus = false, // Keyword creation in progress ? + creatingKeyword = false, // Thesaurus creation in progress ? + selectedKeywordOldId = null; // Keyword id before starting editing + + /** + * Select a thesaurus and search its keywords. + */ + $scope.selectThesaurus = function(t) { + creatingThesaurus = false; + $scope.thesaurusSelected = t; + $scope.thesaurusSelectedActivated = t.activated == 'y'; + searchThesaurusKeyword(); + }; + + + /** + * Search thesaurus keyword based on filter and max number + */ + searchThesaurusKeyword = function() { + if ($scope.thesaurusSelected) { + $http.get('keywords@json?pNewSearch=true&pTypeSearch=1' + + '&pThesauri=' + $scope.thesaurusSelected.key + + '&pMode=searchBox' + + '&maxResults=' + + ($scope.maxNumberOfKeywords || + defaultMaxNumberOfKeywords) + + '&pKeyword=' + ($scope.keywordFilter || '*') + ).success(function(data) { + $scope.keywords = data[0]; + }); + } + }; + + /** + * Add a new local thesaurus and open the modal + */ + $scope.addThesaurus = function(type) { + creatingThesaurus = true; + + $scope.importAs = type; + $scope.thesaurusSelected = { + title: '', + filename: '', + defaultNamespace: 'http://www.mysite.org/thesaurus', + dname: 'theme', + type: 'local' + }; + + $('#thesaurusModal').modal(); + $('#thesaurusModal').on('shown.bs.modal', function() { + var id = $scope.importAs === 'new' ? '#gn-thesaurus-title' : + ($scope.importAs === 'file' ? '#gn-thesaurus-file' : + '#gn-thesaurus-url'); + $(id).focus(); + }); + }; + + /** + * Build a namespace based on page location, thesaurus type + * and filename. eg. http://localhost:8080/thesaurus/theme/commune + */ + $scope.computeThesaurusNs = function() { + $scope.thesaurusSuggestedNs = + location.origin + + '/thesaurus/' + $scope.thesaurusSelected.dname + '/' + + $scope.thesaurusSelected.filename.replace(/[^\d\w]/gi, ''); + }; + + /** + * Use the suggested namespace for the new thesaurus + */ + $scope.useSuggestedNs = function() { + $scope.thesaurusSelected.defaultNamespace = $scope.thesaurusSuggestedNs; + }; + + /** + * Create the thesaurus in the catalog, close the modal on success + * and refresh the list. + */ + $scope.createThesaurus = function() { + var xml = '' + + '' + $scope.thesaurusSelected.title + '' + + '' + $scope.thesaurusSelected.filename + '' + + '' + $scope.thesaurusSelected.defaultNamespace + '' + + '' + $scope.thesaurusSelected.dname + '' + + 'local'; + + $http.post('thesaurus.update', xml, { + headers: {'Content-type': 'application/xml'} + }) + .success(function(data) { + $scope.thesaurusSelected = null; + $('#thesaurusModal').modal('hide'); + loadThesaurus(); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('thesaurusCreationError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + /** + * Thesaurus uploaded with success, close the modal, + * refresh the list. + */ + uploadThesaurusDone = function(data) { + $scope.clear($scope.queue); + $scope.thesaurusUrl = ''; + + $('#thesaurusModal').modal('hide'); + + loadThesaurus(); + }; + + /** + * Thesaurus uploaded with error, broadcast it. + */ + uploadThesaurusError = function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('thesaurusUploadError'), + error: data, + timeout: 0, + type: 'danger'}); + }; + + /** + * Thesaurus upload options. + */ + $scope.thesaurusUploadOptions = { + autoUpload: false, + // TODO: acceptFileTypes: /(\.|\/)(xml|skos|rdf)$/i, + done: uploadThesaurusDone, + fail: uploadThesaurusError + }; + + /** + * Upload the file or URL in the catalog thesaurus repository + */ + $scope.importThesaurus = function(formId) { + // Uploading + $(formId)[0].enctype = ($scope.importAs === 'file' ? + 'multipart/form-data' : ''); + if ($scope.importAs === 'file') { + $scope.submit(); + } else { + $http.get('thesaurus.upload?' + $(formId).serialize()) + .success(uploadThesaurusDone) + .error(uploadThesaurusError); + } + }; + + /** + * Remove a thesaurus from the catalog thesaurus repository + */ + $scope.deleteThesaurus = function() { + $http.get('thesaurus.remove?ref=' + + $scope.thesaurusSelected.key) + .success(function(data) { + $scope.thesaurusSelected = null; + loadThesaurus(); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('thesaurusDeleteError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + /** + * Activate a thesaurus in order to be able to + * use it in the metadata editor. + */ + $scope.enableThesaurus = function() { + $http.get('thesaurus.activate@json?' + + 'ref=' + $scope.thesaurusSelected.key + + '&activated=' + + ($scope.thesaurusSelectedActivated ? 'y' : 'n') + ).success(function(data) { + // TODO + }); + }; + + /** + * Thesaurus creation on going + */ + $scope.isNew = function() { + return creatingThesaurus; + }; + /** + * Keyword creation on going + */ + $scope.isNewKeyword = function() { + return creatingKeyword; + }; + + /** + * Search relation for each types for the current keyword + */ + searchRelation = function(k) { + $scope.keywordSelectedRelation = {}; + $.each(relationTypes, function(index, value) { + $http.get('thesaurus.keyword.links@json?' + + 'request=' + value + + '&thesaurus=' + $scope.thesaurusSelected.key + + '&id=' + encodeURIComponent(k.uri)) + .success(function(data) { + $scope.keywordSelectedRelation[value] = data.descKeys; + }) + .error(); + }); + }; + + /** + * Edit an existing keyword, open the modal, search relations + */ + $scope.editKeyword = function(k) { + $scope.keywordSelected = k; + selectedKeywordOldId = k.uri; + creatingKeyword = false; + $('#keywordModal').modal(); + searchRelation(k); + }; + + /** + * Edit a new keyword and open the modal + */ + $scope.addKeyword = function(k) { + creatingKeyword = true; + $scope.keywordSuggestedUri = ''; + $scope.keywordSelected = { + 'uri': $scope.thesaurusSelected.defaultNamespace + '#', + 'value': {'@language': $scope.lang, '#text': ''}, + 'definition': {'@language': $scope.lang}, + 'defaultLang': $scope.lang + }; + if ($scope.isPlaceType()) { + $scope.keywordSelected.geo = { + west: '', + south: '', + east: '', + north: '' + }; + } + $('#keywordModal').modal(); + }; + + /** + * Build keyword POST body message + */ + buildKeyword = function() { + var geoxml = $scope.isPlaceType() ? + '' + $scope.keywordSelected.geo.west + '' + + '' + $scope.keywordSelected.geo.south + '' + + '' + $scope.keywordSelected.geo.east + '' + + '' + $scope.keywordSelected.geo.north + '' : ''; + + var xml = '' + $scope.keywordSelected.uri + '' + + '' + $scope.thesaurusSelected.dname + '' + + '' + $scope.keywordSelected.definition['#text'] + + '' + + '' + $scope.thesaurusSelected.defaultNamespace + + '' + + '' + $scope.thesaurusSelected.key + '' + + '' + selectedKeywordOldId + '' + + '' + $scope.lang + '' + + '' + $scope.keywordSelected.value['#text'] + '' + + geoxml + + ''; + + return xml; + }; + + /** + * Create the keyword in the thesaurus + */ + $scope.createKeyword = function() { + $http.post('thesaurus.keyword.add', buildKeyword(), { + headers: {'Content-type': 'application/xml'} + }) + .success(function(data) { + $scope.keywordSelected = null; + $('#keywordModal').modal('hide'); + searchThesaurusKeyword(); + creatingKeyword = false; + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('keywordCreationError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + /** + * Update the keyword in the thesaurus + */ + $scope.updateKeyword = function() { + $http.post('thesaurus.keyword.update', buildKeyword(), { + headers: {'Content-type': 'application/xml'} + }) + .success(function(data) { + $scope.keywordSelected = null; + $('#keywordModal').modal('hide'); + searchThesaurusKeyword(); + selectedKeywordOldId = null; + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('keywordUpdateError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + /** + * Remove a keyword + */ + $scope.deleteKeyword = function(k) { + $scope.keywordSelected = k; + $http.get('thesaurus.keyword.remove?pThesaurus=' + k.thesaurus.key + + '&id=' + encodeURIComponent(k.uri)) + .success(function(data) { + searchThesaurusKeyword(); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('keywordDeleteError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + /** + * Build a keyword identifier based on thesaurus + * namespace and keyword label + */ + $scope.computeKeywordId = function() { + $scope.keywordSuggestedUri = + $scope.thesaurusSelected.defaultNamespace + + '#' + + $scope.keywordSelected.value['#text'].replace(/[^\d\w]/gi, ''); + }; + + /** + * Use the suggestion for the keyword uri + */ + $scope.useSuggestedUri = function() { + $scope.keywordSelected.uri = $scope.keywordSuggestedUri; + }; + + /** + * Is the thesaurus a place type thesaurus + */ + $scope.isPlaceType = function() { + if ($scope.thesaurusSelected) { + return $scope.thesaurusSelected.key && + $scope.thesaurusSelected.key.indexOf('.place.') !== -1; + } else { + return false; + } + }; + + /** + * Is the thesaurus external (ie. readonly keywords). + */ + $scope.isExternal = function() { + if ($scope.thesaurusSelected) { + return $scope.thesaurusSelected.type === 'external'; + } else { + return false; + } + }; + + /** + * When updating number of keywords, refresh keyword list + */ + $scope.$watch('maxNumberOfKeywords', function() { + searchThesaurusKeyword(); + }); + + + /** + * When updating the keyword filter, refresh keyword list + */ + $scope.$watch('keywordFilter', function() { + searchThesaurusKeyword(); + }); + + /** + * Load the list of thesaurus from the server + */ + function loadThesaurus() { + $http.get('thesaurus@json').success(function(data) { + $scope.thesaurus = data[0]; + }); + } + + loadThesaurus(); + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/admin/UserGroupController.js b/web-ui/src/main/resources/catalog/js/admin/UserGroupController.js new file mode 100644 index 00000000000..633ef2ccafd --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/admin/UserGroupController.js @@ -0,0 +1,425 @@ +(function() { + goog.provide('gn_usergroup_controller'); + + goog.require('gn_dbtranslation'); + + var module = angular.module('gn_usergroup_controller', + ['gn_dbtranslation']); + + + /** + * UserGroupController provides all necessary operations + * to manage users and groups. + */ + module.controller('GnUserGroupController', [ + '$scope', '$routeParams', '$http', '$rootScope', + '$translate', '$compile', '$location', + 'gnSearchManagerService', + function($scope, $routeParams, $http, $rootScope, + $translate, $compile, $location, + gnSearchManagerService) { + + $scope.pageMenu = { + folder: 'usergroup/', + defaultTab: 'groups', + tabs: + [{ + type: 'groups', + label: 'manageGroups', + icon: 'icon-group', + href: '#/organization/groups' + },{ + type: 'users', + label: 'manageUsers', + icon: 'icon-user', + href: '#/organization/users' + }] + }; + + // The pagination config + $scope.groupRecordsPagination = { + pages: -1, + currentPage: 0, + hitsPerPage: 10 + }; + + // Scope for group + // List of catalog groups + $scope.groups = null; + $scope.groupSelected = {id: $routeParams.userOrGroup}; + // List of metadata records attached to the selected group + $scope.groupRecords = null; + $scope.groupRecordsFilter = null; + // On going changes group ... + $scope.groupUpdated = false; + $scope.groupSearch = {}; + + // Register the search results, filter and pager + // and get the search function back + $scope.groupRecordsSearch = gnSearchManagerService.register({ + records: 'groupRecords', + filter: 'groupRecordsFilter', + pager: 'groupRecordsPagination' + }, $scope); + + // When the current page change trigger the search + $scope.$watch('groupRecordsPagination.currentPage', function() { + $scope.groupRecordsSearch(); + }); + + + // Scope for user + // List of catalog users + $scope.users = null; + $scope.userSelected = {}; + // List of group for selected user + $scope.userGroups = {}; + // Indicate if an update is going on + $scope.userOperation = 'editinfo'; + $scope.userIsAdmin = false; + // On going changes for user ... + $scope.userUpdated = false; + $scope.passwordCheck = ''; + // The pagination config + $scope.userRecordsPagination = { + pages: -1, + currentPage: 0, + hitsPerPage: 10 + }; + // List of metadata records attached to the selected user + $scope.userRecords = null; + $scope.userRecordsFilter = null; + + // Register the search results, filter and pager + // and get the search function back + $scope.userRecordsSearch = gnSearchManagerService.register({ + records: 'userRecords', + filter: 'userRecordsFilter', + pager: 'userRecordsPagination' + }, $scope); + + // When the current page change trigger the search + $scope.$watch('userRecordsPagination.currentPage', function() { + $scope.userRecordsSearch(); + }); + + + + function loadGroups() { + $http.get('admin.group.list@json').success(function(data) { + $scope.groups = data !== 'null' ? data : null; + }).error(function(data) { + // TODO + }).then(function() { + // Search if requested group in location is + // in the list and trigger selection. + // TODO: change route path when selected (issue - controller is + // reloaded) + if ($routeParams.userOrGroup) { + angular.forEach($scope.groups, function(u) { + if (u.name === $routeParams.userOrGroup) { + $scope.selectGroup(u); + } + }); + } + }); + } + function loadUsers() { + $http.get('admin.user.list@json').success(function(data) { + $scope.users = data; + }).error(function(data) { + // TODO + }).then(function() { + // Search if requested user in location is + // in the list and trigger user selection. + if ($routeParams.userOrGroup) { + angular.forEach($scope.users, function(u) { + if (u.username === $routeParams.userOrGroup) { + $scope.selectUser(u); + } + }); + } + }); + } + + + + /** + * Add an new user based on the default + * user config. + */ + $scope.addUser = function() { + $scope.unselectUser(); + $scope.userOperation = 'newuser'; + $scope.userSelected = { + id: '', + username: '', + password: '', + name: '', + surname: '', + profile: 'RegisteredUser', + address: '', + city: '', + state: '', + zip: '', + country: '', + email: '', + organisation: '' + }; + }; + + /** + * Remove current user from selection and + * clear user groups and records. + */ + $scope.unselectUser = function() { + $scope.userSelected = null; + $scope.userGroups = null; + $scope.userUpdated = false; + $scope.userRecords = null; + $scope.userOperation = 'editinfo'; + }; + + /** + * Select a user and retrieve its groups and + * metadata records. + */ + $scope.selectUser = function(u) { + // Load user group and then select user + $http.get('admin.usergroups.list@json?id=' + u.id) + .success(function(data) { + $scope.userGroups = data; + $scope.userSelected = u; + $scope.userIsAdmin = u.profile === 'Administrator'; + }).error(function(data) { + // TODO + }); + + + // Retrieve records in that group + $scope.userRecordsFilter = { + template: 'y or n', + _owner: u.id, + sortBy: 'title' + }; + $scope.userRecordsSearch(); + $scope.userUpdated = false; + }; + + + /** + * Check if the groupId is in the user groups + * list with that profile. + * + * Note: A user can have more than one profile + * for a group. + */ + $scope.isUserGroup = function(groupId, profile) { + if ($scope.userGroups) { + for (var i = 0; i < $scope.userGroups.length; i++) { + if ($scope.userGroups[i].id == groupId && + $scope.userGroups[i].profile == profile) { + return true; + } + } + } + return false; + }; + + /** + * Compute user profile based on group/profile select + * list. This is closely related to the template manipulating + * element ids. + * + * Searching through the list, compute the highest profile + * for the user and set it. + * When a user is a reviewer of a group, the corresponding + * group is also selected in the editor profile list. + */ + $scope.setUserProfile = function(isAdmin) { + $scope.userUpdated = true; + if (isAdmin) { + // Unselect all groups option + for (var i = 0; i < $scope.profiles.length; i++) { + if ($scope.profiles[i] !== 'Administrator') { + $('#groups_' + $scope.profiles[i])[0].selectedIndex = -1; + } + } + $scope.userSelected.profile = + $scope.userIsAdmin ? 'Administrator' : $scope.profiles[0]; + } else { + // Define the highest profile for user + var newprofile = 'RegisteredUser'; + for (var i = 0; i < $scope.profiles.length; i++) { + if ($scope.profiles[i] !== 'Administrator') { + var groups = $('#groups_' + $scope.profiles[i])[0]; + // If one of the group is selected, main user profile is updated + if (groups.selectedIndex > -1 && + groups.options[groups.selectedIndex].value != '') { + newprofile = $scope.profiles[i]; + } + } + } + $scope.userSelected.profile = newprofile; + + // If user is reviewer in one group, he is also editor for that group + var editorGroups = $('#groups_Editor')[0]; + var reviewerGroups = $('#groups_Reviewer')[0]; + if (reviewerGroups.selectedIndex > -1) { + for (var j = 0; j < reviewerGroups.options.length; j++) { + if (reviewerGroups.options[j].selected) { + editorGroups.options[j].selected = true; + } + } + } + } + }; + + + $scope.updatingUser = function() { + $scope.userUpdated = true; + }; + + + /** + * Save a user. + */ + $scope.saveUser = function(formId) { + $http.get('admin.user.update?' + $(formId).serialize()) + .success(function(data) { + $scope.unselectUser(); + loadUsers(); + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('userUpdated'), + timeout: 2, + type: 'success'}); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('userUpdateError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + /** + * Delete a user. + */ + $scope.deleteUser = function(formId) { + $http.get('admin.user.remove?id=' + + $scope.userSelected.id) + .success(function(data) { + $scope.unselectUser(); + loadUsers(); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('userDeleteError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + /** + * Return true if selected user has metadata record. + * This information could be useful to disable a delete button + * for example. + */ + $scope.userHasRecords = function() { + return $scope.userRecords && $scope.userRecords.metadata && + $scope.userRecords.metadata.length > 0; + }; + + + + + + + + + $scope.addGroup = function() { + $scope.unselectGroup(); + $scope.groupSelected = { + id: '', + name: '', + description: '', + email: '' + }; + }; + + $scope.saveGroup = function(formId) { + $http.get('admin.group.update?' + $(formId).serialize()) + .success(function(data) { + $scope.unselectGroup(); + loadGroups(); + $rootScope.$broadcast('StatusUpdated', { + msg: $translate('groupUpdated'), + timeout: 2, + type: 'success'}); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('groupUpdateError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + $scope.deleteGroup = function(formId) { + $http.get('admin.group.remove?id=' + + $scope.groupSelected.id) + .success(function(data) { + $scope.unselectGroup(); + loadGroups(); + }) + .error(function(data) { + $rootScope.$broadcast('StatusUpdated', { + title: $translate('groupDeleteError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + + /** + * Return true if selected group has metadata record. + * This information could be useful to disable a delete button + * for example. + */ + $scope.groupHasRecords = function() { + return $scope.groupRecords && $scope.groupRecords.metadata && + $scope.groupRecords.metadata.length > 0; + }; + + $scope.unselectGroup = function() { + $scope.groupSelected = null; + $scope.groupUpdated = false; + $scope.groupRecords = null; + }; + + $scope.selectGroup = function(g) { + $scope.groupSelected = g; + + // Retrieve records in that group + $scope.groupRecordsFilter = { + template: 'y or n', + group: g.id, + sortBy: 'title' + }; + $scope.groupRecordsSearch(); + $scope.groupUpdated = false; + }; + + $scope.updatingGroup = function() { + $scope.groupUpdated = true; + }; + + loadGroups(); + loadUsers(); + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/edit/EditorController.js b/web-ui/src/main/resources/catalog/js/edit/EditorController.js new file mode 100644 index 00000000000..b119ceeb311 --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/edit/EditorController.js @@ -0,0 +1,171 @@ +(function() { + goog.provide('gn_editor_controller'); + + + var module = angular.module('gn_editor_controller', + []); + + + /** + * Metadata editor controller - draft + */ + module.controller('GnEditorController', [ + '$scope', '$routeParams', '$http', '$rootScope', '$translate', '$compile', + 'gnMetadataManagerService', + 'gnSearchManagerService', + 'gnUtilityService', + function($scope, $routeParams, $http, $rootScope, $translate, $compile, + gnMetadataManagerService, + gnSearchManagerService, + gnUtilityService) { + + + $scope.metadataId = gnUtilityService.getUrlParameter('id'); + $scope.metadataUuid = gnUtilityService.getUrlParameter('uuid'); + $scope.resourceId = gnUtilityService.getUrlParameter('resourceId'); + $scope.tab = gnUtilityService.getUrlParameter('tab'); + $scope.flat = gnUtilityService.getUrlParameter('flat'); + // TODO : propagate flat mode to all call + + /** + * Animation duration for slide up/down + */ + var duration = 300; + + $scope.getEditorForm = function() { + // TODO: init by UUID or resourceId + // TODO: Check requested metadata exist - return message if it happens + // Would you like to create a new one ? + return 'md.edit?id=' + $scope.metadataId + + ($scope.tab ? '&currTab=' + $scope.tab : ''); + }; + + $scope.switchToTab = function(tabIdentifier) { + // $scope.tab = tabIdentifier; + // FIXME: this trigger an edit + // better to use ng-model in the form ? + $('#currTab')[0].value = tabIdentifier; + $scope.save(true); + }; + + + $scope.remove = function(ref, parent) { + // md.element.remove?id=&ref=50&parent=41 + // Call service to remove element from metadata record in session + $http.get('md.element.remove@json?id=' + $scope.metadataId + + '&ref=' + ref + '&parent=' + parent).success(function(data) { + // Remove element from the DOM + var target = $('#gn-el-' + ref); + target.slideUp(duration, function() { $(this).remove();}); + + // TODO: Take care of moving the + sign + }).error(function(data) { + console.log(data); + }); + }; + + /** + * Add another element of the same type to the metadata record. + * + * Default position is after. Other value is before. + */ + $scope.add = function(ref, name, insertRef, position) { + // md.elem.add?id=1250&ref=41&name=gmd:presentationForm + $http.get('md.element.add?id=' + $scope.metadataId + + '&ref=' + ref + '&name=' + name).success(function(data) { + console.log(data); + // Append HTML snippet after current element - compile Angular + var target = $('#gn-el-' + insertRef); + var snippet = $(data); + snippet.css('display', 'none'); // Hide + target[position || 'after'](snippet); // Insert + snippet.slideDown(duration, function() {}); // Slide + + $compile(snippet)($scope); // Compile + + // Remove the Add control from the current element + var addControl = $('#gn-el-' + insertRef + ' .gn-add'); + console.log(addControl); + + }).error(function(data) { + console.log(data); + }); + }; + + + $scope.addChoice = function(ref, parent, name, insertRef) { + // md.elem.add?id=1250&ref=41&name=gmd:presentationForm + $http.get('md.element.add?id=' + $scope.metadataId + + '&ref=' + ref + + '&name=' + parent + + '&child=' + name).success(function(data) { + // Append HTML snippet after current element - compile Angular + var target = $('#gn-el-' + insertRef); + var snippet = $(data); + target.replaceWith(snippet); // Replace + $compile(snippet)($scope); // Compile + }).error(function(data) { + console.log(data); + }); + }; + + /** + * Add a non existing element to the metadata record + */ + $scope.expand = function() { + + }; + + + /** + * Save the metadata record currently in editing session. + * + * If refreshForm is true, then will also update the current form. + * This is required while switching tab for example. Update the tab + * value in the form and trigger save to update the view. + */ + $scope.save = function(refreshForm) { + $http.post( + refreshForm ? 'md.edit.save' : 'md.edit.saveonly', + $('#gn-editor-' + $scope.metadataId).serialize(), + { + headers: {'Content-Type': 'application/x-www-form-urlencoded'} + }).success(function(data) { + console.log(data); + if (refreshForm) { + var snippet = $(data); + $('#gn-editor-' + $scope.metadataId).replaceWith(snippet); + $compile(snippet)($scope); + } + $rootScope.$broadcast('StatusUpdated', { + title: $translate('saveMetadataSuccess') + }); + + }).error(function(data) { + console.log(data); + + $rootScope.$broadcast('StatusUpdated', { + title: $translate('saveMetadataError'), + error: data, + timeout: 0, + type: 'danger'}); + }); + }; + + + $scope.reset = function() { + + }; + + + $scope.highlightRemove = function(ref) { + var target = $('#gn-el-' + ref); + target.addClass('text-danger'); + }; + $scope.unhighlightRemove = function(ref) { + var target = $('#gn-el-' + ref); + target.removeClass('text-danger'); + }; + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/js/search/SearchController.js b/web-ui/src/main/resources/catalog/js/search/SearchController.js new file mode 100644 index 00000000000..5095d93589f --- /dev/null +++ b/web-ui/src/main/resources/catalog/js/search/SearchController.js @@ -0,0 +1,65 @@ +(function() { + goog.provide('gn_search_controller'); + + + var module = angular.module('gn_search_controller', + []); + + + /** + * GnsearchController provides administration tools + */ + module.controller('GnSearchController', [ + '$scope', '$routeParams', '$http', '$rootScope', '$translate', '$compile', + 'gnMetadataManagerService', + 'gnSearchManagerService', + 'gnUtilityService', + function($scope, $routeParams, $http, $rootScope, $translate, $compile, + gnMetadataManagerService, + gnSearchManagerService, + gnUtilityService) { + + /** + * The full text search filter + */ + $scope.searchRecordsFilter = ''; + + /** + * The list of records to be processed + */ + $scope.searchRecords = null; + + /** + * The pagination config + */ + $scope.searchRecordsPagination = { + pages: -1, + currentPage: 0, + hitsPerPage: 20 + }; + + // Register the search results, filter and pager + // and get the search function back + searchFn = gnSearchManagerService.register({ + records: 'searchRecords', + filter: 'searchRecordsFilter', + pager: 'searchRecordsPagination' + // error: function () {console.log('error');}, + // success: function () {console.log('succ');} + }, $scope); + + // Update search filter and reset page + $scope.searchRecordsSearchFor = function(e) { + $scope.searchRecordsFilter = {any: (e ? e.target.value : '')}; + $scope.searchRecordsPagination.currentPage = 0; + searchFn(); + }; + + // When the current page change trigger the search + $scope.$watch('searchRecordsPagination.currentPage', function() { + searchFn(); + }); + + }]); + +})(); diff --git a/web-ui/src/main/resources/catalog/lib/angular-translate.js b/web-ui/src/main/resources/catalog/lib/angular-translate.js new file mode 100644 index 00000000000..84a539bc826 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular-translate.js @@ -0,0 +1,419 @@ +/** + * angular-translate - v1.1.0 - 2013-09-02 + * http://github.com/PascalPrecht/angular-translate + * Copyright (c) 2013 ; Licensed + */ +angular.module('pascalprecht.translate', ['ng']).run([ + '$translate', + function ($translate) { + var key = $translate.storageKey(), storage = $translate.storage(); + if (storage) { + if (!storage.get(key)) { + if (angular.isString($translate.preferredLanguage())) { + $translate.uses($translate.preferredLanguage()); + } else { + storage.set(key, $translate.uses()); + } + } else { + $translate.uses(storage.get(key)); + } + } else if (angular.isString($translate.preferredLanguage())) { + $translate.uses($translate.preferredLanguage()); + } + } +]); +angular.module('pascalprecht.translate').provider('$translate', [ + '$STORAGE_KEY', + function ($STORAGE_KEY) { + var $translationTable = {}, $preferredLanguage, $fallbackLanguage, $uses, $nextLang, $storageFactory, $storageKey = $STORAGE_KEY, $storagePrefix, $missingTranslationHandlerFactory, $interpolationFactory, $interpolatorFactories = [], $loaderFactory, $loaderOptions, $notFoundIndicatorLeft, $notFoundIndicatorRight, NESTED_OBJECT_DELIMITER = '.'; + var translations = function (langKey, translationTable) { + if (!langKey && !translationTable) { + return $translationTable; + } + if (langKey && !translationTable) { + if (angular.isString(langKey)) { + return $translationTable[langKey]; + } else { + angular.extend($translationTable, flatObject(langKey)); + } + } else { + if (!angular.isObject($translationTable[langKey])) { + $translationTable[langKey] = {}; + } + angular.extend($translationTable[langKey], flatObject(translationTable)); + } + return this; + }; + var flatObject = function (data, path, result) { + var key, keyWithPath, val; + if (!path) { + path = []; + } + if (!result) { + result = {}; + } + for (key in data) { + if (!data.hasOwnProperty(key)) + continue; + val = data[key]; + if (angular.isObject(val)) { + flatObject(val, path.concat(key), result); + } else { + keyWithPath = path.length ? '' + path.join(NESTED_OBJECT_DELIMITER) + NESTED_OBJECT_DELIMITER + key : key; + result[keyWithPath] = val; + } + } + return result; + }; + this.translations = translations; + this.addInterpolation = function (factory) { + $interpolatorFactories.push(factory); + return this; + }; + this.useMessageFormatInterpolation = function () { + return this.useInterpolation('$translateMessageFormatInterpolation'); + }; + this.useInterpolation = function (factory) { + $interpolationFactory = factory; + return this; + }; + this.preferredLanguage = function (langKey) { + if (langKey) { + $preferredLanguage = langKey; + return this; + } else { + return $preferredLanguage; + } + }; + this.translationNotFoundIndicator = function (indicator) { + this.translationNotFoundIndicatorLeft(indicator); + this.translationNotFoundIndicatorRight(indicator); + return this; + }; + this.translationNotFoundIndicatorLeft = function (indicator) { + if (!indicator) { + return $notFoundIndicatorLeft; + } + $notFoundIndicatorLeft = indicator; + return this; + }; + this.translationNotFoundIndicatorRight = function (indicator) { + if (!indicator) { + return $notFoundIndicatorRight; + } + $notFoundIndicatorRight = indicator; + return this; + }; + this.fallbackLanguage = function (langKey) { + if (langKey) { + $fallbackLanguage = langKey; + return this; + } else { + return $fallbackLanguage; + } + }; + this.uses = function (langKey) { + if (langKey) { + if (!$translationTable[langKey] && !$loaderFactory) { + throw new Error('$translateProvider couldn\'t find translationTable for langKey: \'' + langKey + '\''); + } + $uses = langKey; + return this; + } else { + return $uses; + } + }; + var storageKey = function (key) { + if (!key) { + if ($storagePrefix) { + return $storagePrefix + $storageKey; + } + return $storageKey; + } + $storageKey = key; + }; + this.storageKey = storageKey; + this.useUrlLoader = function (url) { + return this.useLoader('$translateUrlLoader', { url: url }); + }; + this.useStaticFilesLoader = function (options) { + return this.useLoader('$translateStaticFilesLoader', options); + }; + this.useLoader = function (loaderFactory, options) { + $loaderFactory = loaderFactory; + $loaderOptions = options || {}; + return this; + }; + this.useLocalStorage = function () { + return this.useStorage('$translateLocalStorage'); + }; + this.useCookieStorage = function () { + return this.useStorage('$translateCookieStorage'); + }; + this.useStorage = function (storageFactory) { + $storageFactory = storageFactory; + return this; + }; + this.storagePrefix = function (prefix) { + if (!prefix) { + return prefix; + } + $storagePrefix = prefix; + return this; + }; + this.useMissingTranslationHandlerLog = function () { + return this.useMissingTranslationHandler('$translateMissingTranslationHandlerLog'); + }; + this.useMissingTranslationHandler = function (factory) { + $missingTranslationHandlerFactory = factory; + return this; + }; + this.$get = [ + '$log', + '$injector', + '$rootScope', + '$q', + function ($log, $injector, $rootScope, $q) { + var Storage, defaultInterpolator = $injector.get($interpolationFactory || '$translateDefaultInterpolation'), pendingLoader = false, interpolatorHashMap = {}; + var loadAsync = function (key) { + if (!key) { + throw 'No language key specified for loading.'; + } + var deferred = $q.defer(); + $rootScope.$broadcast('$translateLoadingStart'); + pendingLoader = true; + $nextLang = key; + $injector.get($loaderFactory)(angular.extend($loaderOptions, { key: key })).then(function (data) { + $rootScope.$broadcast('$translateLoadingSuccess'); + var translationTable = {}; + if (angular.isArray(data)) { + angular.forEach(data, function (table) { + angular.extend(translationTable, table); + }); + } else { + angular.extend(translationTable, data); + } + translations(key, translationTable); + pendingLoader = false; + $nextLang = undefined; + deferred.resolve(key); + $rootScope.$broadcast('$translateLoadingEnd'); + }, function (key) { + $rootScope.$broadcast('$translateLoadingError'); + deferred.reject(key); + $nextLang = undefined; + $rootScope.$broadcast('$translateLoadingEnd'); + }); + return deferred.promise; + }; + if ($storageFactory) { + Storage = $injector.get($storageFactory); + if (!Storage.get || !Storage.set) { + throw new Error('Couldn\'t use storage \'' + $storageFactory + '\', missing get() or set() method!'); + } + } + if ($interpolatorFactories.length > 0) { + angular.forEach($interpolatorFactories, function (interpolatorFactory) { + var interpolator = $injector.get(interpolatorFactory); + interpolator.setLocale($preferredLanguage || $uses); + interpolatorHashMap[interpolator.getInterpolationIdentifier()] = interpolator; + }); + } + var $translate = function (translationId, interpolateParams, interpolationId) { + var table = $uses ? $translationTable[$uses] : $translationTable, Interpolator = interpolationId ? interpolatorHashMap[interpolationId] : defaultInterpolator; + if (table && table.hasOwnProperty(translationId)) { + return Interpolator.interpolate(table[translationId], interpolateParams); + } + if ($missingTranslationHandlerFactory && !pendingLoader) { + $injector.get($missingTranslationHandlerFactory)(translationId, $uses); + } + if ($uses && $fallbackLanguage && $uses !== $fallbackLanguage) { + var translation = $translationTable[$fallbackLanguage][translationId]; + if (translation) { + var returnVal; + Interpolator.setLocale($fallbackLanguage); + returnVal = Interpolator.interpolate(translation, interpolateParams); + Interpolator.setLocale($uses); + return returnVal; + } + } + if ($notFoundIndicatorLeft) { + translationId = [ + $notFoundIndicatorLeft, + translationId + ].join(' '); + } + if ($notFoundIndicatorRight) { + translationId = [ + translationId, + $notFoundIndicatorRight + ].join(' '); + } + return translationId; + }; + $translate.preferredLanguage = function () { + return $preferredLanguage; + }; + $translate.fallbackLanguage = function () { + return $fallbackLanguage; + }; + $translate.proposedLanguage = function () { + return $nextLang; + }; + $translate.storage = function () { + return Storage; + }; + $translate.uses = function (key) { + if (!key) { + return $uses; + } + var deferred = $q.defer(); + $rootScope.$broadcast('$translateChangeStart'); + function useLanguage(key) { + $uses = key; + $rootScope.$broadcast('$translateChangeSuccess'); + if ($storageFactory) { + Storage.set($translate.storageKey(), $uses); + } + defaultInterpolator.setLocale($uses); + angular.forEach(interpolatorHashMap, function (interpolator, id) { + interpolatorHashMap[id].setLocale($uses); + }); + deferred.resolve(key); + $rootScope.$broadcast('$translateChangeEnd'); + } + if (!$translationTable[key] && $loaderFactory) { + loadAsync(key).then(useLanguage, function (key) { + $rootScope.$broadcast('$translateChangeError'); + deferred.reject(key); + $rootScope.$broadcast('$translateChangeEnd'); + }); + } else { + useLanguage(key); + } + return deferred.promise; + }; + $translate.storageKey = function () { + return storageKey(); + }; + $translate.refresh = function (langKey) { + var deferred = $q.defer(); + function onLoadSuccess() { + deferred.resolve(); + $rootScope.$broadcast('$translateRefreshEnd'); + } + function onLoadFailure() { + deferred.reject(); + $rootScope.$broadcast('$translateRefreshEnd'); + } + if (!$loaderFactory) { + throw new Error('Couldn\'t refresh translation table, no loader registered!'); + } + if (!langKey) { + $rootScope.$broadcast('$translateRefreshStart'); + for (var lang in $translationTable) { + if ($translationTable.hasOwnProperty(lang)) { + delete $translationTable[lang]; + } + } + var loaders = []; + if ($fallbackLanguage) { + loaders.push(loadAsync($fallbackLanguage)); + } + if ($uses) { + loaders.push($translate.uses($uses)); + } + if (loaders.length > 0) { + $q.all(loaders).then(onLoadSuccess, onLoadFailure); + } else + onLoadSuccess(); + } else if ($translationTable.hasOwnProperty(langKey)) { + $rootScope.$broadcast('$translateRefreshStart'); + delete $translationTable[langKey]; + var loader = null; + if (langKey === $uses) { + loader = $translate.uses($uses); + } else { + loader = loadAsync(langKey); + } + loader.then(onLoadSuccess, onLoadFailure); + } else + deferred.reject(); + return deferred.promise; + }; + if ($loaderFactory) { + if (angular.equals($translationTable, {})) { + $translate.uses($translate.uses()); + } + if ($fallbackLanguage && !$translationTable[$fallbackLanguage]) { + loadAsync($fallbackLanguage); + } + } + return $translate; + } + ]; + } +]); +angular.module('pascalprecht.translate').factory('$translateDefaultInterpolation', [ + '$interpolate', + function ($interpolate) { + var $translateInterpolator = {}, $locale, $identifier = 'default'; + $translateInterpolator.setLocale = function (locale) { + $locale = locale; + }; + $translateInterpolator.getInterpolationIdentifier = function () { + return $identifier; + }; + $translateInterpolator.interpolate = function (string, interpolateParams) { + return $interpolate(string)(interpolateParams); + }; + return $translateInterpolator; + } +]); +angular.module('pascalprecht.translate').constant('$STORAGE_KEY', 'NG_TRANSLATE_LANG_KEY'); +angular.module('pascalprecht.translate').directive('translate', [ + '$filter', + '$interpolate', + function ($filter, $interpolate) { + var translate = $filter('translate'); + return { + restrict: 'AE', + scope: true, + link: function linkFn(scope, element, attr) { + if (attr.translateInterpolation) { + scope.interpolation = attr.translateInterpolation; + } + attr.$observe('translate', function (translationId) { + if (angular.equals(translationId, '') || translationId === undefined) { + scope.translationId = $interpolate(element.text().replace(/^\s+|\s+$/g, ''))(scope.$parent); + } else { + scope.translationId = translationId; + } + }); + attr.$observe('translateValues', function (interpolateParams) { + scope.interpolateParams = interpolateParams; + }); + scope.$on('$translateChangeSuccess', function () { + element.html(translate(scope.translationId, scope.interpolateParams, scope.interpolation)); + }); + scope.$watch('translationId + interpolateParams', function (nValue) { + if (nValue) { + element.html(translate(scope.translationId, scope.interpolateParams, scope.interpolation)); + } + }); + } + }; + } +]); +angular.module('pascalprecht.translate').filter('translate', [ + '$parse', + '$translate', + function ($parse, $translate) { + return function (translationId, interpolateParams, interpolation) { + if (!angular.isObject(interpolateParams)) { + interpolateParams = $parse(interpolateParams)(); + } + return $translate(translationId, interpolateParams, interpolation); + }; + } +]); \ No newline at end of file diff --git a/web-ui/src/main/resources/catalog/lib/angular-translate.min.js b/web-ui/src/main/resources/catalog/lib/angular-translate.min.js new file mode 100644 index 00000000000..b1f84dc5e3a --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular-translate.min.js @@ -0,0 +1 @@ +angular.module("pascalprecht.translate",["ng"]).run(["$translate",function(a){var b=a.storageKey(),c=a.storage();c?c.get(b)?a.uses(c.get(b)):angular.isString(a.preferredLanguage())?a.uses(a.preferredLanguage()):c.set(b,a.uses()):angular.isString(a.preferredLanguage())&&a.uses(a.preferredLanguage())}]),angular.module("pascalprecht.translate").provider("$translate",["$STORAGE_KEY",function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n={},o=a,p=[],q=".",r=function(a,b){if(!a&&!b)return n;if(a&&!b){if(angular.isString(a))return n[a];angular.extend(n,s(a))}else angular.isObject(n[a])||(n[a]={}),angular.extend(n[a],s(b));return this},s=function(a,b,c){var d,e,f;b||(b=[]),c||(c={});for(d in a)a.hasOwnProperty(d)&&(f=a[d],angular.isObject(f)?s(f,b.concat(d),c):(e=b.length?""+b.join(q)+q+d:d,c[e]=f));return c};this.translations=r,this.addInterpolation=function(a){return p.push(a),this},this.useMessageFormatInterpolation=function(){return this.useInterpolation("$translateMessageFormatInterpolation")},this.useInterpolation=function(a){return i=a,this},this.preferredLanguage=function(a){return a?(b=a,this):b},this.translationNotFoundIndicator=function(a){return this.translationNotFoundIndicatorLeft(a),this.translationNotFoundIndicatorRight(a),this},this.translationNotFoundIndicatorLeft=function(a){return a?(l=a,this):l},this.translationNotFoundIndicatorRight=function(a){return a?(m=a,this):m},this.fallbackLanguage=function(a){return a?(c=a,this):c},this.uses=function(a){if(a){if(!n[a]&&!j)throw new Error("$translateProvider couldn't find translationTable for langKey: '"+a+"'");return d=a,this}return d};var t=function(a){return a?(o=a,void 0):g?g+o:o};this.storageKey=t,this.useUrlLoader=function(a){return this.useLoader("$translateUrlLoader",{url:a})},this.useStaticFilesLoader=function(a){return this.useLoader("$translateStaticFilesLoader",a)},this.useLoader=function(a,b){return j=a,k=b||{},this},this.useLocalStorage=function(){return this.useStorage("$translateLocalStorage")},this.useCookieStorage=function(){return this.useStorage("$translateCookieStorage")},this.useStorage=function(a){return f=a,this},this.storagePrefix=function(a){return a?(g=a,this):a},this.useMissingTranslationHandlerLog=function(){return this.useMissingTranslationHandler("$translateMissingTranslationHandlerLog")},this.useMissingTranslationHandler=function(a){return h=a,this},this.$get=["$log","$injector","$rootScope","$q",function(a,g,o,q){var s,u=g.get(i||"$translateDefaultInterpolation"),v=!1,w={},x=function(a){if(!a)throw"No language key specified for loading.";var b=q.defer();return o.$broadcast("$translateLoadingStart"),v=!0,e=a,g.get(j)(angular.extend(k,{key:a})).then(function(c){o.$broadcast("$translateLoadingSuccess");var d={};angular.isArray(c)?angular.forEach(c,function(a){angular.extend(d,a)}):angular.extend(d,c),r(a,d),v=!1,e=void 0,b.resolve(a),o.$broadcast("$translateLoadingEnd")},function(a){o.$broadcast("$translateLoadingError"),b.reject(a),e=void 0,o.$broadcast("$translateLoadingEnd")}),b.promise};if(f&&(s=g.get(f),!s.get||!s.set))throw new Error("Couldn't use storage '"+f+"', missing get() or set() method!");p.length>0&&angular.forEach(p,function(a){var c=g.get(a);c.setLocale(b||d),w[c.getInterpolationIdentifier()]=c});var y=function(a,b,e){var f=d?n[d]:n,i=e?w[e]:u;if(f&&f.hasOwnProperty(a))return i.interpolate(f[a],b);if(h&&!v&&g.get(h)(a,d),d&&c&&d!==c){var j=n[c][a];if(j){var k;return i.setLocale(c),k=i.interpolate(j,b),i.setLocale(d),k}}return l&&(a=[l,a].join(" ")),m&&(a=[a,m].join(" ")),a};return y.preferredLanguage=function(){return b},y.fallbackLanguage=function(){return c},y.proposedLanguage=function(){return e},y.storage=function(){return s},y.uses=function(a){function b(a){d=a,o.$broadcast("$translateChangeSuccess"),f&&s.set(y.storageKey(),d),u.setLocale(d),angular.forEach(w,function(a,b){w[b].setLocale(d)}),c.resolve(a),o.$broadcast("$translateChangeEnd")}if(!a)return d;var c=q.defer();return o.$broadcast("$translateChangeStart"),!n[a]&&j?x(a).then(b,function(a){o.$broadcast("$translateChangeError"),c.reject(a),o.$broadcast("$translateChangeEnd")}):b(a),c.promise},y.storageKey=function(){return t()},y.refresh=function(a){function b(){f.resolve(),o.$broadcast("$translateRefreshEnd")}function e(){f.reject(),o.$broadcast("$translateRefreshEnd")}var f=q.defer();if(!j)throw new Error("Couldn't refresh translation table, no loader registered!");if(a)if(n.hasOwnProperty(a)){o.$broadcast("$translateRefreshStart"),delete n[a];var g=null;g=a===d?y.uses(d):x(a),g.then(b,e)}else f.reject();else{o.$broadcast("$translateRefreshStart");for(var h in n)n.hasOwnProperty(h)&&delete n[h];var i=[];c&&i.push(x(c)),d&&i.push(y.uses(d)),i.length>0?q.all(i).then(b,e):b()}return f.promise},j&&(angular.equals(n,{})&&y.uses(y.uses()),c&&!n[c]&&x(c)),y}]}]),angular.module("pascalprecht.translate").factory("$translateDefaultInterpolation",["$interpolate",function(a){var b,c={},d="default";return c.setLocale=function(a){b=a},c.getInterpolationIdentifier=function(){return d},c.interpolate=function(b,c){return a(b)(c)},c}]),angular.module("pascalprecht.translate").constant("$STORAGE_KEY","NG_TRANSLATE_LANG_KEY"),angular.module("pascalprecht.translate").directive("translate",["$filter","$interpolate",function(a,b){var c=a("translate");return{restrict:"AE",scope:!0,link:function(a,d,e){e.translateInterpolation&&(a.interpolation=e.translateInterpolation),e.$observe("translate",function(c){a.translationId=angular.equals(c,"")||void 0===c?b(d.text().replace(/^\s+|\s+$/g,""))(a.$parent):c}),e.$observe("translateValues",function(b){a.interpolateParams=b}),a.$on("$translateChangeSuccess",function(){d.html(c(a.translationId,a.interpolateParams,a.interpolation))}),a.$watch("translationId + interpolateParams",function(b){b&&d.html(c(a.translationId,a.interpolateParams,a.interpolation))})}}}]),angular.module("pascalprecht.translate").filter("translate",["$parse","$translate",function(a,b){return function(c,d,e){return angular.isObject(d)||(d=a(d)()),b(c,d,e)}}]); \ No newline at end of file diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-animate.js b/web-ui/src/main/resources/catalog/lib/angular/angular-animate.js new file mode 100644 index 00000000000..5e1b7c6fe61 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-animate.js @@ -0,0 +1,708 @@ +/** + * @license AngularJS v1.2.0-rc.2 + * (c) 2010-2012 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, angular, undefined) {'use strict'; + +/** + * @ngdoc overview + * @name ngAnimate + * @description + * + * # ngAnimate + * + * `ngAnimate` is an optional module that provides CSS and JavaScript animation hooks. + * + * {@installModule animate} + * + * # Usage + * + * To see animations in action, all that is required is to define the appropriate CSS classes + * or to register a JavaScript animation via the $animation service. The directives that support animation automatically are: + * `ngRepeat`, `ngInclude`, `ngSwitch`, `ngShow`, `ngHide` and `ngView`. Custom directives can take advantage of animation + * by using the `$animate` service. + * + * Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives: + * + * | Directive | Supported Animations | + * |---------------------------------------------------------- |----------------------------------------------------| + * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move | + * | {@link ngRoute.directive:ngView#animations ngView} | enter and leave | + * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave | + * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave | + * | {@link ng.directive:ngIf#animations ngIf} | enter and leave | + * | {@link ng.directive:ngShow#animations ngClass} | add and remove | + * | {@link ng.directive:ngShow#animations ngShow & ngHide} | add and remove (the ng-hide class value) | + * + * You can find out more information about animations upon visiting each directive page. + * + * Below is an example of how to apply animations to a directive that supports animation hooks: + * + *
    + * 
    + *
    + * 
    + * 
    + * 
    + * + * Keep in mind that if an animation is running, any child elements cannot be animated until the parent element's + * animation has completed. + * + *

    CSS-defined Animations

    + * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes + * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported + * and can be used to play along with this naming structure. + * + * The following code below demonstrates how to perform animations using **CSS transitions** with Angular: + * + *
    + * 
    + *
    + * 
    + *
    + *
    + *
    + * + * The following code below demonstrates how to perform animations using **CSS animations** with Angular: + * + *
    + * 
    + *
    + * 
    + *
    + *
    + *
    + * + * Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing. + * + * Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add + * the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically + * detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be + * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end + * immediately resulting in a DOM element that is at its final state. This final state is when the DOM element + * has no CSS transition/animation classes applied to it. + * + *

    JavaScript-defined Animations

    + * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not + * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module. + * + *
    + * //!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application.
    + * var ngModule = angular.module('YourApp', []);
    + * ngModule.animation('.my-crazy-animation', function() {
    + *   return {
    + *     enter: function(element, done) {
    + *       //run the animation
    + *       //!annotate Cancel Animation|This function (if provided) will perform the cancellation of the animation when another is triggered
    + *       return function(element, done) {
    + *         //cancel the animation
    + *       }
    + *     }
    + *     leave: function(element, done) { },
    + *     move: function(element, done) { },
    + *     show: function(element, done) { },
    + *     hide: function(element, done) { },
    + *     addClass: function(element, className, done) { },
    + *     removeClass: function(element, className, done) { },
    + *   }
    + * });
    + * 
    + * + * JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run + * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits + * the element's CSS class attribute value and then run the matching animation event function (if found). + * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function + * be executed. It should be also noted that only simple class selectors are allowed. + * + * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned. + * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run, + * and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation + * or transition code that is defined via a stylesheet). + * + */ + +angular.module('ngAnimate', ['ng']) + + /** + * @ngdoc object + * @name ngAnimate.$animateProvider + * @description + * + * The `$AnimationProvider` allows developers to register and access custom JavaScript animations directly inside + * of a module. When an animation is triggered, the $animate service will query the $animation function to find any + * animations that match the provided name value. + * + * Requires the {@link ngAnimate `ngAnimate`} module to be installed. + * + * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. + * + */ + .config(['$provide', '$animateProvider', function($provide, $animateProvider) { + var noop = angular.noop; + var forEach = angular.forEach; + var selectors = $animateProvider.$$selectors; + + var NG_ANIMATE_STATE = '$$ngAnimateState'; + var rootAnimateState = {running:true}; + $provide.decorator('$animate', ['$delegate', '$injector', '$sniffer', '$rootElement', '$timeout', '$rootScope', + function($delegate, $injector, $sniffer, $rootElement, $timeout, $rootScope) { + + $rootElement.data(NG_ANIMATE_STATE, rootAnimateState); + + function lookup(name) { + if (name) { + var matches = [], + flagMap = {}, + classes = name.substr(1).split('.'); + + //the empty string value is the default animation + //operation which performs CSS transition and keyframe + //animations sniffing. This is always included for each + //element animation procedure + classes.push(''); + + for(var i=0; i < classes.length; i++) { + var klass = classes[i], + selectorFactoryName = selectors[klass]; + if(selectorFactoryName && !flagMap[klass]) { + matches.push($injector.get(selectorFactoryName)); + flagMap[klass] = true; + } + } + return matches; + } + } + + /** + * @ngdoc object + * @name ngAnimate.$animate + * @requires $timeout, $sniffer, $rootElement + * @function + * + * @description + * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) + * as well as during addClass and removeClass operations. When any of these operations are run, the $animate service + * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) + * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run. + * + * The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives + * will work out of the box without any extra configuration. + * + * Requires the {@link ngAnimate `ngAnimate`} module to be installed. + * + * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. + * + */ + return { + /** + * @ngdoc function + * @name ngAnimate.$animate#enter + * @methodOf ngAnimate.$animate + * @function + * + * @description + * Appends the element to the parent element that resides in the document and then runs the enter animation. Once + * the animation is started, the following CSS classes will be present on the element for the duration of the animation: + * + * Below is a breakdown of each step that occurs during enter animation: + * + * | Animation Step | What the element class attribute looks like | + * |----------------------------------------------------------------------------------------------|-----------------------------------------------| + * | 1. $animate.enter(...) is called | class="my-animation" | + * | 2. element is inserted into the parent element or beside the after element | class="my-animation" | + * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation" | + * | 4. the .ng-enter class is added to the element | class="my-animation ng-enter" | + * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-enter" | + * | 6. the .ng-enter-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-enter ng-enter-active" | + * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-enter ng-enter-active" | + * | 8. The animation ends and both CSS classes are removed from the element | class="my-animation" | + * | 9. The done() callback is fired (if provided) | class="my-animation" | + * + * @param {jQuery/jqLite element} element the element that will be the focus of the enter animation + * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the enter animation + * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the enter animation + * @param {function()=} done callback function that will be called once the animation is complete + */ + enter : function(element, parent, after, done) { + $delegate.enter(element, parent, after); + $rootScope.$$postDigest(function() { + performAnimation('enter', 'ng-enter', element, parent, after, function() { + done && $timeout(done, 0, false); + }); + }); + }, + + /** + * @ngdoc function + * @name ngAnimate.$animate#leave + * @methodOf ngAnimate.$animate + * @function + * + * @description + * Runs the leave animation operation and, upon completion, removes the element from the DOM. Once + * the animation is started, the following CSS classes will be added for the duration of the animation: + * + * Below is a breakdown of each step that occurs during enter animation: + * + * | Animation Step | What the element class attribute looks like | + * |----------------------------------------------------------------------------------------------|----------------------------------------------| + * | 1. $animate.leave(...) is called | class="my-animation" | + * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation" | + * | 3. the .ng-leave class is added to the element | class="my-animation ng-leave" | + * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-leave" | + * | 5. the .ng-leave-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-leave ng-leave-active | + * | 6. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-leave ng-leave-active | + * | 7. The animation ends and both CSS classes are removed from the element | class="my-animation" | + * | 8. The element is removed from the DOM | ... | + * | 9. The done() callback is fired (if provided) | ... | + * + * @param {jQuery/jqLite element} element the element that will be the focus of the leave animation + * @param {function()=} done callback function that will be called once the animation is complete + */ + leave : function(element, done) { + $rootScope.$$postDigest(function() { + performAnimation('leave', 'ng-leave', element, null, null, function() { + $delegate.leave(element, done); + }); + }); + }, + + /** + * @ngdoc function + * @name ngAnimate.$animate#move + * @methodOf ngAnimate.$animate + * @function + * + * @description + * Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parent container or + * add the element directly after the after element if present. Then the move animation will be run. Once + * the animation is started, the following CSS classes will be added for the duration of the animation: + * + * Below is a breakdown of each step that occurs during move animation: + * + * | Animation Step | What the element class attribute looks like | + * |----------------------------------------------------------------------------------------------|---------------------------------------------| + * | 1. $animate.move(...) is called | class="my-animation" | + * | 2. element is moved into the parent element or beside the after element | class="my-animation" | + * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation" | + * | 4. the .ng-move class is added to the element | class="my-animation ng-move" | + * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-move" | + * | 6. the .ng-move-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-move ng-move-active" | + * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-move ng-move-active" | + * | 8. The animation ends and both CSS classes are removed from the element | class="my-animation" | + * | 9. The done() callback is fired (if provided) | class="my-animation" | + * + * @param {jQuery/jqLite element} element the element that will be the focus of the move animation + * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the move animation + * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the move animation + * @param {function()=} done callback function that will be called once the animation is complete + */ + move : function(element, parent, after, done) { + $delegate.move(element, parent, after); + $rootScope.$$postDigest(function() { + performAnimation('move', 'ng-move', element, null, null, function() { + done && $timeout(done, 0, false); + }); + }); + }, + + /** + * @ngdoc function + * @name ngAnimate.$animate#addClass + * @methodOf ngAnimate.$animate + * + * @description + * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class. + * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide + * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions + * or keyframes are defined on the -add CSS class). + * + * Below is a breakdown of each step that occurs during addClass animation: + * + * | Animation Step | What the element class attribute looks like | + * |------------------------------------------------------------------------------------------------|---------------------------------------------| + * | 1. $animate.addClass(element, 'super') is called | class="" | + * | 2. $animate runs any JavaScript-defined animations on the element | class="" | + * | 3. the .super-add class is added to the element | class="super-add" | + * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="super-add" | + * | 5. the .super-add-active class is added (this triggers the CSS transition/animation) | class="super-add super-add-active" | + * | 6. $animate waits for X milliseconds for the animation to complete | class="super-add super-add-active" | + * | 7. The animation ends and both CSS classes are removed from the element | class="" | + * | 8. The super class is added to the element | class="super" | + * | 9. The done() callback is fired (if provided) | class="super" | + * + * @param {jQuery/jqLite element} element the element that will be animated + * @param {string} className the CSS class that will be animated and then attached to the element + * @param {function()=} done callback function that will be called once the animation is complete + */ + addClass : function(element, className, done) { + performAnimation('addClass', className, element, null, null, function() { + $delegate.addClass(element, className, done); + }); + }, + + /** + * @ngdoc function + * @name ngAnimate.$animate#removeClass + * @methodOf ngAnimate.$animate + * + * @description + * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value + * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in + * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if + * no CSS transitions or keyframes are defined on the -remove CSS class). + * + * Below is a breakdown of each step that occurs during removeClass animation: + * + * | Animation Step | What the element class attribute looks like | + * |-----------------------------------------------------------------------------------------------|-------------------------------------------------| + * | 1. $animate.removeClass(element, 'super') is called | class="super" | + * | 2. $animate runs any JavaScript-defined animations on the element | class="super" | + * | 3. the .super-remove class is added to the element | class="super super-remove" | + * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="super super-remove" | + * | 5. the .super-remove-active class is added (this triggers the CSS transition/animation) | class="super super-remove super-remove-active" | + * | 6. $animate waits for X milliseconds for the animation to complete | class="super super-remove super-remove-active" | + * | 7. The animation ends and both CSS all three classes are removed from the element | class="" | + * | 8. The done() callback is fired (if provided) | class="" | + * + * @param {jQuery/jqLite element} element the element that will be animated + * @param {string} className the CSS class that will be animated and then removed from the element + * @param {function()=} done callback function that will be called once the animation is complete + */ + removeClass : function(element, className, done) { + performAnimation('removeClass', className, element, null, null, function() { + $delegate.removeClass(element, className, done); + }); + }, + + /** + * @ngdoc function + * @name ngAnimate.$animate#enabled + * @methodOf ngAnimate.$animate + * @function + * + * @param {boolean=} value If provided then set the animation on or off. + * @return {boolean} Current animation state. + * + * @description + * Globally enables/disables animations. + * + */ + enabled : function(value) { + if (arguments.length) { + rootAnimateState.running = !value; + } + return !rootAnimateState.running; + } + }; + + /* + all animations call this shared animation triggering function internally. + The event variable refers to the JavaScript animation event that will be triggered + and the className value is the name of the animation that will be applied within the + CSS code. Element, parent and after are provided DOM elements for the animation + and the onComplete callback will be fired once the animation is fully complete. + */ + function performAnimation(event, className, element, parent, after, onComplete) { + var classes = (element.attr('class') || '') + ' ' + className; + var animationLookup = (' ' + classes).replace(/\s+/g,'.'), + animations = []; + forEach(lookup(animationLookup), function(animation, index) { + animations.push({ + start : animation[event] + }); + }); + + if (!parent) { + parent = after ? after.parent() : element.parent(); + } + var disabledAnimation = { running : true }; + + //skip the animation if animations are disabled, a parent is already being animated + //or the element is not currently attached to the document body. + if ((parent.inheritedData(NG_ANIMATE_STATE) || disabledAnimation).running) { + //avoid calling done() since there is no need to remove any + //data or className values since this happens earlier than that + //and also use a timeout so that it won't be asynchronous + $timeout(onComplete || noop, 0, false); + return; + } + + var ngAnimateState = element.data(NG_ANIMATE_STATE) || {}; + + //if an animation is currently running on the element then lets take the steps + //to cancel that animation and fire any required callbacks + if(ngAnimateState.running) { + cancelAnimations(ngAnimateState.animations); + ngAnimateState.done(); + } + + element.data(NG_ANIMATE_STATE, { + running:true, + animations:animations, + done:done + }); + + forEach(animations, function(animation, index) { + var fn = function() { + progress(index); + }; + + if(animation.start) { + if(event == 'addClass' || event == 'removeClass') { + animation.endFn = animation.start(element, className, fn); + } else { + animation.endFn = animation.start(element, fn); + } + } else { + fn(); + } + }); + + function cancelAnimations(animations) { + var isCancelledFlag = true; + forEach(animations, function(animation) { + (animation.endFn || noop)(isCancelledFlag); + }); + } + + function progress(index) { + animations[index].done = true; + (animations[index].endFn || noop)(); + for(var i=0;i 0) { + done(); + return; + } + } + + element.addClass(className); + + //we want all the styles defined before and after + var duration = 0; + forEach(element, function(element) { + if (element.nodeType == ELEMENT_NODE) { + var elementStyles = $window.getComputedStyle(element) || {}; + + var transitionDelay = Math.max(parseMaxTime(elementStyles[w3cTransitionProp + delayKey]), + parseMaxTime(elementStyles[vendorTransitionProp + delayKey])); + + var animationDelay = Math.max(parseMaxTime(elementStyles[w3cAnimationProp + delayKey]), + parseMaxTime(elementStyles[vendorAnimationProp + delayKey])); + + var transitionDuration = Math.max(parseMaxTime(elementStyles[w3cTransitionProp + durationKey]), + parseMaxTime(elementStyles[vendorTransitionProp + durationKey])); + + var animationDuration = Math.max(parseMaxTime(elementStyles[w3cAnimationProp + durationKey]), + parseMaxTime(elementStyles[vendorAnimationProp + durationKey])); + + if(animationDuration > 0) { + animationDuration *= Math.max(parseInt(elementStyles[w3cAnimationProp + animationIterationCountKey]) || 0, + parseInt(elementStyles[vendorAnimationProp + animationIterationCountKey]) || 0, + 1); + } + + duration = Math.max(animationDelay + animationDuration, + transitionDelay + transitionDuration, + duration); + } + }); + + /* there is no point in performing a reflow if the animation + timeout is empty (this would cause a flicker bug normally + in the page */ + if(duration > 0) { + var node = element[0]; + + //temporarily disable the transition so that the enter styles + //don't animate twice (this is here to avoid a bug in Chrome/FF). + node.style[w3cTransitionProp + propertyKey] = 'none'; + node.style[vendorTransitionProp + propertyKey] = 'none'; + + var activeClassName = ''; + forEach(className.split(' '), function(klass, i) { + activeClassName += (i > 0 ? ' ' : '') + klass + '-active'; + }); + + //this triggers a reflow which allows for the transition animation to kick in + element.prop('clientWidth'); + node.style[w3cTransitionProp + propertyKey] = ''; + node.style[vendorTransitionProp + propertyKey] = ''; + element.addClass(activeClassName); + + $timeout(done, duration * 1000, false); + + //this will automatically be called by $animate so + //there is no need to attach this internally to the + //timeout done method + return function onEnd(cancelled) { + element.removeClass(className); + element.removeClass(activeClassName); + + //only when the animation is cancelled is the done() + //function not called for this animation therefore + //this must be also called + if(cancelled) { + done(); + } + } + } + else { + element.removeClass(className); + done(); + } + + function parseMaxTime(str) { + var total = 0, values = angular.isString(str) ? str.split(/\s*,\s*/) : []; + forEach(values, function(value) { + total = Math.max(parseFloat(value) || 0, total); + }); + return total; + } + } + + return { + enter : function(element, done) { + return animate(element, 'ng-enter', done); + }, + leave : function(element, done) { + return animate(element, 'ng-leave', done); + }, + move : function(element, done) { + return animate(element, 'ng-move', done); + }, + addClass : function(element, className, done) { + return animate(element, suffixClasses(className, '-add'), done); + }, + removeClass : function(element, className, done) { + return animate(element, suffixClasses(className, '-remove'), done); + } + }; + + function suffixClasses(classes, suffix) { + var className = ''; + classes = angular.isArray(classes) ? classes : classes.split(/\s+/); + forEach(classes, function(klass, i) { + if(klass && klass.length > 0) { + className += (i > 0 ? ' ' : '') + klass + suffix; + } + }); + return className; + } + }]); + }]); + + +})(window, window.angular); diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-animate.min.js b/web-ui/src/main/resources/catalog/lib/angular/angular-animate.min.js new file mode 100644 index 00000000000..768a4d7a19b --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-animate.min.js @@ -0,0 +1,15 @@ +/* + AngularJS v1.2.0-rc.2 + (c) 2010-2012 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(C,n,D){'use strict';n.module("ngAnimate",["ng"]).config(["$provide","$animateProvider",function(A,t){var u=n.noop,v=n.forEach,B=t.$$selectors,p="$$ngAnimateState",z={running:!0};A.decorator("$animate",["$delegate","$injector","$sniffer","$rootElement","$timeout","$rootScope",function(r,n,t,g,m,h){function w(a){if(a){var e=[],d={};a=a.substr(1).split(".");a.push("");for(var b=0;b + + + + + */ + factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) { + var cookies = {}, + lastCookies = {}, + lastBrowserCookies, + runEval = false, + copy = angular.copy, + isUndefined = angular.isUndefined; + + //creates a poller fn that copies all cookies from the $browser to service & inits the service + $browser.addPollFn(function() { + var currentCookies = $browser.cookies(); + if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl + lastBrowserCookies = currentCookies; + copy(currentCookies, lastCookies); + copy(currentCookies, cookies); + if (runEval) $rootScope.$apply(); + } + })(); + + runEval = true; + + //at the end of each eval, push cookies + //TODO: this should happen before the "delayed" watches fire, because if some cookies are not + // strings or browser refuses to store some cookies, we update the model in the push fn. + $rootScope.$watch(push); + + return cookies; + + + /** + * Pushes all the cookies from the service to the browser and verifies if all cookies were stored. + */ + function push() { + var name, + value, + browserCookies, + updated; + + //delete any cookies deleted in $cookies + for (name in lastCookies) { + if (isUndefined(cookies[name])) { + $browser.cookies(name, undefined); + } + } + + //update all cookies updated in $cookies + for(name in cookies) { + value = cookies[name]; + if (!angular.isString(value)) { + if (angular.isDefined(lastCookies[name])) { + cookies[name] = lastCookies[name]; + } else { + delete cookies[name]; + } + } else if (value !== lastCookies[name]) { + $browser.cookies(name, value); + updated = true; + } + } + + //verify what was actually stored + if (updated){ + updated = false; + browserCookies = $browser.cookies(); + + for (name in cookies) { + if (cookies[name] !== browserCookies[name]) { + //delete or reset all cookies that the browser dropped from $cookies + if (isUndefined(browserCookies[name])) { + delete cookies[name]; + } else { + cookies[name] = browserCookies[name]; + } + updated = true; + } + } + } + } + }]). + + + /** + * @ngdoc object + * @name ngCookies.$cookieStore + * @requires $cookies + * + * @description + * Provides a key-value (string-object) storage, that is backed by session cookies. + * Objects put or retrieved from this storage are automatically serialized or + * deserialized by angular's toJson/fromJson. + * + * Requires the {@link ngCookies `ngCookies`} module to be installed. + * + * @example + */ + factory('$cookieStore', ['$cookies', function($cookies) { + + return { + /** + * @ngdoc method + * @name ngCookies.$cookieStore#get + * @methodOf ngCookies.$cookieStore + * + * @description + * Returns the value of given cookie key + * + * @param {string} key Id to use for lookup. + * @returns {Object} Deserialized cookie value. + */ + get: function(key) { + var value = $cookies[key]; + return value ? angular.fromJson(value) : value; + }, + + /** + * @ngdoc method + * @name ngCookies.$cookieStore#put + * @methodOf ngCookies.$cookieStore + * + * @description + * Sets a value for given cookie key + * + * @param {string} key Id for the `value`. + * @param {Object} value Value to be stored. + */ + put: function(key, value) { + $cookies[key] = angular.toJson(value); + }, + + /** + * @ngdoc method + * @name ngCookies.$cookieStore#remove + * @methodOf ngCookies.$cookieStore + * + * @description + * Remove given cookie + * + * @param {string} key Id of the key-value pair to delete. + */ + remove: function(key) { + delete $cookies[key]; + } + }; + + }]); + + +})(window, window.angular); diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-cookies.min.js b/web-ui/src/main/resources/catalog/lib/angular/angular-cookies.min.js new file mode 100644 index 00000000000..4cfebbd4d14 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-cookies.min.js @@ -0,0 +1,10 @@ +/* + AngularJS v1.2.0-rc.2 + (c) 2010-2012 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(p,f,n){'use strict';f.module("ngCookies",["ng"]).factory("$cookies",["$rootScope","$browser",function(d,b){var c={},g={},h,k=!1,l=f.copy,m=f.isUndefined;b.addPollFn(function(){var a=b.cookies();h!=a&&(h=a,l(a,g),l(a,c),k&&d.$apply())})();k=!0;d.$watch(function(){var a,e,d;for(a in g)m(c[a])&&b.cookies(a,n);for(a in c)(e=c[a],f.isString(e))?e!==g[a]&&(b.cookies(a,e),d=!0):f.isDefined(g[a])?c[a]=g[a]:delete c[a];if(d)for(a in e=b.cookies(),c)c[a]!==e[a]&&(m(e[a])?delete c[a]:c[a]=e[a])}); +return c}]).factory("$cookieStore",["$cookies",function(d){return{get:function(b){return(b=d[b])?f.fromJson(b):b},put:function(b,c){d[b]=f.toJson(c)},remove:function(b){delete d[b]}}}])})(window,window.angular); +/* +//@ sourceMappingURL=angular-cookies.min.js.map +*/ diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-cookies.min.js.map b/web-ui/src/main/resources/catalog/lib/angular/angular-cookies.min.js.map new file mode 100644 index 00000000000..21bed425b68 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-cookies.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"angular-cookies.min.js", +"lineCount":7, +"mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAkBC,CAAlB,CAA6B,CAmBtCD,CAAAE,OAAA,CAAe,WAAf,CAA4B,CAAC,IAAD,CAA5B,CAAAC,QAAA,CA4BW,UA5BX,CA4BuB,CAAC,YAAD,CAAe,UAAf,CAA2B,QAAS,CAACC,CAAD,CAAaC,CAAb,CAAuB,CAAA,IACxEC,EAAU,EAD8D,CAExEC,EAAc,EAF0D,CAGxEC,CAHwE,CAIxEC,EAAU,CAAA,CAJ8D,CAKxEC,EAAOV,CAAAU,KALiE,CAMxEC,EAAcX,CAAAW,YAGlBN,EAAAO,UAAA,CAAmB,QAAQ,EAAG,CAC5B,IAAIC,EAAiBR,CAAAC,QAAA,EACjBE,EAAJ,EAA0BK,CAA1B,GACEL,CAGA,CAHqBK,CAGrB,CAFAH,CAAA,CAAKG,CAAL,CAAqBN,CAArB,CAEA,CADAG,CAAA,CAAKG,CAAL,CAAqBP,CAArB,CACA,CAAIG,CAAJ,EAAaL,CAAAU,OAAA,EAJf,CAF4B,CAA9B,CAAA,EAUAL,EAAA,CAAU,CAAA,CAKVL,EAAAW,OAAA,CAQAC,QAAa,EAAG,CAAA,IACVC,CADU,CAEVC,CAFU,CAIVC,CAGJ,KAAKF,CAAL,GAAaV,EAAb,CACMI,CAAA,CAAYL,CAAA,CAAQW,CAAR,CAAZ,CAAJ,EACEZ,CAAAC,QAAA,CAAiBW,CAAjB,CAAuBhB,CAAvB,CAKJ,KAAIgB,CAAJ,GAAYX,EAAZ,CAEE,CADAY,CACK,CADGZ,CAAA,CAAQW,CAAR,CACH,CAAAjB,CAAAoB,SAAA,CAAiBF,CAAjB,CAAL,EAMWA,CANX,GAMqBX,CAAA,CAAYU,CAAZ,CANrB,GAOEZ,CAAAC,QAAA,CAAiBW,CAAjB,CAAuBC,CAAvB,CACA,CAAAC,CAAA,CAAU,CAAA,CARZ,EACMnB,CAAAqB,UAAA,CAAkBd,CAAA,CAAYU,CAAZ,CAAlB,CAAJ,CACEX,CAAA,CAAQW,CAAR,CADF,CACkBV,CAAA,CAAYU,CAAZ,CADlB,CAGE,OAAOX,CAAA,CAAQW,CAAR,CASb,IAAIE,CAAJ,CAIE,IAAKF,CAAL,GAFAK,EAEahB,CAFID,CAAAC,QAAA,EAEJA,CAAAA,CAAb,CACMA,CAAA,CAAQW,CAAR,CAAJ,GAAsBK,CAAA,CAAeL,CAAf,CAAtB,GAEMN,CAAA,CAAYW,CAAA,CAAeL,CAAf,CAAZ,CAAJ,CACE,OAAOX,CAAA,CAAQW,CAAR,CADT,CAGEX,CAAA,CAAQW,CAAR,CAHF,CAGkBK,CAAA,CAAeL,CAAf,CALpB,CAlCU,CARhB,CAEA;MAAOX,EA1BqE,CAA3D,CA5BvB,CAAAH,QAAA,CA2HW,cA3HX,CA2H2B,CAAC,UAAD,CAAa,QAAQ,CAACoB,CAAD,CAAW,CAErD,MAAO,KAYAC,QAAQ,CAACC,CAAD,CAAM,CAEjB,MAAO,CADHP,CACG,CADKK,CAAA,CAASE,CAAT,CACL,EAAQzB,CAAA0B,SAAA,CAAiBR,CAAjB,CAAR,CAAkCA,CAFxB,CAZd,KA4BAS,QAAQ,CAACF,CAAD,CAAMP,CAAN,CAAa,CACxBK,CAAA,CAASE,CAAT,CAAA,CAAgBzB,CAAA4B,OAAA,CAAeV,CAAf,CADQ,CA5BrB,QA0CGW,QAAQ,CAACJ,CAAD,CAAM,CACpB,OAAOF,CAAA,CAASE,CAAT,CADa,CA1CjB,CAF8C,CAAhC,CA3H3B,CAnBsC,CAArC,CAAA,CAkME1B,MAlMF,CAkMUA,MAAAC,QAlMV;", +"sources":["angular-cookies.js"], +"names":["window","angular","undefined","module","factory","$rootScope","$browser","cookies","lastCookies","lastBrowserCookies","runEval","copy","isUndefined","addPollFn","currentCookies","$apply","$watch","push","name","value","updated","isString","isDefined","browserCookies","$cookies","get","key","fromJson","put","toJson","remove"] +} diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-loader.js b/web-ui/src/main/resources/catalog/lib/angular/angular-loader.js new file mode 100644 index 00000000000..7915a483d6f --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-loader.js @@ -0,0 +1,314 @@ +/** + * @license AngularJS v1.2.0-rc.2 + * (c) 2010-2012 Google, Inc. http://angularjs.org + * License: MIT + */ + +( + +/** + * @ngdoc interface + * @name angular.Module + * @description + * + * Interface for configuring angular {@link angular.module modules}. + */ + +function setupModuleLoader(window) { + + function ensure(obj, name, factory) { + return obj[name] || (obj[name] = factory()); + } + + return ensure(ensure(window, 'angular', Object), 'module', function() { + /** @type {Object.} */ + var modules = {}; + + /** + * @ngdoc function + * @name angular.module + * @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, filters, and configuration information. + * `angular.module` is used to configure the {@link AUTO.$injector $injector}. + * + *
    +     * // 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(function($locationProvider) {'use strict';
    +     *   // Configure existing providers
    +     *   $locationProvider.hashPrefix('!');
    +     * });
    +     * 
    + * + * Then you can create an injector and load your modules like this: + * + *
    +     * 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 + * 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) { + if (requires && modules.hasOwnProperty(name)) { + modules[name] = null; + } + return ensure(modules, name, function() { + if (!requires) { + throw minErr('$injector')('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 + * @propertyOf angular.Module + * @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 + * @propertyOf angular.Module + * @returns {string} Name of the module. + * @description + */ + name: name, + + + /** + * @ngdoc method + * @name angular.Module#provider + * @methodOf angular.Module + * @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 + * @methodOf angular.Module + * @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 + * @methodOf angular.Module + * @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 + * @methodOf angular.Module + * @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 + * @methodOf angular.Module + * @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 + * @methodOf angular.Module + * @param {string} name animation name + * @param {Function} animationFactory Factory function for creating new instance of an animation. + * @description + * + * **NOTE**: animations are 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. + * + *
    +           * 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 + * @methodOf angular.Module + * @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 + * @methodOf angular.Module + * @param {string} name Controller name. + * @param {Function} constructor Controller constructor function. + * @description + * See {@link ng.$controllerProvider#register $controllerProvider.register()}. + */ + controller: invokeLater('$controllerProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#directive + * @methodOf angular.Module + * @param {string} name directive name + * @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 + * @methodOf angular.Module + * @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. + */ + config: config, + + /** + * @ngdoc method + * @name angular.Module#run + * @methodOf angular.Module + * @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; + } + } + }); + }; + }); + +} + +)(window); + +/** + * Closure compiler type information + * + * @typedef { { + * requires: !Array., + * invokeQueue: !Array.>, + * + * service: function(string, Function):angular.Module, + * factory: function(string, Function):angular.Module, + * value: function(string, *):angular.Module, + * + * filter: function(string, Function):angular.Module, + * + * init: function(Function):angular.Module + * } } + */ +angular.Module; + diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-loader.min.js b/web-ui/src/main/resources/catalog/lib/angular/angular-loader.min.js new file mode 100644 index 00000000000..ebb7ff60504 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-loader.min.js @@ -0,0 +1,10 @@ +/* + AngularJS v1.2.0-rc.2 + (c) 2010-2012 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(k){'use strict';function d(c,b,e){return c[b]||(c[b]=e())}return d(d(k,"angular",Object),"module",function(){var c={};return function(b,e,f){e&&c.hasOwnProperty(b)&&(c[b]=null);return d(c,b,function(){function a(a,b,d){return function(){c[d||"push"]([a,b,arguments]);return g}}if(!e)throw minErr("$injector")("nomod",b);var c=[],d=[],h=a("$injector","invoke"),g={_invokeQueue:c,_runBlocks:d,requires:e,name:b,provider:a("$provide","provider"),factory:a("$provide","factory"),service:a("$provide", +"service"),value:a("$provide","value"),constant:a("$provide","constant","unshift"),animation:a("$animateProvider","register"),filter:a("$filterProvider","register"),controller:a("$controllerProvider","register"),directive:a("$compileProvider","directive"),config:h,run:function(a){d.push(a);return this}};f&&h(f);return g})}})})(window); +/* +//@ sourceMappingURL=angular-loader.min.js.map +*/ diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-loader.min.js.map b/web-ui/src/main/resources/catalog/lib/angular/angular-loader.min.js.map new file mode 100644 index 00000000000..6b8244f8493 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-loader.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"angular-loader.min.js", +"lineCount":7, +"mappings":"A;;;;;aAgBAA,SAA0B,CAACC,CAAD,CAAS,CAEjCC,QAASA,EAAM,CAACC,CAAD,CAAMC,CAAN,CAAYC,CAAZ,CAAqB,CAClC,MAAOF,EAAA,CAAIC,CAAJ,CAAP,GAAqBD,CAAA,CAAIC,CAAJ,CAArB,CAAiCC,CAAA,EAAjC,CADkC,CAIpC,MAAOH,EAAA,CAAOA,CAAA,CAAOD,CAAP,CAAe,SAAf,CAA0BK,MAA1B,CAAP,CAA0C,QAA1C,CAAoD,QAAQ,EAAG,CAEpE,IAAIC,EAAU,EAmDd,OAAOC,SAAe,CAACJ,CAAD,CAAOK,CAAP,CAAiBC,CAAjB,CAA2B,CAC3CD,CAAJ,EAAgBF,CAAAI,eAAA,CAAuBP,CAAvB,CAAhB,GACEG,CAAA,CAAQH,CAAR,CADF,CACkB,IADlB,CAGA,OAAOF,EAAA,CAAOK,CAAP,CAAgBH,CAAhB,CAAsB,QAAQ,EAAG,CA2MtCQ,QAASA,EAAW,CAACC,CAAD,CAAWC,CAAX,CAAmBC,CAAnB,CAAiC,CACnD,MAAO,SAAQ,EAAG,CAChBC,CAAA,CAAYD,CAAZ,EAA4B,MAA5B,CAAA,CAAoC,CAACF,CAAD,CAAWC,CAAX,CAAmBG,SAAnB,CAApC,CACA,OAAOC,EAFS,CADiC,CA1MrD,GAAI,CAACT,CAAL,CACE,KAAMU,OAAA,CAAO,WAAP,CAAA,CAAoB,OAApB,CAEWf,CAFX,CAAN,CAMF,IAAIY,EAAc,EAAlB,CAGII,EAAY,EAHhB,CAKIC,EAAST,CAAA,CAAY,WAAZ,CAAyB,QAAzB,CALb,CAQIM,EAAiB,cAELF,CAFK,YAGPI,CAHO,UAaTX,CAbS,MAsBbL,CAtBa,UAkCTQ,CAAA,CAAY,UAAZ,CAAwB,UAAxB,CAlCS,SA6CVA,CAAA,CAAY,UAAZ,CAAwB,SAAxB,CA7CU,SAwDVA,CAAA,CAAY,UAAZ;AAAwB,SAAxB,CAxDU,OAmEZA,CAAA,CAAY,UAAZ,CAAwB,OAAxB,CAnEY,UA+ETA,CAAA,CAAY,UAAZ,CAAwB,UAAxB,CAAoC,SAApC,CA/ES,WAgHRA,CAAA,CAAY,kBAAZ,CAAgC,UAAhC,CAhHQ,QA2HXA,CAAA,CAAY,iBAAZ,CAA+B,UAA/B,CA3HW,YAsIPA,CAAA,CAAY,qBAAZ,CAAmC,UAAnC,CAtIO,WAkJRA,CAAA,CAAY,kBAAZ,CAAgC,WAAhC,CAlJQ,QA6JXS,CA7JW,KAyKdC,QAAQ,CAACC,CAAD,CAAQ,CACnBH,CAAAI,KAAA,CAAeD,CAAf,CACA,OAAO,KAFY,CAzKF,CA+KjBb,EAAJ,EACEW,CAAA,CAAOX,CAAP,CAGF,OAAQQ,EAnM8B,CAAjC,CAJwC,CArDmB,CAA/D,CAN0B,CAAnClB,CAAA,CAsREC,MAtRF;", +"sources":["angular-loader.js"], +"names":["setupModuleLoader","window","ensure","obj","name","factory","Object","modules","module","requires","configFn","hasOwnProperty","invokeLater","provider","method","insertMethod","invokeQueue","arguments","moduleInstance","minErr","runBlocks","config","run","block","push"] +} diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-mocks.js b/web-ui/src/main/resources/catalog/lib/angular/angular-mocks.js new file mode 100644 index 00000000000..993912e166c --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-mocks.js @@ -0,0 +1,1962 @@ +/** + * @license AngularJS v1.2.0-rc.2 + * (c) 2010-2012 Google, Inc. http://angularjs.org + * License: MIT + * + * TODO(vojta): wrap whole file into closure during build + */ + +/** + * @ngdoc overview + * @name angular.mock + * @description + * + * Namespace from 'angular-mocks.js' which contains testing related code. + */ +angular.mock = {}; + +/** + * ! This is a private undocumented service ! + * + * @name ngMock.$browser + * + * @description + * This service is a mock implementation of {@link ng.$browser}. It provides fake + * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr, + * cookies, etc... + * + * The api of this service is the same as that of the real {@link ng.$browser $browser}, except + * that there are several helper methods available which can be used in tests. + */ +angular.mock.$BrowserProvider = function() { + this.$get = function() { + return new angular.mock.$Browser(); + }; +}; + +angular.mock.$Browser = function() { + var self = this; + + this.isMock = true; + self.$$url = "http://server/"; + self.$$lastUrl = self.$$url; // used by url polling fn + self.pollFns = []; + + // TODO(vojta): remove this temporary api + self.$$completeOutstandingRequest = angular.noop; + self.$$incOutstandingRequestCount = angular.noop; + + + // register url polling fn + + self.onUrlChange = function(listener) { + self.pollFns.push( + function() { + if (self.$$lastUrl != self.$$url) { + self.$$lastUrl = self.$$url; + listener(self.$$url); + } + } + ); + + return listener; + }; + + self.cookieHash = {}; + self.lastCookieHash = {}; + self.deferredFns = []; + self.deferredNextId = 0; + + self.defer = function(fn, delay) { + delay = delay || 0; + self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId}); + self.deferredFns.sort(function(a,b){ return a.time - b.time;}); + return self.deferredNextId++; + }; + + + self.defer.now = 0; + + + self.defer.cancel = function(deferId) { + var fnIndex; + + angular.forEach(self.deferredFns, function(fn, index) { + if (fn.id === deferId) fnIndex = index; + }); + + if (fnIndex !== undefined) { + self.deferredFns.splice(fnIndex, 1); + return true; + } + + return false; + }; + + + /** + * @name ngMock.$browser#defer.flush + * @methodOf ngMock.$browser + * + * @description + * Flushes all pending requests and executes the defer callbacks. + * + * @param {number=} number of milliseconds to flush. See {@link #defer.now} + */ + self.defer.flush = function(delay) { + if (angular.isDefined(delay)) { + self.defer.now += delay; + } else { + if (self.deferredFns.length) { + self.defer.now = self.deferredFns[self.deferredFns.length-1].time; + } else { + throw Error('No deferred tasks to be flushed'); + } + } + + while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) { + self.deferredFns.shift().fn(); + } + }; + + /** + * @name ngMock.$browser#defer.flushNext + * @methodOf ngMock.$browser + * + * @description + * Flushes next pending request and compares it to the provided delay + * + * @param {number=} expectedDelay the delay value that will be asserted against the delay of the next timeout function + */ + self.defer.flushNext = function(expectedDelay) { + var tick = self.deferredFns.shift(); + expect(tick.time).toEqual(expectedDelay); + tick.fn(); + }; + + /** + * @name ngMock.$browser#defer.now + * @propertyOf ngMock.$browser + * + * @description + * Current milliseconds mock time. + */ + + self.$$baseHref = ''; + self.baseHref = function() { + return this.$$baseHref; + }; +}; +angular.mock.$Browser.prototype = { + +/** + * @name ngMock.$browser#poll + * @methodOf ngMock.$browser + * + * @description + * run all fns in pollFns + */ + poll: function poll() { + angular.forEach(this.pollFns, function(pollFn){ + pollFn(); + }); + }, + + addPollFn: function(pollFn) { + this.pollFns.push(pollFn); + return pollFn; + }, + + url: function(url, replace) { + if (url) { + this.$$url = url; + return this; + } + + return this.$$url; + }, + + cookies: function(name, value) { + if (name) { + if (value == undefined) { + delete this.cookieHash[name]; + } else { + if (angular.isString(value) && //strings only + value.length <= 4096) { //strict cookie storage limits + this.cookieHash[name] = value; + } + } + } else { + if (!angular.equals(this.cookieHash, this.lastCookieHash)) { + this.lastCookieHash = angular.copy(this.cookieHash); + this.cookieHash = angular.copy(this.cookieHash); + } + return this.cookieHash; + } + }, + + notifyWhenNoOutstandingRequests: function(fn) { + fn(); + } +}; + + +/** + * @ngdoc object + * @name ngMock.$exceptionHandlerProvider + * + * @description + * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors passed + * into the `$exceptionHandler`. + */ + +/** + * @ngdoc object + * @name ngMock.$exceptionHandler + * + * @description + * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed + * into it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration + * information. + * + * + *
    + *   describe('$exceptionHandlerProvider', function() {
    + *
    + *     it('should capture log messages and exceptions', function() {
    + *
    + *       module(function($exceptionHandlerProvider) {
    + *         $exceptionHandlerProvider.mode('log');
    + *       });
    + *
    + *       inject(function($log, $exceptionHandler, $timeout) {
    + *         $timeout(function() { $log.log(1); });
    + *         $timeout(function() { $log.log(2); throw 'banana peel'; });
    + *         $timeout(function() { $log.log(3); });
    + *         expect($exceptionHandler.errors).toEqual([]);
    + *         expect($log.assertEmpty());
    + *         $timeout.flush();
    + *         expect($exceptionHandler.errors).toEqual(['banana peel']);
    + *         expect($log.log.logs).toEqual([[1], [2], [3]]);
    + *       });
    + *     });
    + *   });
    + * 
    + */ + +angular.mock.$ExceptionHandlerProvider = function() { + var handler; + + /** + * @ngdoc method + * @name ngMock.$exceptionHandlerProvider#mode + * @methodOf ngMock.$exceptionHandlerProvider + * + * @description + * Sets the logging mode. + * + * @param {string} mode Mode of operation, defaults to `rethrow`. + * + * - `rethrow`: If any errors are passed into the handler in tests, it typically + * means that there is a bug in the application or test, so this mock will + * make these tests fail. + * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` mode stores an + * array of errors in `$exceptionHandler.errors`, to allow later assertion of them. + * See {@link ngMock.$log#assertEmpty assertEmpty()} and + * {@link ngMock.$log#reset reset()} + */ + this.mode = function(mode) { + switch(mode) { + case 'rethrow': + handler = function(e) { + throw e; + }; + break; + case 'log': + var errors = []; + + handler = function(e) { + if (arguments.length == 1) { + errors.push(e); + } else { + errors.push([].slice.call(arguments, 0)); + } + }; + + handler.errors = errors; + break; + default: + throw Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!"); + } + }; + + this.$get = function() { + return handler; + }; + + this.mode('rethrow'); +}; + + +/** + * @ngdoc service + * @name ngMock.$log + * + * @description + * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays + * (one array per logging level). These arrays are exposed as `logs` property of each of the + * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`. + * + */ +angular.mock.$LogProvider = function() { + var debug = true; + + function concat(array1, array2, index) { + return array1.concat(Array.prototype.slice.call(array2, index)); + } + + this.debugEnabled = function(flag) { + if (angular.isDefined(flag)) { + debug = flag; + return this; + } else { + return debug; + } + }; + + this.$get = function () { + var $log = { + log: function() { $log.log.logs.push(concat([], arguments, 0)); }, + warn: function() { $log.warn.logs.push(concat([], arguments, 0)); }, + info: function() { $log.info.logs.push(concat([], arguments, 0)); }, + error: function() { $log.error.logs.push(concat([], arguments, 0)); }, + debug: function() { + if (debug) { + $log.debug.logs.push(concat([], arguments, 0)); + } + } + }; + + /** + * @ngdoc method + * @name ngMock.$log#reset + * @methodOf ngMock.$log + * + * @description + * Reset all of the logging arrays to empty. + */ + $log.reset = function () { + /** + * @ngdoc property + * @name ngMock.$log#log.logs + * @propertyOf ngMock.$log + * + * @description + * Array of messages logged using {@link ngMock.$log#log}. + * + * @example + *
    +       * $log.log('Some Log');
    +       * var first = $log.log.logs.unshift();
    +       * 
    + */ + $log.log.logs = []; + /** + * @ngdoc property + * @name ngMock.$log#info.logs + * @propertyOf ngMock.$log + * + * @description + * Array of messages logged using {@link ngMock.$log#info}. + * + * @example + *
    +       * $log.info('Some Info');
    +       * var first = $log.info.logs.unshift();
    +       * 
    + */ + $log.info.logs = []; + /** + * @ngdoc property + * @name ngMock.$log#warn.logs + * @propertyOf ngMock.$log + * + * @description + * Array of messages logged using {@link ngMock.$log#warn}. + * + * @example + *
    +       * $log.warn('Some Warning');
    +       * var first = $log.warn.logs.unshift();
    +       * 
    + */ + $log.warn.logs = []; + /** + * @ngdoc property + * @name ngMock.$log#error.logs + * @propertyOf ngMock.$log + * + * @description + * Array of messages logged using {@link ngMock.$log#error}. + * + * @example + *
    +       * $log.log('Some Error');
    +       * var first = $log.error.logs.unshift();
    +       * 
    + */ + $log.error.logs = []; + /** + * @ngdoc property + * @name ngMock.$log#debug.logs + * @propertyOf ngMock.$log + * + * @description + * Array of messages logged using {@link ngMock.$log#debug}. + * + * @example + *
    +       * $log.debug('Some Error');
    +       * var first = $log.debug.logs.unshift();
    +       * 
    + */ + $log.debug.logs = [] + }; + + /** + * @ngdoc method + * @name ngMock.$log#assertEmpty + * @methodOf ngMock.$log + * + * @description + * Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown. + */ + $log.assertEmpty = function() { + var errors = []; + angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) { + angular.forEach($log[logLevel].logs, function(log) { + angular.forEach(log, function (logItem) { + errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || '')); + }); + }); + }); + if (errors.length) { + errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " + + "log message was not checked and removed:"); + errors.push(''); + throw new Error(errors.join('\n---------\n')); + } + }; + + $log.reset(); + return $log; + }; +}; + + +(function() { + var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; + + function jsonStringToDate(string) { + var match; + if (match = string.match(R_ISO8061_STR)) { + var date = new Date(0), + tzHour = 0, + tzMin = 0; + if (match[9]) { + tzHour = int(match[9] + match[10]); + tzMin = int(match[9] + match[11]); + } + date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); + date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0)); + return date; + } + return string; + } + + function int(str) { + return parseInt(str, 10); + } + + 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; + } + + + /** + * @ngdoc object + * @name angular.mock.TzDate + * @description + * + * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`. + * + * Mock of the Date type which has its timezone specified via constructor arg. + * + * The main purpose is to create Date-like instances with timezone fixed to the specified timezone + * offset, so that we can test code that depends on local timezone settings without dependency on + * the time zone settings of the machine where the code is running. + * + * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) + * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* + * + * @example + * !!!! WARNING !!!!! + * This is not a complete Date object so only methods that were implemented can be called safely. + * To make matters worse, TzDate instances inherit stuff from Date via a prototype. + * + * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is + * incomplete we might be missing some non-standard methods. This can result in errors like: + * "Date.prototype.foo called on incompatible Object". + * + *
    +   * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
    +   * newYearInBratislava.getTimezoneOffset() => -60;
    +   * newYearInBratislava.getFullYear() => 2010;
    +   * newYearInBratislava.getMonth() => 0;
    +   * newYearInBratislava.getDate() => 1;
    +   * newYearInBratislava.getHours() => 0;
    +   * newYearInBratislava.getMinutes() => 0;
    +   * newYearInBratislava.getSeconds() => 0;
    +   * 
    + * + */ + angular.mock.TzDate = function (offset, timestamp) { + var self = new Date(0); + if (angular.isString(timestamp)) { + var tsStr = timestamp; + + self.origDate = jsonStringToDate(timestamp); + + timestamp = self.origDate.getTime(); + if (isNaN(timestamp)) + throw { + name: "Illegal Argument", + message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string" + }; + } else { + self.origDate = new Date(timestamp); + } + + var localOffset = new Date(timestamp).getTimezoneOffset(); + self.offsetDiff = localOffset*60*1000 - offset*1000*60*60; + self.date = new Date(timestamp + self.offsetDiff); + + self.getTime = function() { + return self.date.getTime() - self.offsetDiff; + }; + + self.toLocaleDateString = function() { + return self.date.toLocaleDateString(); + }; + + self.getFullYear = function() { + return self.date.getFullYear(); + }; + + self.getMonth = function() { + return self.date.getMonth(); + }; + + self.getDate = function() { + return self.date.getDate(); + }; + + self.getHours = function() { + return self.date.getHours(); + }; + + self.getMinutes = function() { + return self.date.getMinutes(); + }; + + self.getSeconds = function() { + return self.date.getSeconds(); + }; + + self.getMilliseconds = function() { + return self.date.getMilliseconds(); + }; + + self.getTimezoneOffset = function() { + return offset * 60; + }; + + self.getUTCFullYear = function() { + return self.origDate.getUTCFullYear(); + }; + + self.getUTCMonth = function() { + return self.origDate.getUTCMonth(); + }; + + self.getUTCDate = function() { + return self.origDate.getUTCDate(); + }; + + self.getUTCHours = function() { + return self.origDate.getUTCHours(); + }; + + self.getUTCMinutes = function() { + return self.origDate.getUTCMinutes(); + }; + + self.getUTCSeconds = function() { + return self.origDate.getUTCSeconds(); + }; + + self.getUTCMilliseconds = function() { + return self.origDate.getUTCMilliseconds(); + }; + + self.getDay = function() { + return self.date.getDay(); + }; + + // provide this method only on browsers that already have it + if (self.toISOString) { + self.toISOString = function() { + return padNumber(self.origDate.getUTCFullYear(), 4) + '-' + + padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' + + padNumber(self.origDate.getUTCDate(), 2) + 'T' + + padNumber(self.origDate.getUTCHours(), 2) + ':' + + padNumber(self.origDate.getUTCMinutes(), 2) + ':' + + padNumber(self.origDate.getUTCSeconds(), 2) + '.' + + padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z' + } + } + + //hide all methods not implemented in this mock that the Date prototype exposes + var unimplementedMethods = ['getUTCDay', + 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', + 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', + 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', + 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString', + 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; + + angular.forEach(unimplementedMethods, function(methodName) { + self[methodName] = function() { + throw Error("Method '" + methodName + "' is not implemented in the TzDate mock"); + }; + }); + + return self; + }; + + //make "tzDateInstance instanceof Date" return true + angular.mock.TzDate.prototype = Date.prototype; +})(); + +angular.mock.animate = angular.module('mock.animate', ['ng']) + + .config(['$provide', function($provide) { + + $provide.decorator('$animate', function($delegate) { + var animate = { + queue : [], + enabled : $delegate.enabled, + flushNext : function(name) { + var tick = animate.queue.shift(); + expect(tick.method).toBe(name); + tick.fn(); + return tick; + } + }; + + forEach(['enter','leave','move','addClass','removeClass'], function(method) { + animate[method] = function() { + var params = arguments; + animate.queue.push({ + method : method, + params : params, + element : angular.isElement(params[0]) && params[0], + parent : angular.isElement(params[1]) && params[1], + after : angular.isElement(params[2]) && params[2], + fn : function() { + $delegate[method].apply($delegate, params); + } + }); + }; + }); + + return animate; + }); + + }]); + + +/** + * @ngdoc function + * @name angular.mock.dump + * @description + * + * *NOTE*: this is not an injectable instance, just a globally available function. + * + * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for debugging. + * + * This method is also available on window, where it can be used to display objects on debug console. + * + * @param {*} object - any object to turn into string. + * @return {string} a serialized string of the argument + */ +angular.mock.dump = function(object) { + return serialize(object); + + function serialize(object) { + var out; + + if (angular.isElement(object)) { + object = angular.element(object); + out = angular.element('
    '); + angular.forEach(object, function(element) { + out.append(angular.element(element).clone()); + }); + out = out.html(); + } else if (angular.isArray(object)) { + out = []; + angular.forEach(object, function(o) { + out.push(serialize(o)); + }); + out = '[ ' + out.join(', ') + ' ]'; + } else if (angular.isObject(object)) { + if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) { + out = serializeScope(object); + } else if (object instanceof Error) { + out = object.stack || ('' + object.name + ': ' + object.message); + } else { + // TODO(i): this prevents methods to be logged, we should have a better way to serialize objects + out = angular.toJson(object, true); + } + } else { + out = String(object); + } + + return out; + } + + function serializeScope(scope, offset) { + offset = offset || ' '; + var log = [offset + 'Scope(' + scope.$id + '): {']; + for ( var key in scope ) { + if (scope.hasOwnProperty(key) && !key.match(/^(\$|this)/)) { + log.push(' ' + key + ': ' + angular.toJson(scope[key])); + } + } + var child = scope.$$childHead; + while(child) { + log.push(serializeScope(child, offset + ' ')); + child = child.$$nextSibling; + } + log.push('}'); + return log.join('\n' + offset); + } +}; + +/** + * @ngdoc object + * @name ngMock.$httpBackend + * @description + * Fake HTTP backend implementation suitable for unit testing applications that use the + * {@link ng.$http $http service}. + * + * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less + * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}. + * + * During unit testing, we want our unit tests to run quickly and have no external dependencies so + * we don’t want to send {@link https://developer.mozilla.org/en/xmlhttprequest XHR} or + * {@link http://en.wikipedia.org/wiki/JSONP JSONP} requests to a real server. All we really need is + * to verify whether a certain request has been sent or not, or alternatively just let the + * application make requests, respond with pre-trained responses and assert that the end result is + * what we expect it to be. + * + * This mock implementation can be used to respond with static or dynamic responses via the + * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc). + * + * When an Angular application needs some data from a server, it calls the $http service, which + * sends the request to a real server using $httpBackend service. With dependency injection, it is + * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify + * the requests and respond with some testing data without sending a request to real server. + * + * There are two ways to specify what test data should be returned as http responses by the mock + * backend when the code under test makes http requests: + * + * - `$httpBackend.expect` - specifies a request expectation + * - `$httpBackend.when` - specifies a backend definition + * + * + * # Request Expectations vs Backend Definitions + * + * Request expectations provide a way to make assertions about requests made by the application and + * to define responses for those requests. The test will fail if the expected requests are not made + * or they are made in the wrong order. + * + * Backend definitions allow you to define a fake backend for your application which doesn't assert + * if a particular request was made or not, it just returns a trained response if a request is made. + * The test will pass whether or not the request gets made during testing. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Request expectationsBackend definitions
    Syntax.expect(...).respond(...).when(...).respond(...)
    Typical usagestrict unit testsloose (black-box) unit testing
    Fulfills multiple requestsNOYES
    Order of requests mattersYESNO
    Request requiredYESNO
    Response requiredoptional (see below)YES
    + * + * In cases where both backend definitions and request expectations are specified during unit + * testing, the request expectations are evaluated first. + * + * If a request expectation has no response specified, the algorithm will search your backend + * definitions for an appropriate response. + * + * If a request didn't match any expectation or if the expectation doesn't have the response + * defined, the backend definitions are evaluated in sequential order to see if any of them match + * the request. The response from the first matched definition is returned. + * + * + * # Flushing HTTP requests + * + * The $httpBackend used in production, always responds to requests with responses asynchronously. + * If we preserved this behavior in unit testing, we'd have to create async unit tests, which are + * hard to write, follow and maintain. At the same time the testing mock, can't respond + * synchronously because that would change the execution of the code under test. For this reason the + * mock $httpBackend has a `flush()` method, which allows the test to explicitly flush pending + * requests and thus preserving the async api of the backend, while allowing the test to execute + * synchronously. + * + * + * # Unit testing with mock $httpBackend + * The following code shows how to setup and use the mock backend in unit testing a controller. + * First we create the controller under test + * +
    +  // The controller code
    +  function MyController($scope, $http) {
    +    var authToken;
    +
    +    $http.get('/auth.py').success(function(data, status, headers) {
    +      authToken = headers('A-Token');
    +      $scope.user = data;
    +    });
    +
    +    $scope.saveMessage = function(message) {
    +      var headers = { 'Authorization': authToken };
    +      $scope.status = 'Saving...';
    +
    +      $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) {
    +        $scope.status = '';
    +      }).error(function() {
    +        $scope.status = 'ERROR!';
    +      });
    +    };
    +  }
    +  
    + * + * Now we setup the mock backend and create the test specs. + * +
    +    // testing controller
    +    describe('MyController', function() {
    +       var $httpBackend, $rootScope, createController;
    +
    +       beforeEach(inject(function($injector) {
    +         // Set up the mock http service responses
    +         $httpBackend = $injector.get('$httpBackend');
    +         // backend definition common for all tests
    +         $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
    +
    +         // Get hold of a scope (i.e. the root scope)
    +         $rootScope = $injector.get('$rootScope');
    +         // The $controller service is used to create instances of controllers
    +         var $controller = $injector.get('$controller');
    +
    +         createController = function() {
    +           return $controller('MyController', {'$scope' : $rootScope });
    +         };
    +       }));
    +
    +
    +       afterEach(function() {
    +         $httpBackend.verifyNoOutstandingExpectation();
    +         $httpBackend.verifyNoOutstandingRequest();
    +       });
    +
    +
    +       it('should fetch authentication token', function() {
    +         $httpBackend.expectGET('/auth.py');
    +         var controller = createController();
    +         $httpBackend.flush();
    +       });
    +
    +
    +       it('should send msg to server', function() {
    +         var controller = createController();
    +         $httpBackend.flush();
    +
    +         // now you don’t care about the authentication, but
    +         // the controller will still send the request and
    +         // $httpBackend will respond without you having to
    +         // specify the expectation and response for this request
    +
    +         $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
    +         $rootScope.saveMessage('message content');
    +         expect($rootScope.status).toBe('Saving...');
    +         $httpBackend.flush();
    +         expect($rootScope.status).toBe('');
    +       });
    +
    +
    +       it('should send auth header', function() {
    +         var controller = createController();
    +         $httpBackend.flush();
    +
    +         $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
    +           // check if the header was send, if it wasn't the expectation won't
    +           // match the request and the test will fail
    +           return headers['Authorization'] == 'xxx';
    +         }).respond(201, '');
    +
    +         $rootScope.saveMessage('whatever');
    +         $httpBackend.flush();
    +       });
    +    });
    +   
    + */ +angular.mock.$HttpBackendProvider = function() { + this.$get = ['$rootScope', createHttpBackendMock]; +}; + +/** + * General factory function for $httpBackend mock. + * Returns instance for unit testing (when no arguments specified): + * - passing through is disabled + * - auto flushing is disabled + * + * Returns instance for e2e testing (when `$delegate` and `$browser` specified): + * - passing through (delegating request to real backend) is enabled + * - auto flushing is enabled + * + * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified) + * @param {Object=} $browser Auto-flushing enabled if specified + * @return {Object} Instance of $httpBackend mock + */ +function createHttpBackendMock($rootScope, $delegate, $browser) { + var definitions = [], + expectations = [], + responses = [], + responsesPush = angular.bind(responses, responses.push); + + function createResponse(status, data, headers) { + if (angular.isFunction(status)) return status; + + return function() { + return angular.isNumber(status) + ? [status, data, headers] + : [200, status, data]; + }; + } + + // TODO(vojta): change params to: method, url, data, headers, callback + function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) { + var xhr = new MockXhr(), + expectation = expectations[0], + wasExpected = false; + + function prettyPrint(data) { + return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp) + ? data + : angular.toJson(data); + } + + function wrapResponse(wrapped) { + if (!$browser && timeout && timeout.then) timeout.then(handleTimeout); + + return handleResponse; + + function handleResponse() { + var response = wrapped.response(method, url, data, headers); + xhr.$$respHeaders = response[2]; + callback(response[0], response[1], xhr.getAllResponseHeaders()); + } + + function handleTimeout() { + for (var i = 0, ii = responses.length; i < ii; i++) { + if (responses[i] === handleResponse) { + responses.splice(i, 1); + callback(-1, undefined, ''); + break; + } + } + } + } + + if (expectation && expectation.match(method, url)) { + if (!expectation.matchData(data)) + throw new Error('Expected ' + expectation + ' with different data\n' + + 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data); + + if (!expectation.matchHeaders(headers)) + throw new Error('Expected ' + expectation + ' with different headers\n' + + 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' + prettyPrint(headers)); + + expectations.shift(); + + if (expectation.response) { + responses.push(wrapResponse(expectation)); + return; + } + wasExpected = true; + } + + var i = -1, definition; + while ((definition = definitions[++i])) { + if (definition.match(method, url, data, headers || {})) { + if (definition.response) { + // if $browser specified, we do auto flush all requests + ($browser ? $browser.defer : responsesPush)(wrapResponse(definition)); + } else if (definition.passThrough) { + $delegate(method, url, data, callback, headers, timeout, withCredentials); + } else throw Error('No response defined !'); + return; + } + } + throw wasExpected ? + new Error('No response defined !') : + new Error('Unexpected request: ' + method + ' ' + url + '\n' + + (expectation ? 'Expected ' + expectation : 'No more request expected')); + } + + /** + * @ngdoc method + * @name ngMock.$httpBackend#when + * @methodOf ngMock.$httpBackend + * @description + * Creates a new backend definition. + * + * @param {string} method HTTP method. + * @param {string|RegExp} url HTTP url. + * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives + * data string and returns true if the data is as expected. + * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header + * object and returns true if the headers match the current definition. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + * + * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}` + * – The respond method takes a set of static data to be returned or a function that can return + * an array containing response status (number), response data (string) and response headers + * (Object). + */ + $httpBackend.when = function(method, url, data, headers) { + var definition = new MockHttpExpectation(method, url, data, headers), + chain = { + respond: function(status, data, headers) { + definition.response = createResponse(status, data, headers); + } + }; + + if ($browser) { + chain.passThrough = function() { + definition.passThrough = true; + }; + } + + definitions.push(definition); + return chain; + }; + + /** + * @ngdoc method + * @name ngMock.$httpBackend#whenGET + * @methodOf ngMock.$httpBackend + * @description + * Creates a new backend definition for GET requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(Object|function(Object))=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + */ + + /** + * @ngdoc method + * @name ngMock.$httpBackend#whenHEAD + * @methodOf ngMock.$httpBackend + * @description + * Creates a new backend definition for HEAD requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(Object|function(Object))=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + */ + + /** + * @ngdoc method + * @name ngMock.$httpBackend#whenDELETE + * @methodOf ngMock.$httpBackend + * @description + * Creates a new backend definition for DELETE requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(Object|function(Object))=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + */ + + /** + * @ngdoc method + * @name ngMock.$httpBackend#whenPOST + * @methodOf ngMock.$httpBackend + * @description + * Creates a new backend definition for POST requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives + * data string and returns true if the data is as expected. + * @param {(Object|function(Object))=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + */ + + /** + * @ngdoc method + * @name ngMock.$httpBackend#whenPUT + * @methodOf ngMock.$httpBackend + * @description + * Creates a new backend definition for PUT requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives + * data string and returns true if the data is as expected. + * @param {(Object|function(Object))=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + */ + + /** + * @ngdoc method + * @name ngMock.$httpBackend#whenJSONP + * @methodOf ngMock.$httpBackend + * @description + * Creates a new backend definition for JSONP requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + */ + createShortMethods('when'); + + + /** + * @ngdoc method + * @name ngMock.$httpBackend#expect + * @methodOf ngMock.$httpBackend + * @description + * Creates a new request expectation. + * + * @param {string} method HTTP method. + * @param {string|RegExp} url HTTP url. + * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that + * receives data string and returns true if the data is as expected, or Object if request body + * is in JSON format. + * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header + * object and returns true if the headers match the current expectation. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + * + * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}` + * – The respond method takes a set of static data to be returned or a function that can return + * an array containing response status (number), response data (string) and response headers + * (Object). + */ + $httpBackend.expect = function(method, url, data, headers) { + var expectation = new MockHttpExpectation(method, url, data, headers); + expectations.push(expectation); + return { + respond: function(status, data, headers) { + expectation.response = createResponse(status, data, headers); + } + }; + }; + + + /** + * @ngdoc method + * @name ngMock.$httpBackend#expectGET + * @methodOf ngMock.$httpBackend + * @description + * Creates a new request expectation for GET requests. For more info see `expect()`. + * + * @param {string|RegExp} url HTTP url. + * @param {Object=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. See #expect for more info. + */ + + /** + * @ngdoc method + * @name ngMock.$httpBackend#expectHEAD + * @methodOf ngMock.$httpBackend + * @description + * Creates a new request expectation for HEAD requests. For more info see `expect()`. + * + * @param {string|RegExp} url HTTP url. + * @param {Object=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + */ + + /** + * @ngdoc method + * @name ngMock.$httpBackend#expectDELETE + * @methodOf ngMock.$httpBackend + * @description + * Creates a new request expectation for DELETE requests. For more info see `expect()`. + * + * @param {string|RegExp} url HTTP url. + * @param {Object=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + */ + + /** + * @ngdoc method + * @name ngMock.$httpBackend#expectPOST + * @methodOf ngMock.$httpBackend + * @description + * Creates a new request expectation for POST requests. For more info see `expect()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that + * receives data string and returns true if the data is as expected, or Object if request body + * is in JSON format. + * @param {Object=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + */ + + /** + * @ngdoc method + * @name ngMock.$httpBackend#expectPUT + * @methodOf ngMock.$httpBackend + * @description + * Creates a new request expectation for PUT requests. For more info see `expect()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that + * receives data string and returns true if the data is as expected, or Object if request body + * is in JSON format. + * @param {Object=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + */ + + /** + * @ngdoc method + * @name ngMock.$httpBackend#expectPATCH + * @methodOf ngMock.$httpBackend + * @description + * Creates a new request expectation for PATCH requests. For more info see `expect()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that + * receives data string and returns true if the data is as expected, or Object if request body + * is in JSON format. + * @param {Object=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + */ + + /** + * @ngdoc method + * @name ngMock.$httpBackend#expectJSONP + * @methodOf ngMock.$httpBackend + * @description + * Creates a new request expectation for JSONP requests. For more info see `expect()`. + * + * @param {string|RegExp} url HTTP url. + * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * request is handled. + */ + createShortMethods('expect'); + + + /** + * @ngdoc method + * @name ngMock.$httpBackend#flush + * @methodOf ngMock.$httpBackend + * @description + * Flushes all pending requests using the trained responses. + * + * @param {number=} count Number of responses to flush (in the order they arrived). If undefined, + * all pending requests will be flushed. If there are no pending requests when the flush method + * is called an exception is thrown (as this typically a sign of programming error). + */ + $httpBackend.flush = function(count) { + $rootScope.$digest(); + if (!responses.length) throw Error('No pending request to flush !'); + + if (angular.isDefined(count)) { + while (count--) { + if (!responses.length) throw Error('No more pending request to flush !'); + responses.shift()(); + } + } else { + while (responses.length) { + responses.shift()(); + } + } + $httpBackend.verifyNoOutstandingExpectation(); + }; + + + /** + * @ngdoc method + * @name ngMock.$httpBackend#verifyNoOutstandingExpectation + * @methodOf ngMock.$httpBackend + * @description + * Verifies that all of the requests defined via the `expect` api were made. If any of the + * requests were not made, verifyNoOutstandingExpectation throws an exception. + * + * Typically, you would call this method following each test case that asserts requests using an + * "afterEach" clause. + * + *
    +   *   afterEach($httpBackend.verifyNoOutstandingExpectation);
    +   * 
    + */ + $httpBackend.verifyNoOutstandingExpectation = function() { + $rootScope.$digest(); + if (expectations.length) { + throw new Error('Unsatisfied requests: ' + expectations.join(', ')); + } + }; + + + /** + * @ngdoc method + * @name ngMock.$httpBackend#verifyNoOutstandingRequest + * @methodOf ngMock.$httpBackend + * @description + * Verifies that there are no outstanding requests that need to be flushed. + * + * Typically, you would call this method following each test case that asserts requests using an + * "afterEach" clause. + * + *
    +   *   afterEach($httpBackend.verifyNoOutstandingRequest);
    +   * 
    + */ + $httpBackend.verifyNoOutstandingRequest = function() { + if (responses.length) { + throw Error('Unflushed requests: ' + responses.length); + } + }; + + + /** + * @ngdoc method + * @name ngMock.$httpBackend#resetExpectations + * @methodOf ngMock.$httpBackend + * @description + * Resets all request expectations, but preserves all backend definitions. Typically, you would + * call resetExpectations during a multiple-phase test when you want to reuse the same instance of + * $httpBackend mock. + */ + $httpBackend.resetExpectations = function() { + expectations.length = 0; + responses.length = 0; + }; + + return $httpBackend; + + + function createShortMethods(prefix) { + angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) { + $httpBackend[prefix + method] = function(url, headers) { + return $httpBackend[prefix](method, url, undefined, headers) + } + }); + + angular.forEach(['PUT', 'POST', 'PATCH'], function(method) { + $httpBackend[prefix + method] = function(url, data, headers) { + return $httpBackend[prefix](method, url, data, headers) + } + }); + } +} + +function MockHttpExpectation(method, url, data, headers) { + + this.data = data; + this.headers = headers; + + this.match = function(m, u, d, h) { + if (method != m) return false; + if (!this.matchUrl(u)) return false; + if (angular.isDefined(d) && !this.matchData(d)) return false; + if (angular.isDefined(h) && !this.matchHeaders(h)) return false; + return true; + }; + + this.matchUrl = function(u) { + if (!url) return true; + if (angular.isFunction(url.test)) return url.test(u); + return url == u; + }; + + this.matchHeaders = function(h) { + if (angular.isUndefined(headers)) return true; + if (angular.isFunction(headers)) return headers(h); + return angular.equals(headers, h); + }; + + this.matchData = function(d) { + if (angular.isUndefined(data)) return true; + if (data && angular.isFunction(data.test)) return data.test(d); + if (data && angular.isFunction(data)) return data(d); + if (data && !angular.isString(data)) return angular.toJson(data) == d; + return data == d; + }; + + this.toString = function() { + return method + ' ' + url; + }; +} + +function MockXhr() { + + // hack for testing $http, $httpBackend + MockXhr.$$lastInstance = this; + + this.open = function(method, url, async) { + this.$$method = method; + this.$$url = url; + this.$$async = async; + this.$$reqHeaders = {}; + this.$$respHeaders = {}; + }; + + this.send = function(data) { + this.$$data = data; + }; + + this.setRequestHeader = function(key, value) { + this.$$reqHeaders[key] = value; + }; + + this.getResponseHeader = function(name) { + // the lookup must be case insensitive, that's why we try two quick lookups and full scan at last + var header = this.$$respHeaders[name]; + if (header) return header; + + name = angular.lowercase(name); + header = this.$$respHeaders[name]; + if (header) return header; + + header = undefined; + angular.forEach(this.$$respHeaders, function(headerVal, headerName) { + if (!header && angular.lowercase(headerName) == name) header = headerVal; + }); + return header; + }; + + this.getAllResponseHeaders = function() { + var lines = []; + + angular.forEach(this.$$respHeaders, function(value, key) { + lines.push(key + ': ' + value); + }); + return lines.join('\n'); + }; + + this.abort = angular.noop; +} + + +/** + * @ngdoc function + * @name ngMock.$timeout + * @description + * + * This service is just a simple decorator for {@link ng.$timeout $timeout} service + * that adds a "flush" and "verifyNoPendingTasks" methods. + */ + +angular.mock.$TimeoutDecorator = function($delegate, $browser) { + + /** + * @ngdoc method + * @name ngMock.$timeout#flush + * @methodOf ngMock.$timeout + * @description + * + * Flushes the queue of pending tasks. + * + * @param {number=} delay maximum timeout amount to flush up until + */ + $delegate.flush = function(delay) { + $browser.defer.flush(delay); + }; + + /** + * @ngdoc method + * @name ngMock.$timeout#flushNext + * @methodOf ngMock.$timeout + * @description + * + * Flushes the next timeout in the queue and compares it to the provided delay + * + * @param {number=} expectedDelay the delay value that will be asserted against the delay of the next timeout function + */ + $delegate.flushNext = function(expectedDelay) { + $browser.defer.flushNext(expectedDelay); + }; + + /** + * @ngdoc method + * @name ngMock.$timeout#verifyNoPendingTasks + * @methodOf ngMock.$timeout + * @description + * + * Verifies that there are no pending tasks that need to be flushed. + */ + $delegate.verifyNoPendingTasks = function() { + if ($browser.deferredFns.length) { + throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' + + formatPendingTasksAsString($browser.deferredFns)); + } + }; + + function formatPendingTasksAsString(tasks) { + var result = []; + angular.forEach(tasks, function(task) { + result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}'); + }); + + return result.join(', '); + } + + return $delegate; +}; + +/** + * + */ +angular.mock.$RootElementProvider = function() { + this.$get = function() { + return angular.element('
    '); + } +}; + +/** + * @ngdoc overview + * @name ngMock + * @description + * + * The `ngMock` is an angular module which is used with `ng` module and adds unit-test configuration as well as useful + * mocks to the {@link AUTO.$injector $injector}. + */ +angular.module('ngMock', ['ng']).provider({ + $browser: angular.mock.$BrowserProvider, + $exceptionHandler: angular.mock.$ExceptionHandlerProvider, + $log: angular.mock.$LogProvider, + $httpBackend: angular.mock.$HttpBackendProvider, + $rootElement: angular.mock.$RootElementProvider +}).config(function($provide) { + $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); +}); + +/** + * @ngdoc overview + * @name ngMockE2E + * @description + * + * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing. + * Currently there is only one mock present in this module - + * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock. + */ +angular.module('ngMockE2E', ['ng']).config(function($provide) { + $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); +}); + +/** + * @ngdoc object + * @name ngMockE2E.$httpBackend + * @description + * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of + * applications that use the {@link ng.$http $http service}. + * + * *Note*: For fake http backend implementation suitable for unit testing please see + * {@link ngMock.$httpBackend unit-testing $httpBackend mock}. + * + * This implementation can be used to respond with static or dynamic responses via the `when` api + * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the + * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch + * templates from a webserver). + * + * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application + * is being developed with the real backend api replaced with a mock, it is often desirable for + * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch + * templates or static files from the webserver). To configure the backend with this behavior + * use the `passThrough` request handler of `when` instead of `respond`. + * + * Additionally, we don't want to manually have to flush mocked out requests like we do during unit + * testing. For this reason the e2e $httpBackend automatically flushes mocked out requests + * automatically, closely simulating the behavior of the XMLHttpRequest object. + * + * To setup the application to run with this http backend, you have to create a module that depends + * on the `ngMockE2E` and your application modules and defines the fake backend: + * + *
    + *   myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
    + *   myAppDev.run(function($httpBackend) {
    + *     phones = [{name: 'phone1'}, {name: 'phone2'}];
    + *
    + *     // returns the current list of phones
    + *     $httpBackend.whenGET('/phones').respond(phones);
    + *
    + *     // adds a new phone to the phones array
    + *     $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
    + *       phones.push(angular.fromJson(data));
    + *     });
    + *     $httpBackend.whenGET(/^\/templates\//).passThrough();
    + *     //...
    + *   });
    + * 
    + * + * Afterwards, bootstrap your app with this new module. + */ + +/** + * @ngdoc method + * @name ngMockE2E.$httpBackend#when + * @methodOf ngMockE2E.$httpBackend + * @description + * Creates a new backend definition. + * + * @param {string} method HTTP method. + * @param {string|RegExp} url HTTP url. + * @param {(string|RegExp)=} data HTTP request body. + * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header + * object and returns true if the headers match the current definition. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. + * + * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}` + * – The respond method takes a set of static data to be returned or a function that can return + * an array containing response status (number), response data (string) and response headers + * (Object). + * - passThrough – `{function()}` – Any request matching a backend definition with `passThrough` + * handler, will be pass through to the real backend (an XHR request will be made to the + * server. + */ + +/** + * @ngdoc method + * @name ngMockE2E.$httpBackend#whenGET + * @methodOf ngMockE2E.$httpBackend + * @description + * Creates a new backend definition for GET requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(Object|function(Object))=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. + */ + +/** + * @ngdoc method + * @name ngMockE2E.$httpBackend#whenHEAD + * @methodOf ngMockE2E.$httpBackend + * @description + * Creates a new backend definition for HEAD requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(Object|function(Object))=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. + */ + +/** + * @ngdoc method + * @name ngMockE2E.$httpBackend#whenDELETE + * @methodOf ngMockE2E.$httpBackend + * @description + * Creates a new backend definition for DELETE requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(Object|function(Object))=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. + */ + +/** + * @ngdoc method + * @name ngMockE2E.$httpBackend#whenPOST + * @methodOf ngMockE2E.$httpBackend + * @description + * Creates a new backend definition for POST requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(string|RegExp)=} data HTTP request body. + * @param {(Object|function(Object))=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. + */ + +/** + * @ngdoc method + * @name ngMockE2E.$httpBackend#whenPUT + * @methodOf ngMockE2E.$httpBackend + * @description + * Creates a new backend definition for PUT requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(string|RegExp)=} data HTTP request body. + * @param {(Object|function(Object))=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. + */ + +/** + * @ngdoc method + * @name ngMockE2E.$httpBackend#whenPATCH + * @methodOf ngMockE2E.$httpBackend + * @description + * Creates a new backend definition for PATCH requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @param {(string|RegExp)=} data HTTP request body. + * @param {(Object|function(Object))=} headers HTTP headers. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. + */ + +/** + * @ngdoc method + * @name ngMockE2E.$httpBackend#whenJSONP + * @methodOf ngMockE2E.$httpBackend + * @description + * Creates a new backend definition for JSONP requests. For more info see `when()`. + * + * @param {string|RegExp} url HTTP url. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. + */ +angular.mock.e2e = {}; +angular.mock.e2e.$httpBackendDecorator = ['$rootScope', '$delegate', '$browser', createHttpBackendMock]; + + +angular.mock.clearDataCache = function() { + var key, + cache = angular.element.cache; + + for(key in cache) { + if (cache.hasOwnProperty(key)) { + var handle = cache[key].handle; + + handle && angular.element(handle.elem).off(); + delete cache[key]; + } + } +}; + + + +(window.jasmine || window.mocha) && (function(window) { + + var currentSpec = null; + + beforeEach(function() { + currentSpec = this; + }); + + afterEach(function() { + var injector = currentSpec.$injector; + + currentSpec.$injector = null; + currentSpec.$modules = null; + currentSpec = null; + + if (injector) { + injector.get('$rootElement').off(); + injector.get('$browser').pollFns.length = 0; + } + + angular.mock.clearDataCache(); + + // clean up jquery's fragment cache + angular.forEach(angular.element.fragments, function(val, key) { + delete angular.element.fragments[key]; + }); + + MockXhr.$$lastInstance = null; + + angular.forEach(angular.callbacks, function(val, key) { + delete angular.callbacks[key]; + }); + angular.callbacks.counter = 0; + }); + + function isSpecRunning() { + return currentSpec && (window.mocha || currentSpec.queue.running); + } + + /** + * @ngdoc function + * @name angular.mock.module + * @description + * + * *NOTE*: This function is also published on window for easy access.
    + * + * This function registers a module configuration code. It collects the configuration information + * which will be used when the injector is created by {@link angular.mock.inject inject}. + * + * See {@link angular.mock.inject inject} for usage example + * + * @param {...(string|Function|Object)} fns any number of modules which are represented as string + * aliases or as anonymous module initialization functions. The modules are used to + * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an + * object literal is passed they will be register as values in the module, the key being + * the module name and the value being what is returned. + */ + window.module = angular.mock.module = function() { + var moduleFns = Array.prototype.slice.call(arguments, 0); + return isSpecRunning() ? workFn() : workFn; + ///////////////////// + function workFn() { + if (currentSpec.$injector) { + throw Error('Injector already created, can not register a module!'); + } else { + var modules = currentSpec.$modules || (currentSpec.$modules = []); + angular.forEach(moduleFns, function(module) { + if (angular.isObject(module) && !angular.isArray(module)) { + modules.push(function($provide) { + angular.forEach(module, function(value, key) { + $provide.value(key, value); + }); + }); + } else { + modules.push(module); + } + }); + } + } + }; + + /** + * @ngdoc function + * @name angular.mock.inject + * @description + * + * *NOTE*: This function is also published on window for easy access.
    + * + * The inject function wraps a function into an injectable function. The inject() creates new + * instance of {@link AUTO.$injector $injector} per test, which is then used for + * resolving references. + * + * See also {@link angular.mock.module module} + * + * Example of what a typical jasmine tests looks like with the inject method. + *
    +   *
    +   *   angular.module('myApplicationModule', [])
    +   *       .value('mode', 'app')
    +   *       .value('version', 'v1.0.1');
    +   *
    +   *
    +   *   describe('MyApp', function() {
    +   *
    +   *     // You need to load modules that you want to test,
    +   *     // it loads only the "ng" module by default.
    +   *     beforeEach(module('myApplicationModule'));
    +   *
    +   *
    +   *     // inject() is used to inject arguments of all given functions
    +   *     it('should provide a version', inject(function(mode, version) {
    +   *       expect(version).toEqual('v1.0.1');
    +   *       expect(mode).toEqual('app');
    +   *     }));
    +   *
    +   *
    +   *     // The inject and module method can also be used inside of the it or beforeEach
    +   *     it('should override a version and test the new version is injected', function() {
    +   *       // module() takes functions or strings (module aliases)
    +   *       module(function($provide) {
    +   *         $provide.value('version', 'overridden'); // override version here
    +   *       });
    +   *
    +   *       inject(function(version) {
    +   *         expect(version).toEqual('overridden');
    +   *       });
    +   *     ));
    +   *   });
    +   *
    +   * 
    + * + * @param {...Function} fns any number of functions which will be injected using the injector. + */ + window.inject = angular.mock.inject = function() { + var blockFns = Array.prototype.slice.call(arguments, 0); + var errorForStack = new Error('Declaration Location'); + return isSpecRunning() ? workFn() : workFn; + ///////////////////// + function workFn() { + var modules = currentSpec.$modules || []; + + modules.unshift('ngMock'); + modules.unshift('ng'); + var injector = currentSpec.$injector; + if (!injector) { + injector = currentSpec.$injector = angular.injector(modules); + } + for(var i = 0, ii = blockFns.length; i < ii; i++) { + try { + injector.invoke(blockFns[i] || angular.noop, this); + } catch (e) { + if(e.stack && errorForStack) e.stack += '\n' + errorForStack.stack; + throw e; + } finally { + errorForStack = null; + } + } + } + }; +})(window); diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-resource.js b/web-ui/src/main/resources/catalog/lib/angular/angular-resource.js new file mode 100644 index 00000000000..8f3f7af0c29 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-resource.js @@ -0,0 +1,549 @@ +/** + * @license AngularJS v1.2.0-rc.2 + * (c) 2010-2012 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, angular, undefined) {'use strict'; + +var $resourceMinErr = angular.$$minErr('$resource'); + +/** + * @ngdoc overview + * @name ngResource + * @description + * + * # ngResource + * + * `ngResource` is the name of the optional Angular module that adds support for interacting with + * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. + * `ngReource` provides the {@link ngResource.$resource `$resource`} serivce. + * + * {@installModule resource} + * + * See {@link ngResource.$resource `$resource`} for usage. + */ + +/** + * @ngdoc object + * @name ngResource.$resource + * @requires $http + * + * @description + * A factory which creates a resource object that lets you interact with + * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. + * + * The returned resource object has action methods which provide high-level behaviors without + * the need to interact with the low level {@link ng.$http $http} service. + * + * Requires the {@link ngResource `ngResource`} module to be installed. + * + * @param {string} url A parametrized URL template with parameters prefixed by `:` as in + * `/user/:username`. If you are using a URL with a port number (e.g. + * `http://example.com:8080/api`), it will be respected. + * + * If you are using a url with a suffix, just add the suffix, like this: + * `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')` + * or even `$resource('http://example.com/resource/:resource_id.:format')` + * If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be + * collapsed down to a single `.`. If you need this sequence to appear and not collapse then you + * can escape it with `/\.`. + * + * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in + * `actions` methods. If any of the parameter value is a function, it will be executed every time + * when a param value needs to be obtained for a request (unless the param was overridden). + * + * Each key value in the parameter object is first bound to url template if present and then any + * excess keys are appended to the url search query after the `?`. + * + * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in + * URL `/path/greet?salutation=Hello`. + * + * If the parameter value is prefixed with `@` then the value of that parameter is extracted from + * the data object (useful for non-GET operations). + * + * @param {Object.=} actions Hash with declaration of custom action that should extend the + * default set of resource actions. The declaration should be created in the format of {@link + * ng.$http#Parameters $http.config}: + * + * {action1: {method:?, params:?, isArray:?, headers:?, ...}, + * action2: {method:?, params:?, isArray:?, headers:?, ...}, + * ...} + * + * Where: + * + * - **`action`** – {string} – The name of action. This name becomes the name of the method on your + * resource object. + * - **`method`** – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`, + * and `JSONP`. + * - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of the + * parameter value is a function, it will be executed every time when a param value needs to be + * obtained for a request (unless the param was overridden). + * - **`url`** – {string} – action specific `url` override. The url templating is supported just like + * for the resource-level urls. + * - **`isArray`** – {boolean=} – If true then the returned object for this action is an array, see + * `returns` section. + * - **`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 to set the `withCredentials` flag on the + * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 + * requests with credentials} for more information. + * - **`responseType`** - `{string}` - see {@link + * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}. + * - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods - + * `response` and `responseError`. Both `response` and `responseError` interceptors get called + * with `http response` object. See {@link ng.$http $http interceptors}. + * + * @returns {Object} A resource "class" object with methods for the default set of resource actions + * optionally extended with custom `actions`. The default set contains these actions: + * + * { 'get': {method:'GET'}, + * 'save': {method:'POST'}, + * 'query': {method:'GET', isArray:true}, + * 'remove': {method:'DELETE'}, + * 'delete': {method:'DELETE'} }; + * + * Calling these methods invoke an {@link ng.$http} with the specified http method, + * destination and parameters. When the data is returned from the server then the object is an + * instance of the resource class. The actions `save`, `remove` and `delete` are available on it + * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create, + * read, update, delete) on server-side data like this: + *
    +        var User = $resource('/user/:userId', {userId:'@id'});
    +        var user = User.get({userId:123}, function() {
    +          user.abc = true;
    +          user.$save();
    +        });
    +     
    + * + * It is important to realize that invoking a $resource object method immediately returns an + * empty reference (object or array depending on `isArray`). Once the data is returned from the + * server the existing reference is populated with the actual data. This is a useful trick since + * usually the resource is assigned to a model which is then rendered by the view. Having an empty + * object results in no rendering, once the data arrives from the server then the object is + * populated with the data and the view automatically re-renders itself showing the new data. This + * means that in most case one never has to write a callback function for the action methods. + * + * The action methods on the class object or instance object can be invoked with the following + * parameters: + * + * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` + * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])` + * - non-GET instance actions: `instance.$action([parameters], [success], [error])` + * + * Success callback is called with (value, responseHeaders) arguments. Error callback is called + * with (httpResponse) argument. + * + * Class actions return empty instance (with additional properties below). + * Instance actions return promise of the action. + * + * The Resource instances and collection have these additional properties: + * + * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this + * instance or collection. + * + * On success, the promise is resolved with the same resource instance or collection object, + * updated with data from server. This makes it easy to use in + * {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view rendering + * until the resource(s) are loaded. + * + * On failure, the promise is resolved with the {@link ng.$http http response} object, + * without the `resource` property. + * + * - `$resolved`: `true` after first server interaction is completed (either with success or rejection), + * `false` before that. Knowing if the Resource has been resolved is useful in data-binding. + * + * @example + * + * # Credit card resource + * + *
    +     // Define CreditCard class
    +     var CreditCard = $resource('/user/:userId/card/:cardId',
    +      {userId:123, cardId:'@id'}, {
    +       charge: {method:'POST', params:{charge:true}}
    +      });
    +
    +     // We can retrieve a collection from the server
    +     var cards = CreditCard.query(function() {
    +       // GET: /user/123/card
    +       // server returns: [ {id:456, number:'1234', name:'Smith'} ];
    +
    +       var card = cards[0];
    +       // each item is an instance of CreditCard
    +       expect(card instanceof CreditCard).toEqual(true);
    +       card.name = "J. Smith";
    +       // non GET methods are mapped onto the instances
    +       card.$save();
    +       // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
    +       // server returns: {id:456, number:'1234', name: 'J. Smith'};
    +
    +       // our custom method is mapped as well.
    +       card.$charge({amount:9.99});
    +       // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
    +     });
    +
    +     // we can create an instance as well
    +     var newCard = new CreditCard({number:'0123'});
    +     newCard.name = "Mike Smith";
    +     newCard.$save();
    +     // POST: /user/123/card {number:'0123', name:'Mike Smith'}
    +     // server returns: {id:789, number:'01234', name: 'Mike Smith'};
    +     expect(newCard.id).toEqual(789);
    + * 
    + * + * The object returned from this function execution is a resource "class" which has "static" method + * for each action in the definition. + * + * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and `headers`. + * When the data is returned from the server then the object is an instance of the resource type and + * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD + * operations (create, read, update, delete) on server-side data. + +
    +     var User = $resource('/user/:userId', {userId:'@id'});
    +     var user = User.get({userId:123}, function() {
    +       user.abc = true;
    +       user.$save();
    +     });
    +   
    + * + * It's worth noting that the success callback for `get`, `query` and other method gets passed + * in the response that came from the server as well as $http header getter function, so one + * could rewrite the above example and get access to http headers as: + * +
    +     var User = $resource('/user/:userId', {userId:'@id'});
    +     User.get({userId:123}, function(u, getResponseHeaders){
    +       u.abc = true;
    +       u.$save(function(u, putResponseHeaders) {
    +         //u => saved user object
    +         //putResponseHeaders => $http header getter
    +       });
    +     });
    +   
    + + * # Buzz client + + Let's look at what a buzz client created with the `$resource` service looks like: + + + + +
    + + +
    +
    +

    + + {{item.actor.name}} + Expand replies: {{item.links.replies[0].count}} +

    + {{item.object.content | html}} +
    + + {{reply.actor.name}}: {{reply.content | html}} +
    +
    +
    +
    + + +
    + */ +angular.module('ngResource', ['ng']). + factory('$resource', ['$http', '$parse', '$q', function($http, $parse, $q) { + var DEFAULT_ACTIONS = { + 'get': {method:'GET'}, + 'save': {method:'POST'}, + 'query': {method:'GET', isArray:true}, + 'remove': {method:'DELETE'}, + 'delete': {method:'DELETE'} + }; + var noop = angular.noop, + forEach = angular.forEach, + extend = angular.extend, + copy = angular.copy, + isFunction = angular.isFunction, + getter = function(obj, path) { + return $parse(path)(obj); + }; + + /** + * 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' : '+')); + } + + function Route(template, defaults) { + this.template = template; + this.defaults = defaults || {}; + this.urlParams = {}; + } + + Route.prototype = { + setUrlParams: function(config, params, actionUrl) { + var self = this, + url = actionUrl || self.template, + val, + encodedVal; + + var urlParams = self.urlParams = {}; + forEach(url.split(/\W/), function(param){ + if (!(new RegExp("^\\d+$").test(param)) && param && (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) { + urlParams[param] = true; + } + }); + url = url.replace(/\\:/g, ':'); + + params = params || {}; + forEach(self.urlParams, function(_, urlParam){ + val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; + if (angular.isDefined(val) && val !== null) { + encodedVal = encodeUriSegment(val); + url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), encodedVal + "$1"); + } else { + url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match, + leadingSlashes, tail) { + if (tail.charAt(0) == '/') { + return tail; + } else { + return leadingSlashes + tail; + } + }); + } + }); + + // strip trailing slashes and set the url + url = url.replace(/\/+$/, ''); + // then replace collapse `/.` if found in the last URL path segment before the query + // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x` + url = url.replace(/\/\.(?=\w+($|\?))/, '.'); + // replace escaped `/\.` with `/.` + config.url = url.replace(/\/\\\./, '/.'); + + + // set params - delegate param encoding to $http + forEach(params, function(value, key){ + if (!self.urlParams[key]) { + config.params = config.params || {}; + config.params[key] = value; + } + }); + } + }; + + + function ResourceFactory(url, paramDefaults, actions) { + var route = new Route(url); + + actions = extend({}, DEFAULT_ACTIONS, actions); + + function extractParams(data, actionParams){ + var ids = {}; + actionParams = extend({}, paramDefaults, actionParams); + forEach(actionParams, function(value, key){ + if (isFunction(value)) { value = value(); } + ids[key] = value && value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; + }); + return ids; + } + + function defaultResponseInterceptor(response) { + return response.resource; + } + + function Resource(value){ + copy(value || {}, this); + } + + forEach(actions, function(action, name) { + var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method); + + Resource[name] = function(a1, a2, a3, a4) { + var params = {}, data, success, error; + + switch(arguments.length) { + case 4: + error = a4; + success = a3; + //fallthrough + case 3: + case 2: + if (isFunction(a2)) { + if (isFunction(a1)) { + success = a1; + error = a2; + break; + } + + success = a2; + error = a3; + //fallthrough + } else { + params = a1; + data = a2; + success = a3; + break; + } + case 1: + if (isFunction(a1)) success = a1; + else if (hasBody) data = a1; + else params = a1; + break; + case 0: break; + default: + throw $resourceMinErr('badargs', + "Expected up to 4 arguments [params, data, success, error], got {0} arguments", arguments.length); + } + + var isInstanceCall = data instanceof Resource; + var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data)); + var httpConfig = {}; + var responseInterceptor = action.interceptor && action.interceptor.response || defaultResponseInterceptor; + var responseErrorInterceptor = action.interceptor && action.interceptor.responseError || undefined; + + forEach(action, function(value, key) { + if (key != 'params' && key != 'isArray' && key != 'interceptor') { + httpConfig[key] = copy(value); + } + }); + + httpConfig.data = data; + route.setUrlParams(httpConfig, extend({}, extractParams(data, action.params || {}), params), action.url); + + var promise = $http(httpConfig).then(function(response) { + var data = response.data, + promise = value.$promise; + + if (data) { + if ( angular.isArray(data) != !!action.isArray ) { + throw $resourceMinErr('badcfg', 'Error in resource configuration. Expected response' + + ' to contain an {0} but got an {1}', + action.isArray?'array':'object', angular.isArray(data)?'array':'object'); + } + if (action.isArray) { + value.length = 0; + forEach(data, function(item) { + value.push(new Resource(item)); + }); + } else { + copy(data, value); + value.$promise = promise; + } + } + + value.$resolved = true; + + (success||noop)(value, response.headers); + + response.resource = value; + + return response; + }, function(response) { + value.$resolved = true; + + (error||noop)(response); + + return $q.reject(response); + }).then(responseInterceptor, responseErrorInterceptor); + + + if (!isInstanceCall) { + // we are creating instance / collection + // - set the initial promise + // - return the instance / collection + value.$promise = promise; + value.$resolved = false; + + return value; + } + + // instance call + return promise; + }; + + + Resource.prototype['$' + name] = function(params, success, error) { + if (isFunction(params)) { + error = success; success = params; params = {}; + } + var result = Resource[name](params, this, success, error); + return result.$promise || result; + }; + }); + + Resource.bind = function(additionalParamDefaults){ + return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); + }; + + return Resource; + } + + return ResourceFactory; + }]); + + +})(window, window.angular); diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-resource.min.js b/web-ui/src/main/resources/catalog/lib/angular/angular-resource.min.js new file mode 100644 index 00000000000..f8ccf9d4661 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-resource.min.js @@ -0,0 +1,14 @@ +/* + AngularJS v1.2.0-rc.2 + (c) 2010-2012 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(H,g,C){'use strict';var A=g.$$minErr("$resource");g.module("ngResource",["ng"]).factory("$resource",["$http","$parse","$q",function(D,y,E){function n(g,h){this.template=g;this.defaults=h||{};this.urlParams={}}function u(l,h,d){function p(c,b){var e={};b=v({},h,b);q(b,function(a,b){t(a)&&(a=a());var m;a&&a.charAt&&"@"==a.charAt(0)?(m=a.substr(1),m=y(m)(c)):m=a;e[b]=m});return e}function b(c){return c.resource}function e(c){z(c||{},this)}var F=new n(l);d=v({},G,d);q(d,function(c,f){var h= +/^(POST|PUT|PATCH)$/i.test(c.method);e[f]=function(a,f,m,l){var d={},r,s,w;switch(arguments.length){case 4:w=l,s=m;case 3:case 2:if(t(f)){if(t(a)){s=a;w=f;break}s=f;w=m}else{d=a;r=f;s=m;break}case 1:t(a)?s=a:h?r=a:d=a;break;case 0:break;default:throw A("badargs",arguments.length);}var n=r instanceof e,k=n?r:c.isArray?[]:new e(r),x={},u=c.interceptor&&c.interceptor.response||b,y=c.interceptor&&c.interceptor.responseError||C;q(c,function(a,c){"params"!=c&&("isArray"!=c&&"interceptor"!=c)&&(x[c]=z(a))}); +x.data=r;F.setUrlParams(x,v({},p(r,c.params||{}),d),c.url);d=D(x).then(function(a){var b=a.data,f=k.$promise;if(b){if(g.isArray(b)!=!!c.isArray)throw A("badcfg",c.isArray?"array":"object",g.isArray(b)?"array":"object");c.isArray?(k.length=0,q(b,function(a){k.push(new e(a))})):(z(b,k),k.$promise=f)}k.$resolved=!0;(s||B)(k,a.headers);a.resource=k;return a},function(a){k.$resolved=!0;(w||B)(a);return E.reject(a)}).then(u,y);return n?d:(k.$promise=d,k.$resolved=!1,k)};e.prototype["$"+f]=function(a,c, +b){t(a)&&(b=c,c=a,a={});a=e[f](a,this,c,b);return a.$promise||a}});e.bind=function(c){return u(l,v({},h,c),d)};return e}var G={get:{method:"GET"},save:{method:"POST"},query:{method:"GET",isArray:!0},remove:{method:"DELETE"},"delete":{method:"DELETE"}},B=g.noop,q=g.forEach,v=g.extend,z=g.copy,t=g.isFunction;n.prototype={setUrlParams:function(l,h,d){var p=this,b=d||p.template,e,n,c=p.urlParams={};q(b.split(/\W/),function(f){!/^\d+$/.test(f)&&(f&&RegExp("(^|[^\\\\]):"+f+"(\\W|$)").test(b))&&(c[f]=!0)}); +b=b.replace(/\\:/g,":");h=h||{};q(p.urlParams,function(c,d){e=h.hasOwnProperty(d)?h[d]:p.defaults[d];g.isDefined(e)&&null!==e?(n=encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"%20").replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+"),b=b.replace(RegExp(":"+d+"(\\W|$)","g"),n+"$1")):b=b.replace(RegExp("(/?):"+d+"(\\W|$)","g"),function(a,c,b){return"/"==b.charAt(0)?b:c+b})});b=b.replace(/\/+$/,"");b=b.replace(/\/\.(?=\w+($|\?))/, +".");l.url=b.replace(/\/\\\./,"/.");q(h,function(c,b){p.urlParams[b]||(l.params=l.params||{},l.params[b]=c)})}};return u}])})(window,window.angular); +/* +//@ sourceMappingURL=angular-resource.min.js.map +*/ diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-resource.min.js.map b/web-ui/src/main/resources/catalog/lib/angular/angular-resource.min.js.map new file mode 100644 index 00000000000..dda271c76ac --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-resource.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"angular-resource.min.js", +"lineCount":11, +"mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAkBC,CAAlB,CAA6B,CAEtC,IAAIC,EAAkBF,CAAAG,SAAA,CAAiB,WAAjB,CAmRtBH,EAAAI,OAAA,CAAe,YAAf,CAA6B,CAAC,IAAD,CAA7B,CAAAC,QAAA,CACU,WADV,CACuB,CAAC,OAAD,CAAU,QAAV,CAAoB,IAApB,CAA0B,QAAQ,CAACC,CAAD,CAAQC,CAAR,CAAgBC,CAAhB,CAAoB,CAwDzEC,QAASA,EAAK,CAACC,CAAD,CAAWC,CAAX,CAAqB,CACjC,IAAAD,SAAA,CAAgBA,CAChB,KAAAC,SAAA,CAAgBA,CAAhB,EAA4B,EAC5B,KAAAC,UAAA,CAAiB,EAHgB,CA2DnCC,QAASA,EAAe,CAACC,CAAD,CAAMC,CAAN,CAAqBC,CAArB,CAA8B,CAKpDC,QAASA,EAAa,CAACC,CAAD,CAAOC,CAAP,CAAoB,CACxC,IAAIC,EAAM,EACVD,EAAA,CAAeE,CAAA,CAAO,EAAP,CAAWN,CAAX,CAA0BI,CAA1B,CACfG,EAAA,CAAQH,CAAR,CAAsB,QAAQ,CAACI,CAAD,CAAQC,CAAR,CAAY,CACpCC,CAAA,CAAWF,CAAX,CAAJ,GAAyBA,CAAzB,CAAiCA,CAAA,EAAjC,CACW,KAAA,CAAAA,EAAA,EAASA,CAAAG,OAAT,EAA4C,GAA5C,EAAyBH,CAAAG,OAAA,CAAa,CAAb,CAAzB,EAAkD,CA/G7D,CA+G6D,CAAA,OAAA,CAAA,CAAA,CA/G7D,CAAA,CAAA,CAAOnB,CAAA,CAAOoB,CAAP,CAAA,CA+GsDC,CA/GtD,CA+GI,EAAkFL,CAAlF,CAAkFA,CAA7FH,EAAA,CAAII,CAAJ,CAAA,CAAW,CAF6B,CAA1C,CAIA,OAAOJ,EAPiC,CAU1CS,QAASA,EAA0B,CAACC,CAAD,CAAW,CAC5C,MAAOA,EAAAC,SADqC,CAI9CC,QAASA,EAAQ,CAACT,CAAD,CAAO,CACtBU,CAAA,CAAKV,CAAL,EAAc,EAAd,CAAkB,IAAlB,CADsB,CAlBxB,IAAIW,EAAQ,IAAIzB,CAAJ,CAAUK,CAAV,CAEZE,EAAA,CAAUK,CAAA,CAAO,EAAP,CAAWc,CAAX,CAA4BnB,CAA5B,CAoBVM,EAAA,CAAQN,CAAR,CAAiB,QAAQ,CAACoB,CAAD,CAASC,CAAT,CAAe,CACtC,IAAIC;AAAU,qBAAAC,KAAA,CAA2BH,CAAAI,OAA3B,CAEdR,EAAA,CAASK,CAAT,CAAA,CAAiB,QAAQ,CAACI,CAAD,CAAKC,CAAL,CAASC,CAAT,CAAaC,CAAb,CAAiB,CAAA,IACpCC,EAAS,EAD2B,CACvB3B,CADuB,CACjB4B,CADiB,CACRC,CAEhC,QAAOC,SAAAC,OAAP,EACA,KAAK,CAAL,CACEF,CACA,CADQH,CACR,CAAAE,CAAA,CAAUH,CAEZ,MAAK,CAAL,CACA,KAAK,CAAL,CACE,GAAIlB,CAAA,CAAWiB,CAAX,CAAJ,CAAoB,CAClB,GAAIjB,CAAA,CAAWgB,CAAX,CAAJ,CAAoB,CAClBK,CAAA,CAAUL,CACVM,EAAA,CAAQL,CACR,MAHkB,CAMpBI,CAAA,CAAUJ,CACVK,EAAA,CAAQJ,CARU,CAApB,IAUO,CACLE,CAAA,CAASJ,CACTvB,EAAA,CAAOwB,CACPI,EAAA,CAAUH,CACV,MAJK,CAMT,KAAK,CAAL,CACMlB,CAAA,CAAWgB,CAAX,CAAJ,CAAoBK,CAApB,CAA8BL,CAA9B,CACSH,CAAJ,CAAapB,CAAb,CAAoBuB,CAApB,CACAI,CADA,CACSJ,CACd,MACF,MAAK,CAAL,CAAQ,KACR,SACE,KAAMvC,EAAA,CAAgB,SAAhB,CAC4E8C,SAAAC,OAD5E,CAAN,CA9BF,CAkCA,IAAIC,EAAiBhC,CAAjBgC,WAAiClB,EAArC,CACIT,EAAQ2B,CAAA,CAAiBhC,CAAjB,CAAyBkB,CAAAe,QAAA,CAAiB,EAAjB,CAAsB,IAAInB,CAAJ,CAAad,CAAb,CAD3D,CAEIkC,EAAa,EAFjB,CAGIC,EAAsBjB,CAAAkB,YAAtBD,EAA4CjB,CAAAkB,YAAAxB,SAA5CuB,EAA2ExB,CAH/E,CAII0B,EAA2BnB,CAAAkB,YAA3BC,EAAiDnB,CAAAkB,YAAAE,cAAjDD,EAAqFtD,CAEzFqB,EAAA,CAAQc,CAAR,CAAgB,QAAQ,CAACb,CAAD,CAAQC,CAAR,CAAa,CACxB,QAAX,EAAIA,CAAJ,GAA8B,SAA9B,EAAuBA,CAAvB,EAAkD,aAAlD,EAA2CA,CAA3C,IACE4B,CAAA,CAAW5B,CAAX,CADF,CACoBS,CAAA,CAAKV,CAAL,CADpB,CADmC,CAArC,CAMA6B;CAAAlC,KAAA,CAAkBA,CAClBgB,EAAAuB,aAAA,CAAmBL,CAAnB,CAA+B/B,CAAA,CAAO,EAAP,CAAWJ,CAAA,CAAcC,CAAd,CAAoBkB,CAAAS,OAApB,EAAqC,EAArC,CAAX,CAAqDA,CAArD,CAA/B,CAA6FT,CAAAtB,IAA7F,CAEI4C,EAAAA,CAAUpD,CAAA,CAAM8C,CAAN,CAAAO,KAAA,CAAuB,QAAQ,CAAC7B,CAAD,CAAW,CAAA,IAClDZ,EAAOY,CAAAZ,KAD2C,CAElDwC,EAAUnC,CAAAqC,SAEd,IAAI1C,CAAJ,CAAU,CACR,GAAKlB,CAAAmD,QAAA,CAAgBjC,CAAhB,CAAL,EAA8B,CAAC,CAACkB,CAAAe,QAAhC,CACE,KAAMjD,EAAA,CAAgB,QAAhB,CAEJkC,CAAAe,QAAA,CAAe,OAAf,CAAuB,QAFnB,CAE6BnD,CAAAmD,QAAA,CAAgBjC,CAAhB,CAAA,CAAsB,OAAtB,CAA8B,QAF3D,CAAN,CAIEkB,CAAAe,QAAJ,EACE5B,CAAA0B,OACA,CADe,CACf,CAAA3B,CAAA,CAAQJ,CAAR,CAAc,QAAQ,CAAC2C,CAAD,CAAO,CAC3BtC,CAAAuC,KAAA,CAAW,IAAI9B,CAAJ,CAAa6B,CAAb,CAAX,CAD2B,CAA7B,CAFF,GAME5B,CAAA,CAAKf,CAAL,CAAWK,CAAX,CACA,CAAAA,CAAAqC,SAAA,CAAiBF,CAPnB,CANQ,CAiBVnC,CAAAwC,UAAA,CAAkB,CAAA,CAEjB,EAAAjB,CAAA,EAASkB,CAAT,EAAezC,CAAf,CAAsBO,CAAAmC,QAAtB,CAEDnC,EAAAC,SAAA,CAAoBR,CAEpB,OAAOO,EA3B+C,CAA1C,CA4BX,QAAQ,CAACA,CAAD,CAAW,CACpBP,CAAAwC,UAAA,CAAkB,CAAA,CAEjB,EAAAhB,CAAA,EAAOiB,CAAP,EAAalC,CAAb,CAED,OAAOtB,EAAA0D,OAAA,CAAUpC,CAAV,CALa,CA5BR,CAAA6B,KAAA,CAkCNN,CAlCM,CAkCeE,CAlCf,CAqCd,OAAKL,EAAL,CAWOQ,CAXP,EAIEnC,CAAAqC,SAGOrC,CAHUmC,CAGVnC,CAFPA,CAAAwC,UAEOxC,CAFW,CAAA,CAEXA,CAAAA,CAPT,CAzFwC,CAwG1CS,EAAAmC,UAAA,CAAmB,GAAnB,CAAyB9B,CAAzB,CAAA,CAAiC,QAAQ,CAACQ,CAAD,CAASC,CAAT;AAAkBC,CAAlB,CAAyB,CAC5DtB,CAAA,CAAWoB,CAAX,CAAJ,GACEE,CAAmC,CAA3BD,CAA2B,CAAlBA,CAAkB,CAARD,CAAQ,CAAAA,CAAA,CAAS,EAD9C,CAGIuB,EAAAA,CAASpC,CAAA,CAASK,CAAT,CAAA,CAAeQ,CAAf,CAAuB,IAAvB,CAA6BC,CAA7B,CAAsCC,CAAtC,CACb,OAAOqB,EAAAR,SAAP,EAA0BQ,CALsC,CA3G5B,CAAxC,CAoHApC,EAAAqC,KAAA,CAAgBC,QAAQ,CAACC,CAAD,CAAyB,CAC/C,MAAO1D,EAAA,CAAgBC,CAAhB,CAAqBO,CAAA,CAAO,EAAP,CAAWN,CAAX,CAA0BwD,CAA1B,CAArB,CAAyEvD,CAAzE,CADwC,CAIjD,OAAOgB,EA/I6C,CAlHtD,IAAIG,EAAkB,KACV,QAAQ,KAAR,CADU,MAEV,QAAQ,MAAR,CAFU,OAGV,QAAQ,KAAR,SAAuB,CAAA,CAAvB,CAHU,QAIV,QAAQ,QAAR,CAJU,CAKpB,QALoB,CAKV,QAAQ,QAAR,CALU,CAAtB,CAOI6B,EAAOhE,CAAAgE,KAPX,CAQI1C,EAAUtB,CAAAsB,QARd,CASID,EAASrB,CAAAqB,OATb,CAUIY,EAAOjC,CAAAiC,KAVX,CAWIR,EAAazB,CAAAyB,WAkDjBhB,EAAA0D,UAAA,CAAkB,cACFV,QAAQ,CAACe,CAAD,CAAS3B,CAAT,CAAiB4B,CAAjB,CAA4B,CAAA,IAC5CC,EAAO,IADqC,CAE5C5D,EAAM2D,CAAN3D,EAAmB4D,CAAAhE,SAFyB,CAG5CiE,CAH4C,CAI5CC,CAJ4C,CAM5ChE,EAAY8D,CAAA9D,UAAZA,CAA6B,EACjCU,EAAA,CAAQR,CAAA+D,MAAA,CAAU,IAAV,CAAR,CAAyB,QAAQ,CAACC,CAAD,CAAO,CAChC,CAAA,OAAAvC,KAAA,CAA0BuC,CAA1B,CAAN,GAA2CA,CAA3C,EAAyDC,MAAJ,CAAW,cAAX,CAA4BD,CAA5B,CAAoC,SAApC,CAAAvC,KAAA,CAAoDzB,CAApD,CAArD,IACIF,CAAA,CAAUkE,CAAV,CADJ,CACuB,CAAA,CADvB,CADsC,CAAxC,CAKAhE;CAAA,CAAMA,CAAAkE,QAAA,CAAY,MAAZ,CAAoB,GAApB,CAENnC,EAAA,CAASA,CAAT,EAAmB,EACnBvB,EAAA,CAAQoD,CAAA9D,UAAR,CAAwB,QAAQ,CAACqE,CAAD,CAAIC,CAAJ,CAAa,CAC3CP,CAAA,CAAM9B,CAAAsC,eAAA,CAAsBD,CAAtB,CAAA,CAAkCrC,CAAA,CAAOqC,CAAP,CAAlC,CAAqDR,CAAA/D,SAAA,CAAcuE,CAAd,CACvDlF,EAAAoF,UAAA,CAAkBT,CAAlB,CAAJ,EAAsC,IAAtC,GAA8BA,CAA9B,EACEC,CACA,CAlCCS,kBAAA,CAiC6BV,CAjC7B,CAAAK,QAAA,CACG,OADH,CACY,GADZ,CAAAA,QAAA,CAEG,OAFH,CAEY,GAFZ,CAAAA,QAAA,CAGG,MAHH,CAGW,GAHX,CAAAA,QAAA,CAIG,OAJH,CAIY,GAJZ,CAAAA,QAAA,CAKG,MALH,CAK8B,KAL9B,CAnBAA,QAAA,CACG,OADH,CACY,GADZ,CAAAA,QAAA,CAEG,OAFH,CAEY,GAFZ,CAAAA,QAAA,CAGG,OAHH,CAGY,GAHZ,CAqDD,CAAAlE,CAAA,CAAMA,CAAAkE,QAAA,CAAgBD,MAAJ,CAAW,GAAX,CAAiBG,CAAjB,CAA4B,SAA5B,CAAuC,GAAvC,CAAZ,CAAyDN,CAAzD,CAAsE,IAAtE,CAFR,EAIE9D,CAJF,CAIQA,CAAAkE,QAAA,CAAgBD,MAAJ,CAAW,OAAX,CAAsBG,CAAtB,CAAiC,SAAjC,CAA4C,GAA5C,CAAZ,CAA8D,QAAQ,CAACI,CAAD,CACxEC,CADwE,CACxDC,CADwD,CAClD,CACxB,MAAsB,GAAtB,EAAIA,CAAA9D,OAAA,CAAY,CAAZ,CAAJ,CACS8D,CADT,CAGSD,CAHT,CAG0BC,CAJF,CADpB,CANmC,CAA7C,CAkBA1E,EAAA,CAAMA,CAAAkE,QAAA,CAAY,MAAZ,CAAoB,EAApB,CAGNlE,EAAA,CAAMA,CAAAkE,QAAA,CAAY,mBAAZ;AAAiC,GAAjC,CAENR,EAAA1D,IAAA,CAAaA,CAAAkE,QAAA,CAAY,QAAZ,CAAsB,IAAtB,CAIb1D,EAAA,CAAQuB,CAAR,CAAgB,QAAQ,CAACtB,CAAD,CAAQC,CAAR,CAAY,CAC7BkD,CAAA9D,UAAA,CAAeY,CAAf,CAAL,GACEgD,CAAA3B,OACA,CADgB2B,CAAA3B,OAChB,EADiC,EACjC,CAAA2B,CAAA3B,OAAA,CAAcrB,CAAd,CAAA,CAAqBD,CAFvB,CADkC,CAApC,CA1CgD,CADlC,CAuMlB,OAAOV,EArQkE,CAAtD,CADvB,CArRsC,CAArC,CAAA,CA+hBEd,MA/hBF,CA+hBUA,MAAAC,QA/hBV;", +"sources":["angular-resource.js"], +"names":["window","angular","undefined","$resourceMinErr","$$minErr","module","factory","$http","$parse","$q","Route","template","defaults","urlParams","ResourceFactory","url","paramDefaults","actions","extractParams","data","actionParams","ids","extend","forEach","value","key","isFunction","charAt","path","obj","defaultResponseInterceptor","response","resource","Resource","copy","route","DEFAULT_ACTIONS","action","name","hasBody","test","method","a1","a2","a3","a4","params","success","error","arguments","length","isInstanceCall","isArray","httpConfig","responseInterceptor","interceptor","responseErrorInterceptor","responseError","setUrlParams","promise","then","$promise","item","push","$resolved","noop","headers","reject","prototype","result","bind","Resource.bind","additionalParamDefaults","config","actionUrl","self","val","encodedVal","split","param","RegExp","replace","_","urlParam","hasOwnProperty","isDefined","encodeURIComponent","match","leadingSlashes","tail"] +} diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-route.js b/web-ui/src/main/resources/catalog/lib/angular/angular-route.js new file mode 100644 index 00000000000..f37116c8752 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-route.js @@ -0,0 +1,871 @@ +/** + * @license AngularJS v1.2.0-rc.2 + * (c) 2010-2012 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, angular, undefined) {'use strict'; + +var copy = angular.copy, + equals = angular.equals, + extend = angular.extend, + forEach = angular.forEach, + isDefined = angular.isDefined, + isFunction = angular.isFunction, + isString = angular.isString, + jqLite = angular.element, + noop = angular.noop, + toJson = angular.toJson; + + +function inherit(parent, extra) { + return extend(new (extend(function() {}, {prototype:parent}))(), extra); +} + +/** + * @ngdoc overview + * @name ngRoute + * @description + * + * # ngRoute + * + * The `ngRoute` module provides routing and deeplinking services and directives for angular apps. + * + * {@installModule route} + * + */ + +var ngRouteModule = angular.module('ngRoute', ['ng']). + provider('$route', $RouteProvider); + +/** + * @ngdoc object + * @name ngRoute.$routeProvider + * @function + * + * @description + * + * Used for configuring routes. See {@link ngRoute.$route $route} for an example. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + */ +function $RouteProvider(){ + var routes = {}; + + /** + * @ngdoc method + * @name ngRoute.$routeProvider#when + * @methodOf ngRoute.$routeProvider + * + * @param {string} path Route path (matched against `$location.path`). If `$location.path` + * contains redundant trailing slash or is missing one, the route will still match and the + * `$location.path` will be updated to add or drop the trailing slash to exactly match the + * route definition. + * + * * `path` can contain named groups starting with a colon (`:name`). All characters up + * to the next slash are matched and stored in `$routeParams` under the given `name` + * when the route matches. + * * `path` can contain named groups starting with a colon and ending with a star (`:name*`). + * All characters are eagerly stored in `$routeParams` under the given `name` + * when the route matches. + * * `path` can contain optional named groups with a question mark (`:name?`). + * + * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match + * `/color/brown/largecode/code/with/slashs/edit` and extract: + * + * * `color: brown` + * * `largecode: code/with/slashs`. + * + * + * @param {Object} route Mapping information to be assigned to `$route.current` on route + * match. + * + * Object properties: + * + * - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly + * created scope or the name of a {@link angular.Module#controller registered controller} + * if passed as a string. + * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be + * published to scope under the `controllerAs` name. + * - `template` – `{string=|function()=}` – html template as a string or a function that + * returns an html template as a string which should be used by {@link + * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. + * This property takes precedence over `templateUrl`. + * + * If `template` is a function, it will be called with the following parameters: + * + * - `{Array.}` - route parameters extracted from the current + * `$location.path()` by applying the current route + * + * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html + * template that should be used by {@link ngRoute.directive:ngView ngView}. + * + * If `templateUrl` is a function, it will be called with the following parameters: + * + * - `{Array.}` - route parameters extracted from the current + * `$location.path()` by applying the current route + * + * - `resolve` - `{Object.=}` - An optional map of dependencies which should + * be injected into the controller. If any of these dependencies are promises, they will be + * resolved and converted to a value before the controller is instantiated and the + * `$routeChangeSuccess` event is fired. The map object is: + * + * - `key` – `{string}`: a name of a dependency to be injected into the controller. + * - `factory` - `{string|function}`: If `string` then it is an alias for a service. + * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} + * and the return value is treated as the dependency. If the result is a promise, it is resolved + * before its value is injected into the controller. Be aware that `ngRoute.$routeParams` will + * still refer to the previous route within these resolve functions. Use `$route.current.params` + * to access the new route parameters, instead. + * + * - `redirectTo` – {(string|function())=} – value to update + * {@link ng.$location $location} path with and trigger route redirection. + * + * If `redirectTo` is a function, it will be called with the following parameters: + * + * - `{Object.}` - route parameters extracted from the current + * `$location.path()` by applying the current route templateUrl. + * - `{string}` - current `$location.path()` + * - `{Object}` - current `$location.search()` + * + * The custom `redirectTo` function is expected to return a string which will be used + * to update `$location.path()` and `$location.search()`. + * + * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search() + * changes. + * + * If the option is set to `false` and url in the browser changes, then + * `$routeUpdate` event is broadcasted on the root scope. + * + * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive + * + * If the option is set to `true`, then the particular route can be matched without being + * case sensitive + * + * @returns {Object} self + * + * @description + * Adds a new route definition to the `$route` service. + */ + this.when = function(path, route) { + routes[path] = extend( + {reloadOnSearch: true}, + route, + path && pathRegExp(path, route) + ); + + // create redirection for trailing slashes + if (path) { + var redirectPath = (path[path.length-1] == '/') + ? path.substr(0, path.length-1) + : path +'/'; + + routes[redirectPath] = extend( + {redirectTo: path}, + pathRegExp(redirectPath, route) + ); + } + + return this; + }; + + /** + * @param path {string} path + * @param opts {Object} options + * @return {?Object} + * + * @description + * Normalizes the given path, returning a regular expression + * and the original path. + * + * Inspired by pathRexp in visionmedia/express/lib/utils.js. + */ + function pathRegExp(path, opts) { + var insensitive = opts.caseInsensitiveMatch, + ret = { + originalPath: path, + regexp: path + }, + keys = ret.keys = []; + + path = path + .replace(/([().])/g, '\\$1') + .replace(/(\/)?:(\w+)([\?|\*])?/g, function(_, slash, key, option){ + var optional = option === '?' ? option : null; + var star = option === '*' ? option : null; + keys.push({ name: key, optional: !!optional }); + slash = slash || ''; + return '' + + (optional ? '' : slash) + + '(?:' + + (optional ? slash : '') + + (star && '(.+)?' || '([^/]+)?') + ')' + + (optional || ''); + }) + .replace(/([\/$\*])/g, '\\$1'); + + ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); + return ret; + } + + /** + * @ngdoc method + * @name ngRoute.$routeProvider#otherwise + * @methodOf ngRoute.$routeProvider + * + * @description + * Sets route definition that will be used on route change when no other route definition + * is matched. + * + * @param {Object} params Mapping information to be assigned to `$route.current`. + * @returns {Object} self + */ + this.otherwise = function(params) { + this.when(null, params); + return this; + }; + + + this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', '$sce', + function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) { + + /** + * @ngdoc object + * @name ngRoute.$route + * @requires $location + * @requires $routeParams + * + * @property {Object} current Reference to the current route definition. + * The route definition contains: + * + * - `controller`: The controller constructor as define in route definition. + * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for + * controller instantiation. The `locals` contain + * the resolved values of the `resolve` map. Additionally the `locals` also contain: + * + * - `$scope` - The current route scope. + * - `$template` - The current route template HTML. + * + * @property {Array.} routes Array of all configured routes. + * + * @description + * `$route` is used for deep-linking URLs to controllers and views (HTML partials). + * It watches `$location.url()` and tries to map the path to an existing route definition. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + * + * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. + * + * The `$route` service is typically used in conjunction with the {@link ngRoute.directive:ngView `ngView`} + * directive and the {@link ngRoute.$routeParams `$routeParams`} service. + * + * @example + This example shows how changing the URL hash causes the `$route` to match a route against the + URL, and the `ngView` pulls in the partial. + + Note that this example is using {@link ng.directive:script inlined templates} + to get it working on jsfiddle as well. + + + +
    + Choose: + Moby | + Moby: Ch1 | + Gatsby | + Gatsby: Ch4 | + Scarlet Letter
    + +
    +
    + +
    $location.path() = {{$location.path()}}
    +
    $route.current.templateUrl = {{$route.current.templateUrl}}
    +
    $route.current.params = {{$route.current.params}}
    +
    $route.current.scope.name = {{$route.current.scope.name}}
    +
    $routeParams = {{$routeParams}}
    +
    +
    + + + controller: {{name}}
    + Book Id: {{params.bookId}}
    +
    + + + controller: {{name}}
    + Book Id: {{params.bookId}}
    + Chapter Id: {{params.chapterId}} +
    + + + angular.module('ngView', ['ngRoute']).config(function($routeProvider, $locationProvider) { + $routeProvider.when('/Book/:bookId', { + templateUrl: 'book.html', + controller: BookCntl, + resolve: { + // I will cause a 1 second delay + delay: function($q, $timeout) { + var delay = $q.defer(); + $timeout(delay.resolve, 1000); + return delay.promise; + } + } + }); + $routeProvider.when('/Book/:bookId/ch/:chapterId', { + templateUrl: 'chapter.html', + controller: ChapterCntl + }); + + // configure html5 to get links working on jsfiddle + $locationProvider.html5Mode(true); + }); + + function MainCntl($scope, $route, $routeParams, $location) { + $scope.$route = $route; + $scope.$location = $location; + $scope.$routeParams = $routeParams; + } + + function BookCntl($scope, $routeParams) { + $scope.name = "BookCntl"; + $scope.params = $routeParams; + } + + function ChapterCntl($scope, $routeParams) { + $scope.name = "ChapterCntl"; + $scope.params = $routeParams; + } + + + + it('should load and compile correct template', function() { + element('a:contains("Moby: Ch1")').click(); + var content = element('.doc-example-live [ng-view]').text(); + expect(content).toMatch(/controller\: ChapterCntl/); + expect(content).toMatch(/Book Id\: Moby/); + expect(content).toMatch(/Chapter Id\: 1/); + + element('a:contains("Scarlet")').click(); + sleep(2); // promises are not part of scenario waiting + content = element('.doc-example-live [ng-view]').text(); + expect(content).toMatch(/controller\: BookCntl/); + expect(content).toMatch(/Book Id\: Scarlet/); + }); + +
    + */ + + /** + * @ngdoc event + * @name ngRoute.$route#$routeChangeStart + * @eventOf ngRoute.$route + * @eventType broadcast on root scope + * @description + * Broadcasted before a route change. At this point the route services starts + * resolving all of the dependencies needed for the route change to occurs. + * Typically this involves fetching the view template as well as any dependencies + * defined in `resolve` route property. Once all of the dependencies are resolved + * `$routeChangeSuccess` is fired. + * + * @param {Route} next Future route information. + * @param {Route} current Current route information. + */ + + /** + * @ngdoc event + * @name ngRoute.$route#$routeChangeSuccess + * @eventOf ngRoute.$route + * @eventType broadcast on root scope + * @description + * Broadcasted after a route dependencies are resolved. + * {@link ngRoute.directive:ngView ngView} listens for the directive + * to instantiate the controller and render the view. + * + * @param {Object} angularEvent Synthetic event object. + * @param {Route} current Current route information. + * @param {Route|Undefined} previous Previous route information, or undefined if current is first route entered. + */ + + /** + * @ngdoc event + * @name ngRoute.$route#$routeChangeError + * @eventOf ngRoute.$route + * @eventType broadcast on root scope + * @description + * Broadcasted if any of the resolve promises are rejected. + * + * @param {Route} current Current route information. + * @param {Route} previous Previous route information. + * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. + */ + + /** + * @ngdoc event + * @name ngRoute.$route#$routeUpdate + * @eventOf ngRoute.$route + * @eventType broadcast on root scope + * @description + * + * The `reloadOnSearch` property has been set to false, and we are reusing the same + * instance of the Controller. + */ + + var forceReload = false, + $route = { + routes: routes, + + /** + * @ngdoc method + * @name ngRoute.$route#reload + * @methodOf ngRoute.$route + * + * @description + * Causes `$route` service to reload the current route even if + * {@link ng.$location $location} hasn't changed. + * + * As a result of that, {@link ngRoute.directive:ngView ngView} + * creates new scope, reinstantiates the controller. + */ + reload: function() { + forceReload = true; + $rootScope.$evalAsync(updateRoute); + } + }; + + $rootScope.$on('$locationChangeSuccess', updateRoute); + + return $route; + + ///////////////////////////////////////////////////// + + /** + * @param on {string} current url + * @param route {Object} route regexp to match the url against + * @return {?Object} + * + * @description + * Check if the route matches the current url. + * + * Inspired by match in + * visionmedia/express/lib/router/router.js. + */ + function switchRouteMatcher(on, route) { + var keys = route.keys, + params = {}; + + if (!route.regexp) return null; + + var m = route.regexp.exec(on); + if (!m) return null; + + for (var i = 1, len = m.length; i < len; ++i) { + var key = keys[i - 1]; + + var val = 'string' == typeof m[i] + ? decodeURIComponent(m[i]) + : m[i]; + + if (key && val) { + params[key.name] = val; + } + } + return params; + } + + function updateRoute() { + var next = parseRoute(), + last = $route.current; + + if (next && last && next.$$route === last.$$route + && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { + last.params = next.params; + copy(last.params, $routeParams); + $rootScope.$broadcast('$routeUpdate', last); + } else if (next || last) { + forceReload = false; + $rootScope.$broadcast('$routeChangeStart', next, last); + $route.current = next; + if (next) { + if (next.redirectTo) { + if (isString(next.redirectTo)) { + $location.path(interpolate(next.redirectTo, next.params)).search(next.params) + .replace(); + } else { + $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) + .replace(); + } + } + } + + $q.when(next). + then(function() { + if (next) { + var locals = extend({}, next.resolve), + template, templateUrl; + + forEach(locals, function(value, key) { + locals[key] = isString(value) ? $injector.get(value) : $injector.invoke(value); + }); + + if (isDefined(template = next.template)) { + if (isFunction(template)) { + template = template(next.params); + } + } else if (isDefined(templateUrl = next.templateUrl)) { + if (isFunction(templateUrl)) { + templateUrl = templateUrl(next.params); + } + templateUrl = $sce.getTrustedResourceUrl(templateUrl); + if (isDefined(templateUrl)) { + next.loadedTemplateUrl = templateUrl; + template = $http.get(templateUrl, {cache: $templateCache}). + then(function(response) { return response.data; }); + } + } + if (isDefined(template)) { + locals['$template'] = template; + } + return $q.all(locals); + } + }). + // after route change + then(function(locals) { + if (next == $route.current) { + if (next) { + next.locals = locals; + copy(next.params, $routeParams); + } + $rootScope.$broadcast('$routeChangeSuccess', next, last); + } + }, function(error) { + if (next == $route.current) { + $rootScope.$broadcast('$routeChangeError', next, last, error); + } + }); + } + } + + + /** + * @returns the current active route, by matching it against the URL + */ + function parseRoute() { + // Match a route + var params, match; + forEach(routes, function(route, path) { + if (!match && (params = switchRouteMatcher($location.path(), route))) { + match = inherit(route, { + params: extend({}, $location.search(), params), + pathParams: params}); + match.$$route = route; + } + }); + // No route matched; fallback to "otherwise" route + return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); + } + + /** + * @returns interpolation of the redirect path with the parameters + */ + function interpolate(string, params) { + var result = []; + forEach((string||'').split(':'), function(segment, i) { + if (i === 0) { + result.push(segment); + } else { + var segmentMatch = segment.match(/(\w+)(.*)/); + var key = segmentMatch[1]; + result.push(params[key]); + result.push(segmentMatch[2] || ''); + delete params[key]; + } + }); + return result.join(''); + } + }]; +} + +ngRouteModule.provider('$routeParams', $RouteParamsProvider); + + +/** + * @ngdoc object + * @name ngRoute.$routeParams + * @requires $route + * + * @description + * The `$routeParams` service allows you to retrieve the current set of route parameters. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + * + * The route parameters are a combination of {@link ng.$location `$location`}'s + * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}. + * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. + * + * In case of parameter name collision, `path` params take precedence over `search` params. + * + * The service guarantees that the identity of the `$routeParams` object will remain unchanged + * (but its properties will likely change) even when a route change occurs. + * + * Note that the `$routeParams` are only updated *after* a route change completes successfully. + * This means that you cannot rely on `$routeParams` being correct in route resolve functions. + * Instead you can use `$route.current.params` to access the new route's parameters. + * + * @example + *
    + *  // Given:
    + *  // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
    + *  // Route: /Chapter/:chapterId/Section/:sectionId
    + *  //
    + *  // Then
    + *  $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
    + * 
    + */ +function $RouteParamsProvider() { + this.$get = function() { return {}; }; +} + +ngRouteModule.directive('ngView', ngViewFactory); + +/** + * @ngdoc directive + * @name ngRoute.directive:ngView + * @restrict ECA + * + * @description + * # Overview + * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by + * including the rendered template of the current route into the main layout (`index.html`) file. + * Every time the current route changes, the included view changes with it according to the + * configuration of the `$route` service. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + * + * @animations + * enter - animation is used to bring new content into the browser. + * leave - animation is used to animate existing content away. + * + * The enter and leave animation occur concurrently. + * + * @scope + * @example + + +
    + Choose: + Moby | + Moby: Ch1 | + Gatsby | + Gatsby: Ch4 | + Scarlet Letter
    + +
    +
    +
    +
    + +
    $location.path() = {{main.$location.path()}}
    +
    $route.current.templateUrl = {{main.$route.current.templateUrl}}
    +
    $route.current.params = {{main.$route.current.params}}
    +
    $route.current.scope.name = {{main.$route.current.scope.name}}
    +
    $routeParams = {{main.$routeParams}}
    +
    +
    + + +
    + controller: {{book.name}}
    + Book Id: {{book.params.bookId}}
    +
    +
    + + +
    + controller: {{chapter.name}}
    + Book Id: {{chapter.params.bookId}}
    + Chapter Id: {{chapter.params.chapterId}} +
    +
    + + + .example-animate-container { + position:relative; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; + } + + .example-animate-container > div { + padding:10px; + } + + .view-example.ng-enter, .view-example.ng-leave { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; + -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; + -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; + + display:block; + width:100%; + border-left:1px solid black; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + padding:10px; + } + + .example-animate-container { + position:relative; + height:100px; + } + + .view-example.ng-enter { + left:100%; + } + .view-example.ng-enter.ng-enter-active { + left:0; + } + + .view-example.ng-leave { } + .view-example.ng-leave.ng-leave-active { + left:-100%; + } + + + + angular.module('ngViewExample', ['ngRoute', 'ngAnimate'], function($routeProvider, $locationProvider) { + $routeProvider.when('/Book/:bookId', { + templateUrl: 'book.html', + controller: BookCntl, + controllerAs: 'book' + }); + $routeProvider.when('/Book/:bookId/ch/:chapterId', { + templateUrl: 'chapter.html', + controller: ChapterCntl, + controllerAs: 'chapter' + }); + + // configure html5 to get links working on jsfiddle + $locationProvider.html5Mode(true); + }); + + function MainCntl($route, $routeParams, $location) { + this.$route = $route; + this.$location = $location; + this.$routeParams = $routeParams; + } + + function BookCntl($routeParams) { + this.name = "BookCntl"; + this.params = $routeParams; + } + + function ChapterCntl($routeParams) { + this.name = "ChapterCntl"; + this.params = $routeParams; + } + + + + it('should load and compile correct template', function() { + element('a:contains("Moby: Ch1")').click(); + var content = element('.doc-example-live [ng-view]').text(); + expect(content).toMatch(/controller\: ChapterCntl/); + expect(content).toMatch(/Book Id\: Moby/); + expect(content).toMatch(/Chapter Id\: 1/); + + element('a:contains("Scarlet")').click(); + content = element('.doc-example-live [ng-view]').text(); + expect(content).toMatch(/controller\: BookCntl/); + expect(content).toMatch(/Book Id\: Scarlet/); + }); + +
    + */ + + +/** + * @ngdoc event + * @name ngRoute.directive:ngView#$viewContentLoaded + * @eventOf ngRoute.directive:ngView + * @eventType emit on the current ngView scope + * @description + * Emitted every time the ngView content is reloaded. + */ +ngViewFactory.$inject = ['$route', '$anchorScroll', '$compile', '$controller', '$animate']; +function ngViewFactory( $route, $anchorScroll, $compile, $controller, $animate) { + return { + restrict: 'ECA', + terminal: true, + priority: 1000, + transclude: 'element', + compile: function(element, attr, linker) { + return function(scope, $element, attr) { + var currentScope, + currentElement, + onloadExp = attr.onload || ''; + + scope.$on('$routeChangeSuccess', update); + update(); + + function cleanupLastView() { + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if(currentElement) { + $animate.leave(currentElement); + currentElement = null; + } + } + + function update() { + var locals = $route.current && $route.current.locals, + template = locals && locals.$template; + + if (template) { + var newScope = scope.$new(); + linker(newScope, function(clone) { + cleanupLastView(); + + clone.html(template); + $animate.enter(clone, null, $element); + + var link = $compile(clone.contents()), + current = $route.current; + + currentScope = current.scope = newScope; + currentElement = clone; + + if (current.controller) { + locals.$scope = currentScope; + var controller = $controller(current.controller, locals); + if (current.controllerAs) { + currentScope[current.controllerAs] = controller; + } + clone.data('$ngControllerController', controller); + clone.contents().data('$ngControllerController', controller); + } + + link(currentScope); + currentScope.$emit('$viewContentLoaded'); + currentScope.$eval(onloadExp); + + // $anchorScroll might listen on event... + $anchorScroll(); + }); + } else { + cleanupLastView(); + } + } + } + } + }; +} + + +})(window, window.angular); diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-route.min.js b/web-ui/src/main/resources/catalog/lib/angular/angular-route.min.js new file mode 100644 index 00000000000..ca302950c72 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-route.min.js @@ -0,0 +1,15 @@ +/* + AngularJS v1.2.0-rc.2 + (c) 2010-2012 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(q,c,I){'use strict';function x(c,f){return m(new (m(function(){},{prototype:c})),f)}function t(c,f,a,p,n){return{restrict:"ECA",terminal:!0,priority:1E3,transclude:"element",compile:function(g,m,D){return function(u,m,e){function g(){k&&(k.$destroy(),k=null);l&&(n.leave(l),l=null)}function s(){var h=c.current&&c.current.locals,y=h&&h.$template;if(y){var z=u.$new();D(z,function(d){g();d.html(y);n.enter(d,null,m);var G=a(d.contents()),r=c.current;k=r.scope=z;l=d;if(r.controller){h.$scope= +k;var e=p(r.controller,h);r.controllerAs&&(k[r.controllerAs]=e);d.data("$ngControllerController",e);d.contents().data("$ngControllerController",e)}G(k);k.$emit("$viewContentLoaded");k.$eval(b);f()})}else g()}var k,l,b=e.onload||"";u.$on("$routeChangeSuccess",s);s()}}}}var A=c.copy,H=c.equals,m=c.extend,w=c.forEach,v=c.isDefined,B=c.isFunction,C=c.isString;q=c.module("ngRoute",["ng"]).provider("$route",function(){function c(a,p){var f=p.caseInsensitiveMatch,g={originalPath:a,regexp:a},m=g.keys=[]; +a=a.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)([\?|\*])?/g,function(a,c,p,e){a="?"===e?e:null;e="*"===e?e:null;m.push({name:p,optional:!!a});c=c||"";return""+(a?"":c)+"(?:"+(a?c:"")+(e&&"(.+)?"||"([^/]+)?")+")"+(a||"")}).replace(/([\/$\*])/g,"\\$1");g.regexp=RegExp("^"+a+"$",f?"i":"");return g}var f={};this.when=function(a,p){f[a]=m({reloadOnSearch:!0},p,a&&c(a,p));if(a){var n="/"==a[a.length-1]?a.substr(0,a.length-1):a+"/";f[n]=m({redirectTo:a},c(n,p))}return this};this.otherwise=function(a){this.when(null, +a);return this};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$http","$templateCache","$sce",function(a,c,n,g,s,q,u,t){function e(){var b=E(),h=l.current;if(b&&h&&b.$$route===h.$$route&&H(b.pathParams,h.pathParams)&&!b.reloadOnSearch&&!k)h.params=b.params,A(h.params,n),a.$broadcast("$routeUpdate",h);else if(b||h)k=!1,a.$broadcast("$routeChangeStart",b,h),(l.current=b)&&b.redirectTo&&(C(b.redirectTo)?c.path(F(b.redirectTo,b.params)).search(b.params).replace():c.url(b.redirectTo(b.pathParams, +c.path(),c.search())).replace()),g.when(b).then(function(){if(b){var a=m({},b.resolve),c,d;w(a,function(b,c){a[c]=C(b)?s.get(b):s.invoke(b)});v(c=b.template)?B(c)&&(c=c(b.params)):v(d=b.templateUrl)&&(B(d)&&(d=d(b.params)),d=t.getTrustedResourceUrl(d),v(d)&&(b.loadedTemplateUrl=d,c=q.get(d,{cache:u}).then(function(b){return b.data})));v(c)&&(a.$template=c);return g.all(a)}}).then(function(c){b==l.current&&(b&&(b.locals=c,A(b.params,n)),a.$broadcast("$routeChangeSuccess",b,h))},function(c){b==l.current&& +a.$broadcast("$routeChangeError",b,h,c)})}function E(){var b,a;w(f,function(e,k){var d;if(d=!a){var f=c.path();d=e.keys;var r={};if(e.regexp)if(f=e.regexp.exec(f)){for(var g=1,l=f.length;g + + +
    + Snippet: + + + + + + + + + + + + + + + + + + + + + + + + + +
    DirectiveHowSourceRendered
    ng-bind-htmlAutomatically uses $sanitize
    <div ng-bind-html="snippet">
    </div>
    ng-bind-htmlBypass $sanitize by explicitly trusting the dangerous value
    <div ng-bind-html="deliberatelyTrustDangerousSnippet()">
    </div>
    ng-bindAutomatically escapes
    <div ng-bind="snippet">
    </div>
    +
    +
    + + it('should sanitize the html snippet by default', function() { + expect(using('#bind-html-with-sanitize').element('div').html()). + toBe('

    an html\nclick here\nsnippet

    '); + }); + + it('should inline raw snippet if bound to a trusted value', function() { + expect(using('#bind-html-with-trust').element("div").html()). + toBe("

    an html\n" + + "click here\n" + + "snippet

    "); + }); + + it('should escape snippet without any filter', function() { + expect(using('#bind-default').element('div').html()). + toBe("<p style=\"color:blue\">an html\n" + + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + + "snippet</p>"); + }); + + it('should update', function() { + input('snippet').enter('new text'); + expect(using('#bind-html-with-sanitize').element('div').html()).toBe('new text'); + expect(using('#bind-html-with-trust').element('div').html()).toBe('new text'); + expect(using('#bind-default').element('div').html()).toBe("new <b onclick=\"alert(1)\">text</b>"); + }); +
    + + */ +var $sanitize = function(html) { + var buf = []; + htmlParser(html, htmlSanitizeWriter(buf)); + return buf.join(''); +}; + + +// Regular Expressions for parsing tags and attributes +var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, + END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, + ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, + BEGIN_TAG_REGEXP = /^/g, + CDATA_REGEXP = //g, + URI_REGEXP = /^((ftp|https?):\/\/|mailto:|tel:|#)/i, + NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character) + + +// Good source of info about elements and attributes +// http://dev.w3.org/html5/spec/Overview.html#semantics +// http://simon.html5.org/html-elements + +// Safe Void Elements - HTML5 +// http://dev.w3.org/html5/spec/Overview.html#void-elements +var voidElements = makeMap("area,br,col,hr,img,wbr"); + +// Elements that you can, intentionally, leave open (and which close themselves) +// http://dev.w3.org/html5/spec/Overview.html#optional-tags +var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), + optionalEndTagInlineElements = makeMap("rp,rt"), + optionalEndTagElements = angular.extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); + +// Safe Block Elements - HTML5 +var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article,aside," + + "blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6," + + "header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); + +// Inline Elements - HTML5 +var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b,bdi,bdo," + + "big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small," + + "span,strike,strong,sub,sup,time,tt,u,var")); + + +// Special Elements (can contain anything) +var specialElements = makeMap("script,style"); + +var validElements = angular.extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements); + +//Attributes that have href and hence need to be sanitized +var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap"); +var validAttrs = angular.extend({}, uriAttrs, makeMap( + 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ + 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ + 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ + 'scope,scrolling,shape,span,start,summary,target,title,type,'+ + 'valign,value,vspace,width')); + +function makeMap(str) { + var obj = {}, items = str.split(','), i; + for (i = 0; i < items.length; i++) obj[items[i]] = true; + return obj; +} + + +/** + * @example + * htmlParser(htmlString, { + * start: function(tag, attrs, unary) {}, + * end: function(tag) {}, + * chars: function(text) {}, + * comment: function(text) {} + * }); + * + * @param {string} html string + * @param {object} handler + */ +function htmlParser( html, handler ) { + var index, chars, match, stack = [], last = html; + stack.last = function() { return stack[ stack.length - 1 ]; }; + + while ( html ) { + chars = true; + + // Make sure we're not in a script or style element + if ( !stack.last() || !specialElements[ stack.last() ] ) { + + // Comment + if ( html.indexOf(""); + + if ( index >= 0 ) { + if (handler.comment) handler.comment( html.substring( 4, index ) ); + html = html.substring( index + 3 ); + chars = false; + } + + // end tag + } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { + match = html.match( END_TAG_REGEXP ); + + if ( match ) { + html = html.substring( match[0].length ); + match[0].replace( END_TAG_REGEXP, parseEndTag ); + chars = false; + } + + // start tag + } else if ( BEGIN_TAG_REGEXP.test(html) ) { + match = html.match( START_TAG_REGEXP ); + + if ( match ) { + html = html.substring( match[0].length ); + match[0].replace( START_TAG_REGEXP, parseStartTag ); + chars = false; + } + } + + if ( chars ) { + index = html.indexOf("<"); + + var text = index < 0 ? html : html.substring( 0, index ); + html = index < 0 ? "" : html.substring( index ); + + if (handler.chars) handler.chars( decodeEntities(text) ); + } + + } else { + html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){ + text = text. + replace(COMMENT_REGEXP, "$1"). + replace(CDATA_REGEXP, "$1"); + + if (handler.chars) handler.chars( decodeEntities(text) ); + + return ""; + }); + + parseEndTag( "", stack.last() ); + } + + if ( html == last ) { + throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block of html: {0}", html); + } + last = html; + } + + // Clean up any remaining tags + parseEndTag(); + + function parseStartTag( tag, tagName, rest, unary ) { + tagName = angular.lowercase(tagName); + if ( blockElements[ tagName ] ) { + while ( stack.last() && inlineElements[ stack.last() ] ) { + parseEndTag( "", stack.last() ); + } + } + + if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) { + parseEndTag( "", tagName ); + } + + unary = voidElements[ tagName ] || !!unary; + + if ( !unary ) + stack.push( tagName ); + + var attrs = {}; + + rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) { + var value = doubleQuotedValue + || singleQuotedValue + || unquotedValue + || ''; + + attrs[name] = decodeEntities(value); + }); + if (handler.start) handler.start( tagName, attrs, unary ); + } + + function parseEndTag( tag, tagName ) { + var pos = 0, i; + tagName = angular.lowercase(tagName); + if ( tagName ) + // Find the closest opened tag of the same type + for ( pos = stack.length - 1; pos >= 0; pos-- ) + if ( stack[ pos ] == tagName ) + break; + + if ( pos >= 0 ) { + // Close all the open elements, up the stack + for ( i = stack.length - 1; i >= pos; i-- ) + if (handler.end) handler.end( stack[ i ] ); + + // Remove the open elements from the stack + stack.length = pos; + } + } +} + +/** + * decodes all entities into regular string + * @param value + * @returns {string} A string with decoded entities. + */ +var hiddenPre=document.createElement("pre"); +function decodeEntities(value) { + hiddenPre.innerHTML=value.replace(//g, '>'); +} + +/** + * create an HTML/XML writer which writes to buffer + * @param {Array} buf use buf.jain('') to get out sanitized html string + * @returns {object} in the form of { + * start: function(tag, attrs, unary) {}, + * end: function(tag) {}, + * chars: function(text) {}, + * comment: function(text) {} + * } + */ +function htmlSanitizeWriter(buf){ + var ignore = false; + var out = angular.bind(buf, buf.push); + return { + start: function(tag, attrs, unary){ + tag = angular.lowercase(tag); + if (!ignore && specialElements[tag]) { + ignore = tag; + } + if (!ignore && validElements[tag] == true) { + out('<'); + out(tag); + angular.forEach(attrs, function(value, key){ + var lkey=angular.lowercase(key); + if (validAttrs[lkey]==true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) { + out(' '); + out(key); + out('="'); + out(encodeEntities(value)); + out('"'); + } + }); + out(unary ? '/>' : '>'); + } + }, + end: function(tag){ + tag = angular.lowercase(tag); + if (!ignore && validElements[tag] == true) { + out(''); + } + if (tag == ignore) { + ignore = false; + } + }, + chars: function(chars){ + if (!ignore) { + out(encodeEntities(chars)); + } + } + }; +} + + +// define ngSanitize module and register $sanitize service +angular.module('ngSanitize', []).value('$sanitize', $sanitize); + +/** + * @ngdoc filter + * @name ngSanitize.filter:linky + * @function + * + * @description + * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and + * plain email address links. + * + * Requires the {@link ngSanitize `ngSanitize`} module to be installed. + * + * @param {string} text Input text. + * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in. + * @returns {string} Html-linkified text. + * + * @usage + + * + * @example + + + +
    + Snippet: + + + + + + + + + + + + + + + + + + + + + +
    FilterSourceRendered
    linky filter +
    <div ng-bind-html="snippet | linky">
    </div>
    +
    +
    +
    linky target +
    <div ng-bind-html="snippetWithTarget | linky:'_blank'">
    </div>
    +
    +
    +
    no filter
    <div ng-bind="snippet">
    </div>
    + + + it('should linkify the snippet with urls', function() { + expect(using('#linky-filter').binding('snippet | linky')). + toBe('Pretty text with some links: ' + + 'http://angularjs.org/, ' + + 'us@somewhere.org, ' + + 'another@somewhere.org, ' + + 'and one more: ftp://127.0.0.1/.'); + }); + + it ('should not linkify snippet without the linky filter', function() { + expect(using('#escaped-html').binding('snippet')). + toBe("Pretty text with some links:\n" + + "http://angularjs.org/,\n" + + "mailto:us@somewhere.org,\n" + + "another@somewhere.org,\n" + + "and one more: ftp://127.0.0.1/."); + }); + + it('should update', function() { + input('snippet').enter('new http://link.'); + expect(using('#linky-filter').binding('snippet | linky')). + toBe('new http://link.'); + expect(using('#escaped-html').binding('snippet')).toBe('new http://link.'); + }); + + it('should work with the target property', function() { + expect(using('#linky-target').binding("snippetWithTarget | linky:'_blank'")). + toBe('http://angularjs.org/'); + }); + + + */ +angular.module('ngSanitize').filter('linky', function() { + var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/, + MAILTO_REGEXP = /^mailto:/; + + return function(text, target) { + if (!text) return text; + var match; + var raw = text; + var html = []; + // TODO(vojta): use $sanitize instead + var writer = htmlSanitizeWriter(html); + var url; + var i; + var properties = {}; + if (angular.isDefined(target)) { + properties.target = target; + } + while ((match = raw.match(LINKY_URL_REGEXP))) { + // We can not end in these as they are sometimes found at the end of the sentence + url = match[0]; + // if we did not match ftp/http/mailto then assume mailto + if (match[2] == match[3]) url = 'mailto:' + url; + i = match.index; + writer.chars(raw.substr(0, i)); + properties.href = url; + writer.start('a', properties); + writer.chars(match[0].replace(MAILTO_REGEXP, '')); + writer.end('a'); + raw = raw.substring(i + match[0].length); + } + writer.chars(raw); + return html.join(''); + }; +}); + + +})(window, window.angular); diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-sanitize.min.js b/web-ui/src/main/resources/catalog/lib/angular/angular-sanitize.min.js new file mode 100644 index 00000000000..fa90c9276c8 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-sanitize.min.js @@ -0,0 +1,15 @@ +/* + AngularJS v1.2.0-rc.2 + (c) 2010-2012 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(m,g,n){'use strict';function h(a){var d={};a=a.split(",");var c;for(c=0;c=c;k--)d.end&&d.end(e[k]);e.length= +c}}var b,f,e=[],l=a;for(e.last=function(){return e[e.length-1]};a;){f=!0;if(e.last()&&v[e.last()])a=a.replace(RegExp("(.*)<\\s*\\/\\s*"+e.last()+"[^>]*>","i"),function(a,b){b=b.replace(E,"$1").replace(F,"$1");d.chars&&d.chars(p(b));return""}),k("",e.last());else{if(0===a.indexOf("\x3c!--"))b=a.indexOf("--\x3e"),0<=b&&(d.comment&&d.comment(a.substring(4,b)),a=a.substring(b+3),f=!1);else if(G.test(a)){if(b=a.match(w))a=a.substring(b[0].length),b[0].replace(w,k),f=!1}else H.test(a)&&(b=a.match(x))&& +(a=a.substring(b[0].length),b[0].replace(x,c),f=!1);f&&(b=a.indexOf("<"),f=0>b?a:a.substring(0,b),a=0>b?"":a.substring(b),d.chars&&d.chars(p(f)))}if(a==l)throw I("badparse",a);l=a}k()}function p(a){q.innerHTML=a.replace(//g,">")}function z(a){var d=!1,c=g.bind(a,a.push);return{start:function(a,b,f){a=g.lowercase(a); +!d&&v[a]&&(d=a);d||!0!=A[a]||(c("<"),c(a),g.forEach(b,function(a,b){var d=g.lowercase(b);!0!=K[d]||!0===B[d]&&!a.match(L)||(c(" "),c(b),c('="'),c(y(a)),c('"'))}),c(f?"/>":">"))},end:function(a){a=g.lowercase(a);d||!0!=A[a]||(c(""));a==d&&(d=!1)},chars:function(a){d||c(y(a))}}}var I=g.$$minErr("$sanitize"),x=/^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,w=/^<\s*\/\s*([\w:-]+)[^>]*>/,D=/([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, +H=/^]/,d=/^mailto:/;return function(c,k){if(!c)return c;var b,f=c,e=[],l=z(e),h,m,n={};g.isDefined(k)&&(n.target=k);for(;b=f.match(a);)h=b[0],b[2]==b[3]&&(h="mailto:"+h),m=b.index,l.chars(f.substr(0,m)),n.href=h,l.start("a",n),l.chars(b[0].replace(d,"")),l.end("a"),f=f.substring(m+b[0].length);l.chars(f);return e.join("")}})})(window,window.angular); +/* +//@ sourceMappingURL=angular-sanitize.min.js.map +*/ diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-sanitize.min.js.map b/web-ui/src/main/resources/catalog/lib/angular/angular-sanitize.min.js.map new file mode 100644 index 00000000000..dcff4597565 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-sanitize.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"angular-sanitize.min.js", +"lineCount":12, +"mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAkBC,CAAlB,CAA6B,CAqLtCC,QAASA,EAAO,CAACC,CAAD,CAAM,CAAA,IAChBC,EAAM,EAAIC,EAAAA,CAAQF,CAAAG,MAAA,CAAU,GAAV,CAAtB,KAAsCC,CACtC,KAAKA,CAAL,CAAS,CAAT,CAAYA,CAAZ,CAAgBF,CAAAG,OAAhB,CAA8BD,CAAA,EAA9B,CAAmCH,CAAA,CAAIC,CAAA,CAAME,CAAN,CAAJ,CAAA,CAAgB,CAAA,CACnD,OAAOH,EAHa,CAmBtBK,QAASA,EAAU,CAAEC,CAAF,CAAQC,CAAR,CAAkB,CAyEnCC,QAASA,EAAa,CAAEC,CAAF,CAAOC,CAAP,CAAgBC,CAAhB,CAAsBC,CAAtB,CAA8B,CAClDF,CAAA,CAAUd,CAAAiB,UAAA,CAAkBH,CAAlB,CACV,IAAKI,CAAA,CAAeJ,CAAf,CAAL,CACE,IAAA,CAAQK,CAAAC,KAAA,EAAR,EAAwBC,CAAA,CAAgBF,CAAAC,KAAA,EAAhB,CAAxB,CAAA,CACEE,CAAA,CAAa,EAAb,CAAiBH,CAAAC,KAAA,EAAjB,CAICG,EAAA,CAAwBT,CAAxB,CAAL,EAA0CK,CAAAC,KAAA,EAA1C,EAA0DN,CAA1D,EACEQ,CAAA,CAAa,EAAb,CAAiBR,CAAjB,CAKF,EAFAE,CAEA,CAFQQ,CAAA,CAAcV,CAAd,CAER,EAFmC,CAAC,CAACE,CAErC,GACEG,CAAAM,KAAA,CAAYX,CAAZ,CAEF,KAAIY,EAAQ,EAEZX,EAAAY,QAAA,CAAaC,CAAb,CAA0B,QAAQ,CAACC,CAAD,CAAQC,CAAR,CAAcC,CAAd,CAAiCC,CAAjC,CAAoDC,CAApD,CAAmE,CAMnGP,CAAA,CAAMI,CAAN,CAAA,CAAcI,CAAA,CALFH,CAKE,EAJTC,CAIS,EAHTC,CAGS,EAFT,EAES,CANqF,CAArG,CAQItB,EAAAwB,MAAJ,EAAmBxB,CAAAwB,MAAA,CAAerB,CAAf,CAAwBY,CAAxB,CAA+BV,CAA/B,CA3B+B,CA8BpDM,QAASA,EAAW,CAAET,CAAF,CAAOC,CAAP,CAAiB,CAAA,IAC/BsB,EAAM,CADyB,CACtB7B,CAEb,IADAO,CACA,CADUd,CAAAiB,UAAA,CAAkBH,CAAlB,CACV,CAEE,IAAMsB,CAAN,CAAYjB,CAAAX,OAAZ,CAA2B,CAA3B,CAAqC,CAArC,EAA8B4B,CAA9B,EACOjB,CAAA,CAAOiB,CAAP,CADP,EACuBtB,CADvB,CAAwCsB,CAAA,EAAxC,EAIF,GAAY,CAAZ,EAAKA,CAAL,CAAgB,CAEd,IAAM7B,CAAN,CAAUY,CAAAX,OAAV,CAAyB,CAAzB,CAA4BD,CAA5B,EAAiC6B,CAAjC,CAAsC7B,CAAA,EAAtC,CACMI,CAAA0B,IAAJ,EAAiB1B,CAAA0B,IAAA,CAAalB,CAAA,CAAOZ,CAAP,CAAb,CAGnBY,EAAAX,OAAA;AAAe4B,CAND,CATmB,CAvGF,IAC/BE,CAD+B,CACxBC,CADwB,CACVpB,EAAQ,EADE,CACEC,EAAOV,CAG5C,KAFAS,CAAAC,KAEA,CAFaoB,QAAQ,EAAG,CAAE,MAAOrB,EAAA,CAAOA,CAAAX,OAAP,CAAsB,CAAtB,CAAT,CAExB,CAAQE,CAAR,CAAA,CAAe,CACb6B,CAAA,CAAQ,CAAA,CAGR,IAAMpB,CAAAC,KAAA,EAAN,EAAuBqB,CAAA,CAAiBtB,CAAAC,KAAA,EAAjB,CAAvB,CA2CEV,CAUA,CAVOA,CAAAiB,QAAA,CAAiBe,MAAJ,CAAW,kBAAX,CAAgCvB,CAAAC,KAAA,EAAhC,CAA+C,QAA/C,CAAyD,GAAzD,CAAb,CAA4E,QAAQ,CAACuB,CAAD,CAAMC,CAAN,CAAW,CACpGA,CAAA,CAAOA,CAAAjB,QAAA,CACGkB,CADH,CACmB,IADnB,CAAAlB,QAAA,CAEGmB,CAFH,CAEiB,IAFjB,CAIHnC,EAAA4B,MAAJ,EAAmB5B,CAAA4B,MAAA,CAAeL,CAAA,CAAeU,CAAf,CAAf,CAEnB,OAAO,EAP6F,CAA/F,CAUP,CAAAtB,CAAA,CAAa,EAAb,CAAiBH,CAAAC,KAAA,EAAjB,CArDF,KAAyD,CAGvD,GAA8B,CAA9B,GAAKV,CAAAqC,QAAA,CAAa,SAAb,CAAL,CACET,CAEA,CAFQ5B,CAAAqC,QAAA,CAAa,QAAb,CAER,CAAc,CAAd,EAAKT,CAAL,GACM3B,CAAAqC,QAEJ,EAFqBrC,CAAAqC,QAAA,CAAiBtC,CAAAuC,UAAA,CAAgB,CAAhB,CAAmBX,CAAnB,CAAjB,CAErB,CADA5B,CACA,CADOA,CAAAuC,UAAA,CAAgBX,CAAhB,CAAwB,CAAxB,CACP,CAAAC,CAAA,CAAQ,CAAA,CAHV,CAHF,KAUO,IAAKW,CAAAC,KAAA,CAA4BzC,CAA5B,CAAL,CAGL,IAFAmB,CAEA,CAFQnB,CAAAmB,MAAA,CAAYuB,CAAZ,CAER,CACE1C,CAEA,CAFOA,CAAAuC,UAAA,CAAgBpB,CAAA,CAAM,CAAN,CAAArB,OAAhB,CAEP,CADAqB,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAkByB,CAAlB,CAAkC9B,CAAlC,CACA,CAAAiB,CAAA,CAAQ,CAAA,CAHV,CAHK,IAUKc,EAAAF,KAAA,CAAsBzC,CAAtB,CAAL,GACLmB,CADK,CACGnB,CAAAmB,MAAA,CAAYyB,CAAZ,CADH;CAIH5C,CAEA,CAFOA,CAAAuC,UAAA,CAAgBpB,CAAA,CAAM,CAAN,CAAArB,OAAhB,CAEP,CADAqB,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAkB2B,CAAlB,CAAoC1C,CAApC,CACA,CAAA2B,CAAA,CAAQ,CAAA,CANL,CAUFA,EAAL,GACED,CAKA,CALQ5B,CAAAqC,QAAA,CAAa,GAAb,CAKR,CAHIH,CAGJ,CAHmB,CAAR,CAAAN,CAAA,CAAY5B,CAAZ,CAAmBA,CAAAuC,UAAA,CAAgB,CAAhB,CAAmBX,CAAnB,CAG9B,CAFA5B,CAEA,CAFe,CAAR,CAAA4B,CAAA,CAAY,EAAZ,CAAiB5B,CAAAuC,UAAA,CAAgBX,CAAhB,CAExB,CAAI3B,CAAA4B,MAAJ,EAAmB5B,CAAA4B,MAAA,CAAeL,CAAA,CAAeU,CAAf,CAAf,CANrB,CAjCuD,CAwDzD,GAAKlC,CAAL,EAAaU,CAAb,CACE,KAAMmC,EAAA,CAAgB,UAAhB,CAAkG7C,CAAlG,CAAN,CAEFU,CAAA,CAAOV,CA/DM,CAmEfY,CAAA,EAvEmC,CAiIrCY,QAASA,EAAc,CAACsB,CAAD,CAAQ,CAC7BC,CAAAC,UAAA,CAAoBF,CAAA7B,QAAA,CAAc,IAAd,CAAmB,MAAnB,CACpB,OAAO8B,EAAAE,UAAP,EAA8BF,CAAAG,YAA9B,EAAuD,EAF1B,CAY/BC,QAASA,EAAc,CAACL,CAAD,CAAQ,CAC7B,MAAOA,EAAA7B,QAAA,CACG,IADH,CACS,OADT,CAAAA,QAAA,CAEGmC,CAFH,CAE4B,QAAQ,CAACN,CAAD,CAAO,CAC9C,MAAO,IAAP,CAAcA,CAAAO,WAAA,CAAiB,CAAjB,CAAd,CAAoC,GADU,CAF3C,CAAApC,QAAA,CAKG,IALH,CAKS,MALT,CAAAA,QAAA,CAMG,IANH,CAMS,MANT,CADsB,CAoB/BqC,QAASA,EAAkB,CAACC,CAAD,CAAK,CAC9B,IAAIC,EAAS,CAAA,CAAb,CACIC,EAAMnE,CAAAoE,KAAA,CAAaH,CAAb,CAAkBA,CAAAxC,KAAlB,CACV,OAAO,OACEU,QAAQ,CAACtB,CAAD,CAAMa,CAAN,CAAaV,CAAb,CAAmB,CAChCH,CAAA,CAAMb,CAAAiB,UAAA,CAAkBJ,CAAlB,CACDqD;CAAAA,CAAL,EAAezB,CAAA,CAAgB5B,CAAhB,CAAf,GACEqD,CADF,CACWrD,CADX,CAGKqD,EAAL,EAAqC,CAAA,CAArC,EAAeG,CAAA,CAAcxD,CAAd,CAAf,GACEsD,CAAA,CAAI,GAAJ,CAYA,CAXAA,CAAA,CAAItD,CAAJ,CAWA,CAVAb,CAAAsE,QAAA,CAAgB5C,CAAhB,CAAuB,QAAQ,CAAC8B,CAAD,CAAQe,CAAR,CAAY,CACzC,IAAIC,EAAKxE,CAAAiB,UAAA,CAAkBsD,CAAlB,CACa,EAAA,CAAtB,EAAIE,CAAA,CAAWD,CAAX,CAAJ,EAAgD,CAAA,CAAhD,GAA+BE,CAAA,CAASF,CAAT,CAA/B,EAAwD,CAAAhB,CAAA3B,MAAA,CAAY8C,CAAZ,CAAxD,GACER,CAAA,CAAI,GAAJ,CAIA,CAHAA,CAAA,CAAII,CAAJ,CAGA,CAFAJ,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAIN,CAAA,CAAeL,CAAf,CAAJ,CACA,CAAAW,CAAA,CAAI,GAAJ,CALF,CAFyC,CAA3C,CAUA,CAAAA,CAAA,CAAInD,CAAA,CAAQ,IAAR,CAAe,GAAnB,CAbF,CALgC,CAD7B,KAsBAqB,QAAQ,CAACxB,CAAD,CAAK,CACdA,CAAA,CAAMb,CAAAiB,UAAA,CAAkBJ,CAAlB,CACDqD,EAAL,EAAqC,CAAA,CAArC,EAAeG,CAAA,CAAcxD,CAAd,CAAf,GACEsD,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAItD,CAAJ,CACA,CAAAsD,CAAA,CAAI,GAAJ,CAHF,CAKItD,EAAJ,EAAWqD,CAAX,GACEA,CADF,CACW,CAAA,CADX,CAPc,CAtBb,OAiCE3B,QAAQ,CAACA,CAAD,CAAO,CACb2B,CAAL,EACEC,CAAA,CAAIN,CAAA,CAAetB,CAAf,CAAJ,CAFgB,CAjCjB,CAHuB,CAvWhC,IAAIgB,EAAkBvD,CAAA4E,SAAA,CAAiB,WAAjB,CAAtB,CAiIItB,EAAmB,4FAjIvB,CAkIEF,EAAiB,2BAlInB,CAmIExB,EAAc,yEAnIhB;AAoIEyB,EAAmB,IApIrB,CAqIEH,EAAyB,SArI3B,CAsIEL,EAAiB,qBAtInB,CAuIEC,EAAe,yBAvIjB,CAwIE6B,EAAa,sCAxIf,CAyIEb,EAA0B,gBAzI5B,CAkJItC,EAAetB,CAAA,CAAQ,wBAAR,CAIf2E,EAAAA,CAA8B3E,CAAA,CAAQ,gDAAR,CAC9B4E,EAAAA,CAA+B5E,CAAA,CAAQ,OAAR,CADnC,KAEIqB,EAAyBvB,CAAA+E,OAAA,CAAe,EAAf,CAAmBD,CAAnB,CAAiDD,CAAjD,CAF7B,CAKI3D,EAAgBlB,CAAA+E,OAAA,CAAe,EAAf,CAAmBF,CAAnB,CAAgD3E,CAAA,CAAQ,4KAAR,CAAhD,CALpB,CAUImB,EAAiBrB,CAAA+E,OAAA,CAAe,EAAf,CAAmBD,CAAnB,CAAiD5E,CAAA,CAAQ,2JAAR,CAAjD,CAVrB;AAgBIuC,EAAkBvC,CAAA,CAAQ,cAAR,CAhBtB,CAkBImE,EAAgBrE,CAAA+E,OAAA,CAAe,EAAf,CAAmBvD,CAAnB,CAAiCN,CAAjC,CAAgDG,CAAhD,CAAgEE,CAAhE,CAlBpB,CAqBImD,EAAWxE,CAAA,CAAQ,0CAAR,CArBf,CAsBIuE,EAAazE,CAAA+E,OAAA,CAAe,EAAf,CAAmBL,CAAnB,CAA6BxE,CAAA,CAC1C,oSAD0C,CAA7B,CAtBjB,CAgLIuD,EAAUuB,QAAAC,cAAA,CAAuB,KAAvB,CA+EdjF,EAAAkF,OAAA,CAAe,YAAf,CAA6B,EAA7B,CAAA1B,MAAA,CAAuC,WAAvC,CA5RgB2B,QAAQ,CAACzE,CAAD,CAAO,CAC7B,IAAIuD,EAAM,EACRxD;CAAA,CAAWC,CAAX,CAAiBsD,CAAA,CAAmBC,CAAnB,CAAjB,CACA,OAAOA,EAAAmB,KAAA,CAAS,EAAT,CAHoB,CA4R/B,CAoGApF,EAAAkF,OAAA,CAAe,YAAf,CAAAG,OAAA,CAAoC,OAApC,CAA6C,QAAQ,EAAG,CAAA,IAClDC,EAAmB,4EAD+B,CAElDC,EAAgB,UAEpB,OAAO,SAAQ,CAAC3C,CAAD,CAAO4C,CAAP,CAAe,CAC5B,GAAI,CAAC5C,CAAL,CAAW,MAAOA,EAClB,KAAIf,CAAJ,CACI4D,EAAM7C,CADV,CAEIlC,EAAO,EAFX,CAIIgF,EAAS1B,CAAA,CAAmBtD,CAAnB,CAJb,CAKIiF,CALJ,CAMIpF,CANJ,CAOIqF,EAAa,EACb5F,EAAA6F,UAAA,CAAkBL,CAAlB,CAAJ,GACEI,CAAAJ,OADF,CACsBA,CADtB,CAGA,KAAA,CAAQ3D,CAAR,CAAgB4D,CAAA5D,MAAA,CAAUyD,CAAV,CAAhB,CAAA,CAEEK,CASA,CATM9D,CAAA,CAAM,CAAN,CASN,CAPIA,CAAA,CAAM,CAAN,CAOJ,EAPgBA,CAAA,CAAM,CAAN,CAOhB,GAP0B8D,CAO1B,CAPgC,SAOhC,CAP4CA,CAO5C,EANApF,CAMA,CANIsB,CAAAS,MAMJ,CALAoD,CAAAnD,MAAA,CAAakD,CAAAK,OAAA,CAAW,CAAX,CAAcvF,CAAd,CAAb,CAKA,CAJAqF,CAAAG,KAIA,CAJkBJ,CAIlB,CAHAD,CAAAvD,MAAA,CAAa,GAAb,CAAkByD,CAAlB,CAGA,CAFAF,CAAAnD,MAAA,CAAaV,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAiB4D,CAAjB,CAAgC,EAAhC,CAAb,CAEA,CADAG,CAAArD,IAAA,CAAW,GAAX,CACA,CAAAoD,CAAA,CAAMA,CAAAxC,UAAA,CAAc1C,CAAd,CAAkBsB,CAAA,CAAM,CAAN,CAAArB,OAAlB,CAERkF,EAAAnD,MAAA,CAAakD,CAAb,CACA,OAAO/E,EAAA0E,KAAA,CAAU,EAAV,CA3BqB,CAJwB,CAAxD,CA3fsC,CAArC,CAAA,CA+hBErF,MA/hBF,CA+hBUA,MAAAC,QA/hBV;", +"sources":["angular-sanitize.js"], +"names":["window","angular","undefined","makeMap","str","obj","items","split","i","length","htmlParser","html","handler","parseStartTag","tag","tagName","rest","unary","lowercase","blockElements","stack","last","inlineElements","parseEndTag","optionalEndTagElements","voidElements","push","attrs","replace","ATTR_REGEXP","match","name","doubleQuotedValue","singleQuotedValue","unquotedValue","decodeEntities","start","pos","end","index","chars","stack.last","specialElements","RegExp","all","text","COMMENT_REGEXP","CDATA_REGEXP","indexOf","comment","substring","BEGING_END_TAGE_REGEXP","test","END_TAG_REGEXP","BEGIN_TAG_REGEXP","START_TAG_REGEXP","$sanitizeMinErr","value","hiddenPre","innerHTML","innerText","textContent","encodeEntities","NON_ALPHANUMERIC_REGEXP","charCodeAt","htmlSanitizeWriter","buf","ignore","out","bind","validElements","forEach","key","lkey","validAttrs","uriAttrs","URI_REGEXP","$$minErr","optionalEndTagBlockElements","optionalEndTagInlineElements","extend","document","createElement","module","$sanitize","join","filter","LINKY_URL_REGEXP","MAILTO_REGEXP","target","raw","writer","url","properties","isDefined","substr","href"] +} diff --git a/web-ui/src/main/resources/catalog/lib/angular/angular-scenario.js b/web-ui/src/main/resources/catalog/lib/angular/angular-scenario.js new file mode 100644 index 00000000000..5d53ace0369 --- /dev/null +++ b/web-ui/src/main/resources/catalog/lib/angular/angular-scenario.js @@ -0,0 +1,29649 @@ +/*! + * jQuery JavaScript Library v1.8.3 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2012 jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time) + */ +(function( window, undefined ) {'use strict'; +var + // A central reference to the root jQuery(document) + rootjQuery, + + // The deferred used on DOM ready + readyList, + + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + location = window.location, + navigator = window.navigator, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // Save a reference to some core methods + core_push = Array.prototype.push, + core_slice = Array.prototype.slice, + core_indexOf = Array.prototype.indexOf, + core_toString = Object.prototype.toString, + core_hasOwn = Object.prototype.hasOwnProperty, + core_trim = String.prototype.trim, + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Used for matching numbers + core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, + + // Used for detecting and trimming whitespace + core_rnotwhite = /\S/, + core_rspace = /\s+/, + + // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, + rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return ( letter + "" ).toUpperCase(); + }, + + // The ready event handler and self cleanup method + DOMContentLoaded = function() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + } else if ( document.readyState === "complete" ) { + // we're here because readyState === "complete" in oldIE + // which is good enough for us to call the dom ready! + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + doc = ( context && context.nodeType ? context.ownerDocument || context : document ); + + // scripts is true for back-compat + selector = jQuery.parseHTML( match[1], doc, true ); + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + this.attr.call( selector, context, true ); + } + + return jQuery.merge( this, selector ); + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.8.3", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return core_slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; + }, + + eq: function( i ) { + i = +i; + return i === -1 ? + this.slice( i ) : + this.slice( i, i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( core_slice.apply( this, arguments ), + "slice", core_slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: core_push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger("ready").off("ready"); + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + isWindow: function( obj ) { + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ core_toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !core_hasOwn.call(obj, "constructor") && + !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || core_hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + // data: string of html + // context (optional): If specified, the fragment will be created in this context, defaults to document + // scripts (optional): If true, will include scripts passed in the html string + parseHTML: function( data, context, scripts ) { + var parsed; + if ( !data || typeof data !== "string" ) { + return null; + } + if ( typeof context === "boolean" ) { + scripts = context; + context = 0; + } + context = context || document; + + // Single tag + if ( (parsed = rsingleTag.exec( data )) ) { + return [ context.createElement( parsed[1] ) ]; + } + + parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); + return jQuery.merge( [], + (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); + }, + + parseJSON: function( data ) { + if ( !data || typeof data !== "string") { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + + } + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + if ( !data || typeof data !== "string" ) { + return null; + } + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && core_rnotwhite.test( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var name, + i = 0, + length = obj.length, + isObj = length === undefined || jQuery.isFunction( obj ); + + if ( args ) { + if ( isObj ) { + for ( name in obj ) { + if ( callback.apply( obj[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( obj[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in obj ) { + if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { + break; + } + } + } + } + + return obj; + }, + + // Use native String.trim function wherever possible + trim: core_trim && !core_trim.call("\uFEFF\xA0") ? + function( text ) { + return text == null ? + "" : + core_trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var type, + ret = results || []; + + if ( arr != null ) { + // The window, strings (and functions) also have 'length' + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + type = jQuery.type( arr ); + + if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { + core_push.call( ret, arr ); + } else { + jQuery.merge( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( core_indexOf ) { + return core_indexOf.call( arr, elem, i ); + } + + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var l = second.length, + i = first.length, + j = 0; + + if ( typeof l === "number" ) { + for ( ; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var retVal, + ret = [], + i = 0, + length = elems.length; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, key, + ret = [], + i = 0, + length = elems.length, + // jquery objects are treated as arrays + isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( key in elems ) { + value = callback( elems[ key ], key, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = core_slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + // Multifunctional method to get and set values of a collection + // The value/s can optionally be executed if it's a function + access: function( elems, fn, key, value, chainable, emptyGet, pass ) { + var exec, + bulk = key == null, + i = 0, + length = elems.length; + + // Sets many values + if ( key && typeof key === "object" ) { + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); + } + chainable = 1; + + // Sets one value + } else if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = pass === undefined && jQuery.isFunction( value ); + + if ( bulk ) { + // Bulk operations only iterate when executing function values + if ( exec ) { + exec = fn; + fn = function( elem, key, value ) { + return exec.call( jQuery( elem ), value ); + }; + + // Otherwise they run against the entire set + } else { + fn.call( elems, value ); + fn = null; + } + } + + if ( fn ) { + for (; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + } + + chainable = 1; + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; + }, + + now: function() { + return ( new Date() ).getTime(); + } +}); + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready, 1 ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} + + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { + + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.split( core_rspace ), function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Control if a given callback is in the list + has: function( fn ) { + return jQuery.inArray( fn, list ) > -1; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( list && ( !fired || stack ) ) { + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var action = tuple[ 0 ], + fn = fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? + function() { + var returned = fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); + } + } : + newDefer[ action ] + ); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] = list.fire + deferred[ tuple[0] ] = list.fire; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = core_slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; + if( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); +jQuery.support = (function() { + + var support, + all, + a, + select, + opt, + input, + fragment, + eventName, + i, + isSupported, + clickFn, + div = document.createElement("div"); + + // Setup + div.setAttribute( "className", "t" ); + div.innerHTML = "
    a"; + + // Support tests won't run in some limited or non-browser environments + all = div.getElementsByTagName("*"); + a = div.getElementsByTagName("a")[ 0 ]; + if ( !all || !a || !all.length ) { + return {}; + } + + // First batch of tests + select = document.createElement("select"); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName("input")[ 0 ]; + + a.style.cssText = "top:1px;float:left;opacity:.5"; + support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: ( div.firstChild.nodeType === 3 ), + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: ( a.getAttribute("href") === "/a" ), + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.5/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: ( input.value === "on" ), + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // Tests for enctype support on a form (#6743) + enctype: !!document.createElement("form").enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", + + // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode + boxModel: ( document.compatMode === "CSS1Compat" ), + + // Will be defined later + submitBubbles: true, + changeBubbles: true, + focusinBubbles: false, + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true, + boxSizingReliable: true, + pixelPosition: false + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent( "onclick", clickFn = function() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + support.noCloneEvent = false; + }); + div.cloneNode( true ).fireEvent("onclick"); + div.detachEvent( "onclick", clickFn ); + } + + // Check if a radio maintains its value + // after being appended to the DOM + input = document.createElement("input"); + input.value = "t"; + input.setAttribute( "type", "radio" ); + support.radioValue = input.value === "t"; + + input.setAttribute( "checked", "checked" ); + + // #11217 - WebKit loses check when the name is after the checked attribute + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + fragment = document.createDocumentFragment(); + fragment.appendChild( div.lastChild ); + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + fragment.removeChild( input ); + fragment.appendChild( div ); + + // Technique from Juriy Zaytsev + // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( div.attachEvent ) { + for ( i in { + submit: true, + change: true, + focusin: true + }) { + eventName = "on" + i; + isSupported = ( eventName in div ); + if ( !isSupported ) { + div.setAttribute( eventName, "return;" ); + isSupported = ( typeof div[ eventName ] === "function" ); + } + support[ i + "Bubbles" ] = isSupported; + } + } + + // Run tests that need a body at doc ready + jQuery(function() { + var container, div, tds, marginDiv, + divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + container = document.createElement("div"); + container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; + body.insertBefore( container, body.firstChild ); + + // Construct the test element + div = document.createElement("div"); + container.appendChild( div ); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + div.innerHTML = "
    t
    "; + tds = div.getElementsByTagName("td"); + tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE <= 8 fail this test) + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Check box-sizing and margin behavior + div.innerHTML = ""; + div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; + support.boxSizing = ( div.offsetWidth === 4 ); + support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); + + // NOTE: To any future maintainer, we've window.getComputedStyle + // because jsdom on node.js will break without it. + if ( window.getComputedStyle ) { + support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; + support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. For more + // info see bug #3333 + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + marginDiv = document.createElement("div"); + marginDiv.style.cssText = div.style.cssText = divReset; + marginDiv.style.marginRight = marginDiv.style.width = "0"; + div.style.width = "1px"; + div.appendChild( marginDiv ); + support.reliableMarginRight = + !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); + } + + if ( typeof div.style.zoom !== "undefined" ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.innerHTML = ""; + div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = "block"; + div.style.overflow = "visible"; + div.innerHTML = "
    "; + div.firstChild.style.width = "5px"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); + + container.style.zoom = 1; + } + + // Null elements to avoid leaks in IE + body.removeChild( container ); + container = div = tds = marginDiv = null; + }); + + // Null elements to avoid leaks in IE + fragment.removeChild( div ); + all = a = select = opt = input = fragment = div = null; + + return support; +})(); +var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, + rmultiDash = /([A-Z])/g; + +jQuery.extend({ + cache: {}, + + deletedIds: [], + + // Remove at next major release (1.9/2.0) + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, l, + + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); + } + } + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + } else if ( jQuery.support.deleteExpando || cache != cache.window ) { + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; + + // nodes accept data unless otherwise specified; rejection can be conditional + return !noData || noData !== true && elem.getAttribute("classid") === noData; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var parts, part, attr, name, l, + elem = this[0], + i = 0, + data = null; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + attr = elem.attributes; + for ( l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( !name.indexOf( "data-" ) ) { + name = jQuery.camelCase( name.substring(5) ); + + dataAttr( elem, name, data[ name ] ); + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + parts = key.split( ".", 2 ); + parts[1] = parts[1] ? "." + parts[1] : ""; + part = parts[1] + "!"; + + return jQuery.access( this, function( value ) { + + if ( value === undefined ) { + data = this.triggerHandler( "getData" + part, [ parts[0] ] ); + + // Try to fetch any internally stored data first + if ( data === undefined && elem ) { + data = jQuery.data( elem, key ); + data = dataAttr( elem, key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + } + + parts[1] = value; + this.each(function() { + var self = jQuery( this ); + + self.triggerHandler( "setData" + part, parts ); + jQuery.data( this, key, value ); + self.triggerHandler( "changeData" + part, parts ); + }); + }, null, value, arguments.length > 1, null, false ); + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery.removeData( elem, type + "queue", true ); + jQuery.removeData( elem, key, true ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var nodeHook, boolHook, fixSpecified, + rclass = /[\t\r\n]/g, + rreturn = /\r/g, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea|)$/i, + rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classNames, i, l, elem, + setClass, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call(this, j, this.className) ); + }); + } + + if ( value && typeof value === "string" ) { + classNames = value.split( core_rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className && classNames.length === 1 ) { + elem.className = value; + + } else { + setClass = " " + elem.className + " "; + + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { + setClass += classNames[ c ] + " "; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var removes, className, elem, c, cl, i, l; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call(this, j, this.className) ); + }); + } + if ( (value && typeof value === "string") || value === undefined ) { + removes = ( value || "" ).split( core_rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + if ( elem.nodeType === 1 && elem.className ) { + + className = (" " + elem.className + " ").replace( rclass, " " ); + + // loop over each item in the removal list + for ( c = 0, cl = removes.length; c < cl; c++ ) { + // Remove until there is nothing to remove, + while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { + className = className.replace( " " + removes[ c ] + " " , " " ); + } + } + elem.className = value ? jQuery.trim( className ) : ""; + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.split( core_rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space separated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var hooks, ret, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var val, + self = jQuery(this); + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, option, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one" || index < 0, + values = one ? null : [], + max = one ? index + 1 : options.length, + i = index < 0 ? + max : + one ? index : 0; + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // oldIE doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + // Don't return options that are disabled or in a disabled optgroup + ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && + ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 + attrFn: {}, + + attr: function( elem, name, value, pass ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { + return jQuery( elem )[ name ]( value ); + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + + } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, value + "" ); + return value; + } + + } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret === null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var propName, attrNames, name, isBool, + i = 0; + + if ( value && elem.nodeType === 1 ) { + + attrNames = value.split( core_rspace ); + + for ( ; i < attrNames.length; i++ ) { + name = attrNames[ i ]; + + if ( name ) { + propName = jQuery.propFix[ name ] || name; + isBool = rboolean.test( name ); + + // See #9699 for explanation of this approach (setting first, then removal) + // Do not do this for boolean attributes (see #10870) + if ( !isBool ) { + jQuery.attr( elem, name, "" ); + } + elem.removeAttribute( getSetAttribute ? name : propName ); + + // Set corresponding property to false for boolean attributes + if ( isBool && propName in elem ) { + elem[ propName ] = false; + } + } + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to it's default in case type is set after value + // This is for element creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }, + // Use the value property for back compat + // Use the nodeHook for button elements in IE6/7 (#1954) + value: { + get: function( elem, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set: function( elem, value, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + // Align boolean attributes with corresponding properties + // Fall back to attribute presence where some booleans are not supported + var attrNode, + property = jQuery.prop( elem, name ); + return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + var propName; + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + // value is true since we know at this point it's type boolean and not false + // Set boolean attributes to the same name and set the DOM property + propName = jQuery.propFix[ name ] || name; + if ( propName in elem ) { + // Only set the IDL specifically if it already exists on the element + elem[ propName ] = true; + } + + elem.setAttribute( name, name.toLowerCase() ); + } + return name; + } +}; + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + fixSpecified = { + name: true, + id: true, + coords: true + }; + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret; + ret = elem.getAttributeNode( name ); + return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? + ret.value : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + ret = document.createAttribute( name ); + elem.setAttributeNode( ret ); + } + return ( ret.value = value + "" ); + } + }; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + if ( value === "" ) { + value = "false"; + } + nodeHook.set( elem, value, name ); + } + }; +} + + +// Some attributes require a special call on IE +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret === null ? undefined : ret; + } + }); + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Normalize to lowercase since IE uppercases css property names + return elem.style.cssText.toLowerCase() || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = value + "" ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); +var rformElems = /^(?:textarea|input|select)$/i, + rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, + rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + hoverHack = function( events ) { + return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); + }; + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + add: function( elem, types, handler, data, selector ) { + + var elemData, eventHandle, events, + t, tns, type, namespaces, handleObj, + handleObjIn, handlers, special; + + // Don't attach events to noData or text/comment nodes (allow plain objects tho) + if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + events = elemData.events; + if ( !events ) { + elemData.events = events = {}; + } + eventHandle = elemData.handle; + if ( !eventHandle ) { + elemData.handle = eventHandle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = jQuery.trim( hoverHack(types) ).split( " " ); + for ( t = 0; t < types.length; t++ ) { + + tns = rtypenamespace.exec( types[t] ) || []; + type = tns[1]; + namespaces = ( tns[2] || "" ).split( "." ).sort(); + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: tns[1], + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + handlers = events[ type ]; + if ( !handlers ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var t, tns, type, origType, namespaces, origCount, + j, events, special, eventType, handleObj, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = jQuery.trim( hoverHack( types || "" ) ).split(" "); + for ( t = 0; t < types.length; t++ ) { + tns = rtypenamespace.exec( types[t] ) || []; + type = origType = tns[1]; + namespaces = tns[2]; + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector? special.delegateType : special.bindType ) || type; + eventType = events[ type ] || []; + origCount = eventType.length; + namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; + + // Remove matching events + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !namespaces || namespaces.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + eventType.splice( j--, 1 ); + + if ( handleObj.selector ) { + eventType.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( eventType.length === 0 && origCount !== eventType.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery.removeData( elem, "events", true ); + } + }, + + // Events that are safe to short-circuit if no handlers are attached. + // Native DOM events should not be added, they may have inline handlers. + customEvent: { + "getData": true, + "setData": true, + "changeData": true + }, + + trigger: function( event, data, elem, onlyHandlers ) { + // Don't do events on text and comment nodes + if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { + return; + } + + // Event object or event type + var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, + type = event.type || event, + namespaces = []; + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "!" ) >= 0 ) { + // Exclusive events trigger only for the exact event (no namespaces) + type = type.slice(0, -1); + exclusive = true; + } + + if ( type.indexOf( "." ) >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + + if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { + // No jQuery handlers for this event type, and it can't have inline handlers + return; + } + + // Caller can pass in an Event, Object, or just an event type string + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + new jQuery.Event( type, event ) : + // Just the event type (string) + new jQuery.Event( type ); + + event.type = type; + event.isTrigger = true; + event.exclusive = exclusive; + event.namespace = namespaces.join( "." ); + event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; + ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; + + // Handle a global trigger + if ( !elem ) { + + // TODO: Stop taunting the data cache; remove global events and always attach to document + cache = jQuery.cache; + for ( i in cache ) { + if ( cache[ i ].events && cache[ i ].events[ type ] ) { + jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); + } + } + return; + } + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data != null ? jQuery.makeArray( data ) : []; + data.unshift( event ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + eventPath = [[ elem, special.bindType || type ]]; + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; + for ( old = elem; cur; cur = cur.parentNode ) { + eventPath.push([ cur, bubbleType ]); + old = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( old === (elem.ownerDocument || document) ) { + eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); + } + } + + // Fire handlers on the event path + for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { + + cur = eventPath[i][0]; + event.type = eventPath[i][1]; + + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + // Note that this is a bare JS function and not a jQuery handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + // IE<9 dies on focus/blur to hidden element (#1486) + if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + old = elem[ ontype ]; + + if ( old ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( old ) { + elem[ ontype ] = old; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event || window.event ); + + var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, + handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), + delegateCount = handlers.delegateCount, + args = core_slice.call( arguments ), + run_all = !event.exclusive && !event.namespace, + special = jQuery.event.special[ event.type ] || {}, + handlerQueue = []; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers that should run if there are delegated events + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && !(event.button && event.type === "click") ) { + + for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { + + // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.disabled !== true || event.type !== "click" ) { + selMatch = {}; + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + sel = handleObj.selector; + + if ( selMatch[ sel ] === undefined ) { + selMatch[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( selMatch[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, matches: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( handlers.length > delegateCount ) { + handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); + } + + // Run delegates first; they may want to stop propagation beneath us + for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { + matched = handlerQueue[ i ]; + event.currentTarget = matched.elem; + + for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { + handleObj = matched.matches[ j ]; + + // Triggered event must either 1) be non-exclusive and have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { + + event.data = handleObj.data; + event.handleObj = handleObj; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** + props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, + originalEvent = event, + fixHook = jQuery.event.fixHooks[ event.type ] || {}, + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = jQuery.Event( originalEvent ); + + for ( i = copy.length; i; ) { + prop = copy[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Target should not be a text node (#504, Safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) + event.metaKey = !!event.metaKey; + + return fixHook.filter? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + + focus: { + delegateType: "focusin" + }, + blur: { + delegateType: "focusout" + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +// Some plugins are using, but it's undocumented/deprecated and will be removed. +// The 1.7 special event interface should provide all the hooks needed now. +jQuery.event.handle = jQuery.event.dispatch; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + var name = "on" + type; + + if ( elem.detachEvent ) { + + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === "undefined" ) { + elem[ name ] = null; + } + + elem.detachEvent( name, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj, + selector = handleObj.selector; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "_submit_attached" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "_submit_attached", true ); + } + }); + // return undefined since we don't need an event listener + }, + + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "_change_attached", true ); + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return !rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { // && selector != null + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + live: function( types, data, fn ) { + jQuery( this.context ).on( types, this.selector, data, fn ); + return this; + }, + die: function( types, fn ) { + jQuery( this.context ).off( types, this.selector || "**", fn ); + return this; + }, + + delegate: function( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate: function( selector, types, fn ) { + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + if ( this[0] ) { + return jQuery.event.trigger( type, data, this[0], true ); + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + guid = fn.guid || jQuery.guid++, + i = 0, + toggler = function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + }; + + // link all the functions, so any of them can unbind this click handler + toggler.guid = guid; + while ( i < args.length ) { + args[ i++ ].guid = guid; + } + + return this.click( toggler ); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; + + if ( rkeyEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; + } + + if ( rmouseEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; + } +}); +/*! + * Sizzle CSS Selector Engine + * Copyright 2012 jQuery Foundation and other contributors + * Released under the MIT license + * http://sizzlejs.com/ + */ +(function( window, undefined ) { + +var cachedruns, + assertGetIdNotName, + Expr, + getText, + isXML, + contains, + compile, + sortOrder, + hasDuplicate, + outermostContext, + + baseHasDuplicate = true, + strundefined = "undefined", + + expando = ( "sizcache" + Math.random() ).replace( ".", "" ), + + Token = String, + document = window.document, + docElem = document.documentElement, + dirruns = 0, + done = 0, + pop = [].pop, + push = [].push, + slice = [].slice, + // Use a stripped-down indexOf if a native one is unavailable + indexOf = [].indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + // Augment a function for special use by Sizzle + markFunction = function( fn, value ) { + fn[ expando ] = value == null || value; + return fn; + }, + + createCache = function() { + var cache = {}, + keys = []; + + return markFunction(function( key, value ) { + // Only keep the most recent entries + if ( keys.push( key ) > Expr.cacheLength ) { + delete cache[ keys.shift() ]; + } + + // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157) + return (cache[ key + " " ] = value); + }, cache ); + }, + + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + + // Regex + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors + operators = "([*^$|!~]?=)", + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", + + // Prefer arguments not in parens/brackets, + // then attribute selectors and non-pseudos (denoted by :), + // then anything else + // These preferences are here to reduce the number of selectors + // needing tokenize in the PSEUDO preFilter + pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", + + // For matchExpr.POS and matchExpr.needsContext + pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), + rpseudo = new RegExp( pseudos ), + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, + + rnot = /^:not/, + rsibling = /[\x20\t\r\n\f]*[+~]/, + rendsWithNot = /:not\($/, + + rheader = /h\d/i, + rinputs = /input|select|textarea|button/i, + + rbackslash = /\\(?!\\)/g, + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "POS": new RegExp( pos, "i" ), + "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + // For use in libraries implementing .is() + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) + }, + + // Support + + // Used for testing something on an element + assert = function( fn ) { + var div = document.createElement("div"); + + try { + return fn( div ); + } catch (e) { + return false; + } finally { + // release memory in IE + div = null; + } + }, + + // Check if getElementsByTagName("*") returns only elements + assertTagNameNoComments = assert(function( div ) { + div.appendChild( document.createComment("") ); + return !div.getElementsByTagName("*").length; + }), + + // Check if getAttribute returns normalized href attributes + assertHrefNotNormalized = assert(function( div ) { + div.innerHTML = ""; + return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && + div.firstChild.getAttribute("href") === "#"; + }), + + // Check if attributes should be retrieved by attribute nodes + assertAttributes = assert(function( div ) { + div.innerHTML = ""; + var type = typeof div.lastChild.getAttribute("multiple"); + // IE8 returns a string for some attributes even when not present + return type !== "boolean" && type !== "string"; + }), + + // Check if getElementsByClassName can be trusted + assertUsableClassName = assert(function( div ) { + // Opera can't find a second classname (in 9.6) + div.innerHTML = ""; + if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { + return false; + } + + // Safari 3.2 caches class attributes and doesn't catch changes + div.lastChild.className = "e"; + return div.getElementsByClassName("e").length === 2; + }), + + // Check if getElementById returns elements by name + // Check if getElementsByName privileges form controls or returns elements by ID + assertUsableName = assert(function( div ) { + // Inject content + div.id = expando + 0; + div.innerHTML = "
    "; + docElem.insertBefore( div, docElem.firstChild ); + + // Test + var pass = document.getElementsByName && + // buggy browsers will return fewer than the correct 2 + document.getElementsByName( expando ).length === 2 + + // buggy browsers will return more than the correct 0 + document.getElementsByName( expando + 0 ).length; + assertGetIdNotName = !document.getElementById( expando ); + + // Cleanup + docElem.removeChild( div ); + + return pass; + }); + +// If slice is not available, provide a backup +try { + slice.call( docElem.childNodes, 0 )[0].nodeType; +} catch ( e ) { + slice = function( i ) { + var elem, + results = []; + for ( ; (elem = this[i]); i++ ) { + results.push( elem ); + } + return results; + }; +} + +function Sizzle( selector, context, results, seed ) { + results = results || []; + context = context || document; + var match, elem, xml, m, + nodeType = context.nodeType; + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + if ( nodeType !== 1 && nodeType !== 9 ) { + return []; + } + + xml = isXML( context ); + + if ( !xml && !seed ) { + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { + push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); + return results; + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); +} + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + return Sizzle( expr, null, null, [ elem ] ).length > 0; +}; + +// Returns a function to use in pseudos for input types +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +// Returns a function to use in pseudos for buttons +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +// Returns a function to use in pseudos for positionals +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( nodeType ) { + if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (see #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + } else { + + // If no nodeType, this is expected to be an array + for ( ; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } + return ret; +}; + +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +// Element contains another +contains = Sizzle.contains = docElem.contains ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); + } : + docElem.compareDocumentPosition ? + function( a, b ) { + return b && !!( a.compareDocumentPosition( b ) & 16 ); + } : + function( a, b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + return false; + }; + +Sizzle.attr = function( elem, name ) { + var val, + xml = isXML( elem ); + + if ( !xml ) { + name = name.toLowerCase(); + } + if ( (val = Expr.attrHandle[ name ]) ) { + return val( elem ); + } + if ( xml || assertAttributes ) { + return elem.getAttribute( name ); + } + val = elem.getAttributeNode( name ); + return val ? + typeof elem[ name ] === "boolean" ? + elem[ name ] ? name : null : + val.specified ? val.value : null : + null; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + // IE6/7 return a modified href + attrHandle: assertHrefNotNormalized ? + {} : + { + "href": function( elem ) { + return elem.getAttribute( "href", 2 ); + }, + "type": function( elem ) { + return elem.getAttribute("type"); + } + }, + + find: { + "ID": assertGetIdNotName ? + function( id, context, xml ) { + if ( typeof context.getElementById !== strundefined && !xml ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + } : + function( id, context, xml ) { + if ( typeof context.getElementById !== strundefined && !xml ) { + var m = context.getElementById( id ); + + return m ? + m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? + [m] : + undefined : + []; + } + }, + + "TAG": assertTagNameNoComments ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + var elem, + tmp = [], + i = 0; + + for ( ; (elem = results[i]); i++ ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }, + + "NAME": assertUsableName && function( tag, context ) { + if ( typeof context.getElementsByName !== strundefined ) { + return context.getElementsByName( name ); + } + }, + + "CLASS": assertUsableClassName && function( className, context, xml ) { + if ( typeof context.getElementsByClassName !== strundefined && !xml ) { + return context.getElementsByClassName( className ); + } + } + }, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( rbackslash, "" ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 3 xn-component of xn+y argument ([+-]?\d*n|) + 4 sign of xn-component + 5 x of xn-component + 6 sign of y-component + 7 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1] === "nth" ) { + // nth-child requires argument + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); + match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); + + // other types prohibit arguments + } else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var unquoted, excess; + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + if ( match[3] ) { + match[2] = match[3]; + } else if ( (unquoted = match[4]) ) { + // Only check arguments that contain a pseudo + if ( rpseudo.test(unquoted) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + unquoted = unquoted.slice( 0, excess ); + match[0] = match[0].slice( 0, excess ); + } + match[2] = unquoted; + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + "ID": assertGetIdNotName ? + function( id ) { + id = id.replace( rbackslash, "" ); + return function( elem ) { + return elem.getAttribute("id") === id; + }; + } : + function( id ) { + id = id.replace( rbackslash, "" ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === id; + }; + }, + + "TAG": function( nodeName ) { + if ( nodeName === "*" ) { + return function() { return true; }; + } + nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); + + return function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ expando ][ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem, context ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.substr( result.length - check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, argument, first, last ) { + + if ( type === "nth" ) { + return function( elem ) { + var node, diff, + parent = elem.parentNode; + + if ( first === 1 && last === 0 ) { + return true; + } + + if ( parent ) { + diff = 0; + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + diff++; + if ( elem === node ) { + break; + } + } + } + } + + // Incorporate the offset (or cast to NaN), then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + }; + } + + return function( elem ) { + var node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + /* falls through */ + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + var nodeType; + elem = elem.firstChild; + while ( elem ) { + if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { + return false; + } + elem = elem.nextSibling; + } + return true; + }, + + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "text": function( elem ) { + var type, attr; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && + (type = elem.type) === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); + }, + + // Input types + "radio": createInputPseudo("radio"), + "checkbox": createInputPseudo("checkbox"), + "file": createInputPseudo("file"), + "password": createInputPseudo("password"), + "image": createInputPseudo("image"), + + "submit": createButtonPseudo("submit"), + "reset": createButtonPseudo("reset"), + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "focus": function( elem ) { + var doc = elem.ownerDocument; + return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + "active": function( elem ) { + return elem === elem.ownerDocument.activeElement; + }, + + // Positional types + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + for ( var i = 0; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + for ( var i = 1; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +function siblingCheck( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; +} + +sortOrder = docElem.compareDocumentPosition ? + function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? + a.compareDocumentPosition : + a.compareDocumentPosition(b) & 4 + ) ? -1 : 1; + } : + function( a, b ) { + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; + } + + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // If the nodes are siblings (or identical) we can do a quick check + if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + +// Always assume the presence of duplicates if sort doesn't +// pass them to our comparison function (as in Google Chrome). +[0, 0].sort( sortOrder ); +baseHasDuplicate = !hasDuplicate; + +// Document sorting and removing duplicates +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + i = 1, + j = 0; + + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( ; (elem = results[i]); i++ ) { + if ( elem === results[ i - 1 ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + return results; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +function tokenize( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ expando ][ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( tokens = [] ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + tokens.push( matched = new Token( match.shift() ) ); + soFar = soFar.slice( matched.length ); + + // Cast descendant combinators to space + matched.type = match[0].replace( rtrim, " " ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + + tokens.push( matched = new Token( match.shift() ) ); + soFar = soFar.slice( matched.length ); + matched.type = type; + matched.matches = match; + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && combinator.dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( checkNonElements || elem.nodeType === 1 ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( !xml ) { + var cache, + dirkey = dirruns + " " + doneName + " ", + cachedkey = dirkey + cachedruns; + while ( (elem = elem[ dir ]) ) { + if ( checkNonElements || elem.nodeType === 1 ) { + if ( (cache = elem[ expando ]) === cachedkey ) { + return elem.sizset; + } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { + if ( elem.sizset ) { + return elem; + } + } else { + elem[ expando ] = cachedkey; + if ( matcher( elem, context, xml ) ) { + elem.sizset = true; + return elem; + } + elem.sizset = false; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( checkNonElements || elem.nodeType === 1 ) { + if ( matcher( elem, context, xml ) ) { + return elem; + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && tokens.join("") + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, expandContext ) { + var elem, j, matcher, + setMatched = [], + matchedCount = 0, + i = "0", + unmatched = seed && [], + outermost = expandContext != null, + contextBackup = outermostContext, + // We must always have either seed elements or context + elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), + // Nested matchers should use non-integer dirruns + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = superMatcher.el; + } + + // Add elements passing elementMatchers directly to results + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + for ( j = 0; (matcher = elementMatchers[j]); j++ ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++superMatcher.el; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + for ( j = 0; (matcher = setMatchers[j]); j++ ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + superMatcher.el = 0; + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ expando ][ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !group ) { + group = tokenize( selector ); + } + i = group.length; + while ( i-- ) { + cached = matcherFromTokens( group[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + } + return cached; +}; + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function select( selector, context, results, seed, xml ) { + var i, tokens, token, type, find, + match = tokenize( selector ), + j = match.length; + + if ( !seed ) { + // Try to minimize operations if there is only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + context.nodeType === 9 && !xml && + Expr.relative[ tokens[1].type ] ) { + + context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; + if ( !context ) { + return results; + } + + selector = selector.slice( tokens.shift().length ); + } + + // Fetch a seed set for right-to-left matching + for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( rbackslash, "" ), + rsibling.test( tokens[0].type ) && context.parentNode || context, + xml + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && tokens.join(""); + if ( !selector ) { + push.apply( results, slice.call( seed, 0 ) ); + return results; + } + + break; + } + } + } + } + } + + // Compile and execute a filtering function + // Provide `match` to avoid retokenization if we modified the selector above + compile( selector, match )( + seed, + context, + xml, + results, + rsibling.test( selector ) + ); + return results; +} + +if ( document.querySelectorAll ) { + (function() { + var disconnectedMatch, + oldSelect = select, + rescape = /'|\\/g, + rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, + + // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA + // A support test would require too much code (would include document ready) + rbuggyQSA = [ ":focus" ], + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + // A support test would require too much code (would include document ready) + // just skip matchesSelector for :active + rbuggyMatches = [ ":active" ], + matches = docElem.matchesSelector || + docElem.mozMatchesSelector || + docElem.webkitMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector; + + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explictly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // IE8 - Some boolean attributes are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here (do not put tests after this one) + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + + // Opera 10-12/IE9 - ^= $= *= and empty values + // Should not select anything + div.innerHTML = "

    "; + if ( div.querySelectorAll("[test^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here (do not put tests after this one) + div.innerHTML = ""; + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push(":enabled", ":disabled"); + } + }); + + // rbuggyQSA always contains :focus, so no need for a length check + rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); + + select = function( selector, context, results, seed, xml ) { + // Only use querySelectorAll when not filtering, + // when this is not xml, + // and when no QSA bugs apply + if ( !seed && !xml && !rbuggyQSA.test( selector ) ) { + var groups, i, + old = true, + nid = expando, + newContext = context, + newSelector = context.nodeType === 9 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + groups[i].join(""); + } + newContext = rsibling.test( selector ) && context.parentNode || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, slice.call( newContext.querySelectorAll( + newSelector + ), 0 ) ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + + return oldSelect( selector, context, results, seed, xml ); + }; + + if ( matches ) { + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + try { + matches.call( div, "[test!='']:sizzle" ); + rbuggyMatches.push( "!=", pseudos ); + } catch ( e ) {} + }); + + // rbuggyMatches always contains :active and :focus, so no need for a length check + rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); + + Sizzle.matchesSelector = function( elem, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + // rbuggyMatches always contains :active, so no need for an existence check + if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) { + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch(e) {} + } + + return Sizzle( expr, null, null, [ elem ] ).length > 0; + }; + } + })(); +} + +// Deprecated +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Back-compat +function setFilters() {} +Expr.filters = setFilters.prototype = Expr.pseudos; +Expr.setFilters = new setFilters(); + +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})( window ); +var runtil = /Until$/, + rparentsprev = /^(?:parents|prev(?:Until|All))/, + isSimple = /^.[^:#\[\.,]*$/, + rneedsContext = jQuery.expr.match.needsContext, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var i, l, length, n, r, ret, + self = this; + + if ( typeof selector !== "string" ) { + return jQuery( selector ).filter(function() { + for ( i = 0, l = self.length; i < l; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }); + } + + ret = this.pushStack( "", "find", selector ); + + for ( i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( n = length; n < ret.length; n++ ) { + for ( r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + rneedsContext.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + ret = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + cur = this[i]; + + while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + } + cur = cur.parentNode; + } + } + + ret = ret.length > 1 ? jQuery.unique( ret ) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +jQuery.fn.andSelf = jQuery.fn.addBack; + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); + + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( this.length > 1 && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rtbody = /]", "i"), + rcheckableType = /^(?:checkbox|radio)$/, + // checked="checked" or checked + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, + rscriptType = /\/(java|ecma)script/i, + rcleanScript = /^\s*\s*$/g, + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
    ", "
    " ], + thead: [ 1, "", "
    " ], + tr: [ 2, "", "
    " ], + td: [ 3, "", "
    " ], + col: [ 2, "", "
    " ], + area: [ 1, "", "" ], + _default: [ 0, "", "" ] + }, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, +// unless wrapped in a div with non-breaking characters in front of it. +if ( !jQuery.support.htmlSerialize ) { + wrapMap._default = [ 1, "X
    ", "
    " ]; +} + +jQuery.fn.extend({ + text: function( value ) { + return jQuery.access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + wrapAll: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapAll( html.call(this, i) ); + }); + } + + if ( this[0] ) { + // The elements to wrap the target around + var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); + + if ( this[0].parentNode ) { + wrap.insertBefore( this[0] ); + } + + wrap.map(function() { + var elem = this; + + while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { + elem = elem.firstChild; + } + + return elem; + }).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapInner( html.call(this, i) ); + }); + } + + return this.each(function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + }); + }, + + wrap: function( html ) { + var isFunction = jQuery.isFunction( html ); + + return this.each(function(i) { + jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); + }); + }, + + unwrap: function() { + return this.parent().each(function() { + if ( !jQuery.nodeName( this, "body" ) ) { + jQuery( this ).replaceWith( this.childNodes ); + } + }).end(); + }, + + append: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 ) { + this.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 ) { + this.insertBefore( elem, this.firstChild ); + } + }); + }, + + before: function() { + if ( !isDisconnected( this[0] ) ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this ); + }); + } + + if ( arguments.length ) { + var set = jQuery.clean( arguments ); + return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); + } + }, + + after: function() { + if ( !isDisconnected( this[0] ) ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + }); + } + + if ( arguments.length ) { + var set = jQuery.clean( arguments ); + return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); + } + }, + + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + jQuery.cleanData( [ elem ] ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function () { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return jQuery.access( this, function( value ) { + var elem = this[0] || {}, + i = 0, + l = this.length; + + if ( value === undefined ) { + return elem.nodeType === 1 ? + elem.innerHTML.replace( rinlinejQuery, "" ) : + undefined; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName( "*" ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch(e) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function( value ) { + if ( !isDisconnected( this[0] ) ) { + // Make sure that the elements are removed from the DOM before they are inserted + // this can help fix replacing a parent with child elements + if ( jQuery.isFunction( value ) ) { + return this.each(function(i) { + var self = jQuery(this), old = self.html(); + self.replaceWith( value.call( this, i, old ) ); + }); + } + + if ( typeof value !== "string" ) { + value = jQuery( value ).detach(); + } + + return this.each(function() { + var next = this.nextSibling, + parent = this.parentNode; + + jQuery( this ).remove(); + + if ( next ) { + jQuery(next).before( value ); + } else { + jQuery(parent).append( value ); + } + }); + } + + return this.length ? + this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : + this; + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, table, callback ) { + + // Flatten any nested arrays + args = [].concat.apply( [], args ); + + var results, first, fragment, iNoClone, + i = 0, + value = args[0], + scripts = [], + l = this.length; + + // We can't cloneNode fragments that contain checked, in WebKit + if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { + return this.each(function() { + jQuery(this).domManip( args, table, callback ); + }); + } + + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + args[0] = value.call( this, i, table ? self.html() : undefined ); + self.domManip( args, table, callback ); + }); + } + + if ( this[0] ) { + results = jQuery.buildFragment( args, this, scripts ); + fragment = results.fragment; + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + table = table && jQuery.nodeName( first, "tr" ); + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + // Fragments from the fragment cache must always be cloned and never used in place. + for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { + callback.call( + table && jQuery.nodeName( this[i], "table" ) ? + findOrAppend( this[i], "tbody" ) : + this[i], + i === iNoClone ? + fragment : + jQuery.clone( fragment, true, true ) + ); + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + + if ( scripts.length ) { + jQuery.each( scripts, function( i, elem ) { + if ( elem.src ) { + if ( jQuery.ajax ) { + jQuery.ajax({ + url: elem.src, + type: "GET", + dataType: "script", + async: false, + global: false, + "throws": true + }); + } else { + jQuery.error("no ajax"); + } + } else { + jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } + }); + } + } + + return this; + } +}); + +function findOrAppend( elem, tag ) { + return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function cloneFixAttributes( src, dest ) { + var nodeName; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + // clearAttributes removes the attributes, which we don't want, + // but also removes the attachEvent events, which we *do* want + if ( dest.clearAttributes ) { + dest.clearAttributes(); + } + + // mergeAttributes, in contrast, only merges back on the + // original attributes, not the events + if ( dest.mergeAttributes ) { + dest.mergeAttributes( src ); + } + + nodeName = dest.nodeName.toLowerCase(); + + if ( nodeName === "object" ) { + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; + } + + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { + dest.innerHTML = src.innerHTML; + } + + } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + + dest.defaultChecked = dest.checked = src.checked; + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + + // IE blanks contents when cloning scripts + } else if ( nodeName === "script" && dest.text !== src.text ) { + dest.text = src.text; + } + + // Event data gets referenced instead of copied if the expando + // gets copied too + dest.removeAttribute( jQuery.expando ); +} + +jQuery.buildFragment = function( args, context, scripts ) { + var fragment, cacheable, cachehit, + first = args[ 0 ]; + + // Set context from what may come in as undefined or a jQuery collection or a node + // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & + // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception + context = context || document; + context = !context.nodeType && context[0] || context; + context = context.ownerDocument || context; + + // Only cache "small" (1/2 KB) HTML strings that are associated with the main document + // Cloning options loses the selected state, so don't cache them + // IE 6 doesn't like it when you put or elements in a fragment + // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache + // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 + if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && + first.charAt(0) === "<" && !rnocache.test( first ) && + (jQuery.support.checkClone || !rchecked.test( first )) && + (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { + + // Mark cacheable and look for a hit + cacheable = true; + fragment = jQuery.fragments[ first ]; + cachehit = fragment !== undefined; + } + + if ( !fragment ) { + fragment = context.createDocumentFragment(); + jQuery.clean( args, context, fragment, scripts ); + + // Update the cache, but only store false + // unless this is a second parsing of the same content + if ( cacheable ) { + jQuery.fragments[ first ] = cachehit && fragment; + } + } + + return { fragment: fragment, cacheable: cacheable }; +}; + +jQuery.fragments = {}; + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + i = 0, + ret = [], + insert = jQuery( selector ), + l = insert.length, + parent = this.length === 1 && this[0].parentNode; + + if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { + insert[ original ]( this[0] ); + return this; + } else { + for ( ; i < l; i++ ) { + elems = ( i > 0 ? this.clone(true) : this ).get(); + jQuery( insert[i] )[ original ]( elems ); + ret = ret.concat( elems ); + } + + return this.pushStack( ret, name, insert.selector ); + } + }; +}); + +function getAll( elem ) { + if ( typeof elem.getElementsByTagName !== "undefined" ) { + return elem.getElementsByTagName( "*" ); + + } else if ( typeof elem.querySelectorAll !== "undefined" ) { + return elem.querySelectorAll( "*" ); + + } else { + return []; + } +} + +// Used in clean, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var srcElements, + destElements, + i, + clone; + + if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { + clone = elem.cloneNode( true ); + + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } + + if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + // IE copies events bound via attachEvent when using cloneNode. + // Calling detachEvent on the clone will also remove the events + // from the original. In order to get around this, we use some + // proprietary methods to clear the events. Thanks to MooTools + // guys for this hotness. + + cloneFixAttributes( elem, clone ); + + // Using Sizzle here is crazy slow, so we use getElementsByTagName instead + srcElements = getAll( elem ); + destElements = getAll( clone ); + + // Weird iteration because IE will replace the length property + // with an element if you are cloning the body and one of the + // elements on the page has a name or id of "length" + for ( i = 0; srcElements[i]; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + cloneFixAttributes( srcElements[i], destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + cloneCopyEvent( elem, clone ); + + if ( deepDataAndEvents ) { + srcElements = getAll( elem ); + destElements = getAll( clone ); + + for ( i = 0; srcElements[i]; ++i ) { + cloneCopyEvent( srcElements[i], destElements[i] ); + } + } + } + + srcElements = destElements = null; + + // Return the cloned set + return clone; + }, + + clean: function( elems, context, fragment, scripts ) { + var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, + safe = context === document && safeFragment, + ret = []; + + // Ensure that context is a document + if ( !context || typeof context.createDocumentFragment === "undefined" ) { + context = document; + } + + // Use the already-created safe fragment if context permits + for ( i = 0; (elem = elems[i]) != null; i++ ) { + if ( typeof elem === "number" ) { + elem += ""; + } + + if ( !elem ) { + continue; + } + + // Convert html string into DOM nodes + if ( typeof elem === "string" ) { + if ( !rhtml.test( elem ) ) { + elem = context.createTextNode( elem ); + } else { + // Ensure a safe container in which to render the html + safe = safe || createSafeFragment( context ); + div = context.createElement("div"); + safe.appendChild( div ); + + // Fix "XHTML"-style tags in all browsers + elem = elem.replace(rxhtmlTag, "<$1>"); + + // Go to html and back, then peel off extra wrappers + tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + depth = wrap[0]; + div.innerHTML = wrap[1] + elem + wrap[2]; + + // Move to the right depth + while ( depth-- ) { + div = div.lastChild; + } + + // Remove IE's autoinserted from table fragments + if ( !jQuery.support.tbody ) { + + // String was a , *may* have spurious + hasBody = rtbody.test(elem); + tbody = tag === "table" && !hasBody ? + div.firstChild && div.firstChild.childNodes : + + // String was a bare or + wrap[1] === "
    " && !hasBody ? + div.childNodes : + []; + + for ( j = tbody.length - 1; j >= 0 ; --j ) { + if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { + tbody[ j ].parentNode.removeChild( tbody[ j ] ); + } + } + } + + // IE completely kills leading whitespace when innerHTML is used + if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); + } + + elem = div.childNodes; + + // Take out of fragment container (we need a fresh div each time) + div.parentNode.removeChild( div ); + } + } + + if ( elem.nodeType ) { + ret.push( elem ); + } else { + jQuery.merge( ret, elem ); + } + } + + // Fix #11356: Clear elements from safeFragment + if ( div ) { + elem = div = safe = null; + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !jQuery.support.appendChecked ) { + for ( i = 0; (elem = ret[i]) != null; i++ ) { + if ( jQuery.nodeName( elem, "input" ) ) { + fixDefaultChecked( elem ); + } else if ( typeof elem.getElementsByTagName !== "undefined" ) { + jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); + } + } + } + + // Append elements to a provided document fragment + if ( fragment ) { + // Special handling of each script element + handleScript = function( elem ) { + // Check if we consider it executable + if ( !elem.type || rscriptType.test( elem.type ) ) { + // Detach the script and store it in the scripts array (if provided) or the fragment + // Return truthy to indicate that it has been handled + return scripts ? + scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : + fragment.appendChild( elem ); + } + }; + + for ( i = 0; (elem = ret[i]) != null; i++ ) { + // Check if we're done after handling an executable script + if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { + // Append to fragment and handle embedded scripts + fragment.appendChild( elem ); + if ( typeof elem.getElementsByTagName !== "undefined" ) { + // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration + jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); + + // Splice the scripts into ret after their former ancestor and advance our index beyond them + ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); + i += jsTags.length; + } + } + } + } + + return ret; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var data, id, elem, type, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = jQuery.support.deleteExpando, + special = jQuery.event.special; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( acceptData || jQuery.acceptData( elem ) ) { + + id = elem[ internalKey ]; + data = id && cache[ id ]; + + if ( data ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Remove cache only if it was not already removed by jQuery.event.remove + if ( cache[ id ] ) { + + delete cache[ id ]; + + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( deleteExpando ) { + delete elem[ internalKey ]; + + } else if ( elem.removeAttribute ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + jQuery.deletedIds.push( id ); + } + } + } + } + } +}); +// Limit scope pollution from any deprecated API +(function() { + +var matched, browser; + +// Use of jQuery.browser is frowned upon. +// More details: http://api.jquery.com/jQuery.browser +// jQuery.uaMatch maintained for back-compat +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; + +jQuery.sub = function() { + function jQuerySub( selector, context ) { + return new jQuerySub.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySub, this ); + jQuerySub.superclass = this; + jQuerySub.fn = jQuerySub.prototype = this(); + jQuerySub.fn.constructor = jQuerySub; + jQuerySub.sub = this.sub; + jQuerySub.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { + context = jQuerySub( context ); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); + }; + jQuerySub.fn.init.prototype = jQuerySub.fn; + var rootjQuerySub = jQuerySub(document); + return jQuerySub; +}; + +})(); +var curCSS, iframe, iframeDoc, + ralpha = /alpha\([^)]*\)/i, + ropacity = /opacity=([^)]*)/, + rposition = /^(top|right|bottom|left)$/, + // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" + // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rmargin = /^margin/, + rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), + rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), + rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), + elemdisplay = { BODY: "block" }, + + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: 0, + fontWeight: 400 + }, + + cssExpand = [ "Top", "Right", "Bottom", "Left" ], + cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], + + eventsToggle = jQuery.fn.toggle; + +// return a css property mapped to a potentially vendor prefixed property +function vendorPropName( style, name ) { + + // shortcut for names that are not vendor prefixed + if ( name in style ) { + return name; + } + + // check for vendor prefixed names + var capName = name.charAt(0).toUpperCase() + name.slice(1), + origName = name, + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in style ) { + return name; + } + } + + return origName; +} + +function isHidden( elem, el ) { + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); +} + +function showHide( elements, show ) { + var elem, display, + values = [], + index = 0, + length = elements.length; + + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + values[ index ] = jQuery._data( elem, "olddisplay" ); + if ( show ) { + // Reset the inline display of this element to learn if it is + // being hidden by cascaded rules or not + if ( !values[ index ] && elem.style.display === "none" ) { + elem.style.display = ""; + } + + // Set elements which have been overridden with display: none + // in a stylesheet to whatever the default browser style is + // for such an element + if ( elem.style.display === "" && isHidden( elem ) ) { + values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); + } + } else { + display = curCSS( elem, "display" ); + + if ( !values[ index ] && display !== "none" ) { + jQuery._data( elem, "olddisplay", display ); + } + } + } + + // Set the display of most of the elements in a second loop + // to avoid the constant reflow + for ( index = 0; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + if ( !show || elem.style.display === "none" || elem.style.display === "" ) { + elem.style.display = show ? values[ index ] || "" : "none"; + } + } + + return elements; +} + +jQuery.fn.extend({ + css: function( name, value ) { + return jQuery.access( this, function( elem, name, value ) { + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + }, + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state, fn2 ) { + var bool = typeof state === "boolean"; + + if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { + return eventsToggle.apply( this, arguments ); + } + + return this.each(function() { + if ( bool ? state : isHidden( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + }); + } +}); + +jQuery.extend({ + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + + } + } + } + }, + + // Exclude the following css properties to add px + cssNumber: { + "fillOpacity": true, + "fontWeight": true, + "lineHeight": true, + "opacity": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: { + // normalize float css property + "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" + }, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = jQuery.camelCase( name ), + style = elem.style; + + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // convert relative number strings (+= or -=) to relative numbers. #7345 + if ( type === "string" && (ret = rrelNum.exec( value )) ) { + value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); + // Fixes bug #9237 + type = "number"; + } + + // Make sure that NaN and null values aren't set. See: #7116 + if ( value == null || type === "number" && isNaN( value ) ) { + return; + } + + // If a number was passed in, add 'px' to the (except for certain CSS properties) + if ( type === "number" && !jQuery.cssNumber[ origName ] ) { + value += "px"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { + // Wrapped to prevent IE from throwing errors when 'invalid' values are provided + // Fixes bug #5509 + try { + style[ name ] = value; + } catch(e) {} + } + + } else { + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, numeric, extra ) { + var val, num, hooks, + origName = jQuery.camelCase( name ); + + // Make sure that we're working with the right name + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name ); + } + + //convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Return, converting to number if forced or a qualifier was provided and val looks numeric + if ( numeric || extra !== undefined ) { + num = parseFloat( val ); + return numeric || jQuery.isNumeric( num ) ? num || 0 : val; + } + return val; + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; + } +}); + +// NOTE: To any future maintainer, we've window.getComputedStyle +// because jsdom on node.js will break without it. +if ( window.getComputedStyle ) { + curCSS = function( elem, name ) { + var ret, width, minWidth, maxWidth, + computed = window.getComputedStyle( elem, null ), + style = elem.style; + + if ( computed ) { + + // getPropertyValue is only needed for .css('filter') in IE9, see #12537 + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right + // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels + // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values + if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret; + }; +} else if ( document.documentElement.currentStyle ) { + curCSS = function( elem, name ) { + var left, rsLeft, + ret = elem.currentStyle && elem.currentStyle[ name ], + style = elem.style; + + // Avoid setting ret to empty string here + // so we don't default to auto + if ( ret == null && style && style[ name ] ) { + ret = style[ name ]; + } + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + // but not position css attributes, as those are proportional to the parent element instead + // and we can't measure the parent instead because it might trigger a "stacking dolls" problem + if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { + + // Remember the original values + left = style.left; + rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; + + // Put in the new values to get a computed value out + if ( rsLeft ) { + elem.runtimeStyle.left = elem.currentStyle.left; + } + style.left = name === "fontSize" ? "1em" : ret; + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + if ( rsLeft ) { + elem.runtimeStyle.left = rsLeft; + } + } + + return ret === "" ? "auto" : ret; + }; +} + +function setPositiveNumber( elem, value, subtract ) { + var matches = rnumsplit.exec( value ); + return matches ? + Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : + value; +} + +function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { + var i = extra === ( isBorderBox ? "border" : "content" ) ? + // If we already have the right measurement, avoid augmentation + 4 : + // Otherwise initialize for horizontal or vertical properties + name === "width" ? 1 : 0, + + val = 0; + + for ( ; i < 4; i += 2 ) { + // both box models exclude margin, so add it if we want it + if ( extra === "margin" ) { + // we use jQuery.css instead of curCSS here + // because of the reliableMarginRight CSS hook! + val += jQuery.css( elem, extra + cssExpand[ i ], true ); + } + + // From this point on we use curCSS for maximum performance (relevant in animations) + if ( isBorderBox ) { + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; + } + + // at this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; + } + } else { + // at this point, extra isn't content, so add padding + val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; + + // at this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with offset property, which is equivalent to the border-box value + var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, + valueIsBorderBox = true, + isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; + + // some non-html elements return undefined for offsetWidth, so check for null/undefined + // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 + // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 + if ( val <= 0 || val == null ) { + // Fall back to computed then uncomputed css if necessary + val = curCSS( elem, name ); + if ( val < 0 || val == null ) { + val = elem.style[ name ]; + } + + // Computed unit is not pixels. Stop here and return. + if ( rnumnonpx.test(val) ) { + return val; + } + + // we need the check for style in case a browser which returns unreliable values + // for getComputedStyle silently falls back to the reliable elem.style + valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); + + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + } + + // use the active box-sizing model to add/subtract irrelevant styles + return ( val + + augmentWidthOrHeight( + elem, + name, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox + ) + ) + "px"; +} + + +// Try to determine the default display value of an element +function css_defaultDisplay( nodeName ) { + if ( elemdisplay[ nodeName ] ) { + return elemdisplay[ nodeName ]; + } + + var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), + display = elem.css("display"); + elem.remove(); + + // If the simple way fails, + // get element's real default display by attaching it to a temp iframe + if ( display === "none" || display === "" ) { + // Use the already-created iframe if possible + iframe = document.body.appendChild( + iframe || jQuery.extend( document.createElement("iframe"), { + frameBorder: 0, + width: 0, + height: 0 + }) + ); + + // Create a cacheable copy of the iframe document on first call. + // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML + // document to it; WebKit & Firefox won't allow reusing the iframe document. + if ( !iframeDoc || !iframe.createElement ) { + iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; + iframeDoc.write(""); + iframeDoc.close(); + } + + elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); + + display = curCSS( elem, "display" ); + document.body.removeChild( iframe ); + } + + // Store the correct default display + elemdisplay[ nodeName ] = display; + + return display; +} + +jQuery.each([ "height", "width" ], function( i, name ) { + jQuery.cssHooks[ name ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + // certain elements can have dimension info if we invisibly show them + // however, it must have a current display style that would benefit from this + if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { + return jQuery.swap( elem, cssShow, function() { + return getWidthOrHeight( elem, name, extra ); + }); + } else { + return getWidthOrHeight( elem, name, extra ); + } + } + }, + + set: function( elem, value, extra ) { + return setPositiveNumber( elem, value, extra ? + augmentWidthOrHeight( + elem, + name, + extra, + jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" + ) : 0 + ); + } + }; +}); + +if ( !jQuery.support.opacity ) { + jQuery.cssHooks.opacity = { + get: function( elem, computed ) { + // IE uses filters for opacity + return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? + ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : + computed ? "1" : ""; + }, + + set: function( elem, value ) { + var style = elem.style, + currentStyle = elem.currentStyle, + opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", + filter = currentStyle && currentStyle.filter || style.filter || ""; + + // IE has trouble with opacity if it does not have layout + // Force it by setting the zoom level + style.zoom = 1; + + // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 + if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && + style.removeAttribute ) { + + // Setting style.filter to null, "" & " " still leave "filter:" in the cssText + // if "filter:" is present at all, clearType is disabled, we want to avoid this + // style.removeAttribute is IE Only, but so apparently is this code path... + style.removeAttribute( "filter" ); + + // if there there is no filter style applied in a css rule, we are done + if ( currentStyle && !currentStyle.filter ) { + return; + } + } + + // otherwise, set new filter values + style.filter = ralpha.test( filter ) ? + filter.replace( ralpha, opacity ) : + filter + " " + opacity; + } + }; +} + +// These hooks cannot be added until DOM ready because the support test +// for it is not run until after DOM ready +jQuery(function() { + if ( !jQuery.support.reliableMarginRight ) { + jQuery.cssHooks.marginRight = { + get: function( elem, computed ) { + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + // Work around by temporarily setting element display to inline-block + return jQuery.swap( elem, { "display": "inline-block" }, function() { + if ( computed ) { + return curCSS( elem, "marginRight" ); + } + }); + } + }; + } + + // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 + // getComputedStyle returns percent when specified for top/left/bottom/right + // rather than make the css module depend on the offset module, we just check for it here + if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { + jQuery.each( [ "top", "left" ], function( i, prop ) { + jQuery.cssHooks[ prop ] = { + get: function( elem, computed ) { + if ( computed ) { + var ret = curCSS( elem, prop ); + // if curCSS returns percentage, fallback to offset + return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; + } + } + }; + }); + } + +}); + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.hidden = function( elem ) { + return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); + }; + + jQuery.expr.filters.visible = function( elem ) { + return !jQuery.expr.filters.hidden( elem ); + }; +} + +// These hooks are used by animate to expand properties +jQuery.each({ + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i, + + // assumes a single number if not a string + parts = typeof value === "string" ? value.split(" ") : [ value ], + expanded = {}; + + for ( i = 0; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( !rmargin.test( prefix ) ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +}); +var r20 = /%20/g, + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, + rselectTextarea = /^(?:select|textarea)/i; + +jQuery.fn.extend({ + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map(function(){ + return this.elements ? jQuery.makeArray( this.elements ) : this; + }) + .filter(function(){ + return this.name && !this.disabled && + ( this.checked || rselectTextarea.test( this.nodeName ) || + rinput.test( this.type ) ); + }) + .map(function( i, elem ){ + var val = jQuery( this ).val(); + + return val == null ? + null : + jQuery.isArray( val ) ? + jQuery.map( val, function( val, i ){ + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + }) : + { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + }).get(); + } +}); + +//Serialize an array of form elements or a set of +//key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, value ) { + // If value is a function, invoke it and return its value + value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); + s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); + }; + + // Set traditional to true for jQuery <= 1.3.2 behavior. + if ( traditional === undefined ) { + traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + }); + + } else { + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ).replace( r20, "+" ); +}; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( jQuery.isArray( obj ) ) { + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + // If array item is non-scalar (array or object), encode its + // numeric index to resolve deserialization ambiguity issues. + // Note that rack (as of 1.0.0) can't currently deserialize + // nested arrays properly, and attempting to do so may cause + // a server error. Possible fixes are to modify rack's + // deserialization algorithm or to provide an option or flag + // to force array serialization to be shallow. + buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); + } + }); + + } else if ( !traditional && jQuery.type( obj ) === "object" ) { + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + // Serialize scalar item. + add( prefix, obj ); + } +} +var + // Document location + ajaxLocParts, + ajaxLocation, + + rhash = /#.*$/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + rquery = /\?/, + rscript = /)<[^<]*)*<\/script>/gi, + rts = /([?&])_=[^&]*/, + rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, + + // Keep a copy of the old load method + _load = jQuery.fn.load, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + allTypes = ["*/"] + ["*"]; + +// #8138, IE may throw an exception when accessing +// a field from window.location if document.domain has been set +try { + ajaxLocation = location.href; +} catch( e ) { + // Use the href attribute of an A element + // since IE will modify it given document.location + ajaxLocation = document.createElement( "a" ); + ajaxLocation.href = ""; + ajaxLocation = ajaxLocation.href; +} + +// Segment location into parts +ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, list, placeBefore, + dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), + i = 0, + length = dataTypes.length; + + if ( jQuery.isFunction( func ) ) { + // For each dataType in the dataTypeExpression + for ( ; i < length; i++ ) { + dataType = dataTypes[ i ]; + // We control if we're asked to add before + // any existing element + placeBefore = /^\+/.test( dataType ); + if ( placeBefore ) { + dataType = dataType.substr( 1 ) || "*"; + } + list = structure[ dataType ] = structure[ dataType ] || []; + // then we add to the structure accordingly + list[ placeBefore ? "unshift" : "push" ]( func ); + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, + dataType /* internal */, inspected /* internal */ ) { + + dataType = dataType || options.dataTypes[ 0 ]; + inspected = inspected || {}; + + inspected[ dataType ] = true; + + var selection, + list = structure[ dataType ], + i = 0, + length = list ? list.length : 0, + executeOnly = ( structure === prefilters ); + + for ( ; i < length && ( executeOnly || !selection ); i++ ) { + selection = list[ i ]( options, originalOptions, jqXHR ); + // If we got redirected to another dataType + // we try there if executing only and not done already + if ( typeof selection === "string" ) { + if ( !executeOnly || inspected[ selection ] ) { + selection = undefined; + } else { + options.dataTypes.unshift( selection ); + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jqXHR, selection, inspected ); + } + } + } + // If we're only executing or nothing was selected + // we try the catchall dataType if not done already + if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jqXHR, "*", inspected ); + } + // unnecessary when only executing (prefilters) + // but it'll be ignored by the caller in that case + return selection; +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } +} + +jQuery.fn.load = function( url, params, callback ) { + if ( typeof url !== "string" && _load ) { + return _load.apply( this, arguments ); + } + + // Don't do a request if no elements are being requested + if ( !this.length ) { + return this; + } + + var selector, type, response, + self = this, + off = url.indexOf(" "); + + if ( off >= 0 ) { + selector = url.slice( off, url.length ); + url = url.slice( 0, off ); + } + + // If it's a function + if ( jQuery.isFunction( params ) ) { + + // We assume that it's the callback + callback = params; + params = undefined; + + // Otherwise, build a param string + } else if ( params && typeof params === "object" ) { + type = "POST"; + } + + // Request the remote document + jQuery.ajax({ + url: url, + + // if "type" variable is undefined, then "GET" method will be used + type: type, + dataType: "html", + data: params, + complete: function( jqXHR, status ) { + if ( callback ) { + self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); + } + } + }).done(function( responseText ) { + + // Save response for use in complete callback + response = arguments; + + // See if a selector was specified + self.html( selector ? + + // Create a dummy div to hold the results + jQuery("
    ") + + // inject the contents of the document in, removing the scripts + // to avoid any 'Permission Denied' errors in IE + .append( responseText.replace( rscript, "" ) ) + + // Locate the specified elements + .find( selector ) : + + // If not, just inject the full result + responseText ); + + }); + + return this; +}; + +// Attach a bunch of functions for handling common AJAX events +jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ + jQuery.fn[ o ] = function( f ){ + return this.on( o, f ); + }; +}); + +jQuery.each( [ "get", "post" ], function( i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + // shift arguments if data argument was omitted + if ( jQuery.isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + return jQuery.ajax({ + type: method, + url: url, + data: data, + success: callback, + dataType: type + }); + }; +}); + +jQuery.extend({ + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + if ( settings ) { + // Building a settings object + ajaxExtend( target, jQuery.ajaxSettings ); + } else { + // Extending ajaxSettings + settings = target; + target = jQuery.ajaxSettings; + } + ajaxExtend( target, settings ); + return target; + }, + + ajaxSettings: { + url: ajaxLocation, + isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), + global: true, + type: "GET", + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + processData: true, + async: true, + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + xml: "application/xml, text/xml", + html: "text/html", + text: "text/plain", + json: "application/json, text/javascript", + "*": allTypes + }, + + contents: { + xml: /xml/, + html: /html/, + json: /json/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText" + }, + + // List of data converters + // 1) key format is "source_type destination_type" (a single space in-between) + // 2) the catchall symbol "*" can be used for source_type + converters: { + + // Convert anything to text + "* text": window.String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": jQuery.parseJSON, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + context: true, + url: true + } + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var // ifModified key + ifModifiedKey, + // Response headers + responseHeadersString, + responseHeaders, + // transport + transport, + // timeout handle + timeoutTimer, + // Cross-domain detection vars + parts, + // To know if global events are to be dispatched + fireGlobals, + // Loop variable + i, + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + // Callbacks context + callbackContext = s.context || s, + // Context for global events + // It's the callbackContext if one was provided in the options + // and if it's a DOM node or a jQuery collection + globalEventContext = callbackContext !== s && + ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? + jQuery( callbackContext ) : jQuery.event, + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + // Status-dependent callbacks + statusCode = s.statusCode || {}, + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + // The jqXHR state + state = 0, + // Default abort message + strAbort = "canceled", + // Fake xhr + jqXHR = { + + readyState: 0, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( !state ) { + var lname = name.toLowerCase(); + name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Raw string + getAllResponseHeaders: function() { + return state === 2 ? responseHeadersString : null; + }, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( state === 2 ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; + } + } + match = responseHeaders[ key.toLowerCase() ]; + } + return match === undefined ? null : match; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( !state ) { + s.mimeType = type; + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + statusText = statusText || strAbort; + if ( transport ) { + transport.abort( statusText ); + } + done( 0, statusText ); + return this; + } + }; + + // Callback for when everything is done + // It is defined here because jslint complains if it is declared + // at the end of the function (which would be more logical and readable) + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Called once + if ( state === 2 ) { + return; + } + + // State is "done" now + state = 2; + + // Clear timeout if it exists + if ( timeoutTimer ) { + clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // If successful, handle type chaining + if ( status >= 200 && status < 300 || status === 304 ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + + modified = jqXHR.getResponseHeader("Last-Modified"); + if ( modified ) { + jQuery.lastModified[ ifModifiedKey ] = modified; + } + modified = jqXHR.getResponseHeader("Etag"); + if ( modified ) { + jQuery.etag[ ifModifiedKey ] = modified; + } + } + + // If not modified + if ( status === 304 ) { + + statusText = "notmodified"; + isSuccess = true; + + // If we have data + } else { + + isSuccess = ajaxConvert( s, response ); + statusText = isSuccess.state; + success = isSuccess.data; + error = isSuccess.error; + isSuccess = !error; + } + } else { + // We extract error from statusText + // then normalize statusText and status for non-aborts + error = statusText; + if ( !statusText || status ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + // Attach deferreds + deferred.promise( jqXHR ); + jqXHR.success = jqXHR.done; + jqXHR.error = jqXHR.fail; + jqXHR.complete = completeDeferred.add; + + // Status-dependent callbacks + jqXHR.statusCode = function( map ) { + if ( map ) { + var tmp; + if ( state < 2 ) { + for ( tmp in map ) { + statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; + } + } else { + tmp = map[ jqXHR.status ]; + jqXHR.always( tmp ); + } + } + return this; + }; + + // Remove hash character (#7531: and string promotion) + // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) + // We also use the url parameter if available + s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); + + // Extract dataTypes list + s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); + + // A cross-domain request is in order when we have a protocol:host:port mismatch + if ( s.crossDomain == null ) { + parts = rurl.exec( s.url.toLowerCase() ); + s.crossDomain = !!( parts && + ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || + ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != + ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) + ); + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( state === 2 ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + fireGlobals = s.global; + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // If data is available, append data to url + if ( s.data ) { + s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Get ifModifiedKey before adding the anti-cache parameter + ifModifiedKey = s.url; + + // Add anti-cache in url if needed + if ( s.cache === false ) { + + var ts = jQuery.now(), + // try replacing _= if it is there + ret = s.url.replace( rts, "$1_=" + ts ); + + // if nothing was replaced, add timestamp to the end + s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + ifModifiedKey = ifModifiedKey || s.url; + if ( jQuery.lastModified[ ifModifiedKey ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); + } + if ( jQuery.etag[ ifModifiedKey ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); + } + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? + s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { + // Abort if not done already and return + return jqXHR.abort(); + + } + + // aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + for ( i in { success: 1, error: 1, complete: 1 } ) { + jqXHR[ i ]( s[ i ] ); + } + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = setTimeout( function(){ + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + state = 1; + transport.send( requestHeaders, done ); + } catch (e) { + // Propagate exception as error if not done + if ( state < 2 ) { + done( -1, e ); + // Simply rethrow otherwise + } else { + throw e; + } + } + } + + return jqXHR; + }, + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {} + +}); + +/* Handles responses to an ajax request: + * - sets all responseXXX fields accordingly + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes, + responseFields = s.responseFields; + + // Fill responseXXX fields + for ( type in responseFields ) { + if ( type in responses ) { + jqXHR[ responseFields[type] ] = responses[ type ]; + } + } + + // Remove auto dataType and get content-type in the process + while( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +// Chain conversions given the request and the original response +function ajaxConvert( s, response ) { + + var conv, conv2, current, tmp, + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(), + prev = dataTypes[ 0 ], + converters = {}, + i = 0; + + // Apply the dataFilter if provided + if ( s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + // Convert to each sequential dataType, tolerating list modification + for ( ; (current = dataTypes[++i]); ) { + + // There's only work to do if current dataType is non-auto + if ( current !== "*" ) { + + // Convert response if prev dataType is non-auto and differs from current + if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split(" "); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.splice( i--, 0, current ); + } + + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s["throws"] ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; + } + } + } + } + + // Update prev for next iteration + prev = current; + } + } + + return { state: "success", data: response }; +} +var oldCallbacks = [], + rquestion = /\?/, + rjsonp = /(=)\?(?=&|$)|\?\?/, + nonce = jQuery.now(); + +// Default jsonp settings +jQuery.ajaxSetup({ + jsonp: "callback", + jsonpCallback: function() { + var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); + this[ callback ] = true; + return callback; + } +}); + +// Detect, normalize options and install callbacks for jsonp requests +jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { + + var callbackName, overwritten, responseContainer, + data = s.data, + url = s.url, + hasCallback = s.jsonp !== false, + replaceInUrl = hasCallback && rjsonp.test( url ), + replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && + !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && + rjsonp.test( data ); + + // Handle iff the expected data type is "jsonp" or we have a parameter to set + if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { + + // Get callback name, remembering preexisting value associated with it + callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? + s.jsonpCallback() : + s.jsonpCallback; + overwritten = window[ callbackName ]; + + // Insert callback into url or form data + if ( replaceInUrl ) { + s.url = url.replace( rjsonp, "$1" + callbackName ); + } else if ( replaceInData ) { + s.data = data.replace( rjsonp, "$1" + callbackName ); + } else if ( hasCallback ) { + s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; + } + + // Use data converter to retrieve json after script execution + s.converters["script json"] = function() { + if ( !responseContainer ) { + jQuery.error( callbackName + " was not called" ); + } + return responseContainer[ 0 ]; + }; + + // force json dataType + s.dataTypes[ 0 ] = "json"; + + // Install callback + window[ callbackName ] = function() { + responseContainer = arguments; + }; + + // Clean-up function (fires after converters) + jqXHR.always(function() { + // Restore preexisting value + window[ callbackName ] = overwritten; + + // Save back as free + if ( s[ callbackName ] ) { + // make sure that re-using the options doesn't screw things around + s.jsonpCallback = originalSettings.jsonpCallback; + + // save the callback name for future use + oldCallbacks.push( callbackName ); + } + + // Call if it was a function and we have a response + if ( responseContainer && jQuery.isFunction( overwritten ) ) { + overwritten( responseContainer[ 0 ] ); + } + + responseContainer = overwritten = undefined; + }); + + // Delegate to script + return "script"; + } +}); +// Install script dataType +jQuery.ajaxSetup({ + accepts: { + script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /javascript|ecmascript/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +}); + +// Handle cache's special case and global +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + s.global = false; + } +}); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function(s) { + + // This transport only deals with cross domain requests + if ( s.crossDomain ) { + + var script, + head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; + + return { + + send: function( _, callback ) { + + script = document.createElement( "script" ); + + script.async = "async"; + + if ( s.scriptCharset ) { + script.charset = s.scriptCharset; + } + + script.src = s.url; + + // Attach handlers for all browsers + script.onload = script.onreadystatechange = function( _, isAbort ) { + + if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { + + // Handle memory leak in IE + script.onload = script.onreadystatechange = null; + + // Remove the script + if ( head && script.parentNode ) { + head.removeChild( script ); + } + + // Dereference the script + script = undefined; + + // Callback if not abort + if ( !isAbort ) { + callback( 200, "success" ); + } + } + }; + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709 and #4378). + head.insertBefore( script, head.firstChild ); + }, + + abort: function() { + if ( script ) { + script.onload( 0, 1 ); + } + } + }; + } +}); +var xhrCallbacks, + // #5280: Internet Explorer will keep connections alive if we don't abort on unload + xhrOnUnloadAbort = window.ActiveXObject ? function() { + // Abort all pending requests + for ( var key in xhrCallbacks ) { + xhrCallbacks[ key ]( 0, 1 ); + } + } : false, + xhrId = 0; + +// Functions to create xhrs +function createStandardXHR() { + try { + return new window.XMLHttpRequest(); + } catch( e ) {} +} + +function createActiveXHR() { + try { + return new window.ActiveXObject( "Microsoft.XMLHTTP" ); + } catch( e ) {} +} + +// Create the request object +// (This is still attached to ajaxSettings for backward compatibility) +jQuery.ajaxSettings.xhr = window.ActiveXObject ? + /* Microsoft failed to properly + * implement the XMLHttpRequest in IE7 (can't request local files), + * so we use the ActiveXObject when it is available + * Additionally XMLHttpRequest can be disabled in IE7/IE8 so + * we need a fallback. + */ + function() { + return !this.isLocal && createStandardXHR() || createActiveXHR(); + } : + // For all other browsers, use the standard XMLHttpRequest object + createStandardXHR; + +// Determine support properties +(function( xhr ) { + jQuery.extend( jQuery.support, { + ajax: !!xhr, + cors: !!xhr && ( "withCredentials" in xhr ) + }); +})( jQuery.ajaxSettings.xhr() ); + +// Create transport if the browser can provide an xhr +if ( jQuery.support.ajax ) { + + jQuery.ajaxTransport(function( s ) { + // Cross domain only allowed if supported through XMLHttpRequest + if ( !s.crossDomain || jQuery.support.cors ) { + + var callback; + + return { + send: function( headers, complete ) { + + // Get a new xhr + var handle, i, + xhr = s.xhr(); + + // Open the socket + // Passing null username, generates a login popup on Opera (#2865) + if ( s.username ) { + xhr.open( s.type, s.url, s.async, s.username, s.password ); + } else { + xhr.open( s.type, s.url, s.async ); + } + + // Apply custom fields if provided + if ( s.xhrFields ) { + for ( i in s.xhrFields ) { + xhr[ i ] = s.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( s.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( s.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !s.crossDomain && !headers["X-Requested-With"] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Need an extra try/catch for cross domain requests in Firefox 3 + try { + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + } catch( _ ) {} + + // Do send the request + // This may raise an exception which is actually + // handled in jQuery.ajax (so no try/catch here) + xhr.send( ( s.hasContent && s.data ) || null ); + + // Listener + callback = function( _, isAbort ) { + + var status, + statusText, + responseHeaders, + responses, + xml; + + // Firefox throws exceptions when accessing properties + // of an xhr when a network error occurred + // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) + try { + + // Was never called and is aborted or complete + if ( callback && ( isAbort || xhr.readyState === 4 ) ) { + + // Only called once + callback = undefined; + + // Do not keep as active anymore + if ( handle ) { + xhr.onreadystatechange = jQuery.noop; + if ( xhrOnUnloadAbort ) { + delete xhrCallbacks[ handle ]; + } + } + + // If it's an abort + if ( isAbort ) { + // Abort it manually if needed + if ( xhr.readyState !== 4 ) { + xhr.abort(); + } + } else { + status = xhr.status; + responseHeaders = xhr.getAllResponseHeaders(); + responses = {}; + xml = xhr.responseXML; + + // Construct response list + if ( xml && xml.documentElement /* #4958 */ ) { + responses.xml = xml; + } + + // When requesting binary data, IE6-9 will throw an exception + // on any attempt to access responseText (#11426) + try { + responses.text = xhr.responseText; + } catch( e ) { + } + + // Firefox throws an exception when accessing + // statusText for faulty cross-domain requests + try { + statusText = xhr.statusText; + } catch( e ) { + // We normalize with Webkit giving an empty statusText + statusText = ""; + } + + // Filter status for non standard behaviors + + // If the request is local and we have data: assume a success + // (success with no data won't get notified, that's the best we + // can do given current implementations) + if ( !status && s.isLocal && !s.crossDomain ) { + status = responses.text ? 200 : 404; + // IE - #1450: sometimes returns 1223 when it should be 204 + } else if ( status === 1223 ) { + status = 204; + } + } + } + } catch( firefoxAccessException ) { + if ( !isAbort ) { + complete( -1, firefoxAccessException ); + } + } + + // Call complete if needed + if ( responses ) { + complete( status, statusText, responses, responseHeaders ); + } + }; + + if ( !s.async ) { + // if we're in sync mode we fire the callback + callback(); + } else if ( xhr.readyState === 4 ) { + // (IE6 & IE7) if it's in cache and has been + // retrieved directly we need to fire the callback + setTimeout( callback, 0 ); + } else { + handle = ++xhrId; + if ( xhrOnUnloadAbort ) { + // Create the active xhrs callbacks list if needed + // and attach the unload handler + if ( !xhrCallbacks ) { + xhrCallbacks = {}; + jQuery( window ).unload( xhrOnUnloadAbort ); + } + // Add to list of active xhrs callbacks + xhrCallbacks[ handle ] = callback; + } + xhr.onreadystatechange = callback; + } + }, + + abort: function() { + if ( callback ) { + callback(0,1); + } + } + }; + } + }); +} +var fxNow, timerId, + rfxtypes = /^(?:toggle|show|hide)$/, + rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), + rrun = /queueHooks$/, + animationPrefilters = [ defaultPrefilter ], + tweeners = { + "*": [function( prop, value ) { + var end, unit, + tween = this.createTween( prop, value ), + parts = rfxnum.exec( value ), + target = tween.cur(), + start = +target || 0, + scale = 1, + maxIterations = 20; + + if ( parts ) { + end = +parts[2]; + unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + + // We need to compute starting value + if ( unit !== "px" && start ) { + // Iteratively approximate from a nonzero starting point + // Prefer the current property, because this process will be trivial if it uses the same units + // Fallback to end or a simple constant + start = jQuery.css( tween.elem, prop, true ) || end || 1; + + do { + // If previous iteration zeroed out, double until we get *something* + // Use a string for doubling factor so we don't accidentally see scale as unchanged below + scale = scale || ".5"; + + // Adjust and apply + start = start / scale; + jQuery.style( tween.elem, prop, start + unit ); + + // Update scale, tolerating zero or NaN from tween.cur() + // And breaking the loop if scale is unchanged or perfect, or if we've just had enough + } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); + } + + tween.unit = unit; + tween.start = start; + // If a +=/-= token was provided, we're doing a relative animation + tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; + } + return tween; + }] + }; + +// Animations created synchronously will run synchronously +function createFxNow() { + setTimeout(function() { + fxNow = undefined; + }, 0 ); + return ( fxNow = jQuery.now() ); +} + +function createTweens( animation, props ) { + jQuery.each( props, function( prop, value ) { + var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( collection[ index ].call( animation, prop, value ) ) { + + // we're done with this property + return; + } + } + }); +} + +function Animation( elem, properties, options ) { + var result, + index = 0, + tweenerIndex = 0, + length = animationPrefilters.length, + deferred = jQuery.Deferred().always( function() { + // don't match elem in the :animated selector + delete tick.elem; + }), + tick = function() { + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length ; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ]); + + if ( percent < 1 && length ) { + return remaining; + } else { + deferred.resolveWith( elem, [ animation ] ); + return false; + } + }, + animation = deferred.promise({ + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { specialEasing: {} }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end, easing ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + // if we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + + for ( ; index < length ; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // resolve when we played the last frame + // otherwise, reject + if ( gotoEnd ) { + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + }), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length ; index++ ) { + result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + return result; + } + } + + createTweens( animation, props ); + + if ( jQuery.isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + jQuery.fx.timer( + jQuery.extend( tick, { + anim: animation, + queue: animation.opts.queue, + elem: elem + }) + ); + + // attach callbacks from options + return animation.progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = jQuery.camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( jQuery.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // not quite $.extend, this wont overwrite keys already present. + // also - reusing 'index' from above because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +jQuery.Animation = jQuery.extend( Animation, { + + tweener: function( props, callback ) { + if ( jQuery.isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.split(" "); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length ; index++ ) { + prop = props[ index ]; + tweeners[ prop ] = tweeners[ prop ] || []; + tweeners[ prop ].unshift( callback ); + } + }, + + prefilter: function( callback, prepend ) { + if ( prepend ) { + animationPrefilters.unshift( callback ); + } else { + animationPrefilters.push( callback ); + } + } +}); + +function defaultPrefilter( elem, props, opts ) { + var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire, + anim = this, + style = elem.style, + orig = {}, + handled = [], + hidden = elem.nodeType && isHidden( elem ); + + // handle queue: false promises + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always(function() { + // doing this makes sure that the complete handler will be called + // before this completes + anim.always(function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + }); + }); + } + + // height/width overflow pass + if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { + // Make sure that nothing sneaks out + // Record all 3 overflow attributes because IE does not + // change the overflow attribute when overflowX and + // overflowY are set to the same value + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Set display property to inline-block for height/width + // animations on inline elements that are having width/height animated + if ( jQuery.css( elem, "display" ) === "inline" && + jQuery.css( elem, "float" ) === "none" ) { + + // inline-level elements accept inline-block; + // block-level elements need to be inline with layout + if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { + style.display = "inline-block"; + + } else { + style.zoom = 1; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + if ( !jQuery.support.shrinkWrapBlocks ) { + anim.done(function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + }); + } + } + + + // show/hide pass + for ( index in props ) { + value = props[ index ]; + if ( rfxtypes.exec( value ) ) { + delete props[ index ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + continue; + } + handled.push( index ); + } + } + + length = handled.length; + if ( length ) { + dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + + // store state if its toggle - enables .stop().toggle() to "reverse" + if ( toggle ) { + dataShow.hidden = !hidden; + } + if ( hidden ) { + jQuery( elem ).show(); + } else { + anim.done(function() { + jQuery( elem ).hide(); + }); + } + anim.done(function() { + var prop; + jQuery.removeData( elem, "fxshow", true ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + }); + for ( index = 0 ; index < length ; index++ ) { + prop = handled[ index ]; + tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); + orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); + + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = tween.start; + if ( hidden ) { + tween.end = tween.start; + tween.start = prop === "width" || prop === "height" ? 1 : 0; + } + } + } + } +} + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || "swing"; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + if ( tween.elem[ tween.prop ] != null && + (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { + return tween.elem[ tween.prop ]; + } + + // passing any value as a 4th parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails + // so, simple values such as "10px" are parsed to Float. + // complex values such as "rotate(1rad)" are returned as is. + result = jQuery.css( tween.elem, tween.prop, false, "" ); + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + // use step hook for back compat - use cssHook if its there - use .style if its + // available and use plain properties where available + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +// Remove in 2.0 - this supports IE8's panic based approach +// to setting things on disconnected nodes + +Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } +}; + +jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" || + // special check for .toggle( handler, handler, ... ) + ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +}); + +jQuery.fn.extend({ + fadeTo: function( speed, to, easing, callback ) { + + // show any hidden elements after setting opacity to 0 + return this.filter( isHidden ).css( "opacity", 0 ).show() + + // animate to the value specified + .end().animate({ opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations resolve immediately + if ( empty ) { + anim.stop( true ); + } + }; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue && type !== false ) { + this.queue( type || "fx", [] ); + } + + return this.each(function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = jQuery._data( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // start the next in the queue if the last step wasn't forced + // timers currently will call their complete callbacks, which will dequeue + // but only if they were gotoEnd + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + }); + } +}); + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + attrs = { height: type }, + i = 0; + + // if we include width, step value is 1 to do all cssExpand values, + // if we don't include width, step value is 2 to skip over Left and Right + includeWidth = includeWidth? 1 : 0; + for( ; i < 4 ; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +// Generate shortcuts for custom animations +jQuery.each({ + slideDown: genFx("show"), + slideUp: genFx("hide"), + slideToggle: genFx("toggle"), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +}); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + jQuery.isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing + }; + + opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : + opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; + + // normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( jQuery.isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p*Math.PI ) / 2; + } +}; + +jQuery.timers = []; +jQuery.fx = Tween.prototype.init; +jQuery.fx.tick = function() { + var timer, + timers = jQuery.timers, + i = 0; + + fxNow = jQuery.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + // Checks the timer has not already been removed + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + if ( timer() && jQuery.timers.push( timer ) && !timerId ) { + timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); + } +}; + +jQuery.fx.interval = 13; + +jQuery.fx.stop = function() { + clearInterval( timerId ); + timerId = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + // Default speed + _default: 400 +}; + +// Back Compat <1.8 extension point +jQuery.fx.step = {}; + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.animated = function( elem ) { + return jQuery.grep(jQuery.timers, function( fn ) { + return elem === fn.elem; + }).length; + }; +} +var rroot = /^(?:body|html)$/i; + +jQuery.fn.offset = function( options ) { + if ( arguments.length ) { + return options === undefined ? + this : + this.each(function( i ) { + jQuery.offset.setOffset( this, options, i ); + }); + } + + var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, + box = { top: 0, left: 0 }, + elem = this[ 0 ], + doc = elem && elem.ownerDocument; + + if ( !doc ) { + return; + } + + if ( (body = doc.body) === elem ) { + return jQuery.offset.bodyOffset( elem ); + } + + docElem = doc.documentElement; + + // Make sure it's not a disconnected DOM node + if ( !jQuery.contains( docElem, elem ) ) { + return box; + } + + // If we don't have gBCR, just use 0,0 rather than error + // BlackBerry 5, iOS 3 (original iPhone) + if ( typeof elem.getBoundingClientRect !== "undefined" ) { + box = elem.getBoundingClientRect(); + } + win = getWindow( doc ); + clientTop = docElem.clientTop || body.clientTop || 0; + clientLeft = docElem.clientLeft || body.clientLeft || 0; + scrollTop = win.pageYOffset || docElem.scrollTop; + scrollLeft = win.pageXOffset || docElem.scrollLeft; + return { + top: box.top + scrollTop - clientTop, + left: box.left + scrollLeft - clientLeft + }; +}; + +jQuery.offset = { + + bodyOffset: function( body ) { + var top = body.offsetTop, + left = body.offsetLeft; + + if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { + top += parseFloat( jQuery.css(body, "marginTop") ) || 0; + left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; + } + + return { top: top, left: left }; + }, + + setOffset: function( elem, options, i ) { + var position = jQuery.css( elem, "position" ); + + // set position first, in-case top/left are set even on static elem + if ( position === "static" ) { + elem.style.position = "relative"; + } + + var curElem = jQuery( elem ), + curOffset = curElem.offset(), + curCSSTop = jQuery.css( elem, "top" ), + curCSSLeft = jQuery.css( elem, "left" ), + calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, + props = {}, curPosition = {}, curTop, curLeft; + + // need to be able to calculate position if either top or left is auto and position is either absolute or fixed + if ( calculatePosition ) { + curPosition = curElem.position(); + curTop = curPosition.top; + curLeft = curPosition.left; + } else { + curTop = parseFloat( curCSSTop ) || 0; + curLeft = parseFloat( curCSSLeft ) || 0; + } + + if ( jQuery.isFunction( options ) ) { + options = options.call( elem, i, curOffset ); + } + + if ( options.top != null ) { + props.top = ( options.top - curOffset.top ) + curTop; + } + if ( options.left != null ) { + props.left = ( options.left - curOffset.left ) + curLeft; + } + + if ( "using" in options ) { + options.using.call( elem, props ); + } else { + curElem.css( props ); + } + } +}; + + +jQuery.fn.extend({ + + position: function() { + if ( !this[0] ) { + return; + } + + var elem = this[0], + + // Get *real* offsetParent + offsetParent = this.offsetParent(), + + // Get correct offsets + offset = this.offset(), + parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); + + // Subtract element margins + // note: when an element has margin: auto the offsetLeft and marginLeft + // are the same in Safari causing offset.left to incorrectly be 0 + offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; + offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; + + // Add offsetParent borders + parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; + parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; + + // Subtract the two offsets + return { + top: offset.top - parentOffset.top, + left: offset.left - parentOffset.left + }; + }, + + offsetParent: function() { + return this.map(function() { + var offsetParent = this.offsetParent || document.body; + while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { + offsetParent = offsetParent.offsetParent; + } + return offsetParent || document.body; + }); + } +}); + + +// Create scrollLeft and scrollTop methods +jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { + var top = /Y/.test( prop ); + + jQuery.fn[ method ] = function( val ) { + return jQuery.access( this, function( elem, method, val ) { + var win = getWindow( elem ); + + if ( val === undefined ) { + return win ? (prop in win) ? win[ prop ] : + win.document.documentElement[ method ] : + elem[ method ]; + } + + if ( win ) { + win.scrollTo( + !top ? val : jQuery( win ).scrollLeft(), + top ? val : jQuery( win ).scrollTop() + ); + + } else { + elem[ method ] = val; + } + }, method, val, arguments.length, null ); + }; +}); + +function getWindow( elem ) { + return jQuery.isWindow( elem ) ? + elem : + elem.nodeType === 9 ? + elem.defaultView || elem.parentWindow : + false; +} +// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods +jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { + jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { + // margin is only for outerHeight, outerWidth + jQuery.fn[ funcName ] = function( margin, value ) { + var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), + extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); + + return jQuery.access( this, function( elem, type, value ) { + var doc; + + if ( jQuery.isWindow( elem ) ) { + // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there + // isn't a whole lot we can do. See pull request at this URL for discussion: + // https://github.com/jquery/jquery/pull/764 + return elem.document.documentElement[ "client" + name ]; + } + + // Get document width or height + if ( elem.nodeType === 9 ) { + doc = elem.documentElement; + + // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest + // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. + return Math.max( + elem.body[ "scroll" + name ], doc[ "scroll" + name ], + elem.body[ "offset" + name ], doc[ "offset" + name ], + doc[ "client" + name ] + ); + } + + return value === undefined ? + // Get width or height on the element, requesting but not forcing parseFloat + jQuery.css( elem, type, value, extra ) : + + // Set width or height on the element + jQuery.style( elem, type, value, extra ); + }, type, chainable ? margin : undefined, chainable, null ); + }; + }); +}); +// Expose jQuery to the global object +window.jQuery = window.$ = jQuery; + +// Expose jQuery as an AMD module, but only for AMD loaders that +// understand the issues with loading multiple versions of jQuery +// in a page that all might call define(). The loader will indicate +// they have special allowances for multiple jQuery versions by +// specifying define.amd.jQuery = true. Register as a named module, +// since jQuery can be concatenated with other files that may use define, +// but not use a proper concatenation script that understands anonymous +// AMD modules. A named AMD is safest and most robust way to register. +// Lowercase jquery is used because AMD module names are derived from +// file names, and jQuery is normally delivered in a lowercase file name. +// Do this after creating the global so that if an AMD module wants to call +// noConflict to hide this version of jQuery, it will work. +if ( typeof define === "function" && define.amd && define.amd.jQuery ) { + define( "jquery", [], function () { return jQuery; } ); +} + +})( window ); + +/** + * @license AngularJS v1.2.0-rc.2 + * (c) 2010-2012 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, document){ + var _jQuery = window.jQuery.noConflict(true); + +/** + * @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(string, string, ...): Error} instance + */ + +function minErr(module) { + return function () { + var code = arguments[0], + prefix = '[' + (module ? module + ':' : '') + code + '] ', + template = arguments[1], + templateArgs = arguments, + stringify = function (obj) { + if (isFunction(obj)) { + return obj.toString().replace(/ \{[\s\S]*$/, ''); + } else if (isUndefined(obj)) { + return 'undefined'; + } else if (!isString(obj)) { + 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 (isFunction(arg)) { + return arg.toString().replace(/ ?\{[\s\S]*$/, ''); + } else if (isUndefined(arg)) { + return 'undefined'; + } else if (!isString(arg)) { + return toJson(arg); + } + return arg; + } + return match; + }); + + message = message + '\nhttp://errors.angularjs.org/' + version.full + '/' + + (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); + }; +} + +//////////////////////////////////// + +/** + * hasOwnProperty may be overwritten by a property of the same name, or entirely + * absent from an object that does not inherit Object.prototype; this copy is + * used instead + */ +var hasOwnPropertyFn = Object.prototype.hasOwnProperty; +var hasOwnPropertyLocal = function(obj, key) { + return hasOwnPropertyFn.call(obj, key); +}; + +/** + * @ngdoc function + * @name angular.lowercase + * @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;}; + + +/** + * @ngdoc function + * @name angular.uppercase + * @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) { + return isString(s) + ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) + : s; +}; +var manualUppercase = function(s) { + 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'), + + + _angular = window.angular, + /** @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, ...) + */ +function isArrayLike(obj) { + if (obj == null || isWindow(obj)) { + return false; + } + + var length = obj.length; + + if (obj.nodeType === 1 && length) { + return true; + } + + return isArray(obj) || !isFunction(obj) && ( + length === 0 || typeof length === "number" && length > 0 && (length - 1) in obj + ); +} + +/** + * @ngdoc function + * @name angular.forEach + * @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. + * + * Note: this function was previously known as `angular.foreach`. + * +
    +     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) { + if (key != 'prototype' && key != 'length' && key != 'name' && 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 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 + * @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 + * @function + * + * @description + * A function that performs no operations. This function can be useful when writing code in the + * functional style. +
    +     function foo(callback) {
    +       var result = calculateResult();
    +       (callback || angular.noop)(result);
    +     }
    +   
    + */ +function noop() {} +noop.$inject = []; + + +/** + * @ngdoc function + * @name angular.identity + * @function + * + * @description + * A function that returns its first argument. This function is useful when writing code in the + * functional style. + * +
    +     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 + * @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 + * @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 + * @function + * + * @description + * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not + * considered to be 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 + * @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 + * @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 + * @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.apply(value) == '[object Date]'; +} + + +/** + * @ngdoc function + * @name angular.isArray + * @function + * + * @description + * Determines if a reference is an `Array`. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is an `Array`. + */ +function isArray(value) { + return toString.apply(value) == '[object Array]'; +} + + +/** + * @ngdoc function + * @name angular.isFunction + * @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.apply(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.apply(obj) === '[object File]'; +} + + +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*/, '').replace(/\s*$/, '') : value; + }; + } + return function(value) { + return isString(value) ? value.trim() : value; + }; +})(); + + +/** + * @ngdoc function + * @name angular.isElement + * @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.on && 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 size = 0, key; + + if (isArray(obj) || isString(obj)) { + return obj.length; + } else if (isObject(obj)){ + for (key in obj) + if (!ownPropsOnly || obj.hasOwnProperty(key)) + size++; + } + + return size; +} + + +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 + * @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, `source` is returned. + * + * Note: this function is used to augment the Object type in Angular expressions. See + * {@link ng.$filter} for more information about Angular arrays. + * + * @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. + */ +function copy(source, destination){ + 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, []); + } 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, {}); + } + } + } else { + if (source === destination) throw ngMinErr('cpi', "Can't copy! Source and destination are identical."); + if (isArray(source)) { + destination.length = 0; + for ( var i = 0; i < source.length; i++) { + destination.push(copy(source[i])); + } + } else { + var h = destination.$$hashKey; + forEach(destination, function(value, key){ + delete destination[key]; + }); + for ( var key in source) { + destination[key] = copy(source[key]); + } + setHashKey(destination,h); + } + } + return destination; +} + +/** + * Create a shallow copy of an object + */ +function shallowCopy(src, dst) { + dst = dst || {}; + + for(var key in src) { + if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') { + dst[key] = src[key]; + } + } + + return dst; +} + + +/** + * @ngdoc function + * @name angular.equals + * @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 pass `===` comparison. + * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal) + * * Both values represent the same regular expression (In JavasScript, + * /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 (/^\$+/.test(key)) { + 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 + * @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 + * @function + * + * @description + * Deserializes a JSON string. + * + * @param {string} json JSON string to deserialize. + * @returns {Object|Array|Date|string|number} Deserialized thingy. + */ +function fromJson(json) { + return isString(json) + ? JSON.parse(json) + : json; +} + + +function toBoolean(value) { + 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.html(''); + } 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.<(string|boolean)> + */ +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 ng.directive:ngApp + * + * @element ANY + * @param {angular.Module} ngApp an optional application + * {@link angular.module module} name to load. + * + * @description + * + * Use this directive to auto-bootstrap an application. Only + * one ngApp directive can be used per HTML document. The directive + * designates the root of the application and is typically placed + * at the root of the page. + * + * The first ngApp found in the document will be auto-bootstrapped. To use multiple applications in an + * HTML document you must manually bootstrap them using {@link angular.bootstrap}. + * Applications cannot be nested. + * + * In the example below if the `ngApp` directive would not be placed + * on the `html` element then the document would not be compiled + * and the `{{ 1+2 }}` would not be resolved to `3`. + * + * `ngApp` is the easiest way to bootstrap an application. + * + + + I can add: 1 + 2 = {{ 1+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 + * @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 api/ng.directive:ngApp ngApp}. + * + * @param {Element} element DOM element which is the root of angular application. + * @param {Array=} modules an array of module declarations. 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); + }); + animate.enabled(true); + }] + ); + 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; + // reset to jQuery or default to us. + if (jQuery) { + jqLite = jQuery; + extend(jQuery.fn, { + scope: JQLitePrototype.scope, + 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; +} + +/** + * 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=true} bindFnToScope + * @returns 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; +} + +/** + * @ngdoc interface + * @name angular.Module + * @description + * + * Interface for configuring angular {@link angular.module modules}. + */ + +function setupModuleLoader(window) { + + function ensure(obj, name, factory) { + return obj[name] || (obj[name] = factory()); + } + + return ensure(ensure(window, 'angular', Object), 'module', function() { + /** @type {Object.} */ + var modules = {}; + + /** + * @ngdoc function + * @name angular.module + * @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, filters, and configuration information. + * `angular.module` is used to configure the {@link AUTO.$injector $injector}. + * + *
    +     * // 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(function($locationProvider) {
    +     *   // Configure existing providers
    +     *   $locationProvider.hashPrefix('!');
    +     * });
    +     * 
    + * + * Then you can create an injector and load your modules like this: + * + *
    +     * 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 + * 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) { + if (requires && modules.hasOwnProperty(name)) { + modules[name] = null; + } + return ensure(modules, name, function() { + if (!requires) { + throw minErr('$injector')('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 + * @propertyOf angular.Module + * @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 + * @propertyOf angular.Module + * @returns {string} Name of the module. + * @description + */ + name: name, + + + /** + * @ngdoc method + * @name angular.Module#provider + * @methodOf angular.Module + * @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 + * @methodOf angular.Module + * @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 + * @methodOf angular.Module + * @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 + * @methodOf angular.Module + * @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 + * @methodOf angular.Module + * @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 + * @methodOf angular.Module + * @param {string} name animation name + * @param {Function} animationFactory Factory function for creating new instance of an animation. + * @description + * + * **NOTE**: animations are 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. + * + *
    +           * 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 + * @methodOf angular.Module + * @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 + * @methodOf angular.Module + * @param {string} name Controller name. + * @param {Function} constructor Controller constructor function. + * @description + * See {@link ng.$controllerProvider#register $controllerProvider.register()}. + */ + controller: invokeLater('$controllerProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#directive + * @methodOf angular.Module + * @param {string} name directive name + * @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 + * @methodOf angular.Module + * @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. + */ + config: config, + + /** + * @ngdoc method + * @name angular.Module#run + * @methodOf angular.Module + * @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; + } + } + }); + }; + }); + +} + +/** + * @ngdoc property + * @name angular.version + * @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.0-rc.2', // all of these placeholder strings will be replaced by grunt's + major: 1, // package task + minor: 2, + dot: 0, + codeName: 'barehand-atomsplitting' +}; + + +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, + '$$minErr': minErr, + 'version': version, + 'isDate': isDate, + 'lowercase': lowercase, + 'uppercase': uppercase, + 'callbacks': {counter: 0} + }); + + angularModule = setupModuleLoader(window); + try { + angularModule('ngLocale'); + } catch (e) { + angularModule('ngLocale', []).provider('$locale', $LocaleProvider); + } + + angularModule('ng', ['ngLocale'], ['$provide', + function ngModule($provide) { + $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, + ngCsp: ngCspDirective, + 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(ngAttributeAliasDirectives). + directive(ngEventDirectives); + $provide.provider({ + $anchorScroll: $AnchorScrollProvider, + $animate: $AnimateProvider, + $browser: $BrowserProvider, + $cacheFactory: $CacheFactoryProvider, + $controller: $ControllerProvider, + $document: $DocumentProvider, + $exceptionHandler: $ExceptionHandlerProvider, + $filter: $FilterProvider, + $interpolate: $InterpolateProvider, + $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, + $$urlUtils: $$UrlUtilsProvider + }); + } + ]); +} + +////////////////////////////////// +//JQLite +////////////////////////////////// + +/** + * @ngdoc function + * @name angular.element + * @function + * + * @description + * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. + * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if + * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite + * implementation (commonly referred to as jqLite). + * + * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded` + * event fired. + * + * jqLite is a tiny, API-compatible subset of jQuery that allows + * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality + * within a very small footprint, so only a subset of the jQuery API - methods, arguments and + * invocation styles - are supported. + * + * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never + * raw DOM references. + * + * ## Angular's jqLite + * Angular's lite version of jQuery 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/on/) - 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/) + * - [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 + * - [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/off/) - 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 and 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 api/ng.$rootScope.Scope scope} of the current + * element or its parent. + * - `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. + */ + +var jqCache = JQLite.cache = {}, + jqName = JQLite.expando = 'ng-' + new Date().getTime(), + 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); }); + +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) { + 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); + } +} + +///////////////////////////////////////////// +function JQLite(element) { + if (element instanceof JQLite) { + return element; + } + if (!(this instanceof JQLite)) { + if (isString(element) && element.charAt(0) != '<') { + throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element'); + } + return new JQLite(element); + } + + if (isString(element)) { + var div = document.createElement('div'); + // Read about the NoScope elements here: + // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx + div.innerHTML = '
     
    ' + element; // IE insanity to make NoScope elements work! + div.removeChild(div.firstChild); // remove the superfluous div + JQLiteAddNodes(this, div.childNodes); + var fragment = jqLite(document.createDocumentFragment()); + fragment.append(this); // detach the elements from the temporary DOM div. + } else { + JQLiteAddNodes(this, element); + } +} + +function JQLiteClone(element) { + return element.cloneNode(true); +} + +function JQLiteDealoc(element){ + JQLiteRemoveData(element); + for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { + JQLiteDealoc(children[i]); + } +} + +function JQLiteOff(element, type, fn, unsupported) { + if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument'); + + var events = JQLiteExpandoStore(element, 'events'), + handle = JQLiteExpandoStore(element, 'handle'); + + if (!handle) return; //no listeners registered + + if (isUndefined(type)) { + forEach(events, function(eventHandler, type) { + removeEventListenerFn(element, type, eventHandler); + delete events[type]; + }); + } else { + forEach(type.split(' '), function(type) { + if (isUndefined(fn)) { + removeEventListenerFn(element, type, events[type]); + delete events[type]; + } else { + arrayRemove(events[type] || [], fn); + } + }); + } +} + +function JQLiteRemoveData(element, name) { + var expandoId = element[jqName], + expandoStore = jqCache[expandoId]; + + if (expandoStore) { + if (name) { + delete jqCache[expandoId].data[name]; + return; + } + + if (expandoStore.handle) { + expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); + JQLiteOff(element); + } + delete jqCache[expandoId]; + element[jqName] = undefined; // ie does not allow deletion of attributes on elements. + } +} + +function JQLiteExpandoStore(element, key, value) { + var expandoId = element[jqName], + expandoStore = jqCache[expandoId || -1]; + + if (isDefined(value)) { + if (!expandoStore) { + element[jqName] = expandoId = jqNextId(); + expandoStore = jqCache[expandoId] = {}; + } + expandoStore[key] = value; + } else { + return expandoStore && expandoStore[key]; + } +} + +function JQLiteData(element, key, value) { + var data = JQLiteExpandoStore(element, 'data'), + isSetter = isDefined(value), + keyDefined = !isSetter && isDefined(key), + isSimpleGetter = keyDefined && !isObject(key); + + if (!data && !isSimpleGetter) { + JQLiteExpandoStore(element, 'data', data = {}); + } + + if (isSetter) { + data[key] = value; + } else { + if (keyDefined) { + if (isSimpleGetter) { + // don't create data in this case. + return data && data[key]; + } else { + extend(data, key); + } + } else { + return data; + } + } +} + +function JQLiteHasClass(element, selector) { + return ((" " + element.className + " ").replace(/[\n\t]/g, " "). + indexOf( " " + selector + " " ) > -1); +} + +function JQLiteRemoveClass(element, cssClasses) { + if (cssClasses) { + forEach(cssClasses.split(' '), function(cssClass) { + element.className = trim( + (" " + element.className + " ") + .replace(/[\n\t]/g, " ") + .replace(" " + trim(cssClass) + " ", " ") + ); + }); + } +} + +function JQLiteAddClass(element, cssClasses) { + if (cssClasses) { + forEach(cssClasses.split(' '), function(cssClass) { + if (!JQLiteHasClass(element, cssClass)) { + element.className = trim(element.className + ' ' + trim(cssClass)); + } + }); + } +} + +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'); + } + + while (element.length) { + if ((value = element.data(name)) !== undefined) return value; + element = element.parent(); + } +} + +////////////////////////////////////////// +// 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. + JQLite(window).on('load', trigger); // fallback to window.onload for others + } + }, + 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) { + return JQLiteInheritedData(element, '$scope'); + }, + + 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; + } +}, function(fn, name){ + /** + * Properties: writes return selection, reads return first value + */ + JQLite.prototype[name] = function(arg1, arg2) { + var i, key; + + // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it + // in a way that survives minification. + if (((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 < this.length; 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. + 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(this.length, 1) : this.length; + 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 < this.length; 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; + }; + + forEach(events[type || event.type], 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 ) { + 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, + + 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.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 (isUndefined(condition)) { + condition = !JQLiteHasClass(element, selector); + } + (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); + }, + + 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) { + return element.getElementsByTagName(selector); + }, + + clone: JQLiteClone, + + triggerHandler: function(element, eventName, eventData) { + var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName]; + eventData = eventData || { + preventDefault: noop, + stopPropagation: noop + }; + + forEach(eventFns, function(fn) { + fn.call(element, eventData); + }); + } +}, function(fn, name){ + /** + * chaining functions + */ + JQLite.prototype[name] = function(arg1, arg2, arg3) { + var value; + for(var i=0; i < this.length; i++) { + if (value == undefined) { + value = fn(this[i], arg1, arg2, arg3); + if (value !== undefined) { + // any function which returns a value needs to be wrapped + value = jqLite(value); + } + } else { + JQLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); + } + } + return value == undefined ? this : value; + }; + + // 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) { + var objType = typeof obj, + key; + + if (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 = nextUid(); + } + } else { + key = obj; + } + + return objType + ':' + key; +} + +/** + * HashMap which can use objects as keys + */ +function HashMap(array){ + 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)] = value; + }, + + /** + * @param key + * @returns the value for the key + */ + get: function(key) { + return this[hashKey(key)]; + }, + + /** + * Remove the key/value pair + * @param key + */ + remove: function(key) { + var value = this[key = hashKey(key)]; + delete this[key]; + return value; + } +}; + +/** + * @ngdoc function + * @name angular.injector + * @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 + *
    + *   // 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();
    + *   });
    + * 
    + */ + + +/** + * @ngdoc overview + * @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 object + * @name AUTO.$injector + * @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: + * + *
    + *   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. + * + *
    + *   // 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 a `$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 AUTO.$injector#get + * @methodOf AUTO.$injector + * + * @description + * Return an instance of the service. + * + * @param {string} name The name of the instance to retrieve. + * @return {*} The instance. + */ + +/** + * @ngdoc method + * @name AUTO.$injector#invoke + * @methodOf AUTO.$injector + * + * @description + * Invoke the method and supply the method arguments from the `$injector`. + * + * @param {!function} fn The function to invoke. The function arguments come form the function annotation. + * @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 AUTO.$injector#has + * @methodOf AUTO.$injector + * + * @description + * Allows the user to query if the particular service exist. + * + * @param {string} Name of the service to query. + * @returns {boolean} returns true if injector has given service. + */ + +/** + * @ngdoc method + * @name AUTO.$injector#instantiate + * @methodOf AUTO.$injector + * @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 AUTO.$injector#annotate + * @methodOf AUTO.$injector + * + * @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. + *
    + *   // 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. + *
    + *   // 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: + * + *
    + *   // 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 object + * @name AUTO.$provide + * + * @description + * + * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance. + * The providers share the same name as the instance they create with `Provider` suffixed to them. + * + * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of + * a service. The Provider can have additional methods which would allow for configuration of the provider. + * + *
    + *   function GreetProvider() {
    + *     var salutation = 'Hello';
    + *
    + *     this.salutation = function(text) {
    + *       salutation = text;
    + *     };
    + *
    + *     this.$get = function() {
    + *       return function (name) {
    + *         return salutation + ' ' + name + '!';
    + *       };
    + *     };
    + *   }
    + *
    + *   describe('Greeter', function(){
    + *
    + *     beforeEach(module(function($provide) {
    + *       $provide.provider('greet', GreetProvider);
    + *     }));
    + *
    + *     it('should greet', inject(function(greet) {
    + *       expect(greet('angular')).toEqual('Hello angular!');
    + *     }));
    + *
    + *     it('should allow configuration of salutation', function() {
    + *       module(function(greetProvider) {
    + *         greetProvider.salutation('Ahoj');
    + *       });
    + *       inject(function(greet) {
    + *         expect(greet('angular')).toEqual('Ahoj angular!');
    + *       });
    + *     });
    + * 
    + */ + +/** + * @ngdoc method + * @name AUTO.$provide#provider + * @methodOf AUTO.$provide + * @description + * + * Register a provider for a service. The providers can be retrieved and can have additional configuration methods. + * + * @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 + */ + +/** + * @ngdoc method + * @name AUTO.$provide#factory + * @methodOf AUTO.$provide + * @description + * + * A short hand for configuring services if only `$get` method is required. + * + * @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 + */ + + +/** + * @ngdoc method + * @name AUTO.$provide#service + * @methodOf AUTO.$provide + * @description + * + * A short hand for registering service of given 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 + */ + + +/** + * @ngdoc method + * @name AUTO.$provide#value + * @methodOf AUTO.$provide + * @description + * + * A short hand for configuring services if the `$get` method is a constant. + * + * @param {string} name The name of the instance. + * @param {*} value The value. + * @returns {Object} registered provider instance + */ + + +/** + * @ngdoc method + * @name AUTO.$provide#constant + * @methodOf AUTO.$provide + * @description + * + * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected + * into configuration function (other modules) and it is not interceptable by + * {@link AUTO.$provide#decorator decorator}. + * + * @param {string} name The name of the constant. + * @param {*} value The constant value. + * @returns {Object} registered instance + */ + + +/** + * @ngdoc method + * @name AUTO.$provide#decorator + * @methodOf AUTO.$provide + * @description + * + * Decoration of service, allows the decorator to intercept the service instance creation. The + * returned instance may be the original instance, or a new instance which delegates to the + * original instance. + * + * @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. 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. + */ + + +function createInjector(modulesToLoad) { + var INSTANTIATING = {}, + providerSuffix = 'Provider', + path = [], + loadedModules = new HashMap(), + 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_) { + 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, value) { return factory(name, valueFn(value)); } + + function constant(name, value) { + 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 = []; + forEach(modulesToLoad, function(module) { + if (loadedModules.get(module)) return; + loadedModules.put(module, true); + + try { + if (isString(module)) { + var moduleFn = angularModule(module); + runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); + + for(var 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. + 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}', path.join(' <- ')); + } + return cache[serviceName]; + } else { + try { + path.unshift(serviceName); + cache[serviceName] = INSTANTIATING; + return cache[serviceName] = factory(serviceName); + } 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 (!fn.$inject) { + // this means that we must be an array. + fn = fn[length]; + } + + + // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke + switch (self ? -1 : args.length) { + case 0: return fn(); + case 1: return fn(args[0]); + case 2: return fn(args[0], args[1]); + case 3: return fn(args[0], args[1], args[2]); + case 4: return fn(args[0], args[1], args[2], args[3]); + case 5: return fn(args[0], args[1], args[2], args[3], args[4]); + case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); + case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); + case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); + default: 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) ? returnedValue : instance; + } + + return { + invoke: invoke, + instantiate: instantiate, + get: getService, + annotate: annotate, + has: function(name) { + return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); + } + }; + } +} + +/** + * @ngdoc function + * @name ng.$anchorScroll + * @requires $window + * @requires $location + * @requires $rootScope + * + * @description + * When called, it checks current value of `$location.hash()` and scroll to related element, + * according to rules specified in + * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}. + * + * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor. + * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. + */ +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 object + * @name ng.$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 function + * @name ng.$animateProvider#register + * @methodOf ng.$animateProvider + * + * @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. + * + * + *
    +   *   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); + }; + + this.$get = ['$timeout', function($timeout) { + + /** + * @ngdoc object + * @name ng.$animate + * + * @description + * The $animate service provides rudimentary DOM manipulation functions to insert, remove, 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 function + * @name ng.$animate#enter + * @methodOf ng.$animate + * @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 {jQuery/jqLite element} element the element which will be inserted into the DOM + * @param {jQuery/jqLite element} parent the parent element which will append the element as a child (if the after element is not present) + * @param {jQuery/jqLite element} 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) { + var afterNode = after && after[after.length - 1]; + var parentNode = parent && parent[0] || afterNode && afterNode.parentNode; + // IE does not like undefined so we have to pass null. + var afterNextSibling = (afterNode && afterNode.nextSibling) || null; + forEach(element, function(node) { + parentNode.insertBefore(node, afterNextSibling); + }); + done && $timeout(done, 0, false); + }, + + /** + * @ngdoc function + * @name ng.$animate#leave + * @methodOf ng.$animate + * @function + * + * @description + * Removes the element from the DOM. Once complete, the done() callback will be fired (if provided). + * + * @param {jQuery/jqLite element} 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(); + done && $timeout(done, 0, false); + }, + + /** + * @ngdoc function + * @name ng.$animate#move + * @methodOf ng.$animate + * @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 {jQuery/jqLite element} element the element which will be moved around within the DOM + * @param {jQuery/jqLite element} parent the parent element where the element will be inserted into (if the after element is not present) + * @param {jQuery/jqLite element} 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 it's 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 function + * @name ng.$animate#addClass + * @methodOf ng.$animate + * @function + * + * @description + * Adds the provided className CSS class value to the provided element. Once complete, the done() callback will be fired (if provided). + * + * @param {jQuery/jqLite element} 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(' ') : ''; + element.addClass(className); + done && $timeout(done, 0, false); + }, + + /** + * @ngdoc function + * @name ng.$animate#removeClass + * @methodOf ng.$animate + * @function + * + * @description + * Removes the provided className CSS class value from the provided element. Once complete, the done() callback will be fired (if provided). + * + * @param {jQuery/jqLite element} 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(' ') : ''; + element.removeClass(className); + done && $timeout(done, 0, false); + }, + + enabled : noop + }; + }]; +}]; + +/** + * ! This is a private undocumented service ! + * + * @name ng.$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 ng.$browser#addPollFn + * @methodOf ng.$browser + * + * @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'), + replacedUrl = null; + + /** + * @name ng.$browser#url + * @methodOf ng.$browser + * + * @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) { + // 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 { + if (replace) { + location.replace(url); + replacedUrl = url; + } else { + location.href = url; + replacedUrl = null; + } + } + return self; + // getter + } else { + // - the replacedUrl is a workaround for an IE8-9 issue with location.replace method that doesn't update + // location.href synchronously + // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 + return replacedUrl || location.href.replace(/%27/g,"'"); + } + }; + + var urlChangeListeners = [], + urlChangeInit = false; + + function fireUrlChange() { + if (lastBrowserUrl == self.url()) return; + + lastBrowserUrl = self.url(); + forEach(urlChangeListeners, function(listener) { + listener(self.url()); + }); + } + + /** + * @name ng.$browser#onUrlChange + * @methodOf ng.$browser + * @TODO(vojta): refactor to use node's syntax for events + * + * @description + * Register callback function that will be called, when url changes. + * + * It's only called when the url is changed by 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) { + 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 + ////////////////////////////////////////////////////////////// + + /** + * Returns current + * (always relative - without domain) + * + * @returns {string=} + */ + self.baseHref = function() { + var href = baseElement.attr('href'); + return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : ''; + }; + + ////////////////////////////////////////////////////////////// + // Cookies API + ////////////////////////////////////////////////////////////// + var lastCookies = {}; + var lastCookieString = ''; + var cookiePath = self.baseHref(); + + /** + * @name ng.$browser#cookies + * @methodOf ng.$browser + * + * @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) { + 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 + var 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 ng.$browser#defer + * @methodOf ng.$browser + * @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 ng.$browser#defer.cancel + * @methodOf ng.$browser.defer + * + * @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 object + * @name ng.$cacheFactory + * + * @description + * Factory that constructs cache objects and gives access to them. + * + *
    + * 
    + *  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");
    + * 
    + *  expect(cache.info()).toEqual({id: 'cacheId', size: 2}); // Since we've specified no options on creation
    + * 
    + * 
    + * + * + * @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. + * + */ +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; + + return caches[cacheId] = { + + put: function(key, 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; + }, + + + get: function(key) { + var lruEntry = lruHash[key]; + + if (!lruEntry) return; + + refresh(lruEntry); + + return data[key]; + }, + + + remove: function(key) { + 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--; + }, + + + removeAll: function() { + data = {}; + size = 0; + lruHash = {}; + freshEnd = staleEnd = null; + }, + + + destroy: function() { + data = null; + stats = null; + lruHash = null; + delete caches[cacheId]; + }, + + + 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 ng.$cacheFactory#info + * @methodOf ng.$cacheFactory + * + * @description + * Get information about all the of 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 ng.$cacheFactory#get + * @methodOf ng.$cacheFactory + * + * @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 object + * @name ng.$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: + *
    + * 
    + * 
    + * 
    + * 
    + *   ...
    + * 
    + * 
    + * + * **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: + * + *
    + * 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: + *
    + * 
    + *
    + * + * or get it via Javascript: + *
    + * $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 function + * @name ng.$compile + * @function + * + * @description + * Compiles a piece of 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 trying to match DOM elements to + * {@link ng.$compileProvider#directive directives}. For each match it + * executes corresponding template function and collects the + * instance functions into a single template function which is then returned. + * + * The template function can then be used once to produce the view or as it is the case with + * {@link ng.directive:ngRepeat repeater} many-times, in which + * case each call results in a view that is a DOM clone of the original template. + * + + + +
    +
    +
    +
    +
    +
    + + it('should auto compile', function() { + expect(element('div[compile]').text()).toBe('Hello Angular'); + input('html').enter('{{name}}!'); + expect(element('div[compile]').text()).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 then 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. + *
    + *     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: + *
    + *     var templateHTML = angular.element('

    {{total}}

    '), + * scope = ....; + * + * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) { + * //attach the clone to DOM document at the right place + * }); + * + * //now we have reference to the cloned DOM via `clone` + *
    + * + * + * 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 service + * @name ng.$compileProvider + * @function + * + * @description + */ +$CompileProvider.$inject = ['$provide']; +function $CompileProvider($provide) { + var hasDirectives = {}, + Suffix = 'Directive', + COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, + CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, + aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/, + imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//; + + // 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 function + * @name ng.$compileProvider#directive + * @methodOf ng.$compileProvider + * @function + * + * @description + * Register a new directive with the compiler. + * + * @param {string} name Name of the directive in camel-case. (ie ngBind which will match as + * ng-bind). + * @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) { + 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) { + 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.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 function + * @name ng.$compileProvider#aHrefSanitizationWhitelist + * @methodOf ng.$compileProvider + * @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)) { + aHrefSanitizationWhitelist = regexp; + return this; + } + return aHrefSanitizationWhitelist; + }; + + + /** + * @ngdoc function + * @name ng.$compileProvider#imgSrcSanitizationWhitelist + * @methodOf ng.$compileProvider + * @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)) { + imgSrcSanitizationWhitelist = regexp; + return this; + } + return imgSrcSanitizationWhitelist; + }; + + + this.$get = [ + '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', + '$controller', '$rootScope', '$document', '$sce', '$$urlUtils', '$animate', + function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, + $controller, $rootScope, $document, $sce, $$urlUtils, $animate) { + + var Attributes = function(element, attr) { + this.$$element = element; + this.$attr = attr || {}; + }; + + Attributes.prototype = { + $normalize: directiveNormalize, + + + /** + * @ngdoc function + * @name ng.$compile.directive.Attributes#$addClass + * @methodOf ng.$compile.directive.Attributes + * @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 function + * @name ng.$compile.directive.Attributes#$removeClass + * @methodOf ng.$compile.directive.Attributes + * @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); + } + }, + + /** + * 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) { + //special case for class attribute addition + removal + //so that class changes can tap into the animation + //hooks provided by the $animate service + if(key == 'class') { + value = value || ''; + var current = this.$$element.attr('class') || ''; + this.$removeClass(tokenDifference(current, value).join(' ')); + this.$addClass(tokenDifference(value, current).join(' ')); + } else { + 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')) { + // NOTE: $$urlUtils.resolve() doesn't support IE < 8 so we don't sanitize for that case. + if (!msie || msie >= 8 ) { + normalizedVal = $$urlUtils.resolve(value); + if (normalizedVal !== '') { + if ((key === 'href' && !normalizedVal.match(aHrefSanitizationWhitelist)) || + (key === 'src' && !normalizedVal.match(imgSrcSanitizationWhitelist))) { + this[key] = value = 'unsafe:' + normalizedVal; + } + } + } + } + + 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); + } + }); + + function tokenDifference(str1, str2) { + var values = [], + tokens1 = str1.split(/\s+/), + tokens2 = str2.split(/\s+/); + + outer: + for(var i=0;i + 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); + return function publicLinkFn(scope, cloneConnectFn){ + 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; + + // 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, nAttrs = node.attributes, + j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { + var attrStartName; + var attrEndName; + var index; + + attr = nAttrs[j]; + if (!msie || msie >= 8 || attr.specified) { + name = attr.name; + // support ngAttr attribute binding + ngAttrName = directiveNormalize(name); + if (NG_ATTR_BINDING.test(ngAttrName)) { + name = ngAttrName.substr(6).toLowerCase(); + } + if ((index = ngAttrName.lastIndexOf('Start')) != -1 && index == ngAttrName.length - 5) { + attrStartName = name; + attrEndName = name.substr(0, name.length - 5) + 'end'; + name = name.substr(0, name.length - 6); + } + nName = directiveNormalize(name.toLowerCase()); + attrsMap[nName] = name; + attrs[nName] = value = trim((msie && name == 'href') + ? decodeURIComponent(node.getAttribute(name, 2)) + : attr.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 find 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) { + element = groupScan(element[0], attrStart, attrEnd); + return linkFn(scope, element, attrs, controllers); + } + } + + /** + * 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. + * @returns linkFn + */ + function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection, originalReplaceDirective) { + var terminalPriority = -Number.MAX_VALUE, + preLinkFns = [], + postLinkFns = [], + newScopeDirective = null, + newIsolateScopeDirective = null, + templateDirective = null, + $compileNode = templateAttrs.$$element = jqLite(compileNode), + directive, + directiveName, + $template, + transcludeDirective, + replaceDirective = originalReplaceDirective, + childTranscludeFn = transcludeFn, + controllerDirectives, + 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) { + assertNoDuplicate('isolated scope', newIsolateScopeDirective, directive, $compileNode); + if (isObject(directiveValue)) { + safeAddClass($compileNode, 'ng-isolate-scope'); + newIsolateScopeDirective = directive; + } + safeAddClass($compileNode, 'ng-scope'); + newScopeDirective = newScopeDirective || directive; + } + + directiveName = directive.name; + + if (directiveValue = directive.controller) { + controllerDirectives = controllerDirectives || {}; + assertNoDuplicate("'" + directiveName + "' controller", + controllerDirectives[directiveName], directive, $compileNode); + controllerDirectives[directiveName] = directive; + } + + if (directiveValue = directive.transclude) { + assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode); + transcludeDirective = directive; + terminalPriority = directive.priority; + if (directiveValue == 'element') { + $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); + } else { + $template = jqLite(JQLiteClone(compileNode)).contents(); + $compileNode.html(''); // clear contents + childTranscludeFn = compile($template, transcludeFn); + } + } + + if (directive.template) { + 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; + $template = jqLite('
    ' + + trim(directiveValue) + + '
    ').contents(); + 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 were already applied and those that weren't + // - collect directives from the template, add them to the second group and sort them + // - append the second group with new directives to the first group + directives = directives.concat( + collectDirectives( + compileNode, + directives.splice(i + 1, directives.length - (i + 1)), + newTemplateAttrs + ) + ); + mergeTemplateAttributes(templateAttrs, newTemplateAttrs); + + ii = directives.length; + } else { + $compileNode.html(directiveValue); + } + } + + if (directive.templateUrl) { + assertNoDuplicate('template', templateDirective, directive, $compileNode); + templateDirective = directive; + + if (directive.replace) { + replaceDirective = directive; + } + nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), + nodeLinkFn, $compileNode, templateAttrs, jqCollection, childTranscludeFn); + 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; + nodeLinkFn.transclude = transcludeDirective && childTranscludeFn; + + // 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; + preLinkFns.push(pre); + } + if (post) { + if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); + post.require = directive.require; + postLinkFns.push(post); + } + } + + + function getControllers(require, $element) { + 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 = $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(require, $element)); + }); + } + return value; + } + + + function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { + var attrs, $element, i, ii, linkFn, controller; + + 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 parentScope = scope.$parent || 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; + + scope.$$isolateBindings[scopeName] = mode + attrName; + + switch (mode) { + + case '@': { + attrs.$observe(attrName, function(value) { + scope[scopeName] = value; + }); + attrs.$$observers[attrName].$$scope = parentScope; + 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 + scope[scopeName] = $interpolate(attrs[attrName])(parentScope); + } + break; + } + + case '=': { + if (optional && !attrs[attrName]) { + return; + } + parentGet = $parse(attrs[attrName]); + parentSet = parentGet.assign || function() { + // reset the change, or we will throw this exception on every $digest + lastValue = scope[scopeName] = parentGet(parentScope); + throw $compileMinErr('nonassign', "Expression '{0}' used with directive '{1}' is non-assignable!", + attrs[attrName], newIsolateScopeDirective.name); + }; + lastValue = scope[scopeName] = parentGet(parentScope); + scope.$watch(function parentValueWatch() { + var parentValue = parentGet(parentScope); + + if (parentValue !== scope[scopeName]) { + // we are out of sync and need to copy + if (parentValue !== lastValue) { + // parent changed and it has precedence + lastValue = scope[scopeName] = parentValue; + } else { + // if the parent can be assigned then do so + parentSet(parentScope, parentValue = lastValue = scope[scopeName]); + } + } + return parentValue; + }); + break; + } + + case '&': { + parentGet = $parse(attrs[attrName]); + scope[scopeName] = function(locals) { + return parentGet(parentScope, locals); + }; + break; + } + + default: { + throw $compileMinErr('iscp', "Invalid isolate scope definition for directive '{0}'. Definition: {... {1}: '{2}' ...}", + newIsolateScopeDirective.name, scopeName, definition); + } + } + }); + } + + if (controllerDirectives) { + forEach(controllerDirectives, function(directive) { + var locals = { + $scope: scope, + $element: $element, + $attrs: attrs, + $transclude: boundTranscludeFn + }, controllerInstance; + + controller = directive.controller; + if (controller == '@') { + controller = attrs[directive.name]; + } + + controllerInstance = $controller(controller, locals); + $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(scope, $element, attrs, + linkFn.require && getControllers(linkFn.require, $element)); + } catch (e) { + $exceptionHandler(e, startingTag($element)); + } + } + + // RECURSION + childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn); + + // POSTLINKING + for(i = 0, ii = postLinkFns.length; i < ii; i++) { + try { + linkFn = postLinkFns[i]; + linkFn(scope, $element, attrs, + linkFn.require && getControllers(linkFn.require, $element)); + } catch (e) { + $exceptionHandler(e, startingTag($element)); + } + } + } + } + + + /** + * 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 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]) { + 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); + } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { + dst[key] = value; + dstAttr[key] = srcAttr[key]; + } + }); + } + + + function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs, + $rootElement, childTranscludeFn) { + 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, { + controller: null, templateUrl: null, transclude: null, scope: null, replace: null + }), + templateUrl = (isFunction(origAsyncDirective.templateUrl)) + ? origAsyncDirective.templateUrl($compileNode, tAttrs) + : origAsyncDirective.templateUrl; + + $compileNode.html(''); + + $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}). + success(function(content) { + var compileNode, tempTemplateAttrs, $template; + + content = denormalizeTemplate(content); + + if (origAsyncDirective.replace) { + $template = jqLite('
    ' + trim(content) + '
    ').contents(); + 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); + collectDirectives(compileNode, directives, tempTemplateAttrs); + mergeTemplateAttributes(tAttrs, tempTemplateAttrs); + } else { + compileNode = beforeTemplateCompileNode; + $compileNode.html(content); + } + + directives.unshift(derivedSyncDirective); + + afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn, $compileNode, origAsyncDirective); + 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(), + controller = linkQueue.shift(), + linkNode = $compileNode[0]; + + if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { + // it was cloned therefore we have to clone as well. + linkNode = JQLiteClone(compileNode); + replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); + } + + afterTemplateNodeLinkFn( + beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller), + scope, linkNode, $rootElement, controller + ); + } + 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, controller) { + if (linkQueue) { + linkQueue.push(scope); + linkQueue.push(node); + linkQueue.push(rootElement); + linkQueue.push(controller); + } else { + afterTemplateNodeLinkFn(function() { + beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller); + }, scope, node, rootElement, controller); + } + }; + } + + + /** + * Sorting function for bound directives. + */ + function byPriority(a, b) { + return b.priority - a.priority; + } + + + 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: valueFn(function textInterpolateLinkFn(scope, node) { + var parent = node.parent(), + bindings = parent.data('$binding') || []; + bindings.push(interpolateFn); + safeAddClass(parent.data('$binding', bindings), 'ng-binding'); + scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { + node[0].nodeValue = value; + }); + }) + }); + } + } + + + function getTrustedContext(node, attrNormalizedName) { + // maction[xlink:href] can source SVG. It's not limited to . + if (attrNormalizedName == "xlinkHref" || + (nodeName_(node) != "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: valueFn(function attrInterpolateLinkFn(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; + + attr[name] = interpolateFn(scope); + ($$observers[name] || ($$observers[name] = [])).$$inter = true; + (attr.$$observers && attr.$$observers[name].$$scope || scope). + $watch(interpolateFn, function interpolateFnWatchAction(value) { + attr.$set(name, value); + }); + }) + }); + } + + + /** + * 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 + } + }]; +} + +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 object + * @name ng.$compile.directive.Attributes + * @description + * + * A shared object between directive compile / linking functions which contains normalized DOM element + * attributes. The the values reflect current binding state `{{ }}`. The normalization is needed + * since all of these are treated as equivalent in Angular: + * + * + */ + +/** + * @ngdoc property + * @name ng.$compile.directive.Attributes#$attr + * @propertyOf ng.$compile.directive.Attributes + * @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 function + * @name ng.$compile.directive.Attributes#$set + * @methodOf ng.$compile.directive.Attributes + * @function + * + * @description + * Set DOM element attribute value. + * + * + * @param {string} name Normalized element attribute name of the property to modify. The name is + * revers 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 +){} + +/** + * @ngdoc object + * @name ng.$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 function + * @name ng.$controllerProvider#register + * @methodOf ng.$controllerProvider + * @param {string} name Controller name + * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI + * annotations in the array notation). + */ + this.register = function(name, constructor) { + if (isObject(name)) { + extend(controllers, name) + } else { + controllers[name] = constructor; + } + }; + + + this.$get = ['$injector', '$window', function($injector, $window) { + + /** + * @ngdoc function + * @name ng.$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 {@link https://gist.github.com/1649788 + * BC version}. + */ + 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 object + * @name ng.$document + * @requires $window + * + * @description + * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` + * element. + */ +function $DocumentProvider(){ + this.$get = ['$window', function(window){ + return jqLite(window.document); + }]; +} + +/** + * @ngdoc function + * @name ng.$exceptionHandler + * @requires $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. + * + * @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) ? toJson(d) : d; + }], + + // default headers + headers: { + common: { + 'Accept': 'application/json, text/plain, */*' + }, + post: CONTENT_TYPE_APPLICATION_JSON, + put: CONTENT_TYPE_APPLICATION_JSON, + patch: CONTENT_TYPE_APPLICATION_JSON + }, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN' + }; + + /** + * Are order by request. I.E. they are applied in the same order as + * array on request, but revers order on response. + */ + var interceptorFactories = this.interceptors = []; + /** + * For historical reasons, response interceptors ordered by the order in which + * they are applied to response. (This is in revers to interceptorFactories) + */ + var responseInterceptorFactories = this.responseInterceptors = []; + + this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', '$$urlUtils', + function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector, $$urlUtils) { + + 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 function + * @name ng.$http + * @requires $httpBackend + * @requires $browser + * @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 {@link https://developer.mozilla.org/en/xmlhttprequest + * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP 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`. + * + *
    +     *   $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. + * + * # Shortcut methods + * + * Since all invocations of the $http service require passing in an HTTP method and URL, and + * POST/PUT requests require request data to be provided as well, shortcut methods + * were created: + * + *
    +     *   $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'`. + * + * Additionally, the defaults can be set at runtime via the `$http.defaults` object in the same + * fashion. + * + * + * # 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. + * + * 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 configuration property `cache` to `true`. When the cache is + * enabled, `$http` stores the response from the server in local cache. Next time 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. + * + * A custom default cache built with $cacheFactory can be provided in $http.defaults.cache. + * To skip it, set configuration property `cache` to `false`. + * + * + * # 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 http `config` object. The function is free to modify + * the `config` or create a new one. The function needs to return the `config` directly or as a + * promise. + * * `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` or create a new one. The function needs to return the `response` directly or as a + * promise. + * * `responseError`: interceptor gets called when a previous interceptor threw an error or resolved + * with a rejection. + * + * + *
    +     *   // 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 || $q.when(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 || $q.when(response);
    +     *       },
    +     *
    +     *       // optional method
    +     *      'responseError': function(rejection) {
    +     *         // do something on error
    +     *         if (canRecover(rejection)) {
    +     *           return responseOrNewPromise
    +     *         }
    +     *         return $q.reject(rejection);
    +     *       };
    +     *     }
    +     *   });
    +     *
    +     *   $httpProvider.interceptors.push('myHttpInterceptor');
    +     *
    +     *
    +     *   // 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. + * + *
    +     *   // 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: + * + * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx + * JSON vulnerability} + * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} + * + * 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 {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx + * JSON vulnerability} allows third party website to turn your JSON resource URL into + * {@link http://en.wikipedia.org/wiki/JSONP 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: + *
    +     * ['one','two']
    +     * 
    + * + * which is vulnerable to attack, your server can return: + *
    +     * )]}',
    +     * ['one','two']
    +     * 
    + * + * Angular will strip the prefix, before processing the JSON. + * + * + * ## Cross Site Request Forgery (XSRF) Protection + * + * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} 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 {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt} for added security. + * + * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName + * properties of either $httpProvider.defaults, 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 to set the `withCredentials` flag on the + * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 + * requests with credentials} for more information. + * - **responseType** - `{string}` - see {@link + * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}. + * + * @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. + * + * @property {Array.} pendingRequests Array of config objects for currently pending + * requests. This is primarily meant to be used for debugging purposes. + * + * + * @example + + +
    + + +
    + + + +
    http status code: {{status}}
    +
    http response data: {{data}}
    +
    +
    + + function FetchCtrl($scope, $http, $templateCache) { + $scope.method = 'GET'; + $scope.url = 'http-hello.html'; + + $scope.fetch = function() { + $scope.code = null; + $scope.response = null; + + $http({method: $scope.method, url: $scope.url, cache: $templateCache}). + success(function(data, status) { + $scope.status = status; + $scope.data = data; + }). + error(function(data, status) { + $scope.data = data || "Request failed"; + $scope.status = status; + }); + }; + + $scope.updateModel = function(method, url) { + $scope.method = method; + $scope.url = url; + }; + } + + + Hello, $http! + + + it('should make an xhr GET request', function() { + element(':button:contains("Sample GET")').click(); + element(':button:contains("fetch")').click(); + expect(binding('status')).toBe('200'); + expect(binding('data')).toMatch(/Hello, \$http!/); + }); + + it('should make a JSONP request to angularjs.org', function() { + element(':button:contains("Sample JSONP")').click(); + element(':button:contains("fetch")').click(); + expect(binding('status')).toBe('200'); + expect(binding('data')).toMatch(/Super Hero!/); + }); + + it('should make JSONP request to invalid URL and invoke the error handler', + function() { + element(':button:contains("Invalid JSONP")').click(); + element(':button:contains("fetch")').click(); + expect(binding('status')).toBe('0'); + expect(binding('data')).toBe('Request failed'); + }); + +
    + */ + function $http(requestConfig) { + var config = { + transformRequest: defaults.transformRequest, + transformResponse: defaults.transformResponse + }; + var headers = mergeHeaders(requestConfig); + + extend(config, requestConfig); + config.headers = headers; + config.method = uppercase(config.method); + + var xsrfValue = $$urlUtils.isSameOrigin(config.url) + ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] + : undefined; + if (xsrfValue) { + headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; + } + + + var serverRequest = function(config) { + headers = config.headers; + var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); + + // strip content-type if data is undefined + if (isUndefined(config.data)) { + forEach(headers, function(value, header) { + if (lowercase(header) === 'content-type') { + delete headers[header]; + } + }); + } + + if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { + config.withCredentials = defaults.withCredentials; + } + + // send request + return sendReq(config, reqData, headers).then(transformResponse, transformResponse); + }; + + var chain = [serverRequest, undefined]; + var promise = $q.when(config); + + // apply interceptors + forEach(reversedInterceptors, function(interceptor) { + if (interceptor.request || interceptor.requestError) { + chain.unshift(interceptor.request, interceptor.requestError); + } + if (interceptor.response || interceptor.responseError) { + chain.push(interceptor.response, interceptor.responseError); + } + }); + + while(chain.length) { + var thenFn = chain.shift(); + var rejectFn = chain.shift(); + + promise = promise.then(thenFn, rejectFn); + } + + promise.success = function(fn) { + promise.then(function(response) { + fn(response.data, response.status, response.headers, config); + }); + return promise; + }; + + promise.error = function(fn) { + promise.then(null, function(response) { + fn(response.data, response.status, response.headers, config); + }); + return promise; + }; + + return promise; + + function transformResponse(response) { + // make a copy since the response must be cacheable + var resp = extend({}, response, { + data: transformData(response.data, response.headers, config.transformResponse) + }); + return (isSuccess(response.status)) + ? resp + : $q.reject(resp); + } + + function mergeHeaders(config) { + var defHeaders = defaults.headers, + reqHeaders = extend({}, config.headers), + defHeaderName, lowercaseDefHeaderName, reqHeaderName; + + defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); + + // execute if header value is function + execHeaders(defHeaders); + execHeaders(reqHeaders); + + // using for-in instead of forEach to avoid unecessary iteration after header has been found + defaultHeadersIteration: + for (defHeaderName in defHeaders) { + lowercaseDefHeaderName = lowercase(defHeaderName); + + for (reqHeaderName in reqHeaders) { + if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { + continue defaultHeadersIteration; + } + } + + reqHeaders[defHeaderName] = defHeaders[defHeaderName]; + } + + return reqHeaders; + + function execHeaders(headers) { + var headerContent; + + forEach(headers, function(headerFn, header) { + if (isFunction(headerFn)) { + headerContent = headerFn(); + if (headerContent != null) { + headers[header] = headerContent; + } else { + delete headers[header]; + } + } + }); + } + } + } + + $http.pendingRequests = []; + + /** + * @ngdoc method + * @name ng.$http#get + * @methodOf ng.$http + * + * @description + * Shortcut method to perform `GET` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name ng.$http#delete + * @methodOf ng.$http + * + * @description + * Shortcut method to perform `DELETE` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name ng.$http#head + * @methodOf ng.$http + * + * @description + * Shortcut method to perform `HEAD` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name ng.$http#jsonp + * @methodOf ng.$http + * + * @description + * Shortcut method to perform `JSONP` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request. + * Should contain `JSON_CALLBACK` string. + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + createShortMethods('get', 'delete', 'head', 'jsonp'); + + /** + * @ngdoc method + * @name ng.$http#post + * @methodOf ng.$http + * + * @description + * Shortcut method to perform `POST` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name ng.$http#put + * @methodOf ng.$http + * + * @description + * Shortcut method to perform `PUT` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + createShortMethodsWithData('post', 'put'); + + /** + * @ngdoc property + * @name ng.$http#defaults + * @propertyOf ng.$http + * + * @description + * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of + * default headers, withCredentials as well as request and response transformations. + * + * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. + */ + $http.defaults = defaults; + + + return $http; + + + function createShortMethods(names) { + forEach(arguments, function(name) { + $http[name] = function(url, config) { + return $http(extend(config || {}, { + method: name, + url: url + })); + }; + }); + } + + + function createShortMethodsWithData(name) { + forEach(arguments, function(name) { + $http[name] = function(url, data, config) { + return $http(extend(config || {}, { + method: name, + url: url, + data: data + })); + }; + }); + } + + + /** + * Makes the request. + * + * !!! ACCESSES CLOSURE VARS: + * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests + */ + function sendReq(config, reqData, reqHeaders) { + var deferred = $q.defer(), + promise = deferred.promise, + cache, + cachedResp, + url = buildUrl(config.url, config.params); + + $http.pendingRequests.push(config); + promise.then(removePendingReq, removePendingReq); + + + if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') { + cache = isObject(config.cache) ? config.cache + : isObject(defaults.cache) ? defaults.cache + : defaultCache; + } + + if (cache) { + cachedResp = cache.get(url); + if (isDefined(cachedResp)) { + if (cachedResp.then) { + // cached request has already been sent, but there is no response yet + cachedResp.then(removePendingReq, removePendingReq); + return cachedResp; + } else { + // serving from cache + if (isArray(cachedResp)) { + resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); + } else { + resolvePromise(cachedResp, 200, {}); + } + } + } else { + // put the promise for the non-transformed response into cache as a placeholder + cache.put(url, promise); + } + } + + // if we won't have the response in cache, send the request to the backend + if (isUndefined(cachedResp)) { + $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, + config.withCredentials, config.responseType); + } + + return promise; + + + /** + * Callback registered to $httpBackend(): + * - caches the response if desired + * - resolves the raw $http promise + * - calls $apply + */ + function done(status, response, headersString) { + if (cache) { + if (isSuccess(status)) { + cache.put(url, [status, response, parseHeaders(headersString)]); + } else { + // remove promise from the cache + cache.remove(url); + } + } + + resolvePromise(response, status, headersString); + if (!$rootScope.$$phase) $rootScope.$apply(); + } + + + /** + * Resolves the raw $http promise. + */ + function resolvePromise(response, status, headers) { + // normalize internal statuses to 0 + status = Math.max(status, 0); + + (isSuccess(status) ? deferred.resolve : deferred.reject)({ + data: response, + status: status, + headers: headersGetter(headers), + config: config + }); + } + + + function removePendingReq() { + var idx = indexOf($http.pendingRequests, config); + if (idx !== -1) $http.pendingRequests.splice(idx, 1); + } + } + + + function buildUrl(url, params) { + if (!params) return url; + var parts = []; + forEachSorted(params, function(value, key) { + if (value == null || value == undefined) return; + if (!isArray(value)) value = [value]; + + forEach(value, function(v) { + if (isObject(v)) { + v = toJson(v); + } + parts.push(encodeUriQuery(key) + '=' + + encodeUriQuery(v)); + }); + }); + return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); + } + + + }]; +} + +var XHR = window.XMLHttpRequest || function() { + try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} + try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} + try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} + throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest."); +}; + + +/** + * @ngdoc object + * @name ng.$httpBackend + * @requires $browser + * @requires $window + * @requires $document + * + * @description + * HTTP backend used by the {@link ng.$http service} that delegates to + * XMLHttpRequest object or JSONP and deals with browser incompatibilities. + * + * You should never need to use this service directly, instead use the higher-level abstractions: + * {@link ng.$http $http} or {@link ngResource.$resource $resource}. + * + * During testing this implementation is swapped with {@link ngMock.$httpBackend mock + * $httpBackend} which can be trained with responses. + */ +function $HttpBackendProvider() { + this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { + return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks, + $document[0], $window.location.protocol.replace(':', '')); + }]; +} + +function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) { + // TODO(vojta): fix the signature + return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { + var status; + $browser.$$incOutstandingRequestCount(); + url = url || $browser.url(); + + if (lowercase(method) == 'jsonp') { + var callbackId = '_' + (callbacks.counter++).toString(36); + callbacks[callbackId] = function(data) { + callbacks[callbackId].data = data; + }; + + var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), + function() { + if (callbacks[callbackId].data) { + completeRequest(callback, 200, callbacks[callbackId].data); + } else { + completeRequest(callback, status || -2); + } + delete callbacks[callbackId]; + }); + } else { + var xhr = new XHR(); + xhr.open(method, url, true); + forEach(headers, function(value, key) { + if (value) xhr.setRequestHeader(key, value); + }); + + // In IE6 and 7, this might be called synchronously when xhr.send below is called and the + // response is in the cache. the promise api will ensure that to the app code the api is + // always async + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + var responseHeaders = xhr.getAllResponseHeaders(); + + // TODO(vojta): remove once Firefox 21 gets released. + // begin: workaround to overcome Firefox CORS http response headers bug + // https://bugzilla.mozilla.org/show_bug.cgi?id=608735 + // Firefox already patched in nightly. Should land in Firefox 21. + + // CORS "simple response headers" http://www.w3.org/TR/cors/ + var value, + simpleHeaders = ["Cache-Control", "Content-Language", "Content-Type", + "Expires", "Last-Modified", "Pragma"]; + if (!responseHeaders) { + responseHeaders = ""; + forEach(simpleHeaders, function (header) { + var value = xhr.getResponseHeader(header); + if (value) { + responseHeaders += header + ": " + value + "\n"; + } + }); + } + // end of the workaround. + + // responseText is the old-school way of retrieving response (supported by IE8 & 9) + // response and responseType properties were introduced in XHR Level2 spec (supported by IE10) + completeRequest(callback, + status || xhr.status, + (xhr.responseType ? xhr.response : xhr.responseText), + responseHeaders); + } + }; + + if (withCredentials) { + xhr.withCredentials = true; + } + + if (responseType) { + xhr.responseType = responseType; + } + + xhr.send(post || ''); + } + + if (timeout > 0) { + var timeoutId = $browserDefer(timeoutRequest, timeout); + } else if (timeout && timeout.then) { + timeout.then(timeoutRequest); + } + + + function timeoutRequest() { + status = -1; + jsonpDone && jsonpDone(); + xhr && xhr.abort(); + } + + function completeRequest(callback, status, response, headersString) { + // URL_MATCH is defined in src/service/location.js + var protocol = (url.match(SERVER_MATCH) || ['', locationProtocol])[1]; + + // cancel timeout and subsequent timeout promise resolution + timeoutId && $browserDefer.cancel(timeoutId); + jsonpDone = xhr = null; + + // fix status code for file protocol (it's always 0) + status = (protocol == 'file') ? (response ? 200 : 404) : status; + + // normalize IE bug (http://bugs.jquery.com/ticket/1450) + status = status == 1223 ? 204 : status; + + callback(status, response, headersString); + $browser.$$completeOutstandingRequest(noop); + } + }; + + function jsonpReq(url, done) { + // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: + // - fetches local scripts via XHR and evals them + // - adds and immediately removes script elements from the document + var script = rawDocument.createElement('script'), + doneWrapper = function() { + rawDocument.body.removeChild(script); + if (done) done(); + }; + + script.type = 'text/javascript'; + script.src = url; + + if (msie) { + script.onreadystatechange = function() { + if (/loaded|complete/.test(script.readyState)) doneWrapper(); + }; + } else { + script.onload = script.onerror = doneWrapper; + } + + rawDocument.body.appendChild(script); + return doneWrapper; + } +} + +var $interpolateMinErr = minErr('$interpolate'); + +/** + * @ngdoc object + * @name ng.$interpolateProvider + * @function + * + * @description + * + * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. + * + * @example + + + +
    + //demo.label// +
    +
    + + it('should interpolate binding with custom symbols', function() { + expect(binding('demo.label')).toBe('This bindings is brought you you by // interpolation symbols.'); + }); + +
    + */ +function $InterpolateProvider() { + var startSymbol = '{{'; + var endSymbol = '}}'; + + /** + * @ngdoc method + * @name ng.$interpolateProvider#startSymbol + * @methodOf ng.$interpolateProvider + * @description + * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. + * + * @param {string=} value new value to set the starting symbol to. + * @returns {string|self} Returns the symbol when used as getter and self if used as setter. + */ + this.startSymbol = function(value){ + if (value) { + startSymbol = value; + return this; + } else { + return startSymbol; + } + }; + + /** + * @ngdoc method + * @name ng.$interpolateProvider#endSymbol + * @methodOf ng.$interpolateProvider + * @description + * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. + * + * @param {string=} value new value to set the ending symbol to. + * @returns {string|self} Returns the symbol when used as getter and self if used as setter. + */ + this.endSymbol = function(value){ + if (value) { + endSymbol = value; + return this; + } else { + return endSymbol; + } + }; + + + this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { + var startSymbolLength = startSymbol.length, + endSymbolLength = endSymbol.length; + + /** + * @ngdoc function + * @name ng.$interpolate + * @function + * + * @requires $parse + * @requires $sce + * + * @description + * + * Compiles a string with markup into an interpolation function. This service is used by the + * HTML {@link ng.$compile $compile} service for data binding. See + * {@link ng.$interpolateProvider $interpolateProvider} for configuring the + * interpolation markup. + * + * +
    +         var $interpolate = ...; // injected
    +         var exp = $interpolate('Hello {{name}}!');
    +         expect(exp({name:'Angular'}).toEqual('Hello Angular!');
    +       
    + * + * + * @param {string} text The text with markup to interpolate. + * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have + * embedded expression in order to return an interpolation function. Strings with no + * embedded expression will return null for the interpolation function. + * @param {string=} trustedContext when provided, the returned function passes the interpolated + * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, + * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that + * provides Strict Contextual Escaping for details. + * @returns {function(context)} an interpolation function which is used to compute the interpolated + * string. The function has these parameters: + * + * * `context`: an object against which any expressions embedded in the strings are evaluated + * against. + * + */ + function $interpolate(text, mustHaveExpression, trustedContext) { + var startIndex, + endIndex, + index = 0, + parts = [], + length = text.length, + hasInterpolation = false, + fn, + exp, + concat = []; + + while(index < length) { + if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && + ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { + (index != startIndex) && parts.push(text.substring(index, startIndex)); + parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); + fn.exp = exp; + index = endIndex + endSymbolLength; + hasInterpolation = true; + } else { + // we did not find anything, so we have to add the remainder to the parts array + (index != length) && parts.push(text.substring(index)); + index = length; + } + } + + if (!(length = parts.length)) { + // we added, nothing, must have been an empty string. + parts.push(''); + length = 1; + } + + // Concatenating expressions makes it hard to reason about whether some combination of concatenated + // values are unsafe to use and could easily lead to XSS. By requiring that a single + // expression be used for iframe[src], object[src], etc., we ensure that the value that's used + // is assigned or constructed by some JS code somewhere that is more testable or make it + // obvious that you bound the value to some user controlled value. This helps reduce the load + // when auditing for XSS issues. + if (trustedContext && parts.length > 1) { + throw $interpolateMinErr('noconcat', + "Error while interpolating: {0}\nStrict Contextual Escaping disallows " + + "interpolations that concatenate multiple expressions when a trusted value is " + + "required. See http://docs.angularjs.org/api/ng.$sce", text); + } + + if (!mustHaveExpression || hasInterpolation) { + concat.length = length; + fn = function(context) { + try { + for(var i = 0, ii = length, part; i|Object.>} search New search params - string or hash object. Hash object + * may contain an array of values, which will be decoded as duplicates in the url. + * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a + * single search parameter. If the value is `null`, the parameter will be deleted. + * + * @return {string} search + */ + 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 (paramValue == undefined || paramValue == null) { + delete this.$$search[search]; + } else { + this.$$search[search] = paramValue; + } + } + + this.$$compose(); + return this; + }, + + /** + * @ngdoc method + * @name ng.$location#hash + * @methodOf ng.$location + * + * @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 ng.$location#replace + * @methodOf ng.$location + * + * @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 object + * @name ng.$location + * + * @requires $browser + * @requires $sniffer + * @requires $rootElement + * + * @description + * The $location service parses the URL in the browser address bar (based on the + * {@link https://developer.mozilla.org/en/window.location 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/dev_guide.services.$location Developer Guide: Angular + * Services: Using $location} + */ + +/** + * @ngdoc object + * @name ng.$locationProvider + * @description + * Use the `$locationProvider` to configure how the application deep linking paths are stored. + */ +function $LocationProvider(){ + var hashPrefix = '', + html5Mode = false; + + /** + * @ngdoc property + * @name ng.$locationProvider#hashPrefix + * @methodOf ng.$locationProvider + * @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 property + * @name ng.$locationProvider#html5Mode + * @methodOf ng.$locationProvider + * @description + * @param {string=} 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; + } + }; + + 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'); + var rewrittenUrl = $location.$$rewrite(absHref); + + if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) { + event.preventDefault(); + if (rewrittenUrl != $browser.url()) { + // update location manually + $location.$$parse(rewrittenUrl); + $rootScope.$apply(); + // hack to work around FF6 bug 684208 when scenario runner clicks on links + window.angular['ff-684208-preventDefault'] = true; + } + } + }); + + + // rewrite hashbang url <> 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) { + if ($rootScope.$broadcast('$locationChangeStart', newUrl, $location.absUrl()).defaultPrevented) { + $browser.url($location.absUrl()); + return; + } + $rootScope.$evalAsync(function() { + var oldUrl = $location.absUrl(); + + $location.$$parse(newUrl); + 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 object + * @name ng.$log + * @requires $window + * + * @description + * Simple service for logging. Default implementation writes the message + * into the browser's console (if present). + * + * The main purpose of this service is to simplify debugging and troubleshooting. + * + * @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 object + * @name ng.$logProvider + * @description + * Use the `$logProvider` to configure how the application logs messages + */ +function $LogProvider(){ + var debug = true, + self = this; + + /** + * @ngdoc property + * @name ng.$logProvider#debugEnabled + * @methodOf ng.$logProvider + * @description + * @param {string=} 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 ng.$log#log + * @methodOf ng.$log + * + * @description + * Write a log message + */ + log: consoleLog('log'), + + /** + * @ngdoc method + * @name ng.$log#info + * @methodOf ng.$log + * + * @description + * Write an information message + */ + info: consoleLog('info'), + + /** + * @ngdoc method + * @name ng.$log#warn + * @methodOf ng.$log + * + * @description + * Write a warning message + */ + warn: consoleLog('warn'), + + /** + * @ngdoc method + * @name ng.$log#error + * @methodOf ng.$log + * + * @description + * Write an error message + */ + error: consoleLog('error'), + + /** + * @ngdoc method + * @name ng.$log#debug + * @methodOf ng.$log + * + * @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; + + if (logFn.apply) { + 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); + } + } + }]; +} + +var $parseMinErr = minErr('$parse'); + +// 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")) +// +// We want to prevent this type of access. For the sake of performance, during the lexing phase we disallow any "dotted" +// access to any member named "constructor". +// +// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor while evaluating +// the expression, which is a stronger but more expensive test. Since reflective calls are expensive anyway, this is not +// such a big deal compared to static dereferencing. +// +// 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. +// +// A developer could foil the name check by aliasing the Function constructor under a different name on the scope. +// +// 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. + +function ensureSafeMemberName(name, fullExpression) { + if (name === "constructor") { + throw $parseMinErr('isecfld', + 'Referencing "constructor" field in Angular expressions is disallowed! 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 && obj.constructor === obj) { + throw $parseMinErr('isecfn', + 'Referencing Function in Angular expressions is disallowed! Expression: {0}', fullExpression); + } else { + return obj; + } +} + + +var OPERATORS = { + '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);} +}; +var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; + +function lex(text, csp){ + var tokens = [], + token, + index = 0, + json = [], + ch, + lastCh = ':'; // can start regexp + + while (index < text.length) { + ch = text.charAt(index); + if (is('"\'')) { + readString(ch); + } else if (isNumber(ch) || is('.') && isNumber(peek())) { + readNumber(); + } else if (isIdent(ch)) { + readIdent(); + // identifiers can only be if the preceding char was a { or , + if (was('{,') && json[0]=='{' && + (token=tokens[tokens.length-1])) { + token.json = token.text.indexOf('.') == -1; + } + } else if (is('(){}[].,;:?')) { + tokens.push({ + index:index, + text:ch, + json:(was(':[,') && is('{[')) || is('}]:,') + }); + if (is('{[')) json.unshift(ch); + if (is('}]')) json.shift(); + index++; + } else if (isWhitespace(ch)) { + index++; + continue; + } else { + var ch2 = ch + peek(), + ch3 = ch2 + peek(2), + fn = OPERATORS[ch], + fn2 = OPERATORS[ch2], + fn3 = OPERATORS[ch3]; + if (fn3) { + tokens.push({index:index, text:ch3, fn:fn3}); + index += 3; + } else if (fn2) { + tokens.push({index:index, text:ch2, fn:fn2}); + index += 2; + } else if (fn) { + tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); + index += 1; + } else { + throwError("Unexpected next character ", index, index+1); + } + } + lastCh = ch; + } + return tokens; + + function is(chars) { + return chars.indexOf(ch) != -1; + } + + function was(chars) { + return chars.indexOf(lastCh) != -1; + } + + function peek(i) { + var num = i || 1; + return index + num < text.length ? text.charAt(index + num) : false; + } + function isNumber(ch) { + return '0' <= ch && ch <= '9'; + } + function isWhitespace(ch) { + return ch == ' ' || ch == '\r' || ch == '\t' || + ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 + } + function isIdent(ch) { + return 'a' <= ch && ch <= 'z' || + 'A' <= ch && ch <= 'Z' || + '_' == ch || ch == '$'; + } + function isExpOperator(ch) { + return ch == '-' || ch == '+' || isNumber(ch); + } + + function throwError(error, start, end) { + end = end || index; + var colStr = (isDefined(start) ? + "s " + start + "-" + index + " [" + text.substring(start, end) + "]" + : " " + end); + throw $parseMinErr('lexerr', "Lexer Error: {0} at column{1} in expression [{2}].", + error, colStr, text); + } + + function readNumber() { + var number = ""; + var start = index; + while (index < text.length) { + var ch = lowercase(text.charAt(index)); + if (ch == '.' || isNumber(ch)) { + number += ch; + } else { + var peekCh = peek(); + if (ch == 'e' && isExpOperator(peekCh)) { + number += ch; + } else if (isExpOperator(ch) && + peekCh && isNumber(peekCh) && + number.charAt(number.length - 1) == 'e') { + number += ch; + } else if (isExpOperator(ch) && + (!peekCh || !isNumber(peekCh)) && + number.charAt(number.length - 1) == 'e') { + throwError('Invalid exponent'); + } else { + break; + } + } + index++; + } + number = 1 * number; + tokens.push({index:start, text:number, json:true, + fn:function() {return number;}}); + } + function readIdent() { + var ident = "", + start = index, + lastDot, peekIndex, methodName, ch; + + while (index < text.length) { + ch = text.charAt(index); + if (ch == '.' || isIdent(ch) || isNumber(ch)) { + if (ch == '.') lastDot = index; + ident += ch; + } else { + break; + } + index++; + } + + //check if this is not a method invocation and if it is back out to last dot + if (lastDot) { + peekIndex = index; + while(peekIndex < text.length) { + ch = text.charAt(peekIndex); + if (ch == '(') { + methodName = ident.substr(lastDot - start + 1); + ident = ident.substr(0, lastDot - start); + index = peekIndex; + break; + } + if(isWhitespace(ch)) { + peekIndex++; + } else { + break; + } + } + } + + + var token = { + index:start, + text:ident + }; + + if (OPERATORS.hasOwnProperty(ident)) { + token.fn = token.json = OPERATORS[ident]; + } else { + var getter = getterFn(ident, csp, text); + token.fn = extend(function(self, locals) { + return (getter(self, locals)); + }, { + assign: function(self, value) { + return setter(self, ident, value, text); + } + }); + } + + tokens.push(token); + + if (methodName) { + tokens.push({ + index:lastDot, + text: '.', + json: false + }); + tokens.push({ + index: lastDot + 1, + text: methodName, + json: false + }); + } + } + + function readString(quote) { + var start = index; + index++; + var string = ""; + var rawString = quote; + var escape = false; + while (index < text.length) { + var ch = text.charAt(index); + rawString += ch; + if (escape) { + if (ch == 'u') { + var hex = text.substring(index + 1, index + 5); + if (!hex.match(/[\da-f]{4}/i)) + throwError( "Invalid unicode escape [\\u" + hex + "]"); + 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) { + index++; + tokens.push({ + index:start, + text:rawString, + string:string, + json:true, + fn:function() { return string; } + }); + return; + } else { + string += ch; + } + index++; + } + throwError("Unterminated quote", start); + } +} + +///////////////////////////////////////// + +function parser(text, json, $filter, csp){ + var ZERO = valueFn(0), + value, + tokens = lex(text, csp), + assignment = _assignment, + functionCall = _functionCall, + fieldAccess = _fieldAccess, + objectIndex = _objectIndex, + filterChain = _filterChain; + + if(json){ + // The extra level of aliasing is here, just in case the lexer misses something, so that + // we prevent any accidental execution in JSON. + assignment = logicalOR; + functionCall = + fieldAccess = + objectIndex = + filterChain = + function() { throwError("is not valid json", {text:text, index:0}); }; + value = primary(); + } else { + value = statements(); + } + if (tokens.length !== 0) { + throwError("is an unexpected token", tokens[0]); + } + value.literal = !!value.literal; + value.constant = !!value.constant; + return value; + + /////////////////////////////////// + function throwError(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), text, text.substring(token.index)); + } + + function peekToken() { + if (tokens.length === 0) + throw $parseMinErr('ueoe', "Unexpected end of expression: {0}", text); + return tokens[0]; + } + + function peek(e1, e2, e3, e4) { + if (tokens.length > 0) { + var token = tokens[0]; + var t = token.text; + if (t==e1 || t==e2 || t==e3 || t==e4 || + (!e1 && !e2 && !e3 && !e4)) { + return token; + } + } + return false; + } + + function expect(e1, e2, e3, e4){ + var token = peek(e1, e2, e3, e4); + if (token) { + if (json && !token.json) { + throwError("is not valid json", token); + } + tokens.shift(); + return token; + } + return false; + } + + function consume(e1){ + if (!expect(e1)) { + throwError("is unexpected, expecting [" + e1 + "]", peek()); + } + } + + function unaryFn(fn, right) { + return extend(function(self, locals) { + return fn(self, locals, right); + }, { + constant:right.constant + }); + } + + function ternaryFn(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 + }); + } + + function binaryFn(left, fn, right) { + return extend(function(self, locals) { + return fn(self, locals, left, right); + }, { + constant:left.constant && right.constant + }); + } + + function statements() { + var statements = []; + while(true) { + if (tokens.length > 0 && !peek('}', ')', ';', ']')) + statements.push(filterChain()); + if (!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; + }; + } + } + } + + function _filterChain() { + var left = expression(); + var token; + while(true) { + if ((token = expect('|'))) { + left = binaryFn(left, token.fn, filter()); + } else { + return left; + } + } + } + + function filter() { + var token = expect(); + var fn = $filter(token.text); + var argsFn = []; + while(true) { + if ((token = expect(':'))) { + argsFn.push(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; + }; + } + } + } + + function expression() { + return assignment(); + } + + function _assignment() { + var left = ternary(); + var right; + var token; + if ((token = expect('='))) { + if (!left.assign) { + throwError("implies assignment but [" + + text.substring(0, token.index) + "] can not be assigned to", token); + } + right = ternary(); + return function(scope, locals){ + return left.assign(scope, right(scope, locals), locals); + }; + } else { + return left; + } + } + + function ternary() { + var left = logicalOR(); + var middle; + var token; + if((token = expect('?'))){ + middle = ternary(); + if((token = expect(':'))){ + return ternaryFn(left, middle, ternary()); + } + else { + throwError('expected :', token); + } + } + else { + return left; + } + } + + function logicalOR() { + var left = logicalAND(); + var token; + while(true) { + if ((token = expect('||'))) { + left = binaryFn(left, token.fn, logicalAND()); + } else { + return left; + } + } + } + + function logicalAND() { + var left = equality(); + var token; + if ((token = expect('&&'))) { + left = binaryFn(left, token.fn, logicalAND()); + } + return left; + } + + function equality() { + var left = relational(); + var token; + if ((token = expect('==','!=','===','!=='))) { + left = binaryFn(left, token.fn, equality()); + } + return left; + } + + function relational() { + var left = additive(); + var token; + if ((token = expect('<', '>', '<=', '>='))) { + left = binaryFn(left, token.fn, relational()); + } + return left; + } + + function additive() { + var left = multiplicative(); + var token; + while ((token = expect('+','-'))) { + left = binaryFn(left, token.fn, multiplicative()); + } + return left; + } + + function multiplicative() { + var left = unary(); + var token; + while ((token = expect('*','/','%'))) { + left = binaryFn(left, token.fn, unary()); + } + return left; + } + + function unary() { + var token; + if (expect('+')) { + return primary(); + } else if ((token = expect('-'))) { + return binaryFn(ZERO, token.fn, unary()); + } else if ((token = expect('!'))) { + return unaryFn(token.fn, unary()); + } else { + return primary(); + } + } + + + function primary() { + var primary; + if (expect('(')) { + primary = filterChain(); + consume(')'); + } else if (expect('[')) { + primary = arrayDeclaration(); + } else if (expect('{')) { + primary = object(); + } else { + var token = expect(); + primary = token.fn; + if (!primary) { + throwError("not a primary expression", token); + } + if (token.json) { + primary.constant = primary.literal = true; + } + } + + var next, context; + while ((next = expect('(', '[', '.'))) { + if (next.text === '(') { + primary = functionCall(primary, context); + context = null; + } else if (next.text === '[') { + context = primary; + primary = objectIndex(primary); + } else if (next.text === '.') { + context = primary; + primary = fieldAccess(primary); + } else { + throwError("IMPOSSIBLE"); + } + } + return primary; + } + + function _fieldAccess(object) { + var field = expect().text; + var getter = getterFn(field, csp, text); + return extend( + function(scope, locals, self) { + return getter(self || object(scope, locals), locals); + }, + { + assign:function(scope, value, locals) { + return setter(object(scope, locals), field, value, text); + } + } + ); + } + + function _objectIndex(obj) { + var indexFn = expression(); + consume(']'); + return extend( + function(self, locals){ + var o = obj(self, locals), + i = indexFn(self, locals), + v, p; + + if (!o) return undefined; + v = ensureSafeObject(o[i], text); + if (v && v.then) { + 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 + return ensureSafeObject(obj(self, locals), text)[key] = value; + } + }); + } + + function _functionCall(fn, contextGetter) { + var argsFn = []; + if (peekToken().text != ')') { + do { + argsFn.push(expression()); + } while (expect(',')); + } + consume(')'); + return function(scope, locals){ + var args = [], + 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; + // IE stupidity! + var v = fnPtr.apply + ? fnPtr.apply(context, args) + : fnPtr(args[0], args[1], args[2], args[3], args[4]); + + // Check for promise + if (v && v.then) { + var p = v; + if (!('$$v' in v)) { + p.$$v = undefined; + p.then(function(val) { p.$$v = val; }); + } + v = v.$$v; + } + + return v; + }; + } + + // This is used with json array declaration + function arrayDeclaration () { + var elementFns = []; + var allConstant = true; + if (peekToken().text != ']') { + do { + var elementFn = expression(); + elementFns.push(elementFn); + if (!elementFn.constant) { + allConstant = false; + } + } while (expect(',')); + } + 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 + }); + } + + function object () { + var keyValues = []; + var allConstant = true; + if (peekToken().text != '}') { + do { + var token = expect(), + key = token.string || token.text; + consume(":"); + var value = expression(); + keyValues.push({key:key, value:value}); + if (!value.constant) { + allConstant = false; + } + } while (expect(',')); + } + 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) { + 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) { + 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); + 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) { + ensureSafeMemberName(key0, fullExp); + ensureSafeMemberName(key1, fullExp); + ensureSafeMemberName(key2, fullExp); + ensureSafeMemberName(key3, fullExp); + ensureSafeMemberName(key4, fullExp); + return function(scope, locals) { + var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, + promise; + + if (pathVal === null || pathVal === undefined) return pathVal; + + pathVal = pathVal[key0]; + if (pathVal && pathVal.then) { + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + if (!key1 || pathVal === null || pathVal === undefined) return pathVal; + + pathVal = pathVal[key1]; + if (pathVal && pathVal.then) { + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + if (!key2 || pathVal === null || pathVal === undefined) return pathVal; + + pathVal = pathVal[key2]; + if (pathVal && pathVal.then) { + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + if (!key3 || pathVal === null || pathVal === undefined) return pathVal; + + pathVal = pathVal[key3]; + if (pathVal && pathVal.then) { + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + if (!key4 || pathVal === null || pathVal === undefined) return pathVal; + + pathVal = pathVal[key4]; + if (pathVal && pathVal.then) { + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + return pathVal; + }; +} + +function getterFn(path, csp, fullExp) { + if (getterFnCache.hasOwnProperty(path)) { + return getterFnCache[path]; + } + + var pathKeys = path.split('.'), + pathKeysLength = pathKeys.length, + fn; + + if (csp) { + fn = (pathKeysLength < 6) + ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp) + : function(scope, locals) { + var i = 0, val; + do { + val = cspSafeGetterFn( + pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], fullExp + )(scope, locals); + + locals = undefined; // clear after first iteration + scope = val; + } while (i < pathKeysLength); + return val; + } + } else { + var code = 'var l, fn, p;\n'; + forEach(pathKeys, function(key, index) { + ensureSafeMemberName(key, fullExp); + code += 'if(s === null || s === undefined) return s;\n' + + 'l=s;\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' + + 'if (s && s.then) {\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;'; + fn = Function('s', 'k', code); // s=scope, k=locals + fn.toString = function() { return code; }; + } + + return getterFnCache[path] = fn; +} + +/////////////////////////////////// + +/** + * @ngdoc function + * @name ng.$parse + * @function + * + * @description + * + * Converts Angular {@link guide/expression expression} into a function. + * + *
    + *   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. + * + */ +function $ParseProvider() { + var cache = {}; + this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { + return function(exp) { + switch(typeof exp) { + case 'string': + return cache.hasOwnProperty(exp) + ? cache[exp] + : cache[exp] = parser(exp, false, $filter, $sniffer.csp); + case 'function': + return exp; + default: + return noop; + } + }; + }]; +} + +/** + * @ngdoc service + * @name ng.$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. + * + *
    + *   // for the purpose of this example let's assume that variables `$q` and `scope` are
    + *   // available in the current lexical scope (they could have been injected or passed in).
    + *
    + *   function asyncGreet(name) {
    + *     var deferred = $q.defer();
    + *
    + *     setTimeout(function() {
    + *       // since this fn executes async in a future turn of the event loop, we need to wrap
    + *       // our code into an $apply call so that the model changes are properly observed.
    + *       scope.$apply(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](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 promises 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 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: + * + *
    + *   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 three 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 promises are recognized by the templating engine in angular, which means that in templates + * you can treat promises attached to a scope as if they were the resulting values. + * - 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 + * + *
    + *    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 + * @name ng.$q#defer + * @methodOf ng.$q + * @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(reject(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 + * @name ng.$q#reject + * @methodOf ng.$q + * @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`. + * + *
    +   *   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) { + 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 + * @name ng.$q#when + * @methodOf ng.$q + * @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 + * @name ng.$q#all + * @methodOf ng.$q + * @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 resolved with the + * same rejection. + */ + 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 + }; +} + +/** + * 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 (shift) 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 object + * @name ng.$rootScopeProvider + * @description + * + * Provider for the $rootScope service. + */ + +/** + * @ngdoc function + * @name ng.$rootScopeProvider#digestTtl + * @methodOf ng.$rootScopeProvider + * @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. + * + * @param {number} limit The number of digest iterations. + */ + + +/** + * @ngdoc object + * @name ng.$rootScope + * @description + * + * Every application has a single root {@link ng.$rootScope.Scope scope}. + * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide + * event processing life-cycle. See {@link guide/scope developer guide on scopes}. + */ +function $RootScopeProvider(){ + var TTL = 10; + var $rootScopeMinErr = minErr('$rootScope'); + + this.digestTtl = function(value) { + if (arguments.length) { + TTL = value; + } + return TTL; + }; + + this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', + function( $injector, $exceptionHandler, $parse, $browser) { + + /** + * @ngdoc function + * @name ng.$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. + *
    +     * 
    +     * 
    + * + * # Inheritance + * A scope can inherit from a parent scope, as in this example: + *
    +         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.$$isolateBindings = {}; + } + + /** + * @ngdoc property + * @name ng.$rootScope.Scope#$id + * @propertyOf ng.$rootScope.Scope + * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for + * debugging. + */ + + + Scope.prototype = { + constructor: Scope, + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$new + * @methodOf ng.$rootScope.Scope + * @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 Child, + child; + + if (isolate) { + child = new Scope(); + child.$root = this.$root; + // ensure that there is just one async queue per $rootScope and it's children + child.$$asyncQueue = this.$$asyncQueue; + child.$$postDigestQueue = this.$$postDigestQueue; + } else { + Child = function() {}; // should be anonymous; This is so that when the minifier munges + // the name it does not become random set of chars. These will then show up as class + // name in the debugger. + Child.prototype = this; + child = new Child(); + child.$id = nextUid(); + } + child['this'] = child; + child.$$listeners = {}; + child.$parent = this; + child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; + child.$$prevSibling = this.$$childTail; + if (this.$$childHead) { + this.$$childTail.$$nextSibling = child; + this.$$childTail = child; + } else { + this.$$childHead = this.$$childTail = child; + } + return child; + }, + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$watch + * @methodOf ng.$rootScope.Scope + * @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 which 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). The inequality is determined according to + * {@link angular.equals} function. To save the value of the object for later comparison, the + * {@link angular.copy} function is used. It also means that watching complex options 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. + * + * + * # Example + *
    +           // 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();
    +           // no variable change
    +           expect(scope.counter).toEqual(0);
    +
    +           scope.name = 'adam';
    +           scope.$digest();
    +           expect(scope.counter).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 object for equality rather than for reference. + * @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 + }; + + // 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() { + arrayRemove(array, watcher); + }; + }, + + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$watchCollection + * @methodOf ng.$rootScope.Scope + * @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 new items + * into the object or array, removing and moving items around. + * + * + * # Example + *
    +          $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 that is fired with both + * the `newCollection` and `oldCollection` as parameters. + * The `newCollection` object is the newly modified data obtained from the `obj` expression and the + * `oldCollection` object is a copy of the former collection data. + * The `scope` refers to the current scope. + * + * @returns {function()} Returns a de-registration function for this listener. When the de-registration function is executed + * then the internal watch operation is terminated. + */ + $watchCollection: function(obj, listener) { + var self = this; + var oldValue; + var newValue; + var changeDetected = 0; + var objGetter = $parse(obj); + var internalArray = []; + var internalObject = {}; + var oldLength = 0; + + function $watchCollectionWatch() { + newValue = objGetter(self); + var newLength, key; + + if (!isObject(newValue)) { + 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++) { + if (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() { + listener(newValue, oldValue, self); + } + + return this.$watch($watchCollectionWatch, $watchCollectionAction); + }, + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$digest + * @methodOf ng.$rootScope.Scope + * @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 a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a + * {@link ng.$compileProvider#directive directives}) 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`. + * + * You may have a need to call `$digest()` from within unit-tests, to simulate the scope + * life-cycle. + * + * # Example + *
    +           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();
    +           // no variable change
    +           expect(scope.counter).toEqual(0);
    +
    +           scope.name = 'adam';
    +           scope.$digest();
    +           expect(scope.counter).toEqual(1);
    +       * 
    + * + */ + $digest: function() { + var watch, value, last, + watchers, + asyncQueue = this.$$asyncQueue, + postDigestQueue = this.$$postDigestQueue, + length, + dirty, ttl = TTL, + next, current, target = this, + watchLog = [], + logIdx, logMsg; + + beginPhase('$digest'); + + do { // "while dirty" loop + dirty = false; + current = target; + + while(asyncQueue.length) { + try { + current.$eval(asyncQueue.shift()); + } catch (e) { + $exceptionHandler(e); + } + } + + 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 && (value = watch.get(current)) !== (last = watch.last) && + !(watch.eq + ? equals(value, last) + : (typeof value == 'number' && typeof last == 'number' + && isNaN(value) && isNaN(last)))) { + dirty = true; + watch.last = watch.eq ? copy(value) : 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); + } + } + } catch (e) { + $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)); + + if(dirty && !(ttl--)) { + clearPhase(); + throw $rootScopeMinErr('infdig', + '{0} $digest() iterations reached. Aborting!\nWatchers 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 ng.$rootScope.Scope#$destroy + * @eventOf ng.$rootScope.Scope + * @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 function + * @name ng.$rootScope.Scope#$destroy + * @methodOf ng.$rootScope.Scope + * @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 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 ($rootScope == this || this.$$destroyed) return; + var parent = this.$parent; + + this.$broadcast('$destroy'); + this.$$destroyed = true; + + 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; + + // This is bogus code that works around Chrome's GC leak + // see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 + this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = + this.$$childTail = null; + }, + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$eval + * @methodOf ng.$rootScope.Scope + * @function + * + * @description + * Executes the `expression` on the current scope returning the result. Any exceptions in the + * expression are propagated (uncaught). This is useful when evaluating Angular expressions. + * + * # Example + *
    +           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. + * + * @returns {*} The result of evaluating the expression. + */ + $eval: function(expr, locals) { + return $parse(expr)(this, locals); + }, + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$evalAsync + * @methodOf ng.$rootScope.Scope + * @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 schedule the evaluation is done running (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 `$digest` cycle, a new $digest cycle will be scheduled. + * It is however encouraged to always call code that changes the model from withing 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(expr); + }, + + $$postDigest : function(expr) { + this.$$postDigestQueue.push(expr); + }, + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$apply + * @methodOf ng.$rootScope.Scope + * @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()` + *
    +           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 function + * @name ng.$rootScope.Scope#$on + * @methodOf ng.$rootScope.Scope + * @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); + + return function() { + namedListeners[indexOf(namedListeners, listener)] = null; + }; + }, + + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$emit + * @methodOf ng.$rootScope.Scope + * @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 set of 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 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): + * + *
    + *   var ngBindHtmlDirective = ['$sce', function($sce) {
    + *     return function(scope, element, attr) {
    + *       scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
    + *         element.html(value || '');
    + *       });
    + *     };
    + *   }];
    + * 
    + * + * ## 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 + * {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest + * Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing (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. (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. | + * | `$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. | + * + * ## Show me an example. + * + * + * + * @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('.htmlComment').html()).toBe('Is anyone reading this?'); + }); + it('should NOT sanitize explicitly trusted values', function() { + expect(element('#explicitlyTrustedHtml').html()).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);
    + *   });
    + * 
    + * + */ + +function $SceProvider() { + var enabled = true; + + /** + * @ngdoc function + * @name ng.sceProvider#enabled + * @methodOf ng.$sceProvider + * @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', '$document', '$sceDelegate', function( + $parse, $document, $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 && msie) { + var documentMode = $document[0].documentMode; + if (documentMode !== undefined && documentMode < 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 = copy(SCE_CONTEXTS); + + /** + * @ngdoc function + * @name ng.sce#isEnabled + * @methodOf ng.$sce + * @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 ng.$sce#parse + * @methodOf ng.$sce + * + * @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 ng.$sce#trustAs + * @methodOf ng.$sce + * + * @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-html-bind-unsafe, 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 ng.$sce#trustAsHtml + * @methodOf ng.$sce + * + * @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 ng.$sce#trustAsUrl + * @methodOf ng.$sce + * + * @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 ng.$sce#trustAsResourceUrl + * @methodOf ng.$sce + * + * @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 ng.$sce#trustAsJs + * @methodOf ng.$sce + * + * @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 ng.$sce#getTrusted + * @methodOf ng.$sce + * + * @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 ng.$sce#getTrustedHtml + * @methodOf ng.$sce + * + * @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 ng.$sce#getTrustedCss + * @methodOf ng.$sce + * + * @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 ng.$sce#getTrustedUrl + * @methodOf ng.$sce + * + * @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 ng.$sce#getTrustedResourceUrl + * @methodOf ng.$sce + * + * @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 ng.$sce#getTrustedJs + * @methodOf ng.$sce + * + * @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 ng.$sce#parseAsHtml + * @methodOf ng.$sce + * + * @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 ng.$sce#parseAsCss + * @methodOf ng.$sce + * + * @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 ng.$sce#parseAsUrl + * @methodOf ng.$sce + * + * @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 ng.$sce#parseAsResourceUrl + * @methodOf ng.$sce + * + * @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 ng.$sce#parseAsJs + * @methodOf ng.$sce + * + * @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; + + angular.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 ng.$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] || {}, + 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 webit browser (533.9) on Boxee box has exactly the same problem as Android has + // so let's not use the history API also + history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee), + hashchange: 'onhashchange' in $window && + // IE8 compatible mode lies + (!document.documentMode || document.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: document.securityPolicy ? document.securityPolicy.isActive : false, + vendorPrefix: vendorPrefix, + transitions : transitions, + animations : animations + }; + }]; +} + +function $TimeoutProvider() { + this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', + function($rootScope, $browser, $q, $exceptionHandler) { + var deferreds = {}; + + + /** + * @ngdoc function + * @name ng.$timeout + * @requires $browser + * + * @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 function + * @name ng.$timeout#cancel + * @methodOf ng.$timeout + * + * @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; + }]; +} + +function $$UrlUtilsProvider() { + this.$get = [function() { + var urlParsingNode = document.createElement("a"), + // 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 our for this + // service. + originUrl = resolve(window.location.href, true); + + /** + * @description + * Normalizes and optionally parses a URL. + * + * NOTE: This is a private service. The API is subject to change unpredictably in any commit. + * + * 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 assining 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/ + * + * @param {string} url The URL to be parsed. + * @param {boolean=} parse When true, returns an object for the parsed URL. Otherwise, returns + * a single string that is the normalized URL. + * @returns {object|string} When parse is true, returns the normalized URL as a string. + * Otherwise, returns an object with the following members. + * + * | 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 | + * + * These fields from the UrlUtils interface are currently not needed and hence not returned. + * + * | member name | Description | + * |---------------|----------------| + * | hostname | The host without the port of the normalizedUrl | + * | pathname | The path following the host in the normalizedUrl | + * | hash | The URL hash if present | + * | search | The query string | + * + */ + function resolve(url, parse) { + var href = url; + if (msie <= 11) { + // 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); + + if (!parse) { + return urlParsingNode.href; + } + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol, + host: urlParsingNode.host + // Currently unused and hence commented out. + // hostname: urlParsingNode.hostname, + // port: urlParsingNode.port, + // pathname: urlParsingNode.pathname, + // hash: urlParsingNode.hash, + // search: urlParsingNode.search + }; + } + + return { + resolve: resolve, + /** + * 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. + */ + isSameOrigin: function isSameOrigin(requestUrl) { + var parsed = (typeof requestUrl === 'string') ? resolve(requestUrl, true) : requestUrl; + return (parsed.protocol === originUrl.protocol && + parsed.host === originUrl.host); + } + }; + }]; +} + +/** + * @ngdoc object + * @name ng.$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() { + input('greeting').enter('Hello, E2E Tests'); + // If we click the button it will block the test runner + // element(':button').click(); + }); + +
    + */ +function $WindowProvider(){ + this.$get = valueFn(window); +} + +/** + * @ngdoc object + * @name ng.$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. + * + *
    + *   // 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`. + *
    + *   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/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer + * Guide. + */ +/** + * @ngdoc method + * @name ng.$filterProvider#register + * @methodOf ng.$filterProvider + * @description + * Register filter factory function. + * + * @param {String} name Name of the filter. + * @param {function} fn The filter factory function which is injectable. + */ + + +/** + * @ngdoc function + * @name ng.$filter + * @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 + */ +$FilterProvider.$inject = ['$provide']; +function $FilterProvider($provide) { + var suffix = 'Filter'; + + function register(name, factory) { + return $provide.factory(name + suffix, factory); + } + this.register = register; + + this.$get = ['$injector', function($injector) { + return function(name) { + return $injector.get(name + suffix); + } + }]; + + //////////////////////////////////////// + + 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 ng.filter:filter + * @function + * + * @description + * Selects a subset of items from `array` and returns it as a new array. + * + * Note: This function is used to augment the `Array` type in Angular expressions. See + * {@link ng.$filter} for more information about Angular arrays. + * + * @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`: Predicate that results in a substring match using the value of `expression` + * string. 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`: 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(expected, actual)|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(expected, actual)`: + * 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(expected, actual) { 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: +
    + + + + + +
    NamePhone
    {{friend.name}}{{friend.phone}}
    +
    + Any:
    + Name only
    + Phone only
    + Equality
    + + + + + + +
    NamePhone
    {{friend.name}}{{friend.phone}}
    + + + it('should search across all fields when filtering with a string', function() { + input('searchText').enter('m'); + expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). + toEqual(['Mary', 'Mike', 'Adam']); + + input('searchText').enter('76'); + expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). + toEqual(['John', 'Julie']); + }); + + it('should search in specific fields when filtering with a predicate object', function() { + input('search.$').enter('i'); + expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). + toEqual(['Mary', 'Mike', 'Julie', 'Juliette']); + }); + it('should use a equal comparison when comparator is true', function() { + input('search.name').enter('Julie'); + input('strict').check(); + expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). + toEqual(['Julie']); + }); + + + */ +function filterFilter() { + return function(array, expression, comperator) { + if (!isArray(array)) return array; + var predicates = []; + predicates.check = function(value) { + for (var j = 0; j < predicates.length; j++) { + if(!predicates[j](value)) { + return false; + } + } + return true; + }; + switch(typeof comperator) { + case "function": + break; + case "boolean": + if(comperator == true) { + comperator = function(obj, text) { + return angular.equals(obj, text); + } + break; + } + default: + comperator = function(obj, text) { + 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 comperator(obj, text); + case "object": + switch (typeof text) { + case "object": + return comperator(obj, text); + break; + 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": + expression = {$:expression}; + case "object": + for (var key in expression) { + if (key == '$') { + (function() { + if (!expression[key]) return; + var path = key + predicates.push(function(value) { + return search(value, expression[path]); + }); + })(); + } else { + (function() { + if (typeof(expression[key]) == 'undefined') { return; } + var path = key; + predicates.push(function(value) { + return search(getter(value,path), expression[path]); + }); + })(); + } + } + 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 ng.filter:currency + * @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 + + + +
    +
    + default currency symbol ($): {{amount | currency}}
    + custom currency identifier (USD$): {{amount | currency:"USD$"}} +
    +
    + + it('should init with 1234.56', function() { + expect(binding('amount | currency')).toBe('$1,234.56'); + expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); + }); + it('should update', function() { + input('amount').enter('-1234'); + expect(binding('amount | currency')).toBe('($1,234.00)'); + expect(binding('amount | currency:"USD$"')).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 ng.filter:number + * @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 + + + +
    + Enter number:
    + Default formatting: {{val | number}}
    + No fractions: {{val | number:0}}
    + Negative number: {{-val | number:4}} +
    +
    + + it('should format numbers', function() { + expect(binding('val | number')).toBe('1,234.568'); + expect(binding('val | number:0')).toBe('1,235'); + expect(binding('-val | number:4')).toBe('-1,234.5679'); + }); + + it('should update', function() { + input('val').enter('3374.333'); + expect(binding('val | number')).toBe('3,374.333'); + expect(binding('val | number:0')).toBe('3,374'); + expect(binding('-val | number:4')).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 (isNaN(number) || !isFinite(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'; + } 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); + } + + var pow = Math.pow(10, fractionSize); + number = Math.round(number * pow) / pow; + var fraction = ('' + number).split(DECIMAL_SEP); + var whole = fraction[0]; + fraction = fraction[1] || ''; + + var pos = 0, + lgroup = pattern.lgSize, + group = pattern.gSize; + + if (whole.length >= (lgroup + group)) { + pos = whole.length - lgroup; + for (var 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 ng.filter:date + * @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(binding("1288323623006 | date:'medium'")). + toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); + expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). + toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); + expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). + 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 ng.filter:json + * @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(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/); + }); + +
    + * + */ +function jsonFilter() { + return function(object) { + return toJson(object, true); + }; +} + + +/** + * @ngdoc filter + * @name ng.filter:lowercase + * @function + * @description + * Converts string to lowercase. + * @see angular.lowercase + */ +var lowercaseFilter = valueFn(lowercase); + + +/** + * @ngdoc filter + * @name ng.filter:uppercase + * @function + * @description + * Converts string to uppercase. + * @see angular.uppercase + */ +var uppercaseFilter = valueFn(uppercase); + +/** + * @ngdoc function + * @name ng.filter:limitTo + * @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`. + * + * Note: This function is used to augment the `Array` type in Angular expressions. See + * {@link ng.$filter} for more information about Angular arrays. + * + * @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 + + + +
    + Limit {{numbers}} to: +

    Output numbers: {{ numbers | limitTo:numLimit }}

    + Limit {{letters}} to: +

    Output letters: {{ letters | limitTo:letterLimit }}

    +
    +
    + + it('should limit the number array to first three items', function() { + expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3'); + expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3'); + expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]'); + expect(binding('letters | limitTo:letterLimit')).toEqual('abc'); + }); + + it('should update the output when -3 is entered', function() { + input('numLimit').enter(-3); + input('letterLimit').enter(-3); + expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]'); + expect(binding('letters | limitTo:letterLimit')).toEqual('ghi'); + }); + + it('should not exceed the maximum size of input array', function() { + input('numLimit').enter(100); + input('letterLimit').enter(100); + expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]'); + expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi'); + }); + +
    + */ +function limitToFilter(){ + return function(input, limit) { + if (!isArray(input) && !isString(input)) return input; + + 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 the array. + * @returns {Array} Sorted copy of the source array. + * + * @example + + + +
    +
    Sorting predicate = {{predicate}}; reverse = {{reverse}}
    +
    + [
    unsorted ] + + + + + + + + + + + +
    Name + (^)Phone NumberAge
    {{friend.name}}{{friend.phone}}{{friend.age}}
    +
    + + + it('should be reverse ordered by aged', function() { + expect(binding('predicate')).toBe('-age'); + expect(repeater('table.friend', 'friend in friends').column('friend.age')). + toEqual(['35', '29', '21', '19', '10']); + expect(repeater('table.friend', 'friend in friends').column('friend.name')). + toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); + }); + + it('should reorder the table when user selects different predicate', function() { + element('.doc-example-live a:contains("Name")').click(); + expect(repeater('table.friend', 'friend in friends').column('friend.name')). + toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); + expect(repeater('table.friend', 'friend in friends').column('friend.age')). + toEqual(['35', '10', '29', '19', '21']); + + element('.doc-example-live a:contains("Phone")').click(); + expect(repeater('table.friend', 'friend in friends').column('friend.phone')). + toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); + expect(repeater('table.friend', 'friend in friends').column('friend.name')). + toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); + }); + + + */ +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); + } + 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 ng.directive:a + * @restrict E + * + * @description + * Modifies the default behavior of html A tag, so that the default action is prevented when href + * attribute is empty. + * + * The reasoning for this change is to allow easy creation of action links with `ngClick` directive + * without changing the location or causing page reloads, e.g.: + * `Save` + */ +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')); + } + + return function(scope, element) { + 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 ng.directive:ngHref + * @restrict A + * + * @description + * Using Angular markup like {{hash}} in an href attribute makes + * the page open to a wrong URL, if the user clicks that link before + * angular has a chance to replace the {{hash}} with actual URL, the + * link will be broken and will most likely return a 404 error. + * The `ngHref` directive solves this problem. + * + * The buggy way to write it: + *
    + * 
    + * 
    + * + * The correct way to write it: + *
    + * 
    + * 
    + * + * @element A + * @param {template} ngHref any string which can contain `{{}}` markup. + * + * @example + * This example uses `link` variable inside `href` attribute: + + +
    +
    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('#link-1').click(); + expect(input('value').val()).toEqual('1'); + expect(element('#link-1').attr('href')).toBe(""); + }); + + it('should execute ng-click but not reload when href empty string', function() { + element('#link-2').click(); + expect(input('value').val()).toEqual('2'); + expect(element('#link-2').attr('href')).toBe(""); + }); + + it('should execute ng-click and change url when ng-href specified', function() { + expect(element('#link-3').attr('href')).toBe("/123"); + + element('#link-3').click(); + expect(browser().window().path()).toEqual('/123'); + }); + + it('should execute ng-click but not reload when href empty string and name specified', function() { + element('#link-4').click(); + expect(input('value').val()).toEqual('4'); + expect(element('#link-4').attr('href')).toBe(''); + }); + + it('should execute ng-click but not reload when no href but name specified', function() { + element('#link-5').click(); + expect(input('value').val()).toEqual('5'); + expect(element('#link-5').attr('href')).toBe(undefined); + }); + + it('should only change url when only ng-href', function() { + input('value').enter('6'); + expect(element('#link-6').attr('href')).toBe('6'); + + element('#link-6').click(); + expect(browser().location().url()).toEqual('/6'); + }); + + + */ + +/** + * @ngdoc directive + * @name ng.directive:ngSrc + * @restrict A + * + * @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: + *
    + * 
    + * 
    + * + * The correct way to write it: + *
    + * 
    + * 
    + * + * @element IMG + * @param {template} ngSrc any string which can contain `{{}}` markup. + */ + +/** + * @ngdoc directive + * @name ng.directive:ngSrcset + * @restrict A + * + * @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: + *
    + * 
    + * 
    + * + * The correct way to write it: + *
    + * 
    + * 
    + * + * @element IMG + * @param {template} ngSrcset any string which can contain `{{}}` markup. + */ + +/** + * @ngdoc directive + * @name ng.directive:ngDisabled + * @restrict A + * + * @description + * + * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: + *
    + * 
    + * + *
    + *
    + * + * The HTML specs do not require browsers to preserve the special attributes such as disabled. + * (The presence of them means true and absence means false) + * This prevents the angular compiler from correctly retrieving the binding expression. + * To solve this problem, we introduce the `ngDisabled` directive. + * + * @example + + + Click me to toggle:
    + +
    + + it('should toggle button', function() { + expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); + input('checked').check(); + expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); + }); + +
    + * + * @element INPUT + * @param {expression} ngDisabled Angular expression that will be evaluated. + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngChecked + * @restrict A + * + * @description + * The HTML specs do not require browsers to preserve the special attributes such as checked. + * (The presence of them means true and absence means false) + * This prevents the angular compiler from correctly retrieving the binding expression. + * To solve this problem, we introduce the `ngChecked` directive. + * @example + + + Check me to check both:
    + +
    + + it('should check both checkBoxes', function() { + expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); + input('master').check(); + expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); + }); + +
    + * + * @element INPUT + * @param {expression} ngChecked Angular expression that will be evaluated. + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngReadonly + * @restrict A + * + * @description + * The HTML specs do not require browsers to preserve the special attributes such as readonly. + * (The presence of them means true and absence means false) + * This prevents the angular compiler from correctly retrieving the binding expression. + * To solve this problem, we introduce the `ngReadonly` directive. + * @example + + + Check me to make text readonly:
    + +
    + + it('should toggle readonly attr', function() { + expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); + input('checked').check(); + expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); + }); + +
    + * + * @element INPUT + * @param {string} expression Angular expression that will be evaluated. + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngSelected + * @restrict A + * + * @description + * The HTML specs do not require browsers to preserve the special attributes such as selected. + * (The presence of them means true and absence means false) + * This prevents the angular compiler from correctly retrieving the binding expression. + * To solve this problem, we introduced the `ngSelected` directive. + * @example + + + Check me to select:
    + +
    + + it('should select Greetings!', function() { + expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); + input('selected').check(); + expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); + }); + +
    + * + * @element OPTION + * @param {string} expression Angular expression that will be evaluated. + */ + +/** + * @ngdoc directive + * @name ng.directive:ngOpen + * @restrict A + * + * @description + * The HTML specs do not require browsers to preserve the special attributes such as open. + * (The presence of them means true and absence means false) + * This prevents the angular compiler from correctly retrieving the binding expression. + * To solve this problem, we introduce the `ngOpen` directive. + * + * @example + + + Check me check multiple:
    +
    + Show/Hide me +
    +
    + + it('should toggle open', function() { + expect(element('#details').prop('open')).toBeFalsy(); + input('open').check(); + expect(element('#details').prop('open')).toBeTruthy(); + }); + +
    + * + * @element DETAILS + * @param {string} expression Angular expression that will be evaluated. + */ + +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, + compile: function() { + return 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) { + attr.$observe(normalized, function(value) { + if (!value) + return; + + attr.$set(attrName, 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) element.prop(attrName, attr[attrName]); + }); + } + }; + }; +}); + +var nullFormCtrl = { + $addControl: noop, + $removeControl: noop, + $setValidity: noop, + $setDirty: noop, + $setPristine: noop +}; + +/** + * @ngdoc object + * @name ng.directive: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) — such as `required`, `url` or `email`), + * - values are arrays of controls or forms that are invalid with given error. + * + * @description + * `FormController` keeps track of all its controls and nested forms as well as 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']; +function FormController(element, attrs) { + 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, '-') : ''; + element. + removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). + addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); + } + + /** + * @ngdoc function + * @name ng.directive:form.FormController#$addControl + * @methodOf ng.directive:form.FormController + * + * @description + * Register a control with the form. + * + * Input elements using ngModelController do this automatically when they are linked. + */ + form.$addControl = function(control) { + controls.push(control); + + if (control.$name && !form.hasOwnProperty(control.$name)) { + form[control.$name] = control; + } + }; + + /** + * @ngdoc function + * @name ng.directive:form.FormController#$removeControl + * @methodOf ng.directive:form.FormController + * + * @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 function + * @name ng.directive:form.FormController#$setValidity + * @methodOf ng.directive:form.FormController + * + * @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 function + * @name ng.directive:form.FormController#$setDirty + * @methodOf ng.directive:form.FormController + * + * @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() { + element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); + form.$dirty = true; + form.$pristine = false; + parentForm.$setDirty(); + }; + + /** + * @ngdoc function + * @name ng.directive:form.FormController#$setPristine + * @methodOf ng.directive:form.FormController + * + * @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 () { + element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); + form.$dirty = false; + form.$pristine = true; + forEach(controls, function(control) { + control.$setPristine(); + }); + }; +} + + +/** + * @ngdoc directive + * @name ng.directive: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. + * + * @param {string=} name|ngForm Name of the form. If specified, the form controller will be published into + * related scope, under this name. + * + */ + + /** + * @ngdoc directive + * @name ng.directive:form + * @restrict E + * + * @description + * Directive that instantiates + * {@link ng.directive:form.FormController FormController}. + * + * If `name` attribute is specified, the form controller is published onto the current scope under + * this name. + * + * # Alias: {@link ng.directive:ngForm `ngForm`} + * + * In angular forms can be nested. This means that the outer form is valid when all of the child + * forms are valid as well. However browsers do not allow nesting of `
    ` elements, for this + * reason angular provides {@link ng.directive:ngForm `ngForm`} alias + * which behaves identical to `` but allows form nesting. + * + * + * # CSS classes + * - `ng-valid` Is set if the form is valid. + * - `ng-invalid` Is set if the form is invalid. + * - `ng-pristine` Is set if the form is pristine. + * - `ng-dirty` Is set if the form is dirty. + * + * + * # Submitting a form and preventing default action + * + * Since the role of forms in client-side Angular applications is different than in classical + * roundtrip apps, it is desirable for the browser not to translate the form submission into a full + * page reload that sends the data to the server. Instead some javascript logic should be triggered + * to handle the form submission in application specific way. + * + * For this reason, Angular prevents the default action (form submission to the server) unless the + * `` element has an `action` attribute specified. + * + * You can use one of the following two ways to specify what javascript method should be called when + * a form is submitted: + * + * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element + * - {@link ng.directive:ngClick ngClick} directive on the first + * button or input field of type submit (input[type=submit]) + * + * To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This + * is because of the following form submission rules coming from the html spec: + * + * - If a form has only one input field then hitting enter in this field triggers form submit + * (`ngSubmit`) + * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter + * doesn't trigger submit + * - if a form has one or more input fields and one or more buttons or input[type=submit] then + * hitting enter in any of the input fields will trigger the click handler on the *first* button or + * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) + * + * @param {string=} name Name of the form. If specified, the form controller will be published into + * related scope, under this name. + * + * @example + + + + + userType: + Required!
    + userType = {{userType}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    + +
    + + it('should initialize to model', function() { + expect(binding('userType')).toEqual('guest'); + expect(binding('myForm.input.$valid')).toEqual('true'); + }); + + it('should be invalid if empty', function() { + input('userType').enter(''); + expect(binding('userType')).toEqual(''); + expect(binding('myForm.input.$valid')).toEqual('false'); + }); + +
    + */ +var formDirectiveFactory = function(isNgForm) { + return ['$timeout', function($timeout) { + var formDirective = { + name: 'form', + restrict: 'E', + controller: FormController, + compile: function() { + return { + pre: function(scope, formElement, attr, controller) { + if (!attr.action) { + // we can't use jq events because if a form is destroyed during submission the default + // action is not prevented. see #1238 + // + // IE 9 is not affected because it doesn't fire a submit event and try to do a full + // page reload if the form was destroyed by submission of the form via a click handler + // on a button in the form. Looks like an IE9 specific bug. + var preventDefaultListener = function(event) { + event.preventDefault + ? event.preventDefault() + : event.returnValue = false; // IE + }; + + addEventListenerFn(formElement[0], 'submit', preventDefaultListener); + + // unregister the preventDefault listener so that we don't not leak memory but in a + // way that will achieve the prevention of the default action. + formElement.on('$destroy', function() { + $timeout(function() { + removeEventListenerFn(formElement[0], 'submit', preventDefaultListener); + }, 0, false); + }); + } + + var parentFormCtrl = formElement.parent().controller('form'), + alias = attr.name || attr.ngForm; + + if (alias) { + setter(scope, alias, controller, alias); + } + if (parentFormCtrl) { + formElement.on('$destroy', function() { + parentFormCtrl.$removeControl(controller); + if (alias) { + setter(scope, alias, undefined, alias); + } + extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards + }); + } + } + }; + } + }; + + return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective; + }]; +}; + +var formDirective = formDirectiveFactory(); +var ngFormDirective = formDirectiveFactory(true); + +var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; +var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/; +var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; + +var inputType = { + + /** + * @ngdoc inputType + * @name ng.directive:input.text + * + * @description + * Standard HTML text input with angular data binding. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Adds `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trimming the + * input. + * + * @example + + + +
    + Single word: + + Required! + + Single word only! + + text = {{text}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    +
    +
    + + it('should initialize to model', function() { + expect(binding('text')).toEqual('guest'); + expect(binding('myForm.input.$valid')).toEqual('true'); + }); + + it('should be invalid if empty', function() { + input('text').enter(''); + expect(binding('text')).toEqual(''); + expect(binding('myForm.input.$valid')).toEqual('false'); + }); + + it('should be invalid if multi word', function() { + input('text').enter('hello world'); + expect(binding('myForm.input.$valid')).toEqual('false'); + }); + + it('should not be trimmed', function() { + input('text').enter('untrimmed '); + expect(binding('text')).toEqual('untrimmed '); + expect(binding('myForm.input.$valid')).toEqual('true'); + }); + +
    + */ + 'text': textInputType, + + + /** + * @ngdoc inputType + * @name ng.directive:input.number + * + * @description + * Text input with number validation and transformation. Sets the `number` validation + * error if not a valid number. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    + Number: + + Required! + + Not valid number! + value = {{value}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    +
    +
    + + it('should initialize to model', function() { + expect(binding('value')).toEqual('12'); + expect(binding('myForm.input.$valid')).toEqual('true'); + }); + + it('should be invalid if empty', function() { + input('value').enter(''); + expect(binding('value')).toEqual(''); + expect(binding('myForm.input.$valid')).toEqual('false'); + }); + + it('should be invalid if over max', function() { + input('value').enter('123'); + expect(binding('value')).toEqual(''); + expect(binding('myForm.input.$valid')).toEqual('false'); + }); + +
    + */ + 'number': numberInputType, + + + /** + * @ngdoc inputType + * @name ng.directive:input.url + * + * @description + * Text input with URL validation. Sets the `url` validation error key if the content is not a + * valid URL. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    + URL: + + Required! + + Not valid url! + text = {{text}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    + myForm.$error.url = {{!!myForm.$error.url}}
    +
    +
    + + it('should initialize to model', function() { + expect(binding('text')).toEqual('http://google.com'); + expect(binding('myForm.input.$valid')).toEqual('true'); + }); + + it('should be invalid if empty', function() { + input('text').enter(''); + expect(binding('text')).toEqual(''); + expect(binding('myForm.input.$valid')).toEqual('false'); + }); + + it('should be invalid if not url', function() { + input('text').enter('xxx'); + expect(binding('myForm.input.$valid')).toEqual('false'); + }); + +
    + */ + 'url': urlInputType, + + + /** + * @ngdoc inputType + * @name ng.directive:input.email + * + * @description + * Text input with email validation. Sets the `email` validation error key if not a valid email + * address. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    + Email: + + Required! + + Not valid email! + text = {{text}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    + myForm.$error.email = {{!!myForm.$error.email}}
    +
    +
    + + it('should initialize to model', function() { + expect(binding('text')).toEqual('me@example.com'); + expect(binding('myForm.input.$valid')).toEqual('true'); + }); + + it('should be invalid if empty', function() { + input('text').enter(''); + expect(binding('text')).toEqual(''); + expect(binding('myForm.input.$valid')).toEqual('false'); + }); + + it('should be invalid if not email', function() { + input('text').enter('xxx'); + expect(binding('myForm.input.$valid')).toEqual('false'); + }); + +
    + */ + 'email': emailInputType, + + + /** + * @ngdoc inputType + * @name ng.directive:input.radio + * + * @description + * HTML radio button. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string} value The value to which the expression should be set when selected. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    + Red
    + Green
    + Blue
    + color = {{color}}
    +
    +
    + + it('should change state', function() { + expect(binding('color')).toEqual('blue'); + + input('color').select('red'); + expect(binding('color')).toEqual('red'); + }); + +
    + */ + 'radio': radioInputType, + + + /** + * @ngdoc inputType + * @name ng.directive:input.checkbox + * + * @description + * HTML checkbox. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} ngTrueValue The value to which the expression should be set when selected. + * @param {string=} ngFalseValue The value to which the expression should be set when not selected. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    + Value1:
    + Value2:
    + value1 = {{value1}}
    + value2 = {{value2}}
    +
    +
    + + it('should change state', function() { + expect(binding('value1')).toEqual('true'); + expect(binding('value2')).toEqual('YES'); + + input('value1').check(); + input('value2').check(); + expect(binding('value1')).toEqual('false'); + expect(binding('value2')).toEqual('NO'); + }); + +
    + */ + 'checkbox': checkboxInputType, + + 'hidden': noop, + 'button': noop, + 'submit': noop, + 'reset': noop +}; + + +function isEmpty(value) { + return isUndefined(value) || value === '' || value === null || value !== value; +} + + +function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { + + var listener = function() { + var value = element.val(); + + // By default we will trim the value + // If the attribute ng-trim exists we will avoid trimming + // e.g. + if (toBoolean(attr.ngTrim || 'T')) { + value = trim(value); + } + + if (ctrl.$viewValue !== value) { + scope.$apply(function() { + ctrl.$setViewValue(value); + }); + } + }; + + // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the + // input event on backspace, delete or cut + if ($sniffer.hasEvent('input')) { + element.on('input', listener); + } else { + var timeout; + + var deferListener = function() { + if (!timeout) { + timeout = $browser.defer(function() { + listener(); + timeout = null; + }); + } + }; + + element.on('keydown', function(event) { + var key = event.keyCode; + + // ignore + // command modifiers arrows + if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; + + deferListener(); + }); + + // if user paste into input using mouse, we need "change" event to catch it + element.on('change', listener); + + // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it + if ($sniffer.hasEvent('paste')) { + element.on('paste cut', deferListener); + } + } + + + ctrl.$render = function() { + element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); + }; + + // pattern validator + var pattern = attr.ngPattern, + patternValidator, + match; + + var validate = function(regexp, value) { + if (isEmpty(value) || regexp.test(value)) { + ctrl.$setValidity('pattern', true); + return value; + } else { + ctrl.$setValidity('pattern', false); + return undefined; + } + }; + + if (pattern) { + match = pattern.match(/^\/(.*)\/([gim]*)$/); + if (match) { + pattern = new RegExp(match[1], match[2]); + patternValidator = function(value) { + return validate(pattern, value) + }; + } else { + patternValidator = function(value) { + var patternObj = scope.$eval(pattern); + + if (!patternObj || !patternObj.test) { + throw minErr('ngPattern')('noregexp', + 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern, + patternObj, startingTag(element)); + } + return validate(patternObj, value); + }; + } + + ctrl.$formatters.push(patternValidator); + ctrl.$parsers.push(patternValidator); + } + + // min length validator + if (attr.ngMinlength) { + var minlength = int(attr.ngMinlength); + var minLengthValidator = function(value) { + if (!isEmpty(value) && value.length < minlength) { + ctrl.$setValidity('minlength', false); + return undefined; + } else { + ctrl.$setValidity('minlength', true); + return value; + } + }; + + ctrl.$parsers.push(minLengthValidator); + ctrl.$formatters.push(minLengthValidator); + } + + // max length validator + if (attr.ngMaxlength) { + var maxlength = int(attr.ngMaxlength); + var maxLengthValidator = function(value) { + if (!isEmpty(value) && value.length > maxlength) { + ctrl.$setValidity('maxlength', false); + return undefined; + } else { + ctrl.$setValidity('maxlength', true); + return value; + } + }; + + ctrl.$parsers.push(maxLengthValidator); + ctrl.$formatters.push(maxLengthValidator); + } +} + +function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { + textInputType(scope, element, attr, ctrl, $sniffer, $browser); + + ctrl.$parsers.push(function(value) { + var empty = isEmpty(value); + if (empty || NUMBER_REGEXP.test(value)) { + ctrl.$setValidity('number', true); + return value === '' ? null : (empty ? value : parseFloat(value)); + } else { + ctrl.$setValidity('number', false); + return undefined; + } + }); + + ctrl.$formatters.push(function(value) { + return isEmpty(value) ? '' : '' + value; + }); + + if (attr.min) { + var min = parseFloat(attr.min); + var minValidator = function(value) { + if (!isEmpty(value) && value < min) { + ctrl.$setValidity('min', false); + return undefined; + } else { + ctrl.$setValidity('min', true); + return value; + } + }; + + ctrl.$parsers.push(minValidator); + ctrl.$formatters.push(minValidator); + } + + if (attr.max) { + var max = parseFloat(attr.max); + var maxValidator = function(value) { + if (!isEmpty(value) && value > max) { + ctrl.$setValidity('max', false); + return undefined; + } else { + ctrl.$setValidity('max', true); + return value; + } + }; + + ctrl.$parsers.push(maxValidator); + ctrl.$formatters.push(maxValidator); + } + + ctrl.$formatters.push(function(value) { + + if (isEmpty(value) || isNumber(value)) { + ctrl.$setValidity('number', true); + return value; + } else { + ctrl.$setValidity('number', false); + return undefined; + } + }); +} + +function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { + textInputType(scope, element, attr, ctrl, $sniffer, $browser); + + var urlValidator = function(value) { + if (isEmpty(value) || URL_REGEXP.test(value)) { + ctrl.$setValidity('url', true); + return value; + } else { + ctrl.$setValidity('url', false); + return undefined; + } + }; + + ctrl.$formatters.push(urlValidator); + ctrl.$parsers.push(urlValidator); +} + +function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { + textInputType(scope, element, attr, ctrl, $sniffer, $browser); + + var emailValidator = function(value) { + if (isEmpty(value) || EMAIL_REGEXP.test(value)) { + ctrl.$setValidity('email', true); + return value; + } else { + ctrl.$setValidity('email', false); + return undefined; + } + }; + + ctrl.$formatters.push(emailValidator); + ctrl.$parsers.push(emailValidator); +} + +function radioInputType(scope, element, attr, ctrl) { + // make the name unique, if not defined + if (isUndefined(attr.name)) { + element.attr('name', nextUid()); + } + + element.on('click', function() { + if (element[0].checked) { + scope.$apply(function() { + ctrl.$setViewValue(attr.value); + }); + } + }); + + ctrl.$render = function() { + var value = attr.value; + element[0].checked = (value == ctrl.$viewValue); + }; + + attr.$observe('value', ctrl.$render); +} + +function checkboxInputType(scope, element, attr, ctrl) { + var trueValue = attr.ngTrueValue, + falseValue = attr.ngFalseValue; + + if (!isString(trueValue)) trueValue = true; + if (!isString(falseValue)) falseValue = false; + + element.on('click', function() { + scope.$apply(function() { + ctrl.$setViewValue(element[0].checked); + }); + }); + + ctrl.$render = function() { + element[0].checked = ctrl.$viewValue; + }; + + ctrl.$formatters.push(function(value) { + return value === trueValue; + }); + + ctrl.$parsers.push(function(value) { + return value ? trueValue : falseValue; + }); +} + + +/** + * @ngdoc directive + * @name ng.directive:textarea + * @restrict E + * + * @description + * HTML textarea element control with angular data-binding. The data-binding and validation + * properties of this element are exactly the same as those of the + * {@link ng.directive:input input element}. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + */ + + +/** + * @ngdoc directive + * @name ng.directive:input + * @restrict E + * + * @description + * HTML input element control with angular data-binding. Input control follows HTML5 input types + * and polyfills the HTML5 validation behavior for older browsers. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {boolean=} ngRequired Sets `required` attribute if set to true + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    +
    + User name: + + Required!
    + Last name: + + Too short! + + Too long!
    +
    +
    + user = {{user}}
    + myForm.userName.$valid = {{myForm.userName.$valid}}
    + myForm.userName.$error = {{myForm.userName.$error}}
    + myForm.lastName.$valid = {{myForm.lastName.$valid}}
    + myForm.lastName.$error = {{myForm.lastName.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    + myForm.$error.minlength = {{!!myForm.$error.minlength}}
    + myForm.$error.maxlength = {{!!myForm.$error.maxlength}}
    +
    +
    + + it('should initialize to model', function() { + expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}'); + expect(binding('myForm.userName.$valid')).toEqual('true'); + expect(binding('myForm.$valid')).toEqual('true'); + }); + + it('should be invalid if empty when required', function() { + input('user.name').enter(''); + expect(binding('user')).toEqual('{"last":"visitor"}'); + expect(binding('myForm.userName.$valid')).toEqual('false'); + expect(binding('myForm.$valid')).toEqual('false'); + }); + + it('should be valid if empty when min length is set', function() { + input('user.last').enter(''); + expect(binding('user')).toEqual('{"name":"guest","last":""}'); + expect(binding('myForm.lastName.$valid')).toEqual('true'); + expect(binding('myForm.$valid')).toEqual('true'); + }); + + it('should be invalid if less than required min length', function() { + input('user.last').enter('xx'); + expect(binding('user')).toEqual('{"name":"guest"}'); + expect(binding('myForm.lastName.$valid')).toEqual('false'); + expect(binding('myForm.lastName.$error')).toMatch(/minlength/); + expect(binding('myForm.$valid')).toEqual('false'); + }); + + it('should be invalid if longer than max length', function() { + input('user.last').enter('some ridiculously long name'); + expect(binding('user')) + .toEqual('{"name":"guest"}'); + expect(binding('myForm.lastName.$valid')).toEqual('false'); + expect(binding('myForm.lastName.$error')).toMatch(/maxlength/); + expect(binding('myForm.$valid')).toEqual('false'); + }); + +
    + */ +var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) { + return { + restrict: 'E', + require: '?ngModel', + link: function(scope, element, attr, ctrl) { + if (ctrl) { + (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer, + $browser); + } + } + }; +}]; + +var VALID_CLASS = 'ng-valid', + INVALID_CLASS = 'ng-invalid', + PRISTINE_CLASS = 'ng-pristine', + DIRTY_CLASS = 'ng-dirty'; + +/** + * @ngdoc object + * @name ng.directive:ngModel.NgModelController + * + * @property {string} $viewValue Actual string value in the view. + * @property {*} $modelValue The value in the model, that the control is bound to. + * @property {Array.} $parsers Array of functions to execute, as a pipeline, whenever + the control reads value from the DOM. Each function is called, in turn, passing the value + through to the next. Used to sanitize / convert the value as well as validation. + For validation, the parsers should update the validity state using + {@link ng.directive:ngModel.NgModelController#$setValidity $setValidity()}, + and return `undefined` for invalid values. + + * + * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever + the model value changes. Each function is called, in turn, passing the value through to the + next. Used to format / convert values for display in the control and validation. + *
    + *      function formatter(value) {
    + *        if (value) {
    + *          return value.toUpperCase();
    + *        }
    + *      }
    + *      ngModel.$formatters.push(formatter);
    + *      
    + * @property {Object} $error An object hash with all errors as keys. + * + * @property {boolean} $pristine True if user has not interacted with the control yet. + * @property {boolean} $dirty True if user has already interacted with the control. + * @property {boolean} $valid True if there is no error. + * @property {boolean} $invalid True if at least one error on the control. + * + * @description + * + * `NgModelController` provides API for the `ng-model` directive. The controller contains + * services for data-binding, validation, CSS update, value formatting and parsing. It + * specifically does not contain any logic which deals with DOM rendering or listening to + * DOM events. The `NgModelController` is meant to be extended by other directives where, the + * directive provides DOM manipulation and the `NgModelController` provides the data-binding. + * Note that you cannot use `NgModelController` in a directive with an isolated scope, + * as, in that case, the `ng-model` value gets put into the isolated scope and does not get + * propogated to the parent scope. + * + * + * This example shows how to use `NgModelController` with a custom control to achieve + * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) + * collaborate together to achieve the desired result. + * + * + + [contenteditable] { + border: 1px solid black; + background-color: white; + min-height: 20px; + } + + .ng-invalid { + border: 1px solid red; + } + + + + angular.module('customControl', []). + directive('contenteditable', function() { + return { + restrict: 'A', // only activate on element attribute + require: '?ngModel', // get a hold of NgModelController + link: function(scope, element, attrs, ngModel) { + if(!ngModel) return; // do nothing if no ng-model + + // Specify how UI should be updated + ngModel.$render = function() { + element.html(ngModel.$viewValue || ''); + }; + + // Listen for change events to enable binding + element.on('blur keyup change', function() { + scope.$apply(read); + }); + read(); // initialize + + // Write data to the model + function read() { + var html = element.html(); + // When we clear the content editable the browser leaves a
    behind + // If strip-br attribute is provided then we strip this out + if( attrs.stripBr && html == '
    ' ) { + html = ''; + } + ngModel.$setViewValue(html); + } + } + }; + }); +
    + +
    +
    Change me!
    + Required! +
    + +
    +
    + + it('should data-bind and become invalid', function() { + var contentEditable = element('[contenteditable]'); + + expect(contentEditable.text()).toEqual('Change me!'); + input('userContent').enter(''); + expect(contentEditable.text()).toEqual(''); + expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/); + }); + + *
    + * + */ +var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', + function($scope, $exceptionHandler, $attr, $element, $parse) { + this.$viewValue = Number.NaN; + this.$modelValue = Number.NaN; + this.$parsers = []; + this.$formatters = []; + this.$viewChangeListeners = []; + this.$pristine = true; + this.$dirty = false; + this.$valid = true; + this.$invalid = false; + this.$name = $attr.name; + + var ngModelGet = $parse($attr.ngModel), + ngModelSet = ngModelGet.assign; + + if (!ngModelSet) { + throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}", + $attr.ngModel, startingTag($element)); + } + + /** + * @ngdoc function + * @name ng.directive:ngModel.NgModelController#$render + * @methodOf ng.directive:ngModel.NgModelController + * + * @description + * Called when the view needs to be updated. It is expected that the user of the ng-model + * directive will implement this method. + */ + this.$render = noop; + + var parentForm = $element.inheritedData('$formController') || nullFormCtrl, + invalidCount = 0, // used to easily determine if we are valid + $error = this.$error = {}; // keep invalid keys here + + + // 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, '-') : ''; + $element. + removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). + addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); + } + + /** + * @ngdoc function + * @name ng.directive:ngModel.NgModelController#$setValidity + * @methodOf ng.directive:ngModel.NgModelController + * + * @description + * Change the validity state, and notifies the form when the control changes validity. (i.e. it + * does not notify form if given validator is already marked as invalid). + * + * This method should be called by validators - i.e. the parser or formatter functions. + * + * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign + * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. + * The `validationErrorKey` should be in camelCase and will get converted into dash-case + * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` + * class and can be bound to as `{{someForm.someControl.$error.myError}}` . + * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). + */ + this.$setValidity = function(validationErrorKey, isValid) { + if ($error[validationErrorKey] === !isValid) return; + + if (isValid) { + if ($error[validationErrorKey]) invalidCount--; + if (!invalidCount) { + toggleValidCss(true); + this.$valid = true; + this.$invalid = false; + } + } else { + toggleValidCss(false); + this.$invalid = true; + this.$valid = false; + invalidCount++; + } + + $error[validationErrorKey] = !isValid; + toggleValidCss(isValid, validationErrorKey); + + parentForm.$setValidity(validationErrorKey, isValid, this); + }; + + /** + * @ngdoc function + * @name ng.directive:ngModel.NgModelController#$setPristine + * @methodOf ng.directive:ngModel.NgModelController + * + * @description + * Sets the control to its pristine state. + * + * This method can be called to remove the 'ng-dirty' class and set the control to its pristine + * state (ng-pristine class). + */ + this.$setPristine = function () { + this.$dirty = false; + this.$pristine = true; + $element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); + }; + + /** + * @ngdoc function + * @name ng.directive:ngModel.NgModelController#$setViewValue + * @methodOf ng.directive:ngModel.NgModelController + * + * @description + * Read a value from view. + * + * This method should be called from within a DOM event handler. + * For example {@link ng.directive:input input} or + * {@link ng.directive:select select} directives call it. + * + * It internally calls all `$parsers` (including validators) and updates the `$modelValue` and the actual model path. + * Lastly it calls all registered change listeners. + * + * @param {string} value Value from the view. + */ + this.$setViewValue = function(value) { + this.$viewValue = value; + + // change to dirty + if (this.$pristine) { + this.$dirty = true; + this.$pristine = false; + $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); + parentForm.$setDirty(); + } + + forEach(this.$parsers, function(fn) { + value = fn(value); + }); + + if (this.$modelValue !== value) { + this.$modelValue = value; + ngModelSet($scope, value); + forEach(this.$viewChangeListeners, function(listener) { + try { + listener(); + } catch(e) { + $exceptionHandler(e); + } + }) + } + }; + + // model -> value + var ctrl = this; + + $scope.$watch(function ngModelWatch() { + var value = ngModelGet($scope); + + // if scope model value and ngModel value are out of sync + if (ctrl.$modelValue !== value) { + + var formatters = ctrl.$formatters, + idx = formatters.length; + + ctrl.$modelValue = value; + while(idx--) { + value = formatters[idx](value); + } + + if (ctrl.$viewValue !== value) { + ctrl.$viewValue = value; + ctrl.$render(); + } + } + }); +}]; + + +/** + * @ngdoc directive + * @name ng.directive:ngModel + * + * @element input + * + * @description + * Is a directive that tells Angular to do two-way data binding. It works together with `input`, + * `select`, `textarea` and even custom form controls that use {@link ng.directive:ngModel.NgModelController + * NgModelController} exposed by this directive. + * + * `ngModel` is responsible for: + * + * - binding the view into the model, which other directives such as `input`, `textarea` or `select` + * require, + * - providing validation behavior (i.e. required, number, email, url), + * - keeping state of the control (valid/invalid, dirty/pristine, validation errors), + * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`), + * - register the control with parent {@link ng.directive:form form}. + * + * Note: `ngModel` will try to bind to the property given by evaluating the expression on the + * current scope. If the property doesn't already exist on this scope, it will be created + * implicitly and added to the scope. + * + * For basic examples, how to use `ngModel`, see: + * + * - {@link ng.directive:input input} + * - {@link ng.directive:input.text text} + * - {@link ng.directive:input.checkbox checkbox} + * - {@link ng.directive:input.radio radio} + * - {@link ng.directive:input.number number} + * - {@link ng.directive:input.email email} + * - {@link ng.directive:input.url url} + * - {@link ng.directive:select select} + * - {@link ng.directive:textarea textarea} + * + */ +var ngModelDirective = function() { + return { + require: ['ngModel', '^?form'], + controller: NgModelController, + link: function(scope, element, attr, ctrls) { + // notify others, especially parent forms + + var modelCtrl = ctrls[0], + formCtrl = ctrls[1] || nullFormCtrl; + + formCtrl.$addControl(modelCtrl); + + element.on('$destroy', function() { + formCtrl.$removeControl(modelCtrl); + }); + } + }; +}; + + +/** + * @ngdoc directive + * @name ng.directive:ngChange + * @restrict E + * + * @description + * Evaluate given expression when user changes the input. + * The expression is not evaluated when the value change is coming from the model. + * + * Note, this directive requires `ngModel` to be present. + * + * @element input + * + * @example + * + * + * + *
    + * + * + *
    + * debug = {{confirmed}}
    + * counter = {{counter}} + *
    + *
    + * + * it('should evaluate the expression if changing from view', function() { + * expect(binding('counter')).toEqual('0'); + * element('#ng-change-example1').click(); + * expect(binding('counter')).toEqual('1'); + * expect(binding('confirmed')).toEqual('true'); + * }); + * + * it('should not evaluate the expression if changing from model', function() { + * element('#ng-change-example2').click(); + * expect(binding('counter')).toEqual('0'); + * expect(binding('confirmed')).toEqual('true'); + * }); + * + *
    + */ +var ngChangeDirective = valueFn({ + require: 'ngModel', + link: function(scope, element, attr, ctrl) { + ctrl.$viewChangeListeners.push(function() { + scope.$eval(attr.ngChange); + }); + } +}); + + +var requiredDirective = function() { + return { + require: '?ngModel', + link: function(scope, elm, attr, ctrl) { + if (!ctrl) return; + attr.required = true; // force truthy in case we are on non input element + + var validator = function(value) { + if (attr.required && (isEmpty(value) || value === false)) { + ctrl.$setValidity('required', false); + return; + } else { + ctrl.$setValidity('required', true); + return value; + } + }; + + ctrl.$formatters.push(validator); + ctrl.$parsers.unshift(validator); + + attr.$observe('required', function() { + validator(ctrl.$viewValue); + }); + } + }; +}; + + +/** + * @ngdoc directive + * @name ng.directive:ngList + * + * @description + * Text input that converts between comma-separated string into an array of strings. + * + * @element input + * @param {string=} ngList optional delimiter that should be used to split the value. If + * specified in form `/something/` then the value will be converted into a regular expression. + * + * @example + + + +
    + List: + + Required! +
    + names = {{names}}
    + myForm.namesInput.$valid = {{myForm.namesInput.$valid}}
    + myForm.namesInput.$error = {{myForm.namesInput.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    +
    +
    + + it('should initialize to model', function() { + expect(binding('names')).toEqual('["igor","misko","vojta"]'); + expect(binding('myForm.namesInput.$valid')).toEqual('true'); + expect(element('span.error').css('display')).toBe('none'); + }); + + it('should be invalid if empty', function() { + input('names').enter(''); + expect(binding('names')).toEqual('[]'); + expect(binding('myForm.namesInput.$valid')).toEqual('false'); + expect(element('span.error').css('display')).not().toBe('none'); + }); + +
    + */ +var ngListDirective = function() { + return { + require: 'ngModel', + link: function(scope, element, attr, ctrl) { + var match = /\/(.*)\//.exec(attr.ngList), + separator = match && new RegExp(match[1]) || attr.ngList || ','; + + var parse = function(viewValue) { + var list = []; + + if (viewValue) { + forEach(viewValue.split(separator), function(value) { + if (value) list.push(trim(value)); + }); + } + + return list; + }; + + ctrl.$parsers.push(parse); + ctrl.$formatters.push(function(value) { + if (isArray(value)) { + return value.join(', '); + } + + return undefined; + }); + } + }; +}; + + +var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; + +var ngValueDirective = function() { + return { + priority: 100, + compile: function(tpl, tplAttr) { + if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { + return function(scope, elm, attr) { + attr.$set('value', scope.$eval(attr.ngValue)); + }; + } else { + return function(scope, elm, attr) { + scope.$watch(attr.ngValue, function valueWatchAction(value) { + attr.$set('value', value); + }); + }; + } + } + }; +}; + +/** + * @ngdoc directive + * @name ng.directive:ngBind + * + * @description + * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element + * with the value of a given expression, and to update the text content when the value of that + * expression changes. + * + * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like + * `{{ expression }}` which is similar but less verbose. + * + * It is preferrable to use `ngBind` instead of `{{ expression }}` when a template is momentarily + * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an + * element attribute, it makes the bindings invisible to the user while the page is loading. + * + * An alternative solution to this problem would be using the + * {@link ng.directive:ngCloak ngCloak} directive. + * + * + * @element ANY + * @param {expression} ngBind {@link guide/expression Expression} to evaluate. + * + * @example + * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. + + + +
    + Enter name:
    + Hello ! +
    +
    + + it('should check ng-bind', function() { + expect(using('.doc-example-live').binding('name')).toBe('Whirled'); + using('.doc-example-live').input('name').enter('world'); + expect(using('.doc-example-live').binding('name')).toBe('world'); + }); + +
    + */ +var ngBindDirective = ngDirective(function(scope, element, attr) { + element.addClass('ng-binding').data('$binding', attr.ngBind); + scope.$watch(attr.ngBind, function ngBindWatchAction(value) { + element.text(value == undefined ? '' : value); + }); +}); + + +/** + * @ngdoc directive + * @name ng.directive:ngBindTemplate + * + * @description + * The `ngBindTemplate` directive specifies that the element + * text content should be replaced with the interpolation of the template + * in the `ngBindTemplate` attribute. + * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` + * expressions. This directive is needed since some HTML elements + * (such as TITLE and OPTION) cannot contain SPAN elements. + * + * @element ANY + * @param {string} ngBindTemplate template of form + * {{ expression }} to eval. + * + * @example + * Try it here: enter text in text box and watch the greeting change. + + + +
    + Salutation:
    + Name:
    +
    
    +       
    +
    + + it('should check ng-bind', function() { + expect(using('.doc-example-live').binding('salutation')). + toBe('Hello'); + expect(using('.doc-example-live').binding('name')). + toBe('World'); + using('.doc-example-live').input('salutation').enter('Greetings'); + using('.doc-example-live').input('name').enter('user'); + expect(using('.doc-example-live').binding('salutation')). + toBe('Greetings'); + expect(using('.doc-example-live').binding('name')). + toBe('user'); + }); + +
    + */ +var ngBindTemplateDirective = ['$interpolate', function($interpolate) { + return function(scope, element, attr) { + // TODO: move this to scenario runner + var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); + element.addClass('ng-binding').data('$binding', interpolateFn); + attr.$observe('ngBindTemplate', function(value) { + element.text(value); + }); + } +}]; + + +/** + * @ngdoc directive + * @name ng.directive:ngBindHtml + * + * @description + * Creates a binding that will innerHTML the result of evaluating the `expression` into the current + * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link + * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize` + * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in + * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to + * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example + * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}. + * + * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you + * will have an exception (instead of an exploit.) + * + * @element ANY + * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. + */ +var ngBindHtmlDirective = ['$sce', function($sce) { + return function(scope, element, attr) { + element.addClass('ng-binding').data('$binding', attr.ngBindHtml); + scope.$watch(attr.ngBindHtml, function ngBindHtmlWatchAction(value) { + element.html($sce.getTrustedHtml(value) || ''); + }); + }; +}]; + +function classDirective(name, selector) { + name = 'ngClass' + name; + return function() { + return { + restrict: 'AC', + link: function(scope, element, attr) { + var oldVal = undefined; + + scope.$watch(attr[name], ngClassWatchAction, true); + + attr.$observe('class', function(value) { + ngClassWatchAction(scope.$eval(attr[name])); + }); + + + if (name !== 'ngClass') { + scope.$watch('$index', function($index, old$index) { + var mod = $index & 1; + if (mod !== old$index & 1) { + if (mod === selector) { + addClass(scope.$eval(attr[name])); + } else { + removeClass(scope.$eval(attr[name])); + } + } + }); + } + + + function ngClassWatchAction(newVal) { + if (selector === true || scope.$index % 2 === selector) { + if (oldVal && !equals(newVal,oldVal)) { + removeClass(oldVal); + } + addClass(newVal); + } + oldVal = copy(newVal); + } + + + function removeClass(classVal) { + attr.$removeClass(flattenClasses(classVal)); + } + + + function addClass(classVal) { + attr.$addClass(flattenClasses(classVal)); + } + + function flattenClasses(classVal) { + if(isArray(classVal)) { + return classVal.join(' '); + } else if (isObject(classVal)) { + var classes = [], i = 0; + forEach(classVal, function(v, k) { + if (v) { + classes.push(k); + } + }); + return classes.join(' '); + } + + return classVal; + }; + } + }; + }; +} + +/** + * @ngdoc directive + * @name ng.directive:ngClass + * + * @description + * The `ngClass` allows you to set CSS classes on HTML an element, dynamically, by databinding + * an expression that represents all classes to be added. + * + * The directive won't add duplicate classes if a particular class was already set. + * + * When the expression changes, the previously added classes are removed and only then the + * new classes are added. + * + * @animations + * add - happens just before the class is applied to the element + * remove - happens just before the class is removed from the element + * + * @element ANY + * @param {expression} ngClass {@link guide/expression Expression} to eval. The result + * of the evaluation can be a string representing space delimited class + * names, an array, or a map of class names to boolean values. In the case of a map, the + * names of the properties whose values are truthy will be added as css classes to the + * element. + * + * @example Example that demostrates basic bindings via ngClass directive. + + +

    Map Syntax Example

    + bold + strike + red +
    +

    Using String Syntax

    + +
    +

    Using Array Syntax

    +
    +
    +
    +
    + + .strike { + text-decoration: line-through; + } + .bold { + font-weight: bold; + } + .red { + color: red; + } + + + it('should let you toggle the class', function() { + + expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/bold/); + expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/red/); + + input('bold').check(); + expect(element('.doc-example-live p:first').prop('className')).toMatch(/bold/); + + input('red').check(); + expect(element('.doc-example-live p:first').prop('className')).toMatch(/red/); + }); + + it('should let you toggle string example', function() { + expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe(''); + input('style').enter('red'); + expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe('red'); + }); + + it('array example should have 3 classes', function() { + expect(element('.doc-example-live p:last').prop('className')).toBe(''); + input('style1').enter('bold'); + input('style2').enter('strike'); + input('style3').enter('red'); + expect(element('.doc-example-live p:last').prop('className')).toBe('bold strike red'); + }); + +
    + + ## Animations + + The example below demonstrates how to perform animations using ngClass. + + + + + +
    + Sample Text +
    + + .my-class-add, .my-class-remove { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + } + + .my-class, + .my-class-add.my-class-add-active { + color: red; + font-size:3em; + } + + .my-class-remove.my-class-remove-active { + font-size:1.0em; + color:black; + } + + + it('should check ng-class', function() { + expect(element('.doc-example-live span').prop('className')).not(). + toMatch(/my-class/); + + using('.doc-example-live').element(':button:first').click(); + + expect(element('.doc-example-live span').prop('className')). + toMatch(/my-class/); + + using('.doc-example-live').element(':button:last').click(); + + expect(element('.doc-example-live span').prop('className')).not(). + toMatch(/my-class/); + }); + +
    + + + ## ngClass and pre-existing CSS3 Transitions/Animations + The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. + Therefore, if any CSS3 Transition/Animation styles (outside of ngAnimate) are set on the element, then, if a ngClass animation + is triggered, the ngClass animation will be skipped so that ngAnimate can allow for the pre-existing transition or animation to + take over. This restriction allows for ngClass to still work with standard CSS3 Transitions/Animations that are defined + outside of ngAnimate. + */ +var ngClassDirective = classDirective('', true); + +/** + * @ngdoc directive + * @name ng.directive:ngClassOdd + * + * @description + * The `ngClassOdd` and `ngClassEven` directives work exactly as + * {@link ng.directive:ngClass ngClass}, except it works in + * conjunction with `ngRepeat` and takes affect only on odd (even) rows. + * + * This directive can be applied only within a scope of an + * {@link ng.directive:ngRepeat ngRepeat}. + * + * @element ANY + * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result + * of the evaluation can be a string representing space delimited class names or an array. + * + * @example + + +
      +
    1. + + {{name}} + +
    2. +
    +
    + + .odd { + color: red; + } + .even { + color: blue; + } + + + it('should check ng-class-odd and ng-class-even', function() { + expect(element('.doc-example-live li:first span').prop('className')). + toMatch(/odd/); + expect(element('.doc-example-live li:last span').prop('className')). + toMatch(/even/); + }); + +
    + */ +var ngClassOddDirective = classDirective('Odd', 0); + +/** + * @ngdoc directive + * @name ng.directive:ngClassEven + * + * @description + * The `ngClassOdd` and `ngClassEven` directives work exactly as + * {@link ng.directive:ngClass ngClass}, except it works in + * conjunction with `ngRepeat` and takes affect only on odd (even) rows. + * + * This directive can be applied only within a scope of an + * {@link ng.directive:ngRepeat ngRepeat}. + * + * @element ANY + * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The + * result of the evaluation can be a string representing space delimited class names or an array. + * + * @example + + +
      +
    1. + + {{name}}       + +
    2. +
    +
    + + .odd { + color: red; + } + .even { + color: blue; + } + + + it('should check ng-class-odd and ng-class-even', function() { + expect(element('.doc-example-live li:first span').prop('className')). + toMatch(/odd/); + expect(element('.doc-example-live li:last span').prop('className')). + toMatch(/even/); + }); + +
    + */ +var ngClassEvenDirective = classDirective('Even', 1); + +/** + * @ngdoc directive + * @name ng.directive:ngCloak + * + * @description + * The `ngCloak` directive is used to prevent the Angular html template from being briefly + * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this + * directive to avoid the undesirable flicker effect caused by the html template display. + * + * The directive can be applied to the `` element, but typically a fine-grained application is + * preferred in order to benefit from progressive rendering of the browser view. + * + * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and + * `angular.min.js` files. Following is the css rule: + * + *
    + * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
    + *   display: none !important;
    + * }
    + * 
    + * + * When this css rule is loaded by the browser, all html elements (including their children) that + * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive + * during the compilation of the template it deletes the `ngCloak` element attribute, which + * makes the compiled element visible. + * + * For the best result, `angular.js` script must be loaded in the head section of the html file; + * alternatively, the css rule (above) must be included in the external stylesheet of the + * application. + * + * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they + * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css + * class `ngCloak` in addition to `ngCloak` directive as shown in the example below. + * + * @element ANY + * + * @example + + +
    {{ 'hello' }}
    +
    {{ 'hello IE7' }}
    +
    + + it('should remove the template directive and css class', function() { + expect(element('.doc-example-live #template1').attr('ng-cloak')). + not().toBeDefined(); + expect(element('.doc-example-live #template2').attr('ng-cloak')). + not().toBeDefined(); + }); + +
    + * + */ +var ngCloakDirective = ngDirective({ + compile: function(element, attr) { + attr.$set('ngCloak', undefined); + element.removeClass('ng-cloak'); + } +}); + +/** + * @ngdoc directive + * @name ng.directive:ngController + * + * @description + * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular + * supports the principles behind the Model-View-Controller design pattern. + * + * MVC components in angular: + * + * * Model — The Model is data in scope properties; scopes are attached to the DOM. + * * View — The template (HTML with data bindings) is rendered into the View. + * * Controller — The `ngController` directive specifies a Controller class; the class has + * methods that typically express the business logic behind the application. + * + * Note that an alternative way to define controllers is via the {@link ngRoute.$route $route} service. + * + * @element ANY + * @scope + * @param {expression} ngController Name of a globally accessible constructor function or an + * {@link guide/expression expression} that on the current scope evaluates to a + * constructor function. The controller instance can further be published into the scope + * by adding `as localName` the controller name attribute. + * + * @example + * Here is a simple form for editing user contact information. Adding, removing, clearing, and + * greeting are methods declared on the controller (see source tab). These methods can + * easily be called from the angular markup. Notice that the scope becomes the `this` for the + * controller's instance. This allows for easy access to the view data from the controller. Also + * notice that any changes to the data are automatically reflected in the View without the need + * for a manual update. The example is included in two different declaration styles based on + * your style preferences. + + + +
    + Name: + [ greet ]
    + Contact: +
      +
    • + + + [ clear + | X ] +
    • +
    • [ add ]
    • +
    +
    +
    + + it('should check controller as', function() { + expect(element('#ctrl-as-exmpl>:input').val()).toBe('John Smith'); + expect(element('#ctrl-as-exmpl li:nth-child(1) input').val()) + .toBe('408 555 1212'); + expect(element('#ctrl-as-exmpl li:nth-child(2) input').val()) + .toBe('john.smith@example.org'); + + element('#ctrl-as-exmpl li:first a:contains("clear")').click(); + expect(element('#ctrl-as-exmpl li:first input').val()).toBe(''); + + element('#ctrl-as-exmpl li:last a:contains("add")').click(); + expect(element('#ctrl-as-exmpl li:nth-child(3) input').val()) + .toBe('yourname@example.org'); + }); + +
    + + + +
    + Name: + [ greet ]
    + Contact: +
      +
    • + + + [ clear + | X ] +
    • +
    • [ add ]
    • +
    +
    +
    + + it('should check controller', function() { + expect(element('#ctrl-exmpl>:input').val()).toBe('John Smith'); + expect(element('#ctrl-exmpl li:nth-child(1) input').val()) + .toBe('408 555 1212'); + expect(element('#ctrl-exmpl li:nth-child(2) input').val()) + .toBe('john.smith@example.org'); + + element('#ctrl-exmpl li:first a:contains("clear")').click(); + expect(element('#ctrl-exmpl li:first input').val()).toBe(''); + + element('#ctrl-exmpl li:last a:contains("add")').click(); + expect(element('#ctrl-exmpl li:nth-child(3) input').val()) + .toBe('yourname@example.org'); + }); + +
    + + */ +var ngControllerDirective = [function() { + return { + scope: true, + controller: '@' + }; +}]; + +/** + * @ngdoc directive + * @name ng.directive:ngCsp + * @priority 1000 + * + * @element html + * @description + * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. + * + * This is necessary when developing things like Google Chrome Extensions. + * + * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). + * For us to be compatible, we just need to implement the "getterFn" in $parse without violating + * any of these restrictions. + * + * AngularJS uses `Function(string)` generated functions as a speed optimization. By applying `ngCsp` + * it is be possible to opt into the CSP compatible mode. When this mode is on AngularJS will + * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will + * be raised. + * + * In order to use this feature put `ngCsp` directive on the root element of the application. + * + * @example + * This example shows how to apply the `ngCsp` directive to the `html` tag. +
    +     
    +     
    +     ...
    +     ...
    +     
    +   
    + */ + +var ngCspDirective = ['$sniffer', function($sniffer) { + return { + priority: 1000, + compile: function() { + $sniffer.csp = true; + } + }; +}]; + +/** + * @ngdoc directive + * @name ng.directive:ngClick + * + * @description + * The ngClick allows you to specify custom behavior when + * element is clicked. + * + * @element ANY + * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon + * click. (Event object is available as `$event`) + * + * @example + + + + count: {{count}} + + + it('should check ng-click', function() { + expect(binding('count')).toBe('0'); + element('.doc-example-live :button').click(); + expect(binding('count')).toBe('1'); + }); + + + */ +/* + * A directive that allows creation of custom onclick handlers that are defined as angular + * expressions and are compiled and executed within the current scope. + * + * Events that are handled via these handler are always configured not to propagate further. + */ +var ngEventDirectives = {}; +forEach( + 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur'.split(' '), + function(name) { + var directiveName = directiveNormalize('ng-' + name); + ngEventDirectives[directiveName] = ['$parse', function($parse) { + return function(scope, element, attr) { + var fn = $parse(attr[directiveName]); + element.on(lowercase(name), function(event) { + scope.$apply(function() { + fn(scope, {$event:event}); + }); + }); + }; + }]; + } +); + +/** + * @ngdoc directive + * @name ng.directive:ngDblclick + * + * @description + * The `ngDblclick` directive allows you to specify custom behavior on dblclick event. + * + * @element ANY + * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon + * dblclick. (Event object is available as `$event`) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngMousedown + * + * @description + * The ngMousedown directive allows you to specify custom behavior on mousedown event. + * + * @element ANY + * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon + * mousedown. (Event object is available as `$event`) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngMouseup + * + * @description + * Specify custom behavior on mouseup event. + * + * @element ANY + * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon + * mouseup. (Event object is available as `$event`) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + +/** + * @ngdoc directive + * @name ng.directive:ngMouseover + * + * @description + * Specify custom behavior on mouseover event. + * + * @element ANY + * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon + * mouseover. (Event object is available as `$event`) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngMouseenter + * + * @description + * Specify custom behavior on mouseenter event. + * + * @element ANY + * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon + * mouseenter. (Event object is available as `$event`) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngMouseleave + * + * @description + * Specify custom behavior on mouseleave event. + * + * @element ANY + * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon + * mouseleave. (Event object is available as `$event`) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngMousemove + * + * @description + * Specify custom behavior on mousemove event. + * + * @element ANY + * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon + * mousemove. (Event object is available as `$event`) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngKeydown + * + * @description + * Specify custom behavior on keydown event. + * + * @element ANY + * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon + * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngKeyup + * + * @description + * Specify custom behavior on keyup event. + * + * @element ANY + * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon + * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngKeypress + * + * @description + * Specify custom behavior on keypress event. + * + * @element ANY + * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon + * keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngSubmit + * + * @description + * Enables binding angular expressions to onsubmit events. + * + * Additionally it prevents the default action (which for form means sending the request to the + * server and reloading the current page) **but only if the form does not contain an `action` + * attribute**. + * + * @element form + * @param {expression} ngSubmit {@link guide/expression Expression} to eval. (Event object is available as `$event`) + * + * @example + + + +
    + Enter text and hit enter: + + +
    list={{list}}
    +
    +
    + + it('should check ng-submit', function() { + expect(binding('list')).toBe('[]'); + element('.doc-example-live #submit').click(); + expect(binding('list')).toBe('["hello"]'); + expect(input('text').val()).toBe(''); + }); + it('should ignore empty strings', function() { + expect(binding('list')).toBe('[]'); + element('.doc-example-live #submit').click(); + element('.doc-example-live #submit').click(); + expect(binding('list')).toBe('["hello"]'); + }); + +
    + */ + +/** + * @ngdoc directive + * @name ng.directive:ngFocus + * + * @description + * Specify custom behavior on focus event. + * + * @element window, input, select, textarea, a + * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon + * focus. (Event object is available as `$event`) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + +/** + * @ngdoc directive + * @name ng.directive:ngBlur + * + * @description + * Specify custom behavior on blur event. + * + * @element window, input, select, textarea, a + * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon + * blur. (Event object is available as `$event`) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + +/** + * @ngdoc directive + * @name ng.directive:ngIf + * @restrict A + * + * @description + * The `ngIf` directive removes and recreates a portion of the DOM tree (HTML) + * conditionally based on **"falsy"** and **"truthy"** values, respectively, evaluated within + * an {expression}. In other words, if the expression assigned to **ngIf evaluates to a false + * value** then **the element is removed from the DOM** and **if true** then **a clone of the + * element is reinserted into the DOM**. + * + * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the + * element in the DOM rather than changing its visibility via the `display` css property. A common + * case when this difference is significant is when using css selectors that rely on an element's + * position within the DOM (HTML), such as the `:first-child` or `:last-child` pseudo-classes. + * + * Note that **when an element is removed using ngIf its scope is destroyed** and **a new scope + * is created when the element is restored**. The scope created within `ngIf` inherits from + * its parent scope using + * {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}. + * An important implication of this is if `ngModel` is used within `ngIf` to bind to + * a javascript primitive defined in the parent scope. In this case any modifications made to the + * variable within the child scope will override (hide) the value in the parent scope. + * + * Also, `ngIf` recreates elements using their compiled state. An example scenario of this behavior + * is if an element's class attribute is directly modified after it's compiled, using something like + * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element + * the added class will be lost because the original compiled state is used to regenerate the element. + * + * Additionally, you can provide animations via the ngAnimate module to animate the **enter** + * and **leave** effects. + * + * @animations + * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container + * leave - happens just before the ngIf contents are removed from the DOM + * + * @element ANY + * @scope + * @param {expression} ngIf If the {@link guide/expression expression} is falsy then + * the element is removed from the DOM tree (HTML). + * + * @example + + + Click me:
    + Show when checked: + + I'm removed when the checkbox is unchecked. + +
    + + .animate-if { + background:white; + border:1px solid black; + padding:10px; + } + + .animate-if.ng-enter, .animate-if.ng-leave { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + } + + .animate-if.ng-enter, + .animate-if.ng-leave.ng-leave-active { + opacity:0; + } + + .animate-if.ng-enter.ng-enter-active, + .animate-if.ng-leave { + opacity:1; + } + +
    + */ +var ngIfDirective = ['$animate', function($animate) { + return { + transclude: 'element', + priority: 1000, + terminal: true, + restrict: 'A', + compile: function (element, attr, transclude) { + return function ($scope, $element, $attr) { + var childElement, childScope; + $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { + if (childElement) { + $animate.leave(childElement); + childElement = undefined; + } + if (childScope) { + childScope.$destroy(); + childScope = undefined; + } + if (toBoolean(value)) { + childScope = $scope.$new(); + transclude(childScope, function (clone) { + childElement = clone; + $animate.enter(clone, $element.parent(), $element); + }); + } + }); + } + } + } +}]; + +/** + * @ngdoc directive + * @name ng.directive:ngInclude + * @restrict ECA + * + * @description + * Fetches, compiles and includes an external HTML fragment. + * + * Keep in mind that: + * + * - by default, the template URL is restricted to the same domain and protocol as the + * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl} on it. 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. Refer Angular's {@link + * ng.$sce Strict Contextual Escaping}. + * - in addition, the browser's + * {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest + * Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing + * (CORS)} policy apply that may further restrict whether the template is successfully loaded. + * (e.g. ngInclude won't work for cross-domain requests on all browsers and for `file://` + * access on some browsers) + * + * @animations + * enter - animation is used to bring new content into the browser. + * leave - animation is used to animate existing content away. + * + * The enter and leave animation occur concurrently. + * + * @scope + * + * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, + * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. + * @param {string=} onload Expression to evaluate when a new partial is loaded. + * + * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll + * $anchorScroll} to scroll the viewport after the content is loaded. + * + * - If the attribute is not set, disable scrolling. + * - If the attribute is set without value, enable scrolling. + * - Otherwise enable scrolling only if the expression evaluates to truthy value. + * + * @example + + +
    + + url of the template: {{template.url}} +
    +
    +
    +
    +
    +
    + + function Ctrl($scope) { + $scope.templates = + [ { name: 'template1.html', url: 'template1.html'} + , { name: 'template2.html', url: 'template2.html'} ]; + $scope.template = $scope.templates[0]; + } + + + Content of template1.html + + + Content of template2.html + + + .example-animate-container { + position:relative; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; + } + + .example-animate-container > div { + padding:10px; + } + + .include-example.ng-enter, .include-example.ng-leave { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + display:block; + padding:10px; + } + + .include-example.ng-enter { + top:-50px; + } + .include-example.ng-enter.ng-enter-active { + top:0; + } + + .include-example.ng-leave { + top:0; + } + .include-example.ng-leave.ng-leave-active { + top:50px; + } + + + it('should load template1.html', function() { + expect(element('.doc-example-live [ng-include]').text()). + toMatch(/Content of template1.html/); + }); + it('should load template2.html', function() { + select('template').option('1'); + expect(element('.doc-example-live [ng-include]').text()). + toMatch(/Content of template2.html/); + }); + it('should change to blank', function() { + select('template').option(''); + expect(element('.doc-example-live [ng-include]')).toBe(undefined); + }); + +
    + */ + + +/** + * @ngdoc event + * @name ng.directive:ngInclude#$includeContentRequested + * @eventOf ng.directive:ngInclude + * @eventType emit on the scope ngInclude was declared in + * @description + * Emitted every time the ngInclude content is requested. + */ + + +/** + * @ngdoc event + * @name ng.directive:ngInclude#$includeContentLoaded + * @eventOf ng.directive:ngInclude + * @eventType emit on the current ngInclude scope + * @description + * Emitted every time the ngInclude content is reloaded. + */ +var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animate', '$sce', + function($http, $templateCache, $anchorScroll, $compile, $animate, $sce) { + return { + restrict: 'ECA', + terminal: true, + transclude: 'element', + compile: function(element, attr, transclusion) { + var srcExp = attr.ngInclude || attr.src, + onloadExp = attr.onload || '', + autoScrollExp = attr.autoscroll; + + return function(scope, $element) { + var changeCounter = 0, + currentScope, + currentElement; + + var cleanupLastIncludeContent = function() { + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if(currentElement) { + $animate.leave(currentElement); + currentElement = null; + } + }; + + scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) { + var thisChangeId = ++changeCounter; + + if (src) { + $http.get(src, {cache: $templateCache}).success(function(response) { + if (thisChangeId !== changeCounter) return; + var newScope = scope.$new(); + + transclusion(newScope, function(clone) { + cleanupLastIncludeContent(); + + currentScope = newScope; + currentElement = clone; + + currentElement.html(response); + $animate.enter(currentElement, null, $element); + $compile(currentElement.contents())(currentScope); + + if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { + $anchorScroll(); + } + + currentScope.$emit('$includeContentLoaded'); + scope.$eval(onloadExp); + }); + }).error(function() { + if (thisChangeId === changeCounter) cleanupLastIncludeContent(); + }); + scope.$emit('$includeContentRequested'); + } else { + cleanupLastIncludeContent(); + } + }); + }; + } + }; +}]; + +/** + * @ngdoc directive + * @name ng.directive:ngInit + * + * @description + * The `ngInit` directive specifies initialization tasks to be executed + * before the template enters execution mode during bootstrap. + * + * @element ANY + * @param {expression} ngInit {@link guide/expression Expression} to eval. + * + * @example + + +
    + {{greeting}} {{person}}! +
    +
    + + it('should check greeting', function() { + expect(binding('greeting')).toBe('Hello'); + expect(binding('person')).toBe('World'); + }); + +
    + */ +var ngInitDirective = ngDirective({ + compile: function() { + return { + pre: function(scope, element, attrs) { + scope.$eval(attrs.ngInit); + } + } + } +}); + +/** + * @ngdoc directive + * @name ng.directive:ngNonBindable + * @priority 1000 + * + * @description + * Sometimes it is necessary to write code which looks like bindings but which should be left alone + * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML. + * + * @element ANY + * + * @example + * In this example there are two location where a simple binding (`{{}}`) is present, but the one + * wrapped in `ngNonBindable` is left alone. + * + * @example + + +
    Normal: {{1 + 2}}
    +
    Ignored: {{1 + 2}}
    +
    + + it('should check ng-non-bindable', function() { + expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); + expect(using('.doc-example-live').element('div:last').text()). + toMatch(/1 \+ 2/); + }); + +
    + */ +var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); + +/** + * @ngdoc directive + * @name ng.directive:ngPluralize + * @restrict EA + * + * @description + * # Overview + * `ngPluralize` is a directive that displays messages according to en-US localization rules. + * These rules are bundled with angular.js, but can be overridden + * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive + * by specifying the mappings between + * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html + * plural categories} and the strings to be displayed. + * + * # Plural categories and explicit number rules + * There are two + * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html + * plural categories} in Angular's default en-US locale: "one" and "other". + * + * While a plural category may match many numbers (for example, in en-US locale, "other" can match + * any number that is not 1), an explicit number rule can only match one number. For example, the + * explicit number rule for "3" matches the number 3. There are examples of plural categories + * and explicit number rules throughout the rest of this documentation. + * + * # Configuring ngPluralize + * You configure ngPluralize by providing 2 attributes: `count` and `when`. + * You can also provide an optional attribute, `offset`. + * + * The value of the `count` attribute can be either a string or an {@link guide/expression + * Angular expression}; these are evaluated on the current scope for its bound value. + * + * The `when` attribute specifies the mappings between plural categories and the actual + * string to be displayed. The value of the attribute should be a JSON object. + * + * The following example shows how to configure ngPluralize: + * + *
    + * 
    + * 
    + *
    + * + * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not + * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" + * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for + * other numbers, for example 12, so that instead of showing "12 people are viewing", you can + * show "a dozen people are viewing". + * + * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted + * into pluralized strings. In the previous example, Angular will replace `{}` with + * `{{personCount}}`. The closed braces `{}` is a placeholder + * for {{numberExpression}}. + * + * # Configuring ngPluralize with offset + * The `offset` attribute allows further customization of pluralized text, which can result in + * a better user experience. For example, instead of the message "4 people are viewing this document", + * you might display "John, Kate and 2 others are viewing this document". + * The offset attribute allows you to offset a number by any desired value. + * Let's take a look at an example: + * + *
    + * 
    + * 
    + * 
    + * + * Notice that we are still using two plural categories(one, other), but we added + * three explicit number rules 0, 1 and 2. + * When one person, perhaps John, views the document, "John is viewing" will be shown. + * When three people view the document, no explicit number rule is found, so + * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. + * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" + * is shown. + * + * Note that when you specify offsets, you must provide explicit number rules for + * numbers from 0 up to and including the offset. If you use an offset of 3, for example, + * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for + * plural categories "one" and "other". + * + * @param {string|expression} count The variable to be bounded to. + * @param {string} when The mapping between plural category to its corresponding strings. + * @param {number=} offset Offset to deduct from the total number. + * + * @example + + + +
    + Person 1:
    + Person 2:
    + Number of People:
    + + + Without Offset: + +
    + + + With Offset(2): + + +
    +
    + + it('should show correct pluralized string', function() { + expect(element('.doc-example-live ng-pluralize:first').text()). + toBe('1 person is viewing.'); + expect(element('.doc-example-live ng-pluralize:last').text()). + toBe('Igor is viewing.'); + + using('.doc-example-live').input('personCount').enter('0'); + expect(element('.doc-example-live ng-pluralize:first').text()). + toBe('Nobody is viewing.'); + expect(element('.doc-example-live ng-pluralize:last').text()). + toBe('Nobody is viewing.'); + + using('.doc-example-live').input('personCount').enter('2'); + expect(element('.doc-example-live ng-pluralize:first').text()). + toBe('2 people are viewing.'); + expect(element('.doc-example-live ng-pluralize:last').text()). + toBe('Igor and Misko are viewing.'); + + using('.doc-example-live').input('personCount').enter('3'); + expect(element('.doc-example-live ng-pluralize:first').text()). + toBe('3 people are viewing.'); + expect(element('.doc-example-live ng-pluralize:last').text()). + toBe('Igor, Misko and one other person are viewing.'); + + using('.doc-example-live').input('personCount').enter('4'); + expect(element('.doc-example-live ng-pluralize:first').text()). + toBe('4 people are viewing.'); + expect(element('.doc-example-live ng-pluralize:last').text()). + toBe('Igor, Misko and 2 other people are viewing.'); + }); + + it('should show data-binded names', function() { + using('.doc-example-live').input('personCount').enter('4'); + expect(element('.doc-example-live ng-pluralize:last').text()). + toBe('Igor, Misko and 2 other people are viewing.'); + + using('.doc-example-live').input('person1').enter('Di'); + using('.doc-example-live').input('person2').enter('Vojta'); + expect(element('.doc-example-live ng-pluralize:last').text()). + toBe('Di, Vojta and 2 other people are viewing.'); + }); + +
    + */ +var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { + var BRACE = /{}/g; + return { + restrict: 'EA', + link: function(scope, element, attr) { + var numberExp = attr.count, + whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs + offset = attr.offset || 0, + whens = scope.$eval(whenExp) || {}, + whensExpFns = {}, + startSymbol = $interpolate.startSymbol(), + endSymbol = $interpolate.endSymbol(), + isWhen = /^when(Minus)?(.+)$/; + + forEach(attr, function(expression, attributeName) { + if (isWhen.test(attributeName)) { + whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] = + element.attr(attr.$attr[attributeName]); + } + }); + forEach(whens, function(expression, key) { + whensExpFns[key] = + $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + + offset + endSymbol)); + }); + + scope.$watch(function ngPluralizeWatch() { + var value = parseFloat(scope.$eval(numberExp)); + + if (!isNaN(value)) { + //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, + //check it against pluralization rules in $locale service + if (!(value in whens)) value = $locale.pluralCat(value - offset); + return whensExpFns[value](scope, element, true); + } else { + return ''; + } + }, function ngPluralizeWatchAction(newVal) { + element.text(newVal); + }); + } + }; +}]; + +/** + * @ngdoc directive + * @name ng.directive:ngRepeat + * + * @description + * The `ngRepeat` directive instantiates a template once per item from a collection. Each template + * instance gets its own scope, where the given loop variable is set to the current collection item, + * and `$index` is set to the item index or key. + * + * Special properties are exposed on the local scope of each template instance, including: + * + * | Variable | Type | Details | + * |-----------|-----------------|-----------------------------------------------------------------------------| + * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | + * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | + * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | + * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | + * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | + * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | + * + * + * # Special repeat start and end points + * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending + * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. + * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) + * up to and including the ending HTML tag where **ng-repeat-end** is placed. + * + * The example below makes use of this feature: + *
    + *   
    + * Header {{ item }} + *
    + *
    + * Body {{ item }} + *
    + *
    + * Footer {{ item }} + *
    + *
    + * + * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: + *
    + *   
    + * Header A + *
    + *
    + * Body A + *
    + *
    + * Footer A + *
    + *
    + * Header B + *
    + *
    + * Body B + *
    + *
    + * Footer B + *
    + *
    + * + * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such + * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). + * + * @animations + * enter - when a new item is added to the list or when an item is revealed after a filter + * leave - when an item is removed from the list or when an item is filtered out + * move - when an adjacent item is filtered out causing a reorder or when the item contents are reordered + * + * @element ANY + * @scope + * @priority 1000 + * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These + * formats are currently supported: + * + * * `variable in expression` – where variable is the user defined loop variable and `expression` + * is a scope expression giving the collection to enumerate. + * + * For example: `album in artist.albums`. + * + * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, + * and `expression` is the scope expression giving the collection to enumerate. + * + * For example: `(name, age) in {'adam':10, 'amalie':12}`. + * + * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function + * which can be used to associate the objects in the collection with the DOM elements. If no tracking function + * is specified the ng-repeat associates elements by identity in the collection. It is an error to have + * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are + * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression, + * before specifying a tracking expression. + * + * For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements + * will be associated by item identity in the array. + * + * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique + * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements + * with the corresponding item in the array by identity. Moving the same object in array would move the DOM + * element in the same way ian the DOM. + * + * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this + * case the object identity does not matter. Two objects are considered equivalent as long as their `id` + * property is same. + * + * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter + * to items in conjunction with a tracking expression. + * + * @example + * This example initializes the scope to a list of names and + * then uses `ngRepeat` to display every person: + + +
    + I have {{friends.length}} friends. They are: + +
      +
    • + [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. +
    • +
    +
    +
    + + .example-animate-container { + background:white; + border:1px solid black; + list-style:none; + margin:0; + padding:0; + } + + .example-animate-container > li { + padding:10px; + list-style:none; + } + + .animate-repeat.ng-enter, + .animate-repeat.ng-leave, + .animate-repeat.ng-move { + -webkit-transition:all linear 0.5s; + -moz-transition:all linear 0.5s; + -o-transition:all linear 0.5s; + transition:all linear 0.5s; + } + + .animate-repeat.ng-enter { + line-height:0; + opacity:0; + padding-top:0; + padding-bottom:0; + } + .animate-repeat.ng-enter.ng-enter-active { + line-height:20px; + opacity:1; + padding:10px; + } + + .animate-repeat.ng-leave { + opacity:1; + line-height:20px; + padding:10px; + } + .animate-repeat.ng-leave.ng-leave-active { + opacity:0; + line-height:0; + padding-top:0; + padding-bottom:0; + } + + .animate-repeat.ng-move { } + .animate-repeat.ng-move.ng-move-active { } + + + it('should render initial data set', function() { + var r = using('.doc-example-live').repeater('ul li'); + expect(r.count()).toBe(10); + expect(r.row(0)).toEqual(["1","John","25"]); + expect(r.row(1)).toEqual(["2","Jessie","30"]); + expect(r.row(9)).toEqual(["10","Samantha","60"]); + expect(binding('friends.length')).toBe("10"); + }); + + it('should update repeater when filter predicate changes', function() { + var r = using('.doc-example-live').repeater('ul li'); + expect(r.count()).toBe(10); + + input('q').enter('ma'); + + expect(r.count()).toBe(2); + expect(r.row(0)).toEqual(["1","Mary","28"]); + expect(r.row(1)).toEqual(["2","Samantha","60"]); + }); + +
    + */ +var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { + var NG_REMOVED = '$$NG_REMOVED'; + var ngRepeatMinErr = minErr('ngRepeat'); + return { + transclude: 'element', + priority: 1000, + terminal: true, + compile: function(element, attr, linker) { + return function($scope, $element, $attr){ + var expression = $attr.ngRepeat; + var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/), + trackByExp, trackByExpGetter, trackByIdFn, trackByIdArrayFn, trackByIdObjFn, lhs, rhs, valueIdentifier, keyIdentifier, + hashFnLocals = {$id: hashKey}; + + if (!match) { + throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", + expression); + } + + lhs = match[1]; + rhs = match[2]; + trackByExp = match[4]; + + if (trackByExp) { + trackByExpGetter = $parse(trackByExp); + trackByIdFn = function(key, value, index) { + // assign key, value, and $index to the locals so that they can be used in hash functions + if (keyIdentifier) hashFnLocals[keyIdentifier] = key; + hashFnLocals[valueIdentifier] = value; + hashFnLocals.$index = index; + return trackByExpGetter($scope, hashFnLocals); + }; + } else { + trackByIdArrayFn = function(key, value) { + return hashKey(value); + } + trackByIdObjFn = function(key) { + return key; + } + } + + match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); + if (!match) { + throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", + lhs); + } + valueIdentifier = match[3] || match[1]; + keyIdentifier = match[2]; + + // Store a list of elements from previous run. This is a hash where key is the item from the + // iterator, and the value is objects with following properties. + // - scope: bound scope + // - element: previous element. + // - index: position + var lastBlockMap = {}; + + //watch props + $scope.$watchCollection(rhs, function ngRepeatAction(collection){ + var index, length, + previousNode = $element[0], // current position of the node + nextNode, + // Same as lastBlockMap but it has the current state. It will become the + // lastBlockMap on the next iteration. + nextBlockMap = {}, + arrayLength, + childScope, + key, value, // key/value of iteration + trackById, + collectionKeys, + block, // last object information {scope, element, id} + nextBlockOrder = []; + + + if (isArrayLike(collection)) { + collectionKeys = collection; + trackByIdFn = trackByIdFn || trackByIdArrayFn; + } else { + trackByIdFn = trackByIdFn || trackByIdObjFn; + // if object, extract keys, sort them and use to determine order of iteration over obj props + collectionKeys = []; + for (key in collection) { + if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { + collectionKeys.push(key); + } + } + collectionKeys.sort(); + } + + arrayLength = collectionKeys.length; + + // locate existing items + length = nextBlockOrder.length = collectionKeys.length; + for(index = 0; index < length; index++) { + key = (collection === collectionKeys) ? index : collectionKeys[index]; + value = collection[key]; + trackById = trackByIdFn(key, value, index); + if(lastBlockMap.hasOwnProperty(trackById)) { + block = lastBlockMap[trackById] + delete lastBlockMap[trackById]; + nextBlockMap[trackById] = block; + nextBlockOrder[index] = block; + } else if (nextBlockMap.hasOwnProperty(trackById)) { + // restore lastBlockMap + forEach(nextBlockOrder, function(block) { + if (block && block.startNode) lastBlockMap[block.id] = block; + }); + // This is a duplicate and we need to throw an error + throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}", + expression, trackById); + } else { + // new never before seen block + nextBlockOrder[index] = { id: trackById }; + nextBlockMap[trackById] = false; + } + } + + // remove existing items + for (key in lastBlockMap) { + if (lastBlockMap.hasOwnProperty(key)) { + block = lastBlockMap[key]; + $animate.leave(block.elements); + forEach(block.elements, function(element) { element[NG_REMOVED] = true}); + block.scope.$destroy(); + } + } + + // we are not using forEach for perf reasons (trying to avoid #call) + for (index = 0, length = collectionKeys.length; index < length; index++) { + key = (collection === collectionKeys) ? index : collectionKeys[index]; + value = collection[key]; + block = nextBlockOrder[index]; + + if (block.startNode) { + // if we have already seen this object, then we need to reuse the + // associated scope/element + childScope = block.scope; + + nextNode = previousNode; + do { + nextNode = nextNode.nextSibling; + } while(nextNode && nextNode[NG_REMOVED]); + + if (block.startNode == nextNode) { + // do nothing + } else { + // existing item which got moved + $animate.move(block.elements, null, jqLite(previousNode)); + } + previousNode = block.endNode; + } else { + // new item which we don't know about + childScope = $scope.$new(); + } + + childScope[valueIdentifier] = value; + if (keyIdentifier) childScope[keyIdentifier] = key; + childScope.$index = index; + childScope.$first = (index === 0); + childScope.$last = (index === (arrayLength - 1)); + childScope.$middle = !(childScope.$first || childScope.$last); + childScope.$odd = !(childScope.$even = index%2==0); + + if (!block.startNode) { + linker(childScope, function(clone) { + $animate.enter(clone, null, jqLite(previousNode)); + previousNode = clone; + block.scope = childScope; + block.startNode = clone[0]; + block.elements = clone; + block.endNode = clone[clone.length - 1]; + nextBlockMap[block.id] = block; + }); + } + } + lastBlockMap = nextBlockMap; + }); + }; + } + }; +}]; + +/** + * @ngdoc directive + * @name ng.directive:ngShow + * + * @description + * The `ngShow` directive shows and hides the given HTML element conditionally based on the expression + * provided to the ngShow attribute. The show and hide mechanism is a achieved by removing and adding + * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is a predefined CSS class present + * in AngularJS which sets the display style to none (using an !important flag). + * + *
    + * 
    + * 
    + * + * + *
    + *
    + * + * When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute + * on the element causing it to become hidden. When true, the ng-hide CSS class is removed + * from the element causing the element not to appear hidden. + * + * ## Why is !important used? + * + * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector + * can be easily overridden by heavier selectors. For example, something as simple + * as changing the display style on a HTML list item would make hidden elements appear visible. + * This also becomes a bigger issue when dealing with CSS frameworks. + * + * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector + * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the + * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. + * + * ### Overriding .ng-hide + * + * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by + * restating the styles for the .ng-hide class in CSS: + *
    + * .ng-hide {
    + *   //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
    + *   display:block!important;
    + *
    + *   //this is just another form of hiding an element
    + *   position:absolute;
    + *   top:-9999px;
    + *   left:-9999px;
    + * }
    + * 
    + * + * Just remember to include the important flag so the CSS override will function. + * + * ## A note about animations with ngShow + * + * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression + * is true and false. This system works similar to the animation system present with ngClass, however, the + * only difference is that you must also include the !important flag to override the display property so + * that you can perform an animation when the element is hidden during the time of the animation. + * + *
    + * //
    + * //a working example can be found at the bottom of this page
    + * //
    + * .my-element.ng-hide-add, .my-element.ng-hide-remove {
    + *   transition:0.5s linear all;
    + *   display:block!important;
    + * }
    + *
    + * .my-element.ng-hide-add { ... }
    + * .my-element.ng-hide-add.ng-hide-add-active { ... }
    + * .my-element.ng-hide-remove { ... }
    + * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
    + * 
    + * + * @animations + * addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible + * removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden + * + * @element ANY + * @param {expression} ngShow If the {@link guide/expression expression} is truthy + * then the element is shown or hidden respectively. + * + * @example + + + Click me:
    +
    + Show: +
    + I show up when your checkbox is checked. +
    +
    +
    + Hide: +
    + I hide when your checkbox is checked. +
    +
    +
    + + .animate-show.ng-hide-add, + .animate-show.ng-hide-remove { + -webkit-transition:all linear 0.5s; + -moz-transition:all linear 0.5s; + -o-transition:all linear 0.5s; + transition:all linear 0.5s; + display:block!important; + } + + .animate-show.ng-hide-add.ng-hide-add-active, + .animate-show.ng-hide-remove { + line-height:0; + opacity:0; + padding:0 10px; + } + + .animate-show.ng-hide-add, + .animate-show.ng-hide-remove.ng-hide-remove-active { + line-height:20px; + opacity:1; + padding:10px; + border:1px solid black; + background:white; + } + + .check-element { + padding:10px; + border:1px solid black; + background:white; + } + + + it('should check ng-show / ng-hide', function() { + expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); + expect(element('.doc-example-live span:last:visible').count()).toEqual(1); + + input('checked').check(); + + expect(element('.doc-example-live span:first:visible').count()).toEqual(1); + expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); + }); + +
    + */ +var ngShowDirective = ['$animate', function($animate) { + return function(scope, element, attr) { + scope.$watch(attr.ngShow, function ngShowWatchAction(value){ + $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide'); + }); + }; +}]; + + +/** + * @ngdoc directive + * @name ng.directive:ngHide + * + * @description + * The `ngHide` directive shows and hides the given HTML element conditionally based on the expression + * provided to the ngHide attribute. The show and hide mechanism is a achieved by removing and adding + * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is a predefined CSS class present + * in AngularJS which sets the display style to none (using an !important flag). + * + *
    + * 
    + * 
    + * + * + *
    + *
    + * + * When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute + * on the element causing it to become hidden. When false, the ng-hide CSS class is removed + * from the element causing the element not to appear hidden. + * + * ## Why is !important used? + * + * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector + * can be easily overridden by heavier selectors. For example, something as simple + * as changing the display style on a HTML list item would make hidden elements appear visible. + * This also becomes a bigger issue when dealing with CSS frameworks. + * + * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector + * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the + * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. + * + * ### Overriding .ng-hide + * + * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by + * restating the styles for the .ng-hide class in CSS: + *
    + * .ng-hide {
    + *   //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
    + *   display:block!important;
    + *
    + *   //this is just another form of hiding an element
    + *   position:absolute;
    + *   top:-9999px;
    + *   left:-9999px;
    + * }
    + * 
    + * + * Just remember to include the important flag so the CSS override will function. + * + * ## A note about animations with ngHide + * + * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression + * is true and false. This system works similar to the animation system present with ngClass, however, the + * only difference is that you must also include the !important flag to override the display property so + * that you can perform an animation when the element is hidden during the time of the animation. + * + *
    + * //
    + * //a working example can be found at the bottom of this page
    + * //
    + * .my-element.ng-hide-add, .my-element.ng-hide-remove {
    + *   transition:0.5s linear all;
    + *   display:block!important;
    + * }
    + *
    + * .my-element.ng-hide-add { ... }
    + * .my-element.ng-hide-add.ng-hide-add-active { ... }
    + * .my-element.ng-hide-remove { ... }
    + * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
    + * 
    + * + * @animations + * removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden + * addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible + * + * @element ANY + * @param {expression} ngHide If the {@link guide/expression expression} is truthy then + * the element is shown or hidden respectively. + * + * @example + + + Click me:
    +
    + Show: +
    + I show up when your checkbox is checked. +
    +
    +
    + Hide: +
    + I hide when your checkbox is checked. +
    +
    +
    + + .animate-hide.ng-hide-add, + .animate-hide.ng-hide-remove { + -webkit-transition:all linear 0.5s; + -moz-transition:all linear 0.5s; + -o-transition:all linear 0.5s; + transition:all linear 0.5s; + display:block!important; + } + + .animate-hide.ng-hide-add.ng-hide-add-active, + .animate-hide.ng-hide-remove { + line-height:0; + opacity:0; + padding:0 10px; + } + + .animate-hide.ng-hide-add, + .animate-hide.ng-hide-remove.ng-hide-remove-active { + line-height:20px; + opacity:1; + padding:10px; + border:1px solid black; + background:white; + } + + .check-element { + padding:10px; + border:1px solid black; + background:white; + } + + + it('should check ng-show / ng-hide', function() { + expect(element('.doc-example-live .check-element:first:hidden').count()).toEqual(1); + expect(element('.doc-example-live .check-element:last:visible').count()).toEqual(1); + + input('checked').check(); + + expect(element('.doc-example-live .check-element:first:visible').count()).toEqual(1); + expect(element('.doc-example-live .check-element:last:hidden').count()).toEqual(1); + }); + +
    + */ +var ngHideDirective = ['$animate', function($animate) { + return function(scope, element, attr) { + scope.$watch(attr.ngHide, function ngHideWatchAction(value){ + $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide'); + }); + }; +}]; + +/** + * @ngdoc directive + * @name ng.directive:ngStyle + * + * @description + * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. + * + * @element ANY + * @param {expression} ngStyle {@link guide/expression Expression} which evals to an + * object whose keys are CSS style names and values are corresponding values for those CSS + * keys. + * + * @example + + + + +
    + Sample Text +
    myStyle={{myStyle}}
    +
    + + span { + color: black; + } + + + it('should check ng-style', function() { + expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); + element('.doc-example-live :button[value=set]').click(); + expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); + element('.doc-example-live :button[value=clear]').click(); + expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); + }); + +
    + */ +var ngStyleDirective = ngDirective(function(scope, element, attr) { + scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { + if (oldStyles && (newStyles !== oldStyles)) { + forEach(oldStyles, function(val, style) { element.css(style, '');}); + } + if (newStyles) element.css(newStyles); + }, true); +}); + +/** + * @ngdoc directive + * @name ng.directive:ngSwitch + * @restrict EA + * + * @description + * The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression. + * Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location + * as specified in the template. + * + * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it + * from the template cache), ngSwitch simply choses one of the nested elements and makes it visible based on which element + * matches the value obtained from the evaluated expression. In other words, you define a container element + * (where you place the directive), place an expression on the **on="..." attribute** + * (or the **ng-switch="..." attribute**), define any inner elements inside of the directive and place + * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on + * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default + * attribute is displayed. + * + * @animations + * enter - happens after the ngSwtich contents change and the matched child element is placed inside the container + * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM + * + * @usage + * + * ... + * ... + * ... + * + * + * @scope + * @param {*} ngSwitch|on expression to match against ng-switch-when. + * @paramDescription + * On child elements add: + * + * * `ngSwitchWhen`: the case statement to match against. If match then this + * case will be displayed. If the same match appears multiple times, all the + * elements will be displayed. + * * `ngSwitchDefault`: the default case when no other case match. If there + * are multiple default cases, all of them will be displayed when no other + * case match. + * + * + * @example + + +
    + + selection={{selection}} +
    +
    +
    Settings Div
    +
    Home Span
    +
    default
    +
    +
    +
    + + function Ctrl($scope) { + $scope.items = ['settings', 'home', 'other']; + $scope.selection = $scope.items[0]; + } + + + .animate-switch-container { + position:relative; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; + } + + .animate-switch-container > div { + padding:10px; + } + + .animate-switch-container > .ng-enter, + .animate-switch-container > .ng-leave { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + } + + .animate-switch-container > .ng-enter { + top:-50px; + } + .animate-switch-container > .ng-enter.ng-enter-active { + top:0; + } + + .animate-switch-container > .ng-leave { + top:0; + } + .animate-switch-container > .ng-leave.ng-leave-active { + top:50px; + } + + + it('should start in settings', function() { + expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); + }); + it('should change to home', function() { + select('selection').option('home'); + expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); + }); + it('should select default', function() { + select('selection').option('other'); + expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); + }); + +
    + */ +var ngSwitchDirective = ['$animate', function($animate) { + return { + restrict: 'EA', + require: 'ngSwitch', + + // asks for $scope to fool the BC controller module + controller: ['$scope', function ngSwitchController() { + this.cases = {}; + }], + link: function(scope, element, attr, ngSwitchController) { + var watchExpr = attr.ngSwitch || attr.on, + selectedTranscludes, + selectedElements, + selectedScopes = []; + + scope.$watch(watchExpr, function ngSwitchWatchAction(value) { + for (var i= 0, ii=selectedScopes.length; i + + +
    +
    +
    + {{text}} +
    +
    + + it('should have transcluded', function() { + input('title').enter('TITLE'); + input('text').enter('TEXT'); + expect(binding('title')).toEqual('TITLE'); + expect(binding('text')).toEqual('TEXT'); + }); + + + * + */ +var ngTranscludeDirective = ngDirective({ + controller: ['$transclude', function($transclude) { + // remember the transclusion fn but call it during linking so that we don't process transclusion before directives on + // the parent element even when the transclusion replaces the current element. (we can't use priority here because + // that applies only to compile fns and not controllers + this.$transclude = $transclude; + }], + + link: function($scope, $element, $attrs, controller) { + controller.$transclude(function(clone) { + $element.html(''); + $element.append(clone); + }); + } +}); + +/** + * @ngdoc directive + * @name ng.directive:script + * + * @description + * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the + * template can be used by `ngInclude`, `ngView` or directive templates. + * + * @restrict E + * @param {'text/ng-template'} type must be set to `'text/ng-template'` + * + * @example + + + + + Load inlined template +
    +
    + + it('should load template defined inside script tag', function() { + element('#tpl-link').click(); + expect(element('#tpl-content').text()).toMatch(/Content of the template/); + }); + +
    + */ +var scriptDirective = ['$templateCache', function($templateCache) { + return { + restrict: 'E', + terminal: true, + compile: function(element, attr) { + if (attr.type == 'text/ng-template') { + var templateUrl = attr.id, + // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent + text = element[0].text; + + $templateCache.put(templateUrl, text); + } + } + }; +}]; + +/** + * @ngdoc directive + * @name ng.directive:select + * @restrict E + * + * @description + * HTML `SELECT` element with angular data-binding. + * + * # `ngOptions` + * + * Optionally `ngOptions` attribute can be used to dynamically generate a list of `` + * DOM element. + * * `trackexpr`: Used when working with an array of objects. The result of this expression will be + * used to identify the objects in the array. The `trackexpr` will most likely refer to the + * `value` variable (e.g. `value.propertyName`). + * + * @example + + + +
    +
      +
    • + Name: + [X] +
    • +
    • + [add] +
    • +
    +
    + Color (null not allowed): +
    + + Color (null allowed): + + +
    + + Color grouped by shade: +
    + + + Select bogus.
    +
    + Currently selected: {{ {selected_color:color} }} +
    +
    +
    +
    + + it('should check ng-options', function() { + expect(binding('{selected_color:color}')).toMatch('red'); + select('color').option('0'); + expect(binding('{selected_color:color}')).toMatch('black'); + using('.nullable').select('color').option(''); + expect(binding('{selected_color:color}')).toMatch('null'); + }); + +
    + */ + +var ngOptionsDirective = valueFn({ terminal: true }); +var selectDirective = ['$compile', '$parse', function($compile, $parse) { + //0000111110000000000022220000000000000000000000333300000000000000444444444444444440000000005555555555555555500000006666666666666666600000000000000007777000000000000000000088888 + var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/, + nullModelCtrl = {$setViewValue: noop}; + + return { + restrict: 'E', + require: ['select', '?ngModel'], + controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { + var self = this, + optionsMap = {}, + ngModelCtrl = nullModelCtrl, + nullOption, + unknownOption; + + + self.databound = $attrs.ngModel; + + + self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { + ngModelCtrl = ngModelCtrl_; + nullOption = nullOption_; + unknownOption = unknownOption_; + } + + + self.addOption = function(value) { + optionsMap[value] = true; + + if (ngModelCtrl.$viewValue == value) { + $element.val(value); + if (unknownOption.parent()) unknownOption.remove(); + } + }; + + + self.removeOption = function(value) { + if (this.hasOption(value)) { + delete optionsMap[value]; + if (ngModelCtrl.$viewValue == value) { + this.renderUnknownOption(value); + } + } + }; + + + self.renderUnknownOption = function(val) { + var unknownVal = '? ' + hashKey(val) + ' ?'; + unknownOption.val(unknownVal); + $element.prepend(unknownOption); + $element.val(unknownVal); + unknownOption.prop('selected', true); // needed for IE + } + + + self.hasOption = function(value) { + return optionsMap.hasOwnProperty(value); + } + + $scope.$on('$destroy', function() { + // disable unknown option so that we don't do work when the whole select is being destroyed + self.renderUnknownOption = noop; + }); + }], + + link: function(scope, element, attr, ctrls) { + // if ngModel is not defined, we don't need to do anything + if (!ctrls[1]) return; + + var selectCtrl = ctrls[0], + ngModelCtrl = ctrls[1], + multiple = attr.multiple, + optionsExp = attr.ngOptions, + nullOption = false, // if false, user will not be able to select it (used by ngOptions) + emptyOption, + // we can't just jqLite('